Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Set up Patrol on the Patrol page
rcourtman159db4ba3cb1
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 70a8356b52..7cc1cc44a4 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -20,6 +20,17 @@## Purpose+### Patrol setup panel reuses existing AI endpoints++The Patrol page setup panel adds no endpoint or payload field. It calls+`PUT /api/settings/ai/update` (provider key or Ollama URL with `enabled`,+then `patrol_model`, `model` only when empty, and `patrol_interval_minutes`+only when the cost model slows the untouched default), `POST+/api/ai/test/{provider}`, `GET /api/ai/models`, `GET+/api/ai/patrol/model-guidance`, `GET /api/ai/patrol/cost-preview` and `POST+/api/ai/patrol/readiness`, with the same meanings Provider & Models and+Patrol settings rely on.+### Patrol autonomy reports the Pro default`GET /api/ai/patrol/autonomy` adds `default_mode_applied`. It is true only whendiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex fc28f1bedf..b257a2718b 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -20,6 +20,14 @@## Purpose+### Patrol setup panel uses existing form primitives++`PatrolSetupPanel.tsx` builds the provider choice from `SelectionCardGroup`+(compact), the inputs from the shared form classes, results from+`InlineNotice`, and actions from `Button`. It adds no shared primitive; at+phone width the cards stack two per row and the action buttons keep 44px+targets.+### Patrol header default-mode notice uses existing primitivesThe Pro default notice in `PatrolIntelligenceHeader.tsx` is a `role="status"`diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 60d512edcf..16f97b5eee 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -15,6 +15,38 @@## Purpose+### One-page Patrol setup on the Patrol page++When Patrol is blocked because no provider is connected, Pulse Intelligence+is off, or the provider refused the saved key (`provider_auth`),+`PatrolIntelligenceWorkspace.tsx` shows `PatrolSetupPanel.tsx` inside the+setup card instead of a link to Provider & Models. The panel covers the two+routes most paid installs use: a cloud API key (Anthropic, OpenAI, Gemini,+DeepSeek, OpenRouter) or Ollama. It names the model Pulse will use from the+Patrol model guidance table and prices it with the cost preview before+anything is saved, at the schedule it will save: a per-token model on the+untouched 6-hour default gets the same slower schedule picking it on Patrol+settings proposes. Connect writes the key or Ollama URL with `enabled: true`,+runs the provider test that Provider & Models runs (the model list hides a+refused key behind an empty list; only a `provider_*` cause stops setup,+because the test probes the provider's default model and a model-level cause+is what setup is about to replace), picks the guided model from the+provider's own list (best guidance level, undated alias first, never a+caution model), saves it as the Patrol model (and as the shared model only+when there is none), then runs the Patrol model check and shows its verdict.+Ready means the check verified a Patrol mode; the panel then offers `Run+Patrol now`, which re-reads Patrol state before the run gate. Once started,+the panel stays mounted until the operator finishes, because polling flips+the readiness cause mid-setup. The saved key is cleared from the page after+connect. Subscription CLIs, custom endpoints, other providers and model+overrides stay on Provider & Models, linked from the panel. `provider_auth`+also routes the setup action to Provider & Models instead of the model check.+`patrolSetupModel.ts` holds the pure decisions. Proofs:+`frontend-modern/src/features/patrol/__tests__/patrolSetupModel.test.ts`,+`frontend-modern/src/features/patrol/__tests__/PatrolSetupPanel.render.test.tsx`,+`frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts`+and `frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts`.+### Pro default notice and the not-running headerA Pro install that never chose a Patrol mode runs Ask first.@@ -148,6 +180,8 @@ sources, and retains the note as operator context.37. `frontend-modern/src/features/patrol/patrolHomePresentation.ts`38. `frontend-modern/src/features/patrol/PatrolRecentWorkPanel.tsx`39. `frontend-modern/src/features/patrol/PatrolWeeklyDigestCard.tsx`+40. `frontend-modern/src/features/patrol/PatrolSetupPanel.tsx`+41. `frontend-modern/src/features/patrol/patrolSetupModel.ts`## Shared Boundariesdiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 4aa61ae657..b48db9a7f2 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -6879,6 +6879,8 @@"frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts","frontend-modern/src/features/patrol/PatrolObjectivesPanel.tsx","frontend-modern/src/features/patrol/PatrolRecentWorkPanel.tsx",+ "frontend-modern/src/features/patrol/patrolSetupModel.ts",+ "frontend-modern/src/features/patrol/PatrolSetupPanel.tsx","frontend-modern/src/features/patrol/PatrolSuppressionRules.tsx","frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts","frontend-modern/src/pages/AIIntelligence.tsx",@@ -6925,6 +6927,8 @@"frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts","frontend-modern/src/features/patrol/PatrolObjectivesPanel.tsx","frontend-modern/src/features/patrol/PatrolRecentWorkPanel.tsx",+ "frontend-modern/src/features/patrol/patrolSetupModel.ts",+ "frontend-modern/src/features/patrol/PatrolSetupPanel.tsx","frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts","frontend-modern/src/pages/AIIntelligence.tsx","frontend-modern/src/stores/aiIntelligence.ts",@@ -6946,6 +6950,8 @@"frontend-modern/src/features/patrol/__tests__/PatrolObjectivesPanel.test.tsx","frontend-modern/src/features/patrol/__tests__/PatrolRecentWorkPanel.test.tsx","frontend-modern/src/features/patrol/__tests__/patrolRunAcceptance.test.ts",+ "frontend-modern/src/features/patrol/__tests__/patrolSetupModel.test.ts",+ "frontend-modern/src/features/patrol/__tests__/PatrolSetupPanel.render.test.tsx","frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts","frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx","frontend-modern/src/stores/__tests__/aiIntelligence.test.ts",diff --git a/frontend-modern/browser-verification/f9b9b8c51cc0bbd9.json b/frontend-modern/browser-verification/f9b9b8c51cc0bbd9.jsonnew file mode 100644index 0000000000..4da65cf5d8--- /dev/null+++ b/frontend-modern/browser-verification/f9b9b8c51cc0bbd9.json@@ -0,0 +1,56 @@+{+ "version": 1,+ "base_sha": "31da7e79521133b322349fd740f7e29851852b9f",+ "verified_at": "2026-10-12T21:25:00Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx",+ "frontend-modern/src/features/patrol/PatrolSetupPanel.tsx",+ "frontend-modern/src/features/patrol/patrolControlPresentation.ts",+ "frontend-modern/src/features/patrol/patrolSetupModel.ts",+ "frontend-modern/src/utils/patrolRuntimeActions.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx": "fa041ffc778e25a0456fa05b3a01053964015ca066cedf3784ecf8f6e6dee778",+ "frontend-modern/src/features/patrol/PatrolSetupPanel.tsx": "d03cf70b925b0febafcac02a4c007642aaa3fe3fb2548d1594505bfb17c90bec",+ "frontend-modern/src/features/patrol/patrolControlPresentation.ts": "e2782489dc1abf33b1516753f52d9de4d8dfec71e1d614e9a9d9f0d4935d7efd",+ "frontend-modern/src/features/patrol/patrolSetupModel.ts": "ff062f40c16f1fe1fd180d25cdc28167134c5e3415c85527a1397d9442ebbda9",+ "frontend-modern/src/utils/patrolRuntimeActions.ts": "a06a675187edbb40735912bd5047c1745dbb0d872febb21142dd51cb778cbb65"+ },+ "routes": [+ "/patrol"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 900+ },+ {+ "width": 375,+ "height": 812+ }+ ],+ "states": [+ "Fresh Pro install, no provider: setup card subtitle 'Patrol needs an AI model before it can check your infrastructure.', panel with six provider cards, Anthropic preselected, model claude-haiku-4-5 and 'About $7.62 a month ... checking every 12 hours' from the live cost preview before any save",+ "Ollama route: pull hint for qwen3:8b before connect, 'No per-token bill' cost line",+ "Ollama reachable but qwen3:8b not installed (local fake Ollama listing no models): the provider test's model_unavailable is not treated as a refused connection, and the pull-command message (no semicolons, 'It is about a 5 GB download and needs 8 GB of free memory.') shows, no model check run",+ "Ollama URL with nothing listening: 'Ollama did not accept the connection: Pulse could not maintain a healthy connection to this provider. Check provider reachability, base URL, ...'",+ "Ollama listing qwen3:8b: settings saved (enabled, ollama URL, patrol_model and shared model ollama:qwen3:8b, schedule unchanged at 6 hours), real Patrol model check ran and failed honestly (no tool calls) with the backend's summary and a 'Check qwen3:8b again' button",+ "Verdict, heading 'Set up Patrol' and retry stay mounted through 40+ seconds of polling after the readiness cause flipped from no provider to model check failed",+ "Invalid test Anthropic key: provider test refusal shown as 'Anthropic did not accept the connection: ... Check the API key and connect again.', key field cleared, no model list or check",+ "Reload with the refused key saved (readiness cause provider_auth): panel shown with Anthropic preselected and subtitle 'Your AI provider refused Patrol's connection. Reconnect it so Patrol can run.'",+ "Check pass (readiness POST stubbed in the page; the fake model cannot pass the real check): 'Patrol is ready' with Run Patrol now and Done",+ "Phone width: no horizontal overflow, provider cards 66px, action buttons 44px"+ ],+ "interactions": [+ "Provider card switch resets key and model state",+ "Connect and check by button and by Enter in the field",+ "Check qwen3:8b again re-runs only the model check",+ "Run Patrol now re-reads Patrol state before the run gate; with the real check still failing the gate stayed shut and the card returned to the model-check route"+ ],+ "browser": {+ "client": "Claude desktop browser pane",+ "engine": "Chromium"+ },+ "scope": "Vite dev server on this branch proxied to a private non-mock pulse-enterprise stack on :7681 with a dev Pro licence, plus a local fake Ollama on :11555. A passing model check and a real first Patrol run were not exercised end to end: the pass response was stubbed in the page."+}diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsxindex 47fc806a53..b4eca86920 100644--- a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx@@ -1,4 +1,4 @@-import { createMemo, For, Show } from 'solid-js';+import { createMemo, createSignal, For, Show } from 'solid-js';import HistoryIcon from 'lucide-solid/icons/history';import SettingsIcon from 'lucide-solid/icons/settings';import ShieldAlertIcon from 'lucide-solid/icons/shield-alert';@@ -22,7 +22,13 @@ import {import { Button, ButtonLink } from '@/components/shared/Button';import { MetadataBadge } from '@/components/shared/MetadataBadge';import { StatusIndicatorBadge } from '@/components/shared/StatusIndicatorBadge';-import { getPatrolSetupAction, getPatrolSetupHint } from '@/utils/patrolRuntimeActions';+import {+ getPatrolSetupAction,+ getPatrolSetupHint,+ isPatrolConnectCause,+} from '@/utils/patrolRuntimeActions';+import { PatrolSetupPanel } from './PatrolSetupPanel';+import { getPatrolSetupInitialProvider } from './patrolSetupModel';import {getPatrolProInvestigationHandoff,getPatrolWatchOnlyInvestigationNudge,@@ -34,6 +40,7 @@ import {PATROL_WORKSPACE_QUEUE_TITLE,PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION,PATROL_WORKSPACE_RUN_RECORD_TITLE,+ PATROL_WORKSPACE_SETUP_ACTIVE_DESCRIPTION,PATROL_WORKSPACE_SETUP_TITLE,getPatrolWorkspaceSetupDescription,} from './patrolControlPresentation';@@ -68,8 +75,15 @@ export function PatrolIntelligenceWorkspace(props: {getPatrolWorkTypeComposition(state.findingsTabBadgeFindings()),);const isHistoryOpen = () => state.activeTab() === 'history';+ // Once the operator starts the setup panel it stays until they finish:+ // polling flips the readiness cause mid-setup (no provider, then model+ // check failed or passed) and would otherwise unmount the panel along+ // with its verdict.+ const [setupPanelActive, setSetupPanelActive] = createSignal(false);const isSetupOnly = () =>- !isHistoryOpen() && !state.selectedRun() && state.shouldShowPatrolSetupOnly();+ !isHistoryOpen() &&+ !state.selectedRun() &&+ (state.shouldShowPatrolSetupOnly() || setupPanelActive());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@@ -104,7 +118,9 @@ export function PatrolIntelligenceWorkspace(props: {isHistoryOpen()? PATROL_WORKSPACE_HISTORY_DESCRIPTION: isSetupOnly()- ? getPatrolWorkspaceSetupDescription(setupCause())+ ? setupPanelActive()+ ? PATROL_WORKSPACE_SETUP_ACTIVE_DESCRIPTION+ : getPatrolWorkspaceSetupDescription(setupCause()): state.selectedRun()? PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION: getPatrolQueueWorkspaceDescription({@@ -310,21 +326,50 @@ export function PatrolIntelligenceWorkspace(props: {<div class="min-w-0"><div class="flex items-center gap-2 text-amber-800 dark:text-amber-200"><ShieldAlertIcon class="h-5 w-5 shrink-0" aria-hidden="true" />- <h3 class="text-sm font-semibold">Patrol cannot run yet</h3>+ <h3 class="text-sm font-semibold">+ {setupPanelActive() ? 'Set up Patrol' : 'Patrol cannot run yet'}+ </h3></div>- <p class="mt-2 text-sm leading-6 text-base-content">{setupReason()}</p>- <Show when={setupHint()}>- <p class="mt-1 text-xs leading-5 text-muted">{setupHint()}</p>+ <Show when={!setupPanelActive()}>+ <p class="mt-2 text-sm leading-6 text-base-content">{setupReason()}</p></Show>- <ButtonLink- href={setupAction().href}- variant="primary"- size="sm"- class="mt-4 gap-1.5"+ <Show+ when={setupPanelActive() || isPatrolConnectCause(setupCause())}+ fallback={+ <>+ <Show when={setupHint()}>+ <p class="mt-1 text-xs leading-5 text-muted">{setupHint()}</p>+ </Show>+ <ButtonLink+ href={setupAction().href}+ variant="primary"+ size="sm"+ class="mt-4 gap-1.5"+ >+ <SettingsIcon class="h-4 w-4" aria-hidden="true" />+ {setupAction().label}+ </ButtonLink>+ </>+ }>- <SettingsIcon class="h-4 w-4" aria-hidden="true" />- {setupAction().label}- </ButtonLink>+ <div class="mt-4">+ <PatrolSetupPanel+ initialProvider={getPatrolSetupInitialProvider(+ state.patrolReadiness()?.provider,+ )}+ onStart={() => setSetupPanelActive(true)}+ onDone={() => {+ setSetupPanelActive(false);+ void state.handleRefreshPatrol();+ }}+ onRunPatrol={() => {+ setSetupPanelActive(false);+ // Readiness must be re-read before the run gate opens.+ void state.handleRefreshPatrol().then(() => state.handleRunPatrol());+ }}+ />+ </div>+ </Show></div><div class="rounded-md border border-amber-200 p-3 dark:border-amber-900/25"><div class="flex items-center gap-2">diff --git a/frontend-modern/src/features/patrol/PatrolSetupPanel.tsx b/frontend-modern/src/features/patrol/PatrolSetupPanel.tsxnew file mode 100644index 0000000000..31ed544d93--- /dev/null+++ b/frontend-modern/src/features/patrol/PatrolSetupPanel.tsx@@ -0,0 +1,300 @@+import { createResource, createSignal, onCleanup, Show } from 'solid-js';+import CheckCircleIcon from 'lucide-solid/icons/check-circle-2';+import CircleAlertIcon from 'lucide-solid/icons/circle-alert';+import { AIAPI } from '@/api/ai';+import { getPatrolCostPreview, getPatrolModelGuidance } from '@/api/aiPatrolCost';+import { runPatrolModelReadiness } from '@/api/patrol';+import { settingsTabPath } from '@/components/Settings/settingsNavigationModel';+import { getAIProviderConfig } from '@/components/Settings/aiSettingsModel';+import { Button } from '@/components/shared/Button';+import { ExternalTextLink } from '@/components/shared/ExternalTextLink';+import { formControl, formHelpText, formLabel } from '@/components/shared/Form';+import { InlineNotice } from '@/components/shared/InlineNotice';+import { SelectionCardGroup } from '@/components/shared/SelectionCardGroup';+import { aiChatStore } from '@/stores/aiChat';+import { syncAIRuntimeSettings } from '@/stores/aiRuntimeState';+import { splitModelRoute } from '@/utils/aiPatrolCostPresentation';+import { logger } from '@/utils/logger';+import {+ buildPatrolSetupConnectRequest,+ buildPatrolSetupModelRequest,+ getPatrolSetupCheckVerdict,+ getPatrolSetupCostLine,+ getPatrolSetupIntervalAdjust,+ getPatrolSetupNoModelMessage,+ getPatrolSetupOllamaHint,+ getPatrolSetupProviderFailure,+ getPatrolSetupSuggestedRoute,+ PATROL_SETUP_DEFAULT_OLLAMA_URL,+ PATROL_SETUP_PROVIDER_OPTIONS,+ pickPatrolSetupModel,+ type PatrolSetupCheckVerdict,+ type PatrolSetupPhase,+ type PatrolSetupProvider,+} from './patrolSetupModel';++const errorText = (error: unknown, fallback: string) =>+ error instanceof Error && error.message.trim() ? error.message.trim() : fallback;++export function PatrolSetupPanel(props: {+ /** Provider to start on, such as the one whose key was refused. */+ initialProvider?: PatrolSetupProvider;+ /** Keep the panel mounted while setup runs, whatever polling reports. */+ onStart: () => void;+ /** Re-read Patrol state once setup is finished. */+ onDone: () => void;+ /** Re-read Patrol state, then start the first run. */+ onRunPatrol: () => void;+}) {+ const [provider, setProvider] = createSignal<PatrolSetupProvider>(+ props.initialProvider ?? 'anthropic',+ );+ const [apiKey, setApiKey] = createSignal('');+ const [ollamaUrl, setOllamaUrl] = createSignal(PATROL_SETUP_DEFAULT_OLLAMA_URL);+ const [phase, setPhase] = createSignal<PatrolSetupPhase>('idle');+ const [error, setError] = createSignal('');+ const [modelId, setModelId] = createSignal('');+ const [verdict, setVerdict] = createSignal<PatrolSetupCheckVerdict | null>(null);+ let checkAbort: AbortController | undefined;+ onCleanup(() => checkAbort?.abort());++ const [guidance] = createResource(() => getPatrolModelGuidance().catch(() => null));+ const suggestedRoute = () => getPatrolSetupSuggestedRoute(provider(), guidance());+ const [costPreview] = createResource(suggestedRoute, (model) =>+ model ? getPatrolCostPreview({ model }).catch(() => null) : null,+ );+ const costLine = () => getPatrolSetupCostLine(costPreview(), costPreview()?.interval_minutes);+ const providerConfig = () => getAIProviderConfig(provider());+ const busy = () => phase() === 'connecting' || phase() === 'checking';+ const connectRequest = () =>+ buildPatrolSetupConnectRequest(provider(), { apiKey: apiKey(), ollamaUrl: ollamaUrl() });++ const selectProvider = (next: PatrolSetupProvider) => {+ setProvider(next);+ setApiKey('');+ setError('');+ setModelId('');+ setVerdict(null);+ if (phase() === 'failed') setPhase('idle');+ };++ const runCheck = async (model: string) => {+ checkAbort?.abort();+ const controller = new AbortController();+ checkAbort = controller;+ setPhase('checking');+ setError('');+ try {+ const result = await runPatrolModelReadiness({ model }, controller.signal);+ if (controller.signal.aborted) return;+ const next = getPatrolSetupCheckVerdict(result);+ setVerdict(next);+ setPhase(next.ready ? 'ready' : 'failed');+ } catch (err) {+ if (controller.signal.aborted) return;+ setVerdict(getPatrolSetupCheckVerdict(null));+ setError(errorText(err, ''));+ setPhase('failed');+ }+ };++ const connect = async (event: Event) => {+ event.preventDefault();+ const request = connectRequest();+ if (!request || busy()) return;+ props.onStart();+ setPhase('connecting');+ setError('');+ setVerdict(null);+ try {+ const connected = await AIAPI.updateSettings(request);+ syncAIRuntimeSettings(connected);+ void aiChatStore.refreshEnabledFromServer();+ // The key is saved now; keep it out of the page.+ setApiKey('');++ // The model list hides a rejected key behind an empty list, so ask the+ // provider directly first, the same test Provider & Models runs.+ const refused = getPatrolSetupProviderFailure(+ providerConfig().title,+ await AIAPI.testProvider(provider()),+ );+ if (refused) {+ setError(refused);+ setPhase('failed');+ return;+ }++ const listed = await AIAPI.getModels();+ const picked = pickPatrolSetupModel(provider(), listed.models ?? [], guidance());+ if (!picked) {+ setError(+ listed.error?.trim()+ ? `${providerConfig().title} did not return its models: ${listed.error.trim()}`+ : getPatrolSetupNoModelMessage(provider(), suggestedRoute()),+ );+ setPhase('failed');+ return;+ }++ const savedInterval = connected.patrol_interval_minutes ?? 360;+ const projection = await getPatrolCostPreview({ model: picked }).catch(() => null);+ const updated = await AIAPI.updateSettings(+ buildPatrolSetupModelRequest(picked, {+ sharedModel: connected.model ?? '',+ intervalAdjust: getPatrolSetupIntervalAdjust(projection, savedInterval),+ }),+ );+ syncAIRuntimeSettings(updated);+ setModelId(picked);+ await runCheck(picked);+ } catch (err) {+ logger.debug('[PatrolSetup] Setup failed', err);+ setError(errorText(err, 'Pulse could not save the provider settings.'));+ setPhase('failed');+ }+ };++ const modelLabel = () => splitModelRoute(modelId()).model;++ return (+ <div class="space-y-4" data-testid="patrol-setup-panel">+ <Show+ when={phase() !== 'ready'}+ fallback={+ <div class="space-y-3" role="status" data-testid="patrol-setup-ready">+ <InlineNotice tone="success" icon={<CheckCircleIcon />}>+ <p class="font-medium">{verdict()?.headline}</p>+ <p class="text-xs">+ {modelLabel()}: {verdict()?.detail}+ </p>+ </InlineNotice>+ <div class="flex flex-wrap gap-2">+ <Button type="button" variant="primary" size="sm" onClick={() => props.onRunPatrol()}>+ Run Patrol now+ </Button>+ <Button type="button" variant="secondary" size="sm" onClick={() => props.onDone()}>+ Done+ </Button>+ </div>+ </div>+ }+ >+ <form class="space-y-4" onSubmit={(event) => void connect(event)}>+ <p class="text-sm leading-6 text-base-content">+ Connect a model and Patrol starts checking your infrastructure. Pulse picks the model,+ shows what it costs, and tests it before Patrol runs.+ </p>+ <SelectionCardGroup+ options={PATROL_SETUP_PROVIDER_OPTIONS}+ value={provider()}+ onChange={selectProvider}+ variant="compact"+ disabled={busy()}+ />+ <Show+ when={provider() === 'ollama'}+ fallback={+ <div>+ <label for="patrol-setup-api-key" class={formLabel}>+ {providerConfig().title} API key+ </label>+ <input+ id="patrol-setup-api-key"+ type="password"+ autocomplete="off"+ class={formControl}+ value={apiKey()}+ placeholder={providerConfig().placeholder}+ disabled={busy()}+ onInput={(event) => setApiKey(event.currentTarget.value)}+ />+ <p class={formHelpText}>+ <ExternalTextLink href={providerConfig().actionLinkHref}>+ Get an API key from {providerConfig().title}+ </ExternalTextLink>+ </p>+ </div>+ }+ >+ <div>+ <label for="patrol-setup-ollama-url" class={formLabel}>+ Ollama server URL+ </label>+ <input+ id="patrol-setup-ollama-url"+ type="url"+ class={formControl}+ value={ollamaUrl()}+ disabled={busy()}+ onInput={(event) => setOllamaUrl(event.currentTarget.value)}+ />+ <p class={formHelpText}>{getPatrolSetupOllamaHint(suggestedRoute())}</p>+ </div>+ </Show>+ <Show when={suggestedRoute()}>+ <div class="text-xs leading-5 text-muted" data-testid="patrol-setup-cost">+ <p>+ Model:{' '}+ <span class="font-medium text-base-content">+ {splitModelRoute(suggestedRoute()).model}+ </span>+ </p>+ <Show when={costLine()}>+ <p>{costLine()}</p>+ </Show>+ </div>+ </Show>++ <Show when={phase() === 'failed'}>+ <InlineNotice tone="danger" icon={<CircleAlertIcon />} data-testid="patrol-setup-error">+ <Show when={verdict()}>+ <p class="font-medium">{verdict()?.headline}</p>+ <p class="text-xs">{verdict()?.detail}</p>+ </Show>+ <Show when={error()}>+ <p class="text-xs">{error()}</p>+ </Show>+ </InlineNotice>+ </Show>+ <Show when={phase() === 'checking'}>+ <p class="text-xs text-muted" role="status">+ Testing {modelLabel()} with a Patrol check on sample data. This can take up to two+ minutes.+ </p>+ </Show>++ <div class="flex flex-wrap items-center gap-x-4 gap-y-2">+ <Button+ type="submit"+ variant="primary"+ size="sm"+ isLoading={phase() === 'connecting'}+ disabled={busy() || !connectRequest()}+ >+ {phase() === 'connecting' ? 'Connecting' : 'Connect and check'}+ </Button>+ <Show when={modelId() && phase() !== 'connecting'}>+ <Button+ type="button"+ variant="secondary"+ size="sm"+ isLoading={phase() === 'checking'}+ disabled={busy()}+ onClick={() => void runCheck(modelId())}+ >+ Check {modelLabel()} again+ </Button>+ </Show>+ <a+ href={settingsTabPath('system-ai')}+ class="text-xs font-medium text-blue-700 hover:underline dark:text-blue-300"+ >+ Other providers, subscriptions and model choice+ </a>+ </div>+ </form>+ </Show>+ </div>+ );+}diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.tsindex 30d77ddaa1..430eba5e6e 100644--- a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts+++ b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts@@ -27,6 +27,22 @@ describe('PatrolIntelligenceWorkspace trust strip', () => {expect(workspaceSource).not.toContain('trust.dismissed_as_noise');});+ it('connects a provider in place for config-level causes and keeps setup through polling', () => {+ expect(workspaceSource).toContain(+ 'when={setupPanelActive() || isPatrolConnectCause(setupCause())}',+ );+ expect(workspaceSource).toContain('<PatrolSetupPanel');+ expect(workspaceSource).toContain('getPatrolSetupInitialProvider(');+ expect(workspaceSource).toContain('(state.shouldShowPatrolSetupOnly() || setupPanelActive())');+ // The first run waits for readiness to be re-read, or the run gate stays shut.+ expect(workspaceSource).toContain(+ 'void state.handleRefreshPatrol().then(() => state.handleRunPatrol());',+ );+ expect(workspaceSource).toContain(+ "setupPanelActive() ? 'Set up Patrol' : 'Patrol cannot run yet'",+ );+ });+it('does not invent trust signals not on FindingsTrustSummary', () => {// No mention of arbitrary keys like "patrol_score" or "health_grade".expect(workspaceSource).not.toMatch(/trust\.patrol_score/);diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolSetupPanel.render.test.tsx b/frontend-modern/src/features/patrol/__tests__/PatrolSetupPanel.render.test.tsxnew file mode 100644index 0000000000..62b5ad1d19--- /dev/null+++ b/frontend-modern/src/features/patrol/__tests__/PatrolSetupPanel.render.test.tsx@@ -0,0 +1,239 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { AISettings, PatrolCostProjection, PatrolModelReadinessSnapshot } from '@/types/ai';+import { PatrolSetupPanel } from '../PatrolSetupPanel';++const mocks = vi.hoisted(() => ({+ updateSettings: vi.fn(),+ getModels: vi.fn(),+ testProvider: vi.fn(),+ getPatrolCostPreview: vi.fn(),+ getPatrolModelGuidance: vi.fn(),+ runPatrolModelReadiness: vi.fn(),+ syncAIRuntimeSettings: vi.fn(),+ refreshEnabledFromServer: vi.fn(),+}));++vi.mock('@/api/ai', () => ({+ AIAPI: {+ updateSettings: mocks.updateSettings,+ getModels: mocks.getModels,+ testProvider: mocks.testProvider,+ },+}));+vi.mock('@/api/aiPatrolCost', () => ({+ getPatrolCostPreview: mocks.getPatrolCostPreview,+ getPatrolModelGuidance: mocks.getPatrolModelGuidance,+}));+vi.mock('@/api/patrol', () => ({ runPatrolModelReadiness: mocks.runPatrolModelReadiness }));+vi.mock('@/stores/aiRuntimeState', () => ({ syncAIRuntimeSettings: mocks.syncAIRuntimeSettings }));+vi.mock('@/stores/aiChat', () => ({+ aiChatStore: { refreshEnabledFromServer: mocks.refreshEnabledFromServer },+}));++const haikuProjection = {+ provider: 'anthropic',+ model: 'claude-haiku-4-5',+ model_route: 'anthropic:claude-haiku-4-5',+ billed_per_token: true,+ pricing_known: true,+ interval_minutes: 360,+ projected_30d_usd: 15.24,+ recommended_interval_minutes: 720,+ interval_estimates: [+ { interval_minutes: 360, projected_30d_usd: 15.24 },+ { interval_minutes: 720, projected_30d_usd: 7.62 },+ ],+} as PatrolCostProjection;++const settings = (overrides: Partial<AISettings> = {}) =>+ ({ enabled: true, model: '', patrol_interval_minutes: 360, ...overrides }) as AISettings;++const renderPanel = () => {+ const props = { onStart: vi.fn(), onDone: vi.fn(), onRunPatrol: vi.fn() };+ render(() => <PatrolSetupPanel {...props} />);+ return props;+};++describe('PatrolSetupPanel', () => {+ beforeEach(() => {+ mocks.getPatrolModelGuidance.mockResolvedValue({+ rules: [+ { provider: 'anthropic', model_prefix: 'claude-haiku-4-5', level: 'suggested', reason: '' },+ {+ provider: 'ollama',+ model_prefix: 'qwen3:8b',+ model_exact: true,+ level: 'recommended',+ reason: '',+ },+ ],+ });+ mocks.getPatrolCostPreview.mockResolvedValue(haikuProjection);+ mocks.testProvider.mockResolvedValue({ success: true, message: 'ok', provider: 'anthropic' });+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it('names the model and its monthly cost before anything is saved', async () => {+ renderPanel();+ expect(await screen.findByText('claude-haiku-4-5')).toBeInTheDocument();+ expect(+ await screen.findByText(+ /About \$7\.62 a month on your provider bill, checking every 12 hours/,+ ),+ ).toBeInTheDocument();+ expect(mocks.getPatrolCostPreview).toHaveBeenCalledWith({+ model: 'anthropic:claude-haiku-4-5',+ });+ expect(screen.getByRole('button', { name: 'Connect and check' })).toBeDisabled();+ expect(mocks.updateSettings).not.toHaveBeenCalled();+ });++ it('connects, picks and saves the guided model, checks it, and offers the first run', async () => {+ mocks.updateSettings+ .mockResolvedValueOnce(settings())+ .mockResolvedValueOnce(settings({ patrol_model: 'anthropic:claude-haiku-4-5' }));+ mocks.getModels.mockResolvedValue({+ models: [+ { id: 'anthropic:claude-haiku-4-5-20251001', name: 'Haiku', provider: 'anthropic' },+ { id: 'anthropic:claude-haiku-4-5', name: 'Haiku', provider: 'anthropic' },+ { id: 'anthropic:claude-opus-4-1', name: 'Opus', provider: 'anthropic' },+ ],+ });+ mocks.runPatrolModelReadiness.mockResolvedValue({+ status: 'pass',+ max_verified_mode: 'approval',+ summary: '',+ } as PatrolModelReadinessSnapshot);+ const props = renderPanel();+ await screen.findByText('claude-haiku-4-5');++ const key = screen.getByLabelText('Anthropic API key') as HTMLInputElement;+ fireEvent.input(key, { target: { value: ' sk-ant-test ' } });+ fireEvent.click(screen.getByRole('button', { name: 'Connect and check' }));++ expect(await screen.findByTestId('patrol-setup-ready')).toHaveTextContent('Patrol is ready');+ expect(props.onStart).toHaveBeenCalledTimes(1);+ expect(mocks.updateSettings).toHaveBeenNthCalledWith(1, {+ enabled: true,+ anthropic_api_key: 'sk-ant-test',+ });+ expect(mocks.updateSettings).toHaveBeenNthCalledWith(2, {+ patrol_model: 'anthropic:claude-haiku-4-5',+ model: 'anthropic:claude-haiku-4-5',+ patrol_interval_minutes: 720,+ });+ expect(mocks.runPatrolModelReadiness).toHaveBeenCalledWith(+ { model: 'anthropic:claude-haiku-4-5' },+ expect.any(AbortSignal),+ );+ expect(mocks.syncAIRuntimeSettings).toHaveBeenCalledTimes(2);++ fireEvent.click(screen.getByRole('button', { name: 'Run Patrol now' }));+ expect(props.onRunPatrol).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole('button', { name: 'Done' }));+ expect(props.onDone).toHaveBeenCalledTimes(1);+ });++ it('keeps a failed check on screen with the reason and a retry', async () => {+ mocks.updateSettings+ .mockResolvedValueOnce(settings())+ .mockResolvedValueOnce(settings({ patrol_model: 'ollama:qwen3:8b' }));+ mocks.getModels.mockResolvedValue({+ models: [{ id: 'ollama:qwen3:8b', name: 'qwen3:8b', provider: 'ollama' }],+ });+ mocks.getPatrolCostPreview.mockResolvedValue({ ...haikuProjection, billed_per_token: false });+ mocks.runPatrolModelReadiness.mockResolvedValue({+ status: 'fail',+ summary: 'The model made no tool call.',+ recommendation: 'Choose another model.',+ } as PatrolModelReadinessSnapshot);+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: /Ollama/ }));+ expect(screen.getByLabelText('Ollama server URL')).toHaveValue('http://localhost:11434');+ expect(await screen.findByText(/ollama pull qwen3:8b/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Connect and check' }));++ const error = await screen.findByTestId('patrol-setup-error');+ expect(error).toHaveTextContent('The model did not pass Patrol’s check');+ expect(error).toHaveTextContent('The model made no tool call. Choose another model.');+ expect(mocks.updateSettings).toHaveBeenNthCalledWith(2, {+ patrol_model: 'ollama:qwen3:8b',+ model: 'ollama:qwen3:8b',+ });++ fireEvent.click(screen.getByRole('button', { name: 'Check qwen3:8b again' }));+ await waitFor(() => expect(mocks.runPatrolModelReadiness).toHaveBeenCalledTimes(2));+ });++ it('says to pull the model when Ollama has nothing Pulse can pick', async () => {+ mocks.updateSettings.mockResolvedValueOnce(settings());+ // Ollama answers, but the provider test's default model is not pulled.+ mocks.testProvider.mockResolvedValue({+ success: false,+ message: 'Selected model unavailable',+ provider: 'ollama',+ cause: 'model_unavailable',+ });+ mocks.getModels.mockResolvedValue({ models: [] });+ renderPanel();++ fireEvent.click(await screen.findByRole('button', { name: /Ollama/ }));+ fireEvent.click(screen.getByRole('button', { name: 'Connect and check' }));++ expect(await screen.findByTestId('patrol-setup-error')).toHaveTextContent(+ 'Pulse reached Ollama, but qwen3:8b is not installed there.',+ );+ expect(mocks.updateSettings).toHaveBeenCalledTimes(1);+ expect(mocks.runPatrolModelReadiness).not.toHaveBeenCalled();+ });++ it('reports a rejected key from the provider test instead of guessing a model', async () => {+ mocks.updateSettings.mockResolvedValueOnce(settings());+ mocks.testProvider.mockResolvedValue({+ success: false,+ message: 'Provider authentication issue',+ provider: 'anthropic',+ cause: 'provider_auth',+ summary: 'The provider rejected the configured credentials or account access.',+ recommendation: 'Check the API key on the Provider & Models settings page.',+ });+ renderPanel();+ await screen.findByText('claude-haiku-4-5');++ fireEvent.input(screen.getByLabelText('Anthropic API key'), {+ target: { value: 'sk-ant-bad' },+ });+ fireEvent.click(screen.getByRole('button', { name: 'Connect and check' }));++ expect(await screen.findByTestId('patrol-setup-error')).toHaveTextContent(+ 'Anthropic did not accept the connection: The provider rejected the configured credentials or account access. Check the API key and connect again.',+ );+ expect(mocks.testProvider).toHaveBeenCalledWith('anthropic');+ expect(mocks.getModels).not.toHaveBeenCalled();+ expect(mocks.runPatrolModelReadiness).not.toHaveBeenCalled();+ // The saved key is not left in the page.+ expect(screen.getByLabelText('Anthropic API key')).toHaveValue('');+ });++ it('reports a model list failure after the provider answered', async () => {+ mocks.updateSettings.mockResolvedValueOnce(settings());+ mocks.getModels.mockResolvedValue({ models: [], error: 'Failed to fetch model list' });+ renderPanel();+ await screen.findByText('claude-haiku-4-5');++ fireEvent.input(screen.getByLabelText('Anthropic API key'), { target: { value: 'sk-ant-ok' } });+ fireEvent.click(screen.getByRole('button', { name: 'Connect and check' }));++ expect(await screen.findByTestId('patrol-setup-error')).toHaveTextContent(+ 'Anthropic did not return its models: Failed to fetch model list',+ );+ expect(mocks.runPatrolModelReadiness).not.toHaveBeenCalled();+ });+});diff --git a/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.tsindex dd3769db55..d97157f6a9 100644--- a/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts+++ b/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts@@ -17,6 +17,8 @@ import {PATROL_AUTONOMY_POLICY_PRESENTATION,PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION,PATROL_WORKSPACE_QUEUE_TITLE,+ PATROL_WORKSPACE_CONNECT_DESCRIPTION,+ PATROL_WORKSPACE_RECONNECT_DESCRIPTION,PATROL_WORKSPACE_SETUP_DESCRIPTION,} from '../patrolControlPresentation';@@ -31,6 +33,16 @@ describe('patrolControlPresentation', () => {}});+ it('asks for a model, not a model check, when no provider is connected or AI is off', () => {+ for (const cause of ['provider_not_configured', 'assistant_disabled']) {+ expect(getPatrolWorkspaceSetupDescription(cause)).toBe(PATROL_WORKSPACE_CONNECT_DESCRIPTION);+ }+ expect(PATROL_WORKSPACE_CONNECT_DESCRIPTION).not.toMatch(/tool check/);+ expect(getPatrolWorkspaceSetupDescription('provider_auth')).toBe(+ PATROL_WORKSPACE_RECONNECT_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__/patrolSetupModel.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolSetupModel.test.tsnew file mode 100644index 0000000000..43d1e45e36--- /dev/null+++ b/frontend-modern/src/features/patrol/__tests__/patrolSetupModel.test.ts@@ -0,0 +1,251 @@+import { describe, expect, it } from 'vitest';++import type {+ PatrolCostProjection,+ PatrolModelGuidanceResponse,+ PatrolModelReadinessSnapshot,+} from '@/types/ai';+import {+ buildPatrolSetupConnectRequest,+ buildPatrolSetupModelRequest,+ getPatrolSetupCheckVerdict,+ getPatrolSetupCostLine,+ getPatrolSetupInitialProvider,+ getPatrolSetupIntervalAdjust,+ getPatrolSetupNoModelMessage,+ getPatrolSetupOllamaHint,+ getPatrolSetupProviderFailure,+ getPatrolSetupSuggestedRoute,+ PATROL_SETUP_PROVIDER_OPTIONS,+ pickPatrolSetupModel,+} from '../patrolSetupModel';++const guidance: PatrolModelGuidanceResponse = {+ rules: [+ {+ provider: 'ollama',+ model_prefix: 'qwen3:8b',+ model_exact: true,+ level: 'recommended',+ reason: 'r',+ },+ {+ provider: 'gemini',+ model_prefix: 'gemini-',+ exclude: ['!flash-lite'],+ level: 'caution',+ reason: 'c',+ },+ {+ provider: 'gemini',+ model_prefix: 'gemini-2.5-flash',+ exclude: ['lite', 'image', 'live'],+ level: 'suggested',+ reason: 's',+ },+ { provider: 'anthropic', model_prefix: 'claude-haiku-4-5', level: 'suggested', reason: 's' },+ ],+};++const projection = (overrides: Partial<PatrolCostProjection> = {}): PatrolCostProjection =>+ ({+ provider: 'anthropic',+ model: 'claude-haiku-4-5',+ model_route: 'anthropic:claude-haiku-4-5',+ billed_per_token: true,+ pricing_known: true,+ interval_minutes: 360,+ projected_30d_usd: 15.24,+ recommended_interval_minutes: 720,+ interval_estimates: [+ { interval_minutes: 360, projected_30d_usd: 15.24 },+ { interval_minutes: 720, projected_30d_usd: 7.62 },+ ],+ ...overrides,+ }) as PatrolCostProjection;++const readiness = (+ overrides: Partial<PatrolModelReadinessSnapshot>,+): PatrolModelReadinessSnapshot =>+ ({ status: 'fail', summary: '', ...overrides }) as PatrolModelReadinessSnapshot;++describe('patrolSetupModel', () => {+ it('offers the two routes most paid installs use and leaves the rest to Provider & Models', () => {+ expect(PATROL_SETUP_PROVIDER_OPTIONS.map((option) => option.value)).toEqual([+ 'anthropic',+ 'openai',+ 'gemini',+ 'deepseek',+ 'openrouter',+ 'ollama',+ ]);+ });++ it('starts on the provider readiness names, else Anthropic', () => {+ expect(getPatrolSetupInitialProvider('gemini')).toBe('gemini');+ expect(getPatrolSetupInitialProvider(' Ollama ')).toBe('ollama');+ expect(getPatrolSetupInitialProvider('groq')).toBe('anthropic');+ expect(getPatrolSetupInitialProvider(undefined)).toBe('anthropic');+ });++ it('builds the connect write only once the required field is filled', () => {+ expect(buildPatrolSetupConnectRequest('anthropic', { apiKey: ' ', ollamaUrl: '' })).toBeNull();+ expect(+ buildPatrolSetupConnectRequest('gemini', { apiKey: ' AIza-test ', ollamaUrl: '' }),+ ).toEqual({+ enabled: true,+ gemini_api_key: 'AIza-test',+ });+ expect(buildPatrolSetupConnectRequest('openrouter', { apiKey: 'k', ollamaUrl: '' })).toEqual({+ enabled: true,+ openrouter_api_key: 'k',+ });+ expect(+ buildPatrolSetupConnectRequest('ollama', { apiKey: 'ignored', ollamaUrl: '' }),+ ).toBeNull();+ expect(+ buildPatrolSetupConnectRequest('ollama', {+ apiKey: 'ignored',+ ollamaUrl: ' http://ollama:11434 ',+ }),+ ).toEqual({ enabled: true, ollama_base_url: 'http://ollama:11434' });+ });++ it('prices the guided route before anything is saved, recommended before suggested', () => {+ expect(getPatrolSetupSuggestedRoute('ollama', guidance)).toBe('ollama:qwen3:8b');+ expect(getPatrolSetupSuggestedRoute('gemini', guidance)).toBe('gemini:gemini-2.5-flash');+ expect(getPatrolSetupSuggestedRoute('anthropic', guidance)).toBe('anthropic:claude-haiku-4-5');+ expect(getPatrolSetupSuggestedRoute('openai', guidance)).toBe('');+ expect(getPatrolSetupSuggestedRoute('anthropic', null)).toBe('');+ });++ it('picks the guided model from the connected provider, alias before dated build', () => {+ const models = [+ { id: 'anthropic:claude-opus-4-1', provider: 'anthropic' },+ { id: 'anthropic:claude-haiku-4-5-20251001', provider: 'anthropic' },+ { id: 'anthropic:claude-haiku-4-5', provider: 'anthropic' },+ { id: 'ollama:qwen3:8b', provider: 'ollama' },+ ];+ expect(pickPatrolSetupModel('anthropic', models, guidance)).toBe('anthropic:claude-haiku-4-5');+ // Another provider's guided model is never picked for this one.+ expect(pickPatrolSetupModel('openai', models, guidance)).toBeNull();+ });++ it('never picks a caution model and returns null when nothing is guided', () => {+ const gemini = [+ { id: 'gemini:gemini-2.5-flash-lite', provider: 'gemini' },+ { id: 'gemini:gemini-2.5-flash', provider: 'gemini' },+ ];+ expect(pickPatrolSetupModel('gemini', gemini, guidance)).toBe('gemini:gemini-2.5-flash');+ expect(pickPatrolSetupModel('gemini', [gemini[0]], guidance)).toBeNull();+ expect(pickPatrolSetupModel('ollama', [], guidance)).toBeNull();+ });++ it('reads the provider from the id when the server omits it', () => {+ expect(pickPatrolSetupModel('ollama', [{ id: 'ollama:qwen3:8b' }], guidance)).toBe(+ 'ollama:qwen3:8b',+ );+ });++ it('slows only the untouched 6-hour default for a per-token model', () => {+ expect(getPatrolSetupIntervalAdjust(projection(), 360)?.to).toBe(720);+ expect(getPatrolSetupIntervalAdjust(projection(), 60)).toBeNull();+ expect(getPatrolSetupIntervalAdjust(projection({ billed_per_token: false }), 360)).toBeNull();+ });++ it('gives the Assistant the same model only when it has none', () => {+ expect(+ buildPatrolSetupModelRequest('ollama:qwen3:8b', { sharedModel: '', intervalAdjust: null }),+ ).toEqual({ patrol_model: 'ollama:qwen3:8b', model: 'ollama:qwen3:8b' });+ expect(+ buildPatrolSetupModelRequest('anthropic:claude-haiku-4-5', {+ sharedModel: 'openai:gpt-5',+ intervalAdjust: getPatrolSetupIntervalAdjust(projection(), 360),+ }),+ ).toEqual({ patrol_model: 'anthropic:claude-haiku-4-5', patrol_interval_minutes: 720 });+ });++ it('states the monthly cost at the schedule the setup will save', () => {+ expect(getPatrolSetupCostLine(null)).toBe('');+ expect(getPatrolSetupCostLine(projection(), 360)).toBe(+ 'About $7.62 a month on your provider bill, checking every 12 hours. Investigating new findings adds to this. Pulse slows the schedule from every 6 hours to keep the bill down.',+ );+ expect(getPatrolSetupCostLine(projection({ recommended_interval_minutes: 360 }), 360)).toBe(+ 'About $15.24 a month on your provider bill, checking every 6 hours. Investigating new findings adds to this.',+ );+ expect(getPatrolSetupCostLine(projection({ billed_per_token: false }))).toBe(+ 'No per-token bill: Patrol runs on your own hardware.',+ );+ expect(getPatrolSetupCostLine(projection({ pricing_known: false }))).toMatch(+ /no price on file/,+ );+ });++ it('calls a check ready only when it verified a Patrol mode', () => {+ expect(getPatrolSetupCheckVerdict(readiness({ max_verified_mode: 'approval' }))).toMatchObject({+ ready: true,+ headline: 'Patrol is ready',+ });+ const watchOnly = getPatrolSetupCheckVerdict(readiness({ max_verified_mode: 'monitor' }));+ expect(watchOnly.ready).toBe(true);+ expect(watchOnly.detail).toMatch(/Investigations need a model that also passes for Ask first/);+ const failed = getPatrolSetupCheckVerdict(+ readiness({ summary: 'No tool call.', recommendation: 'Pick another model.' }),+ );+ expect(failed).toEqual({+ ready: false,+ headline: 'The model did not pass Patrol’s check',+ detail: 'No tool call. Pick another model.',+ });+ expect(getPatrolSetupCheckVerdict(null).ready).toBe(false);+ });++ it('turns a refused provider test into a fix-it-here sentence', () => {+ expect(+ getPatrolSetupProviderFailure('Anthropic', {+ success: true,+ message: '',+ provider: 'anthropic',+ }),+ ).toBe('');+ expect(getPatrolSetupProviderFailure('Anthropic', null)).toBe('');+ // The provider answered; only its default model is missing, which setup replaces.+ expect(+ getPatrolSetupProviderFailure('Ollama', {+ success: false,+ message: 'Selected model unavailable',+ provider: 'ollama',+ cause: 'model_unavailable',+ }),+ ).toBe('');+ expect(+ getPatrolSetupProviderFailure('Anthropic', {+ success: false,+ message: 'Provider authentication issue',+ provider: 'anthropic',+ cause: 'provider_auth',+ summary: 'The provider rejected the configured credentials.',+ recommendation: 'Go to Provider & Models.',+ }),+ ).toBe(+ 'Anthropic did not accept the connection: The provider rejected the configured credentials. Check the API key and connect again.',+ );+ expect(+ getPatrolSetupProviderFailure('Ollama', {+ success: false,+ message: 'Connection refused',+ provider: 'ollama',+ cause: 'provider_connection',+ recommendation: 'Check the server URL.',+ }),+ ).toBe('Ollama did not accept the connection: Connection refused. Check the server URL.');+ });++ it('tells an Ollama user to pull the model, before and after connecting', () => {+ expect(getPatrolSetupOllamaHint('ollama:qwen3:8b')).toContain('ollama pull qwen3:8b');+ expect(getPatrolSetupNoModelMessage('ollama', 'ollama:qwen3:8b')).toContain(+ 'Run "ollama pull qwen3:8b" on the Ollama server',+ );+ expect(getPatrolSetupNoModelMessage('anthropic', '')).toMatch(/Provider & Models/);+ });+});diff --git a/frontend-modern/src/features/patrol/patrolControlPresentation.ts b/frontend-modern/src/features/patrol/patrolControlPresentation.tsindex fdb43d180a..3079f09eb9 100644--- a/frontend-modern/src/features/patrol/patrolControlPresentation.ts+++ b/frontend-modern/src/features/patrol/patrolControlPresentation.ts@@ -12,6 +12,7 @@ import {} from '@/utils/aiFindingPresentation';import type { PatrolWorkTypeComposition } from '@/utils/aiFindingPresentation';import { getPatrolRunCoverageSummary } from '@/utils/patrolRunPresentation';+import { isPatrolConfigLevelCause, PATROL_PROVIDER_AUTH_CAUSE } from '@/utils/patrolRuntimeActions';import type { UpgradeDestination } from '@/utils/upgradeNavigation';export const PATROL_AUTONOMY_POLICY_PRESENTATION: Record<@@ -57,10 +58,21 @@ export const PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION =* 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 const PATROL_WORKSPACE_CONNECT_DESCRIPTION =+ 'Patrol needs an AI model before it can check your infrastructure.';++export const PATROL_WORKSPACE_RECONNECT_DESCRIPTION =+ 'Your AI provider refused Patrol’s connection. Reconnect it so Patrol can run.';++export const PATROL_WORKSPACE_SETUP_ACTIVE_DESCRIPTION =+ 'Connect a model and check it here. Patrol starts once the check passes.';+export function getPatrolWorkspaceSetupDescription(cause?: string | null): string {- return cause === 'budget_exhausted'- ? PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION- : PATROL_WORKSPACE_SETUP_DESCRIPTION;+ if (cause === 'budget_exhausted') return PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION;+ // No provider or AI off: the model check is not the next step yet.+ if (isPatrolConfigLevelCause(cause ?? undefined)) return PATROL_WORKSPACE_CONNECT_DESCRIPTION;+ if (cause === PATROL_PROVIDER_AUTH_CAUSE) return PATROL_WORKSPACE_RECONNECT_DESCRIPTION;+ return PATROL_WORKSPACE_SETUP_DESCRIPTION;}export const PATROL_WORKSPACE_QUEUE_TITLE = 'Open work';diff --git a/frontend-modern/src/features/patrol/patrolSetupModel.ts b/frontend-modern/src/features/patrol/patrolSetupModel.tsnew file mode 100644index 0000000000..b8c096b063--- /dev/null+++ b/frontend-modern/src/features/patrol/patrolSetupModel.ts@@ -0,0 +1,268 @@+import type { SelectionCardOption } from '@/components/shared/SelectionCardGroup';+import type {+ AIProviderTestResult,+ AISettingsUpdateRequest,+ ModelInfo,+ PatrolCostProjection,+ PatrolModelGuidanceResponse,+ PatrolModelReadinessSnapshot,+} from '@/types/ai';+import {+ formatPatrolCostUSD,+ formatPatrolIntervalPhrase,+ getPatrolGuidedModelIds,+ getPatrolIntervalAutoAdjust,+ PATROL_COST_DEFAULT_INTERVAL_MINUTES,+ resolvePatrolModelGuidance,+ splitModelRoute,+ type PatrolIntervalAutoAdjust,+} from '@/utils/aiPatrolCostPresentation';++/**+ * One-page Patrol setup, shown on the Patrol page when no provider is+ * configured or Pulse Intelligence is off. It covers the two routes most+ * paid installs use (a cloud API key, or Ollama on their own hardware),+ * picks the Patrol model from Pulse's guidance table instead of a raw list,+ * prices it before anything is saved, and runs the Patrol model check in the+ * same step. Everything else (subscription CLIs, custom endpoints, other+ * providers, model overrides) stays on Provider & Models.+ */++export type PatrolSetupProvider =+ 'anthropic' | 'openai' | 'gemini' | 'deepseek' | 'openrouter' | 'ollama';++export const PATROL_SETUP_PROVIDER_OPTIONS: SelectionCardOption<PatrolSetupProvider>[] = [+ { value: 'anthropic', title: 'Anthropic', description: 'Claude' },+ { value: 'openai', title: 'OpenAI', description: 'GPT' },+ { value: 'gemini', title: 'Gemini', description: 'Google' },+ { value: 'deepseek', title: 'DeepSeek', description: 'Low cost' },+ { value: 'openrouter', title: 'OpenRouter', description: 'Many models' },+ { value: 'ollama', title: 'Ollama', description: 'Your hardware' },+];++const PATROL_SETUP_API_KEY_FIELDS: Record<+ Exclude<PatrolSetupProvider, 'ollama'>,+ keyof AISettingsUpdateRequest+> = {+ anthropic: 'anthropic_api_key',+ openai: 'openai_api_key',+ gemini: 'gemini_api_key',+ deepseek: 'deepseek_api_key',+ openrouter: 'openrouter_api_key',+};++export const PATROL_SETUP_DEFAULT_OLLAMA_URL = 'http://localhost:11434';++/** Start on the provider readiness names (the one that refused), else Anthropic. */+export function getPatrolSetupInitialProvider(+ readinessProvider?: string | null,+): PatrolSetupProvider {+ const named = readinessProvider?.trim().toLowerCase();+ const match = PATROL_SETUP_PROVIDER_OPTIONS.find((option) => option.value === named);+ return match ? match.value : 'anthropic';+}++export type PatrolSetupPhase = 'idle' | 'connecting' | 'checking' | 'ready' | 'failed';++export interface PatrolSetupInput {+ apiKey: string;+ ollamaUrl: string;+}++/**+ * The settings write that connects the provider and turns Pulse+ * Intelligence on, or null while the required field is empty.+ */+export function buildPatrolSetupConnectRequest(+ provider: PatrolSetupProvider,+ input: PatrolSetupInput,+): AISettingsUpdateRequest | null {+ if (provider === 'ollama') {+ const url = input.ollamaUrl.trim();+ return url ? { enabled: true, ollama_base_url: url } : null;+ }+ const key = input.apiKey.trim();+ if (!key) return null;+ return { enabled: true, [PATROL_SETUP_API_KEY_FIELDS[provider]]: key };+}++/**+ * The provider:model route Pulse's guidance table names for a provider+ * (recommended before suggested), used to price Patrol before anything is+ * saved. The exact model id comes from the provider's own list after connect.+ */+export function getPatrolSetupSuggestedRoute(+ provider: PatrolSetupProvider,+ guidance: PatrolModelGuidanceResponse | null | undefined,+): string {+ const rules = (guidance?.rules ?? []).filter(+ (rule) =>+ rule.provider.toLowerCase() === provider &&+ (rule.level === 'recommended' || rule.level === 'suggested'),+ );+ const best = rules.find((rule) => rule.level === 'recommended') ?? rules[0];+ return best ? `${provider}:${best.model_prefix}` : '';+}++/**+ * Pick the Patrol model from the connected provider's list: the best guided+ * level wins, and among equals the shortest id, which is the undated alias+ * when the provider lists both (claude-haiku-4-5 before its dated build).+ */+export function pickPatrolSetupModel(+ provider: PatrolSetupProvider,+ models: Pick<ModelInfo, 'id' | 'provider'>[],+ guidance: PatrolModelGuidanceResponse | null | undefined,+): string | null {+ const own = models.filter(+ (model) => (model.provider?.trim() || splitModelRoute(model.id).provider) === provider,+ );+ const annotations = resolvePatrolModelGuidance(own, guidance);+ const ranked = getPatrolGuidedModelIds(annotations);+ if (ranked.length === 0) return null;+ const topLevel = annotations.get(ranked[0])?.level;+ const top = ranked.filter((id) => annotations.get(id)?.level === topLevel);+ return [...top].sort((a, b) => a.length - b.length || a.localeCompare(b))[0] ?? null;+}++/**+ * The schedule the setup saves with the model: a per-token model on the+ * untouched 6-hour default gets the cost model's slower schedule, exactly as+ * picking it on Patrol settings would. A schedule the operator chose stays.+ */+export function getPatrolSetupIntervalAdjust(+ projection: PatrolCostProjection | null | undefined,+ savedIntervalMinutes: number,+): PatrolIntervalAutoAdjust | null {+ return getPatrolIntervalAutoAdjust(projection, {+ currentIntervalMinutes: savedIntervalMinutes,+ savedIntervalMinutes,+ });+}++/** The settings write that selects the Patrol model (and schedule, when adjusted). */+export function buildPatrolSetupModelRequest(+ modelId: string,+ options: { sharedModel: string; intervalAdjust: PatrolIntervalAutoAdjust | null },+): AISettingsUpdateRequest {+ const request: AISettingsUpdateRequest = { patrol_model: modelId };+ // A fresh install has no shared model either; give the Assistant the same+ // one so the provider the operator just connected also answers chat.+ if (!options.sharedModel.trim()) request.model = modelId;+ if (options.intervalAdjust) request.patrol_interval_minutes = options.intervalAdjust.to;+ return request;+}++function intervalEstimateUSD(projection: PatrolCostProjection, minutes: number): number | null {+ const match = projection.interval_estimates?.find((entry) => entry.interval_minutes === minutes);+ return match ? match.projected_30d_usd : null;+}++/**+ * One sentence for what Patrol will cost on this route, at the schedule the+ * setup will save. Empty until the preview loads.+ */+export function getPatrolSetupCostLine(+ projection: PatrolCostProjection | null | undefined,+ savedIntervalMinutes: number = PATROL_COST_DEFAULT_INTERVAL_MINUTES,+): string {+ if (!projection) return '';+ if (!projection.pricing_known) {+ return 'Pulse has no price on file for this model, so check the provider’s pricing page.';+ }+ if (!projection.billed_per_token) {+ return 'No per-token bill: Patrol runs on your own hardware.';+ }+ const adjust = getPatrolSetupIntervalAdjust(projection, savedIntervalMinutes);+ const minutes = adjust ? adjust.to : projection.interval_minutes;+ const usd = intervalEstimateUSD(projection, minutes) ?? projection.projected_30d_usd;+ const schedule = formatPatrolIntervalPhrase(minutes);+ const slowed = adjust+ ? ' Pulse slows the schedule from every 6 hours to keep the bill down.'+ : '';+ return `About ${formatPatrolCostUSD(usd)} a month on your provider bill, checking ${schedule}. Investigating new findings adds to this.${slowed}`;+}++export interface PatrolSetupCheckVerdict {+ ready: boolean;+ headline: string;+ detail: string;+}++/** Plain-language verdict for the Patrol model check the setup runs. */+export function getPatrolSetupCheckVerdict(+ result: PatrolModelReadinessSnapshot | null | undefined,+): PatrolSetupCheckVerdict {+ if (!result) {+ return {+ ready: false,+ headline: 'The Patrol model check did not finish',+ detail: 'Check again. If it keeps stopping, open Provider & Models to test the provider.',+ };+ }+ if (result.max_verified_mode === 'approval') {+ return {+ ready: true,+ headline: 'Patrol is ready',+ detail: 'The model passed Patrol’s check for Watch only and Ask first.',+ };+ }+ if (result.max_verified_mode === 'monitor') {+ return {+ ready: true,+ headline: 'Patrol is ready to watch',+ detail:+ 'The model passed Patrol’s check for Watch only. Investigations need a model that also passes for Ask first.',+ };+ }+ const detail = [result.summary, result.recommendation]+ .map((part) => part?.trim())+ .filter(Boolean)+ .join(' ');+ return {+ ready: false,+ headline: 'The model did not pass Patrol’s check',+ detail: detail || 'Choose another model on Provider & Models and check again.',+ };+}++/**+ * Why the provider refused the connection, from the same provider test+ * Provider & Models runs, or '' when it answered. A rejected key is fixed+ * right here, so say that instead of pointing at the settings page.+ */+export function getPatrolSetupProviderFailure(+ providerTitle: string,+ result: AIProviderTestResult | null | undefined,+): string {+ if (!result || result.success) return '';+ // The test probes the provider's default model. A model-level cause+ // (model_unavailable and friends) means the provider answered; setup is+ // about to pick its own model, and the model list says what is missing.+ const cause = result.cause?.trim();+ if (cause && !cause.startsWith('provider_')) return '';+ const raw = (result.summary || result.message || '').trim();+ const summary = raw && !/[.!?]$/.test(raw) ? `${raw}.` : raw;+ const lead = `${providerTitle} did not accept the connection${summary ? `: ${summary}` : '.'}`;+ if (result.cause === 'provider_auth') return `${lead} Check the API key and connect again.`;+ const next = result.recommendation?.trim();+ return next ? `${lead} ${next}` : lead;+}++/** Before connecting Ollama: the model has to be on the server already. */+export function getPatrolSetupOllamaHint(suggestedRoute: string): string {+ const model = splitModelRoute(suggestedRoute).model || 'qwen3:8b';+ return `Install ${model} on the Ollama server first: ollama pull ${model}. It is about a 5 GB download and needs 8 GB of free memory.`;+}++/** What to say when the connected provider lists no model Pulse can pick. */+export function getPatrolSetupNoModelMessage(+ provider: PatrolSetupProvider,+ suggestedRoute: string,+): string {+ if (provider === 'ollama') {+ const model = splitModelRoute(suggestedRoute).model || 'qwen3:8b';+ return `Pulse reached Ollama, but ${model} is not installed there. Run "ollama pull ${model}" on the Ollama server, then try again. It is about a 5 GB download and needs 8 GB of free memory.`;+ }+ return 'Pulse connected, but none of this provider’s models has a Patrol suggestion. Choose a model on Provider & Models.';+}diff --git a/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts b/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.tsindex 1136cf72f2..8f5190e41c 100644--- a/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts+++ b/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts@@ -3,11 +3,31 @@ import {getPatrolProviderSettingsAction,getPatrolSetupAction,getPatrolSetupHint,+ isPatrolConfigLevelCause,+ isPatrolConnectCause,PATROL_BUDGET_EXHAUSTED_CAUSE,PATROL_PROVIDER_SETTINGS_ACTION,} from '@/utils/patrolRuntimeActions';describe('patrolRuntimeActions', () => {+ it('names the causes the Patrol page can fix in place by connecting a provider', () => {+ expect(isPatrolConfigLevelCause('provider_not_configured')).toBe(true);+ expect(isPatrolConfigLevelCause('assistant_disabled')).toBe(true);+ expect(isPatrolConfigLevelCause('provider_auth')).toBe(false);+ expect(isPatrolConnectCause('provider_auth')).toBe(true);+ expect(isPatrolConnectCause('provider_not_configured')).toBe(true);+ expect(isPatrolConnectCause('model_unsupported_tools')).toBe(false);+ for (const cause of [+ 'model_unsupported_tools',+ PATROL_BUDGET_EXHAUSTED_CAUSE,+ 'none',+ '',+ undefined,+ ]) {+ expect(isPatrolConfigLevelCause(cause)).toBe(false);+ }+ });+it('centralizes the Patrol provider settings action', () => {expect(PATROL_PROVIDER_SETTINGS_ACTION).toEqual({label: 'Check Patrol model',@@ -20,7 +40,8 @@ describe('patrolRuntimeActions', () => {});it('routes config-level causes to Provider & Models instead of the model check', () => {- for (const cause of ['assistant_disabled', 'provider_not_configured']) {+ // A refused key is fixed where the key lives, not by re-running the model check.+ for (const cause of ['assistant_disabled', 'provider_not_configured', 'provider_auth']) {expect(getPatrolSetupAction(cause)).toEqual({label: 'Open Provider & Models',href: '/settings/pulse-intelligence/provider',diff --git a/frontend-modern/src/utils/patrolRuntimeActions.ts b/frontend-modern/src/utils/patrolRuntimeActions.tsindex 9e1d1e7057..0b539cb509 100644--- a/frontend-modern/src/utils/patrolRuntimeActions.ts+++ b/frontend-modern/src/utils/patrolRuntimeActions.ts@@ -15,6 +15,18 @@ export const PATROL_PROVIDER_SETTINGS_ACTION: PatrolRuntimeActionPresentation =// Provider & Models, where the enable toggle and API key / Ollama fields live.const PATROL_CONFIG_LEVEL_CAUSES = new Set(['assistant_disabled', 'provider_not_configured']);+/** True when Patrol is blocked because no provider is connected or AI is off. */+export const isPatrolConfigLevelCause = (cause?: string): boolean =>+ !!cause && PATROL_CONFIG_LEVEL_CAUSES.has(cause);++// The provider refused the saved key. Reconnecting fixes it, so the Patrol+// page offers its setup panel rather than the model check.+export const PATROL_PROVIDER_AUTH_CAUSE = 'provider_auth';++/** True when the Patrol page's own setup panel is the fix for the block. */+export const isPatrolConnectCause = (cause?: string): boolean =>+ isPatrolConfigLevelCause(cause) || cause === PATROL_PROVIDER_AUTH_CAUSE;+export const getPatrolProviderSettingsAction = (): PatrolRuntimeActionPresentation => ({...PATROL_PROVIDER_SETTINGS_ACTION,});@@ -28,7 +40,7 @@ export const getPatrolSetupAction = (cause?: string): PatrolRuntimeActionPresentif (cause === PATROL_BUDGET_EXHAUSTED_CAUSE) {return { label: 'Raise the cost budget', href: settingsTabPath('system-ai') };}- if (cause && PATROL_CONFIG_LEVEL_CAUSES.has(cause)) {+ if (isPatrolConnectCause(cause)) {return { label: 'Open Provider & Models', href: settingsTabPath('system-ai') };}return { ...PATROL_PROVIDER_SETTINGS_ACTION };@@ -40,7 +52,7 @@ export const getPatrolSetupHint = (cause?: string): string => {if (cause === PATROL_BUDGET_EXHAUSTED_CAUSE) {return '';}- if (cause && PATROL_CONFIG_LEVEL_CAUSES.has(cause)) {+ if (isPatrolConnectCause(cause)) {return '';}return 'Open Patrol settings and run the model check. Provider connectivity can be healthy even when the selected model cannot use Patrol tools.';diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex bd424bf064..2cbe5187a3 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -17,10 +17,12 @@ PATROL_PAGE_AND_STATE_EXACT_FILES = ["frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts","frontend-modern/src/features/patrol/__tests__/PatrolObjectivesPanel.test.tsx","frontend-modern/src/features/patrol/__tests__/PatrolRecentWorkPanel.test.tsx",+ "frontend-modern/src/features/patrol/__tests__/PatrolSetupPanel.render.test.tsx","frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts","frontend-modern/src/features/patrol/__tests__/patrolHomePresentation.test.ts","frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts","frontend-modern/src/features/patrol/__tests__/patrolRunAcceptance.test.ts",+ "frontend-modern/src/features/patrol/__tests__/patrolSetupModel.test.ts","frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts","frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx","frontend-modern/src/stores/__tests__/aiIntelligence.test.ts",