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
Centralize AI runtime frontend read model
rcourtmande1f608c0202
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex a227fce61f..d955f88e40 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -417,6 +417,12 @@ request the canonical commercial destination from the shared license boundary,but they must leave internal-versus-external navigation semantics to`frontend-primitives` instead of hardcoding pricing URLs or tab-open behaviorinside lifecycle-owned settings surfaces.+That same lifecycle-owned settings surface must also keep assistant+availability as an app-shell fact instead of an AI-runtime fetch. Agent+Profiles may read the shared browser bootstrap availability state to decide+whether assistant affordances render, but they must not mount+`frontend-modern/src/stores/aiRuntimeState.ts` or call `/api/settings/ai`+just to decide whether to show assistant-adjacent UI.That same platform-connections ownership now also includes mock-runtimecontinuity for API-backed platforms. When `/api/system/mock-mode` flips arunning server between real and mock data, the canonical TrueNAS and VMwarediff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 2a2c5ff3c1..a29afca058 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -38,6 +38,7 @@ runtime cost control, and shared AI transport surfaces.16. `frontend-modern/src/utils/aiProviderPresentation.ts`17. `frontend-modern/src/utils/aiSessionDiffPresentation.ts`18. `frontend-modern/src/utils/textPresentation.ts`+19. `frontend-modern/src/stores/aiRuntimeState.ts`## Shared Boundaries@@ -186,6 +187,13 @@ availability fact used by the app shell. `internal/api/ai_handlers.go`,closed assistant affordance, so unrelated shells do not probe`/api/settings/ai` or `/api/ai/sessions` during ordinary route bootstrap justto decide whether the assistant drawer may be opened.+That same frontend runtime boundary now also owns the shared AI read model for+AI-owned surfaces. `frontend-modern/src/stores/aiRuntimeState.ts` is the+canonical frontend owner for shared `/api/settings/ai` and `/api/ai/models`+reads used by chat, Patrol, and AI usage surfaces, while+`frontend-modern/src/components/Settings/useAISettingsState.ts` remains the+write-side settings owner. AI-owned surfaces must not fork their own mount-time+settings/model fetch loops once this store exists.That same settings/runtime boundary now also governs BYOK first-run setup:`frontend-modern/src/components/Settings/useAISettingsState.ts` may send onlyprovider credentials or base URLs when the operator connects a provider, anddiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 590d86a91e..bde0416738 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -369,6 +369,10 @@ Own canonical runtime payload shapes between backend and frontend.the write-side settings owner. Non-AI settings surfaces such as`frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`must not probe `/api/settings/ai` just to gate assistant affordances.+ AI-owned refresh actions may still force a shared reload or sync that+ store after an owned settings mutation, but they must not reintroduce+ page-local mount loops that fetch `/api/settings/ai` or `/api/ai/models`+ separately for chat, Patrol, and cost/budget views.23. Keep API-backed first-target onboarding canonical on that same sharedinfrastructure-settings boundary:`frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`,diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 78ca79dd17..1b1066a28d 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -218,6 +218,15 @@ work extends shared components instead of creating new local variants.route bootstrap. Closed assistant chrome and non-AI settings panels maynot initialize assistant runtime state until an owned assistant or Patrolsurface is actually open.+ AI-owned frontend surfaces that need shared settings or model-catalog+ truth must route those reads through+ `frontend-modern/src/stores/aiRuntimeState.ts` rather than each feature+ bootstrapping `/api/settings/ai` or `/api/ai/models` independently.+ Non-AI settings panels such as+ `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`+ must stay on the app-shell assistant-availability fact instead of+ re-reading raw AI settings just to decide whether assistant affordances+ should render.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 33bb8f488d..391a5c1d36 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -106,6 +106,11 @@ semantics, and `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts` nowowns the canonical summary normalization so Patrol consumers inherit onegoverned recent-change and policy-posture snapshot instead of reintroducinghook-local fallback logic.+That same Patrol hook boundary now consumes shared AI settings/model truth+through `frontend-modern/src/stores/aiRuntimeState.ts` instead of mounting its+own `/api/settings/ai` or `/api/ai/models` reads. Patrol-specific state still+owns local toggle optimism, run-status orchestration, and Patrol-only copy, but+the underlying AI runtime catalog must stay shared with chat and AI settings.The Patrol page now also treats Patrol runtime availability as a first-classrender contract: the header chip, primary summary card, and status bar mustall route through the shared `frontend-modern/src/utils/patrolRuntimePresentation.ts`diff --git a/frontend-modern/src/components/AI/AICostDashboard.tsx b/frontend-modern/src/components/AI/AICostDashboard.tsxindex 84cbf92289..9bdb7eed11 100644--- a/frontend-modern/src/components/AI/AICostDashboard.tsx+++ b/frontend-modern/src/components/AI/AICostDashboard.tsx@@ -10,10 +10,11 @@ import {} from '@/components/shared/Table';import { SectionHeader } from '@/components/shared/SectionHeader';import { AIAPI } from '@/api/ai';+import { aiRuntimeSettings, loadAIRuntimeSettings } from '@/stores/aiRuntimeState';import { formatNumber } from '@/utils/format';import { logger } from '@/utils/logger';import { notificationStore } from '@/stores/notifications';-import type { AICostSummary, AISettings } from '@/types/ai';+import type { AICostSummary } from '@/types/ai';import { getAIProviderDisplayName } from '@/utils/aiProviderPresentation';import {AI_COST_DAILY_TOKEN_EMPTY_STATE,@@ -85,7 +86,6 @@ export const AICostDashboard: Component = () => {const [loading, setLoading] = createSignal(false);const [loadError, setLoadError] = createSignal<string | null>(null);const [summary, setSummary] = createSignal<AICostSummary | null>(null);- const [aiSettings, setAISettings] = createSignal<AISettings | null>(null);let requestSeq = 0;const anyPricingKnown = createMemo(() => {@@ -170,11 +170,9 @@ export const AICostDashboard: Component = () => {const loadBudgetSettings = async () => {try {- const s = await AIAPI.getSettings();- setAISettings(s);+ await loadAIRuntimeSettings();} catch (err) {logger.debug('[AICostDashboard] Failed to load AI settings for budget:', err);- setAISettings(null);}};@@ -183,7 +181,7 @@ export const AICostDashboard: Component = () => {});const parsedBudgetUSD30d = createMemo(() => {- const s = aiSettings();+ const s = aiRuntimeSettings();const n = s?.cost_budget_usd_30d;if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) return null;return n;diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsxindex d3287bf1f7..c2f9512934 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx@@ -79,8 +79,6 @@ const {},clearInitialPrompt: vi.fn(),clearFindingId: vi.fn(),- settingsVersionSignal: vi.fn(() => 0),- notifySettingsChanged: vi.fn(),};const mockByType = vi.fn((_type: string): Array<{ name: string }> => []);@@ -151,7 +149,6 @@ vi.mock('../MentionAutocomplete', () => ({</button>{props.resources.map((resource) => (<button- key={resource.id}type="button"data-testid={`mention-select-${resource.id}`}onClick={() => props.onSelect(resource)}@@ -177,10 +174,15 @@ vi.mock('@/hooks/useResources', () => ({// ── Lazy import after mocks ────────────────────────────────────────────────let AIChat: typeof import('../index').AIChat;+let resetAIRuntimeState: typeof import('@/stores/aiRuntimeState').resetAIRuntimeState;beforeAll(async () => {- const mod = await import('../index');- AIChat = mod.AIChat;+ const [chatModule, runtimeModule] = await Promise.all([+ import('../index'),+ import('@/stores/aiRuntimeState'),+ ]);+ AIChat = chatModule.AIChat;+ resetAIRuntimeState = runtimeModule.resetAIRuntimeState;});// ── Helpers ────────────────────────────────────────────────────────────────@@ -193,9 +195,9 @@ function renderChat(onClose = vi.fn()) {beforeEach(() => {vi.clearAllMocks();+ resetAIRuntimeState();mockAiChatStore.isOpenSignal.mockReturnValue(true);mockAiChatStore.context = { initialPrompt: undefined, findingId: undefined };- mockAiChatStore.settingsVersionSignal.mockReturnValue(0);mockChat.messages.mockReturnValue([]);mockChat.isLoading.mockReturnValue(false);mockChat.sessionId.mockReturnValue('');diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex 5b39a6090d..6dfc7a86c3 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -13,6 +13,15 @@ import { AIAPI } from '@/api/ai';import { AIChatAPI, type ChatSession } from '@/api/aiChat';import { notificationStore } from '@/stores/notifications';import { aiChatStore } from '@/stores/aiChat';+import {+ aiRuntimeModels,+ aiRuntimeModelsError,+ aiRuntimeModelsLoading,+ aiRuntimeSettings,+ loadAIRuntimeModels,+ loadAIRuntimeSettings,+ syncAIRuntimeSettings,+} from '@/stores/aiRuntimeState';import { logger } from '@/utils/logger';import { AI_CHAT_SESSION_EMPTY_STATE } from '@/utils/aiChatPresentation';import {@@ -26,7 +35,6 @@ import { isAppContainerDiscoveryResourceType } from '@/utils/discoveryTarget';import {getActionableAgentIdFromResource,isAgentFacetInfrastructureResource,- hasAgentFacet as resourceHasAgentFacet,} from '@/utils/agentResources';import { normalizeChatMentionKeyPart } from '@/utils/chatIdentifiers';import {@@ -37,7 +45,7 @@ import { useChat } from './hooks/useChat';import { ChatMessages } from './ChatMessages';import { ModelSelector } from './ModelSelector';import { MentionAutocomplete, type MentionResource } from './MentionAutocomplete';-import type { PendingApproval, PendingQuestion, ModelInfo } from './types';+import type { PendingApproval, PendingQuestion } from './types';import { formatIdentifierLabel } from '@/utils/textPresentation';const MODEL_SESSION_STORAGE_KEY = 'pulse:ai_chat_models_by_session';@@ -61,9 +69,6 @@ export const AIChat: Component<AIChatProps> = (props) => {const [showSessions, setShowSessions] = createSignal(false);const [sessionDropdownPosition, setSessionDropdownPosition] = createSignal({ top: 0, right: 0 });let sessionButtonRef: HTMLButtonElement | undefined;- const [models, setModels] = createSignal<ModelInfo[]>([]);- const [modelsLoading, setModelsLoading] = createSignal(false);- const [modelsError, setModelsError] = createSignal('');const [defaultModel, setDefaultModel] = createSignal('');const [chatOverrideModel, setChatOverrideModel] = createSignal('');const [controlLevel, setControlLevel] = createSignal<AIControlLevel>('read_only');@@ -139,14 +144,14 @@ export const AIChat: Component<AIChatProps> = (props) => {const defaultModelLabel = createMemo(() => {const fallback = defaultModel().trim();if (!fallback) return '';- const match = models().find((model) => model.id === fallback);+ const match = aiRuntimeModels().find((model) => model.id === fallback);return match ? match.name || match.id.split(':').pop() || match.id : fallback;});const chatOverrideLabel = createMemo(() => {const override = chatOverrideModel().trim();if (!override) return '';- const match = models().find((model) => model.id === override);+ const match = aiRuntimeModels().find((model) => model.id === override);return match ? match.name || match.id.split(':').pop() || match.id : override;});@@ -156,45 +161,32 @@ export const AIChat: Component<AIChatProps> = (props) => {if (notify) {notificationStore.info('Refreshing models...', 2000);}- setModelsLoading(true);- setModelsError('');try {- const result = await AIAPI.getModels();- const nextModels = result.models || [];- setModels(nextModels);- if (result.error) {- setModelsError(result.error);+ const nextModels = await loadAIRuntimeModels(true);+ const modelLoadError = aiRuntimeModelsError();+ if (modelLoadError) {if (notify) {- notificationStore.warning(result.error, 6000);+ notificationStore.warning(modelLoadError, 6000);}} else if (notify) {notificationStore.success(`Models refreshed (${nextModels.length})`, 2000);}} catch (error) {logger.error('[AIChat] Failed to load models:', error);- setModels([]);const message = error instanceof Error ? error.message : 'Failed to load models.';- setModelsError(message);notificationStore.error(message);- } finally {- setModelsLoading(false);}};- const loadSettings = async () => {- try {- const settings = await AIAPI.getSettings();- const chatOverride = (settings.chat_model || '').trim();- const fallback = chatOverride || (settings.model || '').trim();- const resolvedControl = normalizeAIControlLevel(settings.control_level);- setDefaultModel(fallback);- setChatOverrideModel(chatOverride);- setControlLevel(resolvedControl);- setDiscoveryEnabled(settings.discovery_enabled ?? false);- } catch (error) {- logger.error('[AIChat] Failed to load AI settings:', error);- }- };+ createEffect(() => {+ const settings = aiRuntimeSettings();+ const chatOverride = (settings?.chat_model || '').trim();+ const fallback = chatOverride || (settings?.model || '').trim();+ setDefaultModel(fallback);+ setChatOverrideModel(chatOverride);+ setControlLevel(normalizeAIControlLevel(settings?.control_level));+ setDiscoveryEnabled(settings?.discovery_enabled ?? false);+ });const updateControlLevel = async (nextLevel: 'read_only' | 'controlled' | 'autonomous') => {if (controlSaving() || nextLevel === controlLevel()) {@@ -206,9 +198,9 @@ export const AIChat: Component<AIChatProps> = (props) => {try {const updated = await AIAPI.updateSettings({ control_level: nextLevel });const resolved = normalizeAIControlLevel(updated.control_level || nextLevel);+ syncAIRuntimeSettings(updated);setControlLevel(resolved);if (resolved === 'autonomous') setAutonomousBannerDismissed(false);- aiChatStore.notifySettingsChanged();notificationStore.success(`Control mode set to ${getAIChatControlLevelPresentation(resolved).label}`,2000,@@ -253,31 +245,18 @@ export const AIChat: Component<AIChatProps> = (props) => {// AI not running - silently clear dynamic state instead of logging on// unrelated routes or after the assistant is disabled.setSessions([]);- setModels([]);- setModelsError('');+ setDefaultModel('');+ setChatOverrideModel('');+ setDiscoveryEnabled(false);+ setControlLevel('read_only');return;}- await refreshSessions();- await loadSettings();- await loadModels();+ await Promise.all([refreshSessions(), loadAIRuntimeSettings(), loadAIRuntimeModels()]);} catch (error) {logger.error('[AIChat] Failed to initialize:', error);}};- // Refresh models when AI settings change (e.g., new API key added)- createEffect(() => {- const version = aiChatStore.settingsVersionSignal();- if (!isOpen()) {- return;- }- // Skip the initial run (version 0)- if (version > 0) {- loadModels();- loadSettings();- }- });-// Pre-fill input when opened with an initialPrompt (e.g., "Discuss with Assistant" from findings)createEffect(() => {const ctx = aiChatStore.context;@@ -394,7 +373,6 @@ export const AIChat: Component<AIChatProps> = (props) => {value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;const asString = (value: unknown): string | undefined =>typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;- const hasAgentFacet = (resource: Resource): boolean => resourceHasAgentFacet(resource);const getAgentActionId = (resource: Resource): string => {return getActionableAgentIdFromResource(resource) || resource.id;};@@ -549,7 +527,6 @@ export const AIChat: Component<AIChatProps> = (props) => {for (const runtime of dockerHosts) {const dockerActionId = getDockerActionId(runtime);const label = getPreferredResourceDisplayName(runtime);- const hostnameOrId = getPreferredResourceHostname(runtime) || runtime.id;const runtimeStatus =runtime.status === 'online' || runtime.status === 'running'? 'online'@@ -889,13 +866,13 @@ export const AIChat: Component<AIChatProps> = (props) => {{/* Model selector */}<ModelSelector- models={models()}+ models={aiRuntimeModels()}selectedModel={chat.model()}defaultModelLabel={defaultModelLabel()}chatOverrideModel={chatOverrideModel()}chatOverrideLabel={chatOverrideLabel()}- isLoading={modelsLoading()}- error={modelsError()}+ isLoading={aiRuntimeModelsLoading()}+ error={aiRuntimeModelsError()}onModelSelect={selectModel}onRefresh={() => loadModels(true)}/>diff --git a/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx b/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsxindex 3439bdbaef..192fbb6fc1 100644--- a/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx+++ b/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';import { AICostDashboard } from '../AICostDashboard';+import { resetAIRuntimeState } from '@/stores/aiRuntimeState';import type { AICostSummary, AISettings } from '@/types/ai';// ---- mock function handles ----@@ -131,6 +132,7 @@ function renderDashboard() {describe('AICostDashboard', () => {beforeEach(() => {+ resetAIRuntimeState();getCostSummaryMock.mockReset();getSettingsMock.mockReset();resetCostHistoryMock.mockReset();diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsxindex a50480f471..ad9b543e67 100644--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';import { Route, Router } from '@solidjs/router';+import { resetAIRuntimeState } from '@/stores/aiRuntimeState';import type { AISettings as AISettingsType } from '@/types/ai';import { AISettings } from '../AISettings';@@ -17,7 +18,6 @@ const revertSessionMock = vi.fn();const notificationSuccessMock = vi.fn();const notificationErrorMock = vi.fn();const notificationInfoMock = vi.fn();-const notifySettingsChangedMock = vi.fn();const loggerDebugMock = vi.fn();const loggerErrorMock = vi.fn();const hasFeatureMock = vi.fn();@@ -56,12 +56,6 @@ vi.mock('@/stores/notifications', () => ({},}));-vi.mock('@/stores/aiChat', () => ({- aiChatStore: {- notifySettingsChanged: (...args: unknown[]) => notifySettingsChangedMock(...args),- },-}));-vi.mock('@/utils/logger', () => ({logger: {debug: (...args: unknown[]) => loggerDebugMock(...args),@@ -129,7 +123,6 @@ const resetAllMocks = () => {notificationSuccessMock.mockReset();notificationErrorMock.mockReset();notificationInfoMock.mockReset();- notifySettingsChangedMock.mockReset();loggerDebugMock.mockReset();loggerErrorMock.mockReset();hasFeatureMock.mockReset();@@ -164,6 +157,7 @@ const setupDefaultMocks = () => {describe('AISettings model loading error states', () => {beforeEach(() => {+ resetAIRuntimeState();resetAllMocks();setupDefaultMocks();});@@ -272,12 +266,15 @@ describe('AISettings model loading error states', () => {await waitFor(() => {expect(getModelsMock).toHaveBeenCalledTimes(1);+ expect(screen.getByText('Claude Sonnet')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /refresh/i })).not.toBeDisabled();});// Trigger a refresh that returns an errorfireEvent.click(screen.getByRole('button', { name: /refresh/i }));await waitFor(() => {+ expect(getModelsMock).toHaveBeenCalledTimes(2);expect(screen.getByText(/Failed to load models: API key revoked/)).toBeInTheDocument();});diff --git a/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsxindex ae2700b4b5..6df16417a7 100644--- a/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx@@ -64,9 +64,9 @@ vi.mock('@/api/agentProfiles', () => ({},}));-vi.mock('@/api/ai', () => ({- AIAPI: {- getSettings: () => Promise.resolve({ enabled: false, configured: false }),+vi.mock('@/stores/aiChat', () => ({+ aiChatStore: {+ enabled: false,},}));diff --git a/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts b/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.tsindex eb7e5adc89..7bb6076a9d 100644--- a/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts@@ -236,7 +236,8 @@ describe('monitored-system model guardrails', () => {expect(agentProfilesPanelStateSource).toContain('const { resources } = useResources()');expect(agentProfilesPanelStateSource).toContain('const loadData = async () =>');expect(agentProfilesPanelStateSource).toContain('const handleSave = async () =>');- expect(agentProfilesPanelStateSource).toContain('AIAPI.getSettings()');+ expect(agentProfilesPanelStateSource).toContain("aiChatStore.enabled === true");+ expect(agentProfilesPanelStateSource).not.toContain('AIAPI.getSettings()');expect(agentProfilesPanelStateSource).toContain('AgentProfilesAPI.listProfiles()');expect(agentProfilesPanelStateSource).toContain('AgentProfilesAPI.listAssignments()');expect(agentProfilesPresentationSource).toContain('export function getAgentProfilesEmptyState');@@ -929,18 +930,17 @@ describe('monitored-system model guardrails', () => {});it('keeps setup and node summary fallbacks aware of v6 agent facets', () => {- expect(setupCompletionPanelSource).toContain('const hasAgentFacet = (resource: Resource)');- expect(setupCompletionPanelSource).toContain("resource.type === 'agent'");- expect(setupCompletionPanelSource).toContain('const agentFacetResources = resources.filter(');+ expect(setupCompletionPanelSource).toContain('buildSetupCompletionConnectedSystems');+ expect(setupCompletionPanelSource).toContain('buildSetupCompletionViewModel');expect(setupCompletionPanelSource).toContain('Open Infrastructure Install');+ expect(setupCompletionPanelSource).toContain('Open Platform connections');expect(setupCompletionPanelSource).toContain('The canonical install flow now lives in Infrastructure Operations.',);+ expect(setupCompletionPanelSource).not.toContain('const hasAgentFacet = (resource: Resource)');+ expect(setupCompletionPanelSource).not.toContain('const agentFacetResources = resources.filter(');expect(setupCompletionPanelSource).not.toContain('state.nodes || []');expect(setupCompletionPanelSource).not.toContain('state.hosts || []');- expect(setupCompletionPanelSource).not.toContain(- '(state.hosts || []).length > 0\n ? state.hosts\n : resources',- );expect(infrastructureSelectorSource).toContain('useInfrastructureSelectorState');expect(infrastructureSelectorSource).not.toContain('const hasAgentFacet = (resource: Resource): boolean =>',@@ -992,8 +992,9 @@ describe('monitored-system model guardrails', () => {});it('keeps AI chat mention resources aware of agent facets beyond host type', () => {- expect(aiChatSource).toContain('const hasAgentFacet = (resource: Resource): boolean =>');expect(aiChatSource).toContain('isAgentFacetInfrastructureResource');+ expect(aiChatSource).toContain('const agentResources = allResources().filter((resource) =>');+ expect(aiChatSource).toContain('getActionableAgentIdFromResource(resource) || resource.id;');expect(aiChatSource).not.toContain("resource.type === 'truenas'");expect(aiChatSource).not.toContain("resource.type === 'host'");expect(aiChatSource).toContain("type: 'agent'");diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 039db8f33c..10372c96df 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -75,6 +75,7 @@ import aiSettingsModelSource from '../aiSettingsModel.ts?raw';import aiRuntimeControlsSectionSource from '../AIRuntimeControlsSection.tsx?raw';import aiSettingsStatusAndActionsSource from '../AISettingsStatusAndActions.tsx?raw';import aiSettingsStateSource from '../useAISettingsState.ts?raw';+import aiRuntimeStateSource from '@/stores/aiRuntimeState.ts?raw';import diagnosticsModelSource from '../diagnosticsModel.ts?raw';import diagnosticsPanelSource from '../DiagnosticsPanel.tsx?raw';import diagnosticsResultsPanelSource from '../DiagnosticsResultsPanel.tsx?raw';@@ -1132,8 +1133,12 @@ describe('Settings architecture guardrails', () => {expect(aiSettingsStateSource).toContain('const handleEnabledToggle = async (newValue: boolean) =>',);+ expect(aiSettingsStateSource).toContain("} from '@/stores/aiRuntimeState';");expect(aiSettingsStateSource).toContain("getUpgradeActionDestination('ai_autofix')");expect(aiSettingsStateSource).toContain('AIAPI.getSettings()');+ expect(aiSettingsStateSource).toContain('syncAIRuntimeSettings(data ?? null);');+ expect(aiSettingsStateSource).toContain('await loadAIRuntimeModels(true);');+ expect(aiSettingsStateSource).not.toContain('AIAPI.getModels()');expect(aiSettingsStateSource).toContain('const payload: Record<string, unknown> = { enabled: true };',);@@ -1146,6 +1151,11 @@ describe('Settings architecture guardrails', () => {expect(aiSettingsStateSource).toContain('runStartProTrialAction({');expect(aiSettingsStateSource).not.toContain('startProTrial()');expect(aiSettingsStateSource).not.toContain('getTrialAlreadyUsedMessage()');+ expect(aiRuntimeStateSource).toContain('export async function loadAIRuntimeSettings');+ expect(aiRuntimeStateSource).toContain('export async function loadAIRuntimeModels');+ expect(aiRuntimeStateSource).toContain('const next = await AIAPI.getSettings()');+ expect(aiRuntimeStateSource).toContain('const result = await AIAPI.getModels()');+ expect(aiRuntimeStateSource).toContain("eventBus.on('org_switched'");});it('keeps the updates settings shell behind extracted install-guide owners', () => {diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.tsindex aaf446a952..662a28a087 100644--- a/frontend-modern/src/components/Settings/useAISettingsState.ts+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts@@ -9,7 +9,13 @@ import {type ProviderHealthState,type ProviderTestResult,} from '@/components/Settings/aiSettingsModel';-import { aiChatStore } from '@/stores/aiChat';+import {+ aiRuntimeModels,+ aiRuntimeModelsError,+ clearAIRuntimeModels,+ loadAIRuntimeModels,+ syncAIRuntimeSettings,+} from '@/stores/aiRuntimeState';import {hasFeature,loadRuntimeCapabilities,@@ -163,12 +169,14 @@ export const useAISettingsState = () => {(data?.configured_providers?.length ?? 0) > 0;const syncModelCatalogForSettings = (data: AISettingsType | null | undefined) => {+ syncAIRuntimeSettings(data ?? null);if (hasProviderBackedModels(data)) {void loadModels();return;}setAvailableModels([]);setModelsError('');+ clearAIRuntimeModels();};createEffect((wasPaywallVisible) => {@@ -251,12 +259,13 @@ export const useAISettingsState = () => {setModelsLoading(true);setModelsError('');try {- const result = await AIAPI.getModels();- if (result.error) {- setModelsError(result.error);- logger.debug('[AISettings] API returned error for models:', result.error);+ await loadAIRuntimeModels(true);+ const nextError = aiRuntimeModelsError();+ if (nextError) {+ setModelsError(nextError);+ logger.debug('[AISettings] API returned error for models:', nextError);}- setAvailableModels(result.models ?? []);+ setAvailableModels(aiRuntimeModels());} catch (error) {const message = getAIModelsLoadErrorMessage(error instanceof Error ? error.message : '');setModelsError(message);@@ -481,7 +490,6 @@ export const useAISettingsState = () => {void runProviderPreflight(updated);handleCloseSetupModal();notificationStore.success('Pulse Assistant enabled! You can customize settings below.');- aiChatStore.notifySettingsChanged();} catch (error) {logger.error('[AISettings] Setup failed:', error);notificationStore.error(error instanceof Error ? error.message : 'Setup failed');@@ -694,7 +702,6 @@ export const useAISettingsState = () => {syncModelCatalogForSettings(updated);void runProviderPreflight(updated);notificationStore.success('Pulse Assistant settings saved');- aiChatStore.notifySettingsChanged();} catch (error) {logger.error('[AISettings] Failed to save settings:', error);notificationStore.error(getAISettingsSaveErrorMessage(error instanceof Error ? error.message : ''));@@ -787,7 +794,6 @@ export const useAISettingsState = () => {if (provider === 'ollama') setForm('ollamaBaseUrl', '');notificationStore.success(`${provider} credentials cleared`);- aiChatStore.notifySettingsChanged();} catch (error) {logger.error(`[AISettings] Clear ${provider} failed:`, error);notificationStore.error(@@ -806,7 +812,6 @@ export const useAISettingsState = () => {syncModelCatalogForSettings(updated);void runProviderPreflight(updated);notificationStore.success(newValue ? 'Pulse Assistant enabled' : 'Pulse Assistant disabled');- aiChatStore.notifySettingsChanged();} catch (error) {setForm('enabled', !newValue);logger.error('[AISettings] Failed to toggle AI:', error);diff --git a/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts b/frontend-modern/src/components/Settings/useAgentProfilesPanelState.tsindex 308f8d3d9d..b65554fd4b 100644--- a/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts+++ b/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts@@ -1,6 +1,5 @@import { createEffect, createMemo, createSignal, onMount } from 'solid-js';import { useWebSocket } from '@/contexts/appRuntime';-import { AIAPI } from '@/api/ai';import {AgentProfilesAPI,MISSING_AGENT_PROFILE_ASSIGNMENT_MESSAGE,@@ -20,6 +19,7 @@ import {getUpgradeActionDestination,} from '@/stores/licenseCommercial';import { loadRuntimeCapabilities } from '@/stores/license';+import { aiChatStore } from '@/stores/aiChat';import type { ConnectedInfrastructureItem } from '@/types/api';import type { Resource } from '@/types/resource';import { formatRelativeTime } from '@/utils/format';@@ -42,7 +42,6 @@ import {import {getPreferredInfrastructureDisplayName,getPreferredNamedEntityLabel,- getPreferredResourceDisplayName,getPreferredResourceHostname,} from '@/utils/resourceIdentity';import {@@ -79,7 +78,7 @@ export const useAgentProfilesPanelState = () => {const [startingTrial, setStartingTrial] = createSignal(false);const canStartTrial = () => canOfferCommercialTrial();- const [aiAvailable, setAiAvailable] = createSignal(false);+ const aiAvailable = createMemo(() => aiChatStore.enabled === true);const [profiles, setProfiles] = createSignal<AgentProfile[]>([]);const [assignments, setAssignments] = createSignal<AgentProfileAssignment[]>([]);const [loading, setLoading] = createSignal(true);@@ -238,13 +237,6 @@ export const useAgentProfilesPanelState = () => {onMount(async () => {await loadRuntimeCapabilities();- try {- const aiSettings = await AIAPI.getSettings();- setAiAvailable(aiSettings.enabled && aiSettings.configured);- } catch {- setAiAvailable(false);- }-if (hasAgentProfiles()) {await loadData();} else {diff --git a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.tsindex ef5d5ff9cf..256983f5b2 100644--- a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts+++ b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts@@ -6,6 +6,7 @@ import {onCleanup,onMount,} from 'solid-js';+import { AIAPI } from '@/api/ai';import {getPatrolAutonomySettings,getPatrolRunHistory,@@ -18,7 +19,13 @@ import {type PatrolStatus,} from '@/api/patrol';import { aiIntelligenceStore } from '@/stores/aiIntelligence';-import { apiFetchJSON } from '@/utils/apiClient';+import {+ aiRuntimeModels,+ aiRuntimeSettings,+ loadAIRuntimeModels,+ loadAIRuntimeSettings,+ syncAIRuntimeSettings,+} from '@/stores/aiRuntimeState';import { notificationStore } from '@/stores/notifications';import { hasTriggeringAlert } from '@/utils/findingAlertIdentity';import { usePatrolStream } from '@/hooks/usePatrolStream';@@ -30,31 +37,12 @@ import {canStartCommercialTrial,getUpgradeActionDestination,} from '@/stores/licenseCommercial';+import type { AISettings } from '@/types/ai';import { getCanonicalScopeResourceIds } from '@/utils/patrolFormat';import { buildPatrolInvestigationContextSummary } from './patrolInvestigationContextModel';import { trackPaywallViewed } from '@/utils/upgradeMetrics';import { runStartProTrialAction } from '@/utils/trialStartAction';-interface ModelInfo {- id: string;- name: string;- description: string;- notable: boolean;-}--interface AISettings {- patrol_model?: string;- patrol_interval_minutes?: number;- patrol_enabled?: boolean;- model?: string;- alert_triggered_analysis?: boolean;- patrol_alert_triggers_enabled?: boolean;- patrol_anomaly_triggers_enabled?: boolean;- patrol_event_triggers_enabled?: boolean;- patrol_auto_fix?: boolean;- auto_fix_model?: string;-}-type PatrolTab = 'findings' | 'history';export function usePatrolIntelligenceState() {@@ -75,7 +63,7 @@ export function usePatrolIntelligenceState() {const [showAdvancedSettings, setShowAdvancedSettings] = createSignal(false);const [isSavingAdvanced, setIsSavingAdvanced] = createSignal(false);const [fullModeUnlocked, setFullModeUnlocked] = createSignal(false);- const [availableModels, setAvailableModels] = createSignal<ModelInfo[]>([]);+ const availableModels = aiRuntimeModels;const [patrolModel, setPatrolModel] = createSignal<string>('');const [defaultModel, setDefaultModel] = createSignal<string>('');const [patrolInterval, setPatrolInterval] = createSignal<number>(360);@@ -185,31 +173,20 @@ export function usePatrolIntelligenceState() {}}- async function loadModels() {- try {- const data = await apiFetchJSON<{ models: ModelInfo[] }>('/api/ai/models');- setAvailableModels(data?.models || []);- } catch (err) {- console.error('Failed to load models:', err);- }- }+ const applyPatrolAISettings = (data: AISettings | null | undefined) => {+ setPatrolModel(data?.patrol_model || '');+ setDefaultModel(data?.model || '');+ setPatrolInterval(data?.patrol_interval_minutes ?? 360);+ setPatrolEnabledLocal(data?.patrol_enabled ?? true);+ setAlertTriggeredAnalysis(!alertAnalysisLocked() && data?.alert_triggered_analysis !== false);+ const legacyEventTriggersEnabled = data?.patrol_event_triggers_enabled !== false;+ setPatrolAlertTriggers(data?.patrol_alert_triggers_enabled ?? legacyEventTriggersEnabled);+ setPatrolAnomalyTriggers(data?.patrol_anomaly_triggers_enabled ?? legacyEventTriggersEnabled);+ };- async function loadAISettings() {- try {- const data = await apiFetchJSON<AISettings>('/api/settings/ai');- if (!data) return;- setPatrolModel(data.patrol_model || '');- setDefaultModel(data.model || '');- setPatrolInterval(data.patrol_interval_minutes ?? 360);- setPatrolEnabledLocal(data.patrol_enabled ?? true);- setAlertTriggeredAnalysis(!alertAnalysisLocked() && data.alert_triggered_analysis !== false);- const legacyEventTriggersEnabled = data.patrol_event_triggers_enabled !== false;- setPatrolAlertTriggers(data.patrol_alert_triggers_enabled ?? legacyEventTriggersEnabled);- setPatrolAnomalyTriggers(data.patrol_anomaly_triggers_enabled ?? legacyEventTriggersEnabled);- } catch (err) {- console.error('Failed to load AI settings:', err);- }- }+ createEffect(() => {+ applyPatrolAISettings(aiRuntimeSettings());+ });async function handleTogglePatrol() {if (isTogglingPatrol()) return;@@ -222,10 +199,8 @@ export function usePatrolIntelligenceState() {clearSafetyTimer();}try {- const data = await apiFetchJSON<AISettings>('/api/settings/ai/update', {- method: 'PUT',- body: JSON.stringify({ patrol_enabled: newValue }),- });+ const data = await AIAPI.updateSettings({ patrol_enabled: newValue });+ syncAIRuntimeSettings(data);if (typeof data?.patrol_enabled === 'boolean') {setPatrolEnabledLocal(data.patrol_enabled);} else {@@ -284,11 +259,9 @@ export function usePatrolIntelligenceState() {if (isUpdatingSettings()) return;setIsUpdatingSettings(true);try {- await apiFetchJSON('/api/settings/ai/update', {- method: 'PUT',- body: JSON.stringify({ patrol_model: modelId }),- });- setPatrolModel(modelId);+ const updated = await AIAPI.updateSettings({ patrol_model: modelId });+ syncAIRuntimeSettings(updated);+ setPatrolModel(updated.patrol_model || modelId);} catch (err) {console.error('Failed to update patrol model:', err);notificationStore.error('Failed to update patrol model');@@ -301,12 +274,10 @@ export function usePatrolIntelligenceState() {if (isUpdatingSettings()) return;setIsUpdatingSettings(true);try {- await apiFetchJSON('/api/settings/ai/update', {- method: 'PUT',- body: JSON.stringify({ patrol_interval_minutes: minutes }),- });- setPatrolInterval(minutes);- setPatrolEnabledLocal(minutes > 0);+ const updated = await AIAPI.updateSettings({ patrol_interval_minutes: minutes });+ syncAIRuntimeSettings(updated);+ setPatrolInterval(updated.patrol_interval_minutes ?? minutes);+ setPatrolEnabledLocal((updated.patrol_interval_minutes ?? minutes) > 0);refetchPatrolStatus();} catch (err) {console.error('Failed to update patrol interval:', err);@@ -322,10 +293,8 @@ export function usePatrolIntelligenceState() {const previous = alertTriggeredAnalysis();setAlertTriggeredAnalysis(enabled);try {- await apiFetchJSON('/api/settings/ai/update', {- method: 'PUT',- body: JSON.stringify({ alert_triggered_analysis: enabled }),- });+ const updated = await AIAPI.updateSettings({ alert_triggered_analysis: enabled });+ syncAIRuntimeSettings(updated);} catch (err) {console.error('Failed to update alert-triggered analysis:', err);setAlertTriggeredAnalysis(previous);@@ -341,10 +310,8 @@ export function usePatrolIntelligenceState() {const previous = patrolAlertTriggers();setPatrolAlertTriggers(enabled);try {- await apiFetchJSON('/api/settings/ai/update', {- method: 'PUT',- body: JSON.stringify({ patrol_alert_triggers_enabled: enabled }),- });+ const updated = await AIAPI.updateSettings({ patrol_alert_triggers_enabled: enabled });+ syncAIRuntimeSettings(updated);} catch (err) {console.error('Failed to update alert-triggered patrols:', err);setPatrolAlertTriggers(previous);@@ -360,10 +327,8 @@ export function usePatrolIntelligenceState() {const previous = patrolAnomalyTriggers();setPatrolAnomalyTriggers(enabled);try {- await apiFetchJSON('/api/settings/ai/update', {- method: 'PUT',- body: JSON.stringify({ patrol_anomaly_triggers_enabled: enabled }),- });+ const updated = await AIAPI.updateSettings({ patrol_anomaly_triggers_enabled: enabled });+ syncAIRuntimeSettings(updated);} catch (err) {console.error('Failed to update anomaly-triggered patrols:', err);setPatrolAnomalyTriggers(previous);@@ -664,8 +629,8 @@ export function usePatrolIntelligenceState() {loadRuntimeCapabilities(),loadAllData(),loadAutonomySettings(),- loadModels(),- loadAISettings(),+ loadAIRuntimeModels(),+ loadAIRuntimeSettings(),]);});diff --git a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsxindex 0e96b2e459..05bbd8ac16 100644--- a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx+++ b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';import { createSignal } from 'solid-js';+import { resetAIRuntimeState } from '@/stores/aiRuntimeState';import { getPublicPricingUrl } from '@/utils/pricingHandoff';import { AIIntelligence } from '../AIIntelligence';@@ -122,6 +123,9 @@ vi.mock('@/api/patrol', () => ({vi.mock('@/api/ai', () => ({AIAPI: {getCorrelations: (...args: unknown[]) => getCorrelationsMock(...args),+ getModels: (...args: unknown[]) => apiFetchJSONMock('/api/ai/models', ...args),+ getSettings: (...args: unknown[]) => apiFetchJSONMock('/api/settings/ai', ...args),+ updateSettings: (...args: unknown[]) => apiFetchJSONMock('/api/settings/ai/update', ...args),},}));@@ -135,6 +139,7 @@ vi.mock('@/stores/license', () => ({}));vi.mock('@/stores/licenseCommercial', () => ({+ canStartCommercialTrial: () => licenseStatusMock()?.trial_eligible !== false,getUpgradeActionDestination: (...args: unknown[]) => getUpgradeActionDestinationMock(...args),commercialPosture: (...args: unknown[]) => licenseStatusMock(...args),licenseStatus: (...args: unknown[]) => licenseStatusMock(...args),@@ -317,6 +322,7 @@ const defaultAISettings = {describe('AIIntelligence entitlement gating', () => {beforeEach(() => {+ resetAIRuntimeState();getPatrolStatusMock.mockReset();getPatrolAutonomySettingsMock.mockReset();updatePatrolAutonomySettingsMock.mockReset();diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.tsindex 7bfcd2c2eb..12766a4875 100644--- a/frontend-modern/src/stores/aiChat.ts+++ b/frontend-modern/src/stores/aiChat.ts@@ -96,7 +96,6 @@ const [aiChatContext, setAIChatContext] = createSignal<AIChatContext>({});const [contextItems, setContextItems] = createSignal<ContextItem[]>([]);const [messages, setMessages] = createSignal<Message[]>(loadMessagesFromStorage());const [aiEnabled, setAiEnabled] = createSignal<boolean | null>(null); // null = not checked yet-const [settingsVersion, setSettingsVersion] = createSignal(0); // Increments when AI settings change// Session management stateconst [currentSessionId, setCurrentSessionId] = createSignal<string>(loadOrCreateSessionId());@@ -193,14 +192,6 @@ export const aiChatStore = {setAiEnabled(enabled);},- // Signal for settings changes - components can watch this to refresh- settingsVersionSignal: settingsVersion,-- // Notify that AI settings have changed (call after saving settings)- notifySettingsChanged() {- setSettingsVersion((v) => v + 1);- },-// Set messages (for persistence from AIChat component)setMessages(msgs: Message[]) {setMessages(msgs);diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex a41be7910b..8d8b6b7aa3 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -3709,8 +3709,8 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 113,- "heading_line": 81,+ "line": 114,+ "heading_line": 82,}],)