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
Break app runtime hook cycle and restore quickstart proof
rcourtman5afa3969769b
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex eaaf6b426e..b14d740942 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -151,6 +151,7 @@ management, and fleet control surfaces.4. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.5. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.6. Add or change profile management, the extracted agent profiles runtime owner, the pure unified-agent inventory/install model, the API-backed platform connections workspace shell, route model, reporting summary owner, shared install/inventory/dialog section owners, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners plus their shared model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureReportingPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInventorySection.tsx`, `frontend-modern/src/components/Settings/InfrastructureActiveRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureIgnoredRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx`, `frontend-modern/src/components/Settings/InfrastructurePlatformConnectionsSummaryCard.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/ProxmoxSettingsPanel.tsx`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ProxmoxDirectWorkspace.tsx`, `frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx`, `frontend-modern/src/components/Settings/ProxmoxDirectConnectionsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDiscoveryResultsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDeleteNodeDialog.tsx`, `frontend-modern/src/components/Settings/ProxmoxNodeModalStack.tsx`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts`, `frontend-modern/src/components/Settings/NodeModal.tsx`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`.+ Those lifecycle-owned settings hooks may consume websocket state only through `frontend-modern/src/contexts/appRuntime.ts`; they must not import `frontend-modern/src/App.tsx` or recreate root-shell providers.7. Preserve canonical token-lifecycle reads in shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows do not revoke a displayed relay pairing token after `lastUsedAt` proves that an already paired device is actively depending on that credential.8. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows reuse the canonical mobile token route instead of reintroducing wildcard or browser-authored runtime token bundles.9. Preserve the dedicated backend-owned `relay:mobile:access` capability and its governed backward-compatible route inventory plus the shared helper call sites around it, so lifecycle-adjacent setup and install flows do not widen the mobile device credential back into general AI chat/execute scope ownership.@@ -1762,3 +1763,12 @@ resource surfaces may show host SMART-backed disk telemetry through the sharedmetrics target that monitoring projects for the resource instead of reviving abrowser-local disk collector, agent/device concatenation scheme, or othersurface-local history identity.+The browser-side runtime boundary is now explicit too. Lifecycle-owned+settings hooks such as+`frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts` and+`frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`+may read websocket state only through+`frontend-modern/src/contexts/appRuntime.ts`. They must not import `@/App` or+recreate app-shell providers, because `frontend-modern/src/App.tsx` owns+provider placement while lifecycle hooks must stay lazy-load safe and+shell-independent.diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 634dfa348d..c2d66b9762 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -521,3 +521,11 @@ shared incident category and provider context carried only as shared alert andtimeline metadata. Alert history may surface VMware alarm, task, and snapshotcontext inside that shared model, but it must not fork into VMware-only alerttypes, badges, or incident chrome.+That same alert-shell boundary now also treats websocket access as a shared+app-runtime dependency rather than an alerts-owned provider. Alert shells such+as `frontend-modern/src/pages/Alerts.tsx` and+`frontend-modern/src/features/alerts/tabs/HistoryTab.tsx` may consume live+state only through `frontend-modern/src/contexts/appRuntime.ts`; they must not+import `@/App` or create reverse dependencies into the root shell chunk,+because alerts surfaces must remain lazy-load safe and must not blank the app+before auth/bootstrap finishes.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex a17b8c9132..62a1cd9157 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -135,7 +135,8 @@ Own canonical runtime payload shapes between backend and frontend.## Extension Points1. Add or change payload fields through handler + contract tests together-2. Update frontend API types in lockstep with backend contract changes+2. Update frontend API types in lockstep with backend contract changes.+ Websocket-backed API consumers such as `frontend-modern/src/components/Settings/useAPITokenManagerState.ts` and `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx` may read runtime context only through `frontend-modern/src/contexts/appRuntime.ts`; they must not import `frontend-modern/src/App.tsx`, because payload ownership remains in the API contract rather than the root shell.3. Add dedicated contract tests for new stable payloads4. Route unified resource sensitivity, routing, and `aiSafeSummary` payload changes through `internal/api/resources.go`, `internal/api/contract_test.go`, and the canonical frontend resource consumer proofs together; resource governance metadata must not ship as an API-only or frontend-only heuristic5. Route unified-resource action, lifecycle, and export audit reads through `internal/api/activity_audit_handlers.go`, `internal/api/router_routes_licensing.go`, and `internal/api/contract_test.go` together so the control-plane execution trail stays on a governed API contract instead of a store-only shape@@ -2329,3 +2330,11 @@ canonical disk `MetricsTarget.ResourceID` the unified resource alreadyexposes. Storage drawers and other consumers must not fork a disk-local livehistory route, alternate query identity, or feature-specific fallback payloadwhen the governed chart API already owns that transport.+The shared browser contract now also includes a neutral app-runtime context+boundary for websocket-backed API consumers. API-contract-owned hooks such as+`frontend-modern/src/components/Settings/useAPITokenManagerState.ts` and+`frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`+may read websocket state through `frontend-modern/src/contexts/appRuntime.ts`,+but payload truth, bootstrap rules, and commercial identity still belong to+the governed API handlers and contract tests. Those hooks must not import+`@/App` or treat root-shell ownership as transport authority.diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 2bd1575c58..d269a0588c 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -1047,3 +1047,10 @@ may start shared app-shell services, auth refresh, and websocket recovery, butit must not boot a storage-only disk history collector now that storagedrawers read the canonical backend metrics-history contract through sharedchart primitives.+That same hosted browser shell boundary now also treats+`frontend-modern/src/App.tsx` as provider placement only. Shared runtime+consumers must import websocket and dark-mode hooks from+`frontend-modern/src/contexts/appRuntime.ts` instead of importing `@/App`, so+lazy hosted and settings chunks cannot create a reverse dependency into the+app shell and blank the mounted browser surface before auth/bootstrap+completes.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex d5488e4a56..2feeaca1c1 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -144,7 +144,11 @@ work extends shared components instead of creating new local variants.1. Add shared primitives in `frontend-modern/src/components/shared/`2. Route new top-level settings surfaces through the canonical settings shell- instead of introducing page-local framing+ instead of introducing page-local framing.+ Shared shells and primitives that need websocket or dark-mode context must+ consume `frontend-modern/src/contexts/appRuntime.ts`; they must not import+ `frontend-modern/src/App.tsx`, because `App.tsx` owns provider placement+ while frontend primitives own reusable consumption.3. Add feature-specific presentation only when no shared primitive should own it4. Add guardrail tests when a new shared pattern is introduced5. Keep shared platform-connections shell state on the reusable settings boundary: `frontend-modern/src/components/Settings/useSettingsInfrastructurePanelProps.ts`, `frontend-modern/src/components/Settings/InfrastructurePlatformConnectionsSummaryCard.tsx`, and `frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx` must continue to derive provider counts, availability, and shared subtab copy from one infrastructure-settings source instead of creating provider-local summary fetches or VMware-only shell vocabulary.@@ -1764,3 +1768,12 @@ read, write, and busy charts through `HistoryChart` plus`useHistoryChartState`, using the canonical physical-disk history resource id,instead of reviving `diskMetricsHistory`, a page-local ring buffer, or anotherstorage-only live chart primitive for the same telemetry.+The shared shell boundary now also includes+`frontend-modern/src/contexts/appRuntime.ts` as the only neutral owner for+app-level websocket and dark-mode consumption. Shared shells and primitives+such as `frontend-modern/src/components/Settings/Settings.tsx`,+`frontend-modern/src/components/shared/TagBadges.tsx`, and+`frontend-modern/src/components/shared/useInfrastructureSummaryTableState.ts`+may consume that module, but they must not import `@/App` or recreate shell+providers. `frontend-modern/src/App.tsx` owns provider placement; primitives+own reusable consumption only.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex d63e0ef467..8dce35a7d6 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -697,3 +697,8 @@ store-backed disk history path as longer-term disk charts, with the backenddoing range selection and fallback. Feature-local polling loops or browser-sidedisk ring buffers are forbidden because they duplicate live sampling work anddrift out of sync with the governed history timeline.+That same hot-path ownership now also requires lazy-load-safe websocket+consumption. `frontend-modern/src/components/Dashboard/useDashboardState.ts`+may read connection and alert state only through+`frontend-modern/src/contexts/appRuntime.ts`; it must not import `@/App` or+create a reverse dependency into the root shell just to read websocket state.diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex bc33aa663e..1f47efa62a 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -379,3 +379,9 @@ reads, expose the backend-owned Pulse Mobile relay access token creator, andthe relay pairing UI may revoke a displayed token only when that metadata stillshows no `lastUsedAt`. Refreshing or hiding a QR payload must not delete atoken that an already paired device is actively depending on.+That same token-management boundary now also depends on one neutral+app-runtime context owner. `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`+may consume websocket-backed revocation fan-out through+`frontend-modern/src/contexts/appRuntime.ts`, but security/privacy authority+stays in the governed API token contract. The hook must not import `@/App` or+borrow root-shell ownership as token-management authority.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex ff48f5a1c9..2524033096 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -11,6 +11,7 @@"registry_file": "docs/release-control/v6/internal/subsystems/registry.json","dependency_subsystem_ids": ["api-contracts",+ "cloud-paid","frontend-primitives","unified-resources"]@@ -124,6 +125,7 @@ querying, and the operator-facing storage health presentation layer.31. Keep VMware datastore classification neutral on the shared storage adapter contract. When `frontend-modern/src/features/storageBackups/resourceStorageMapping.ts`, `frontend-modern/src/features/storageBackups/resourceStoragePresentation.ts`, and `frontend-modern/src/features/storageBackups/storageAdapters.ts` evolve canonical storage-record mapping, VMware-backed datastores must continue to land on the shared storage route as inventory-only datastores with neutral protection fallback, not as backup repositories, backup targets, or recovery-protected resources.32. Keep infrastructure summary chart bucketing presentation-only on the adjacent shared API boundary. When `internal/api/router.go` normalizes mixed-cadence infrastructure history into equal-time summary buckets for operator-facing summary cards, storage and recovery may consume the resulting visual context only; they must not reinterpret those normalized chart samples as recovery freshness windows, backup cadence, or restore evidence.33. Keep workload chart downsampling presentation-only on that same adjacent shared API boundary. When `internal/api/router.go` caps mixed-cadence workload history into equal-time buckets for operator-facing workload cards, storage and recovery may consume the resulting visual context only; they must not reinterpret those shaped chart samples as recovery freshness windows, backup cadence, or restore evidence.+34. Keep storage and recovery websocket reads on the neutral app-runtime boundary. `frontend-modern/src/components/Recovery/RecoveryPointDetails.tsx`, `frontend-modern/src/components/Storage/useStoragePageResources.ts`, and storage/recovery-adjacent dashboard composition may consume live websocket state only through `frontend-modern/src/contexts/appRuntime.ts`, not by importing `frontend-modern/src/App.tsx` or rebuilding shell-local providers.## Forbidden Paths@@ -1909,3 +1911,11 @@ canonical history target. Storage must not keep a drawer-local live metricscollector, agent-id/device fallback stream, or separate "real-time" historystore once monitoring and `/api/metrics-store/history` already own the disktimeline.+The same shell/runtime split now applies to websocket consumers:+`frontend-modern/src/components/Recovery/RecoveryPointDetails.tsx`,+`frontend-modern/src/components/Storage/useStoragePageResources.ts`, and+`frontend-modern/src/pages/Dashboard.tsx` may consume websocket state only+through `frontend-modern/src/contexts/appRuntime.ts`. They must not import+`@/App` or create storage/recovery-local shell coupling, because provider+placement remains app-shell-owned and storage/recovery surfaces must stay+lazy-load safe.diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsxindex 067462d4e4..3181b3762f 100644--- a/frontend-modern/src/App.tsx+++ b/frontend-modern/src/App.tsx@@ -2,8 +2,6 @@ import {Show,lazy,createSignal,- createContext,- useContext,createEffect,createMemo,onCleanup,@@ -11,7 +9,6 @@ import {} from 'solid-js';import type { JSX } from 'solid-js';import { Router, Route, Navigate, useNavigate, useLocation } from '@solidjs/router';-import { getGlobalWebSocketStore } from './stores/websocket-global';import { ToastContainer } from './components/Toast/Toast';import { ErrorBoundary } from './components/ErrorBoundary';import { SecurityWarning } from './components/SecurityWarning';@@ -46,6 +43,7 @@ import {clearPendingAppShellRestoreTop,readPendingAppShellRestoreTop,} from '@/utils/appShellScrollRestoration';+import { DarkModeContext, WebSocketContext, useWebSocket } from '@/contexts/appRuntime';function isPublicRoutePath(pathname: string): boolean {// Public routes must be viewable without authentication.@@ -89,29 +87,6 @@ const ROOT_WORKLOADS_PATH = buildWorkloadsPath();const STORAGE_PATH = buildStoragePath();const RECOVERY_ROUTE_PATH = buildRecoveryPath();-// Enhanced store type with proper typing-type EnhancedStore = ReturnType<typeof getGlobalWebSocketStore>;--// Export WebSocket context for other components-export const WebSocketContext = createContext<EnhancedStore>();-export const useWebSocket = () => {- const context = useContext(WebSocketContext);- if (!context) {- throw new Error('useWebSocket must be used within WebSocketContext.Provider');- }- return context;-};--// Dark mode context for reactive theme switching-export const DarkModeContext = createContext<() => boolean>();-export const useDarkMode = () => {- const context = useContext(DarkModeContext);- if (!context) {- throw new Error('useDarkMode must be used within DarkModeContext.Provider');- }- return context;-};-// Helper to detect if an update is actively in progress (not just checking for updates)function isUpdateInProgress(status: string | undefined): boolean {if (!status) return false;@@ -121,7 +96,7 @@ function isUpdateInProgress(status: string | undefined): boolean {// Global update progress watcher - shows modal in ALL tabs when an update is runningfunction GlobalUpdateProgressWatcher() {- const wsContext = useContext(WebSocketContext);+ const wsContext = useWebSocket();const navigate = useNavigate();const [showProgressModal, setShowProgressModal] = createSignal(false);const [hasAutoOpened, setHasAutoOpened] = createSignal(false);diff --git a/frontend-modern/src/__tests__/App.architecture.test.ts b/frontend-modern/src/__tests__/App.architecture.test.tsindex 76658d2b10..c3d32a91fa 100644--- a/frontend-modern/src/__tests__/App.architecture.test.ts+++ b/frontend-modern/src/__tests__/App.architecture.test.ts@@ -1,12 +1,16 @@import { describe, expect, it } from 'vitest';import appSource from '@/App.tsx?raw';import appLayoutSource from '@/AppLayout.tsx?raw';+import appRuntimeContextSource from '@/contexts/appRuntime.ts?raw';import appRuntimeStateSource from '@/useAppRuntimeState.ts?raw';describe('App architecture', () => {it('keeps App as the entry shell that delegates runtime and chrome ownership', () => {expect(appSource).toContain('DASHBOARD_PATH,');expect(appSource).toContain("import { AppLayout } from '@/AppLayout';");+ expect(appSource).toContain(+ "import { DarkModeContext, WebSocketContext, useWebSocket } from '@/contexts/appRuntime';",+ );expect(appSource).toContain("import { useAppRuntimeState } from '@/useAppRuntimeState';");expect(appSource).toContain("import {");expect(appSource).toContain("} from '@/utils/appShellScrollRestoration';");@@ -25,6 +29,8 @@ describe('App architecture', () => {);expect(appSource).not.toContain('function ConnectionStatusBadge(');expect(appSource).not.toContain('function AppLayout(');+ expect(appSource).not.toContain('export const WebSocketContext = createContext<');+ expect(appSource).not.toContain('export const DarkModeContext = createContext<');expect(appSource).not.toContain('ActiveUseTrialNudge');expect(appSource).not.toContain('const [organizations, setOrganizations] = createSignal(');expect(appSource).not.toContain('const [themePreference, setThemePreference] =');@@ -67,5 +73,15 @@ describe('App architecture', () => {expect(appRuntimeStateSource).not.toContain("import { startMetricsCollector } from '@/stores/metricsCollector';");expect(appRuntimeStateSource).not.toContain('startMetricsCollector();');expect(appRuntimeStateSource).not.toContain('function AppLayout(');+ expect(appRuntimeContextSource).toContain(+ "import { createContext, useContext } from 'solid-js';",+ );+ expect(appRuntimeContextSource).toContain(+ 'export const WebSocketContext = createContext<WebSocketStore>();',+ );+ expect(appRuntimeContextSource).toContain('export const useWebSocket = () => {');+ expect(appRuntimeContextSource).toContain(+ 'export const DarkModeContext = createContext<() => boolean>();',+ );});});diff --git a/frontend-modern/src/components/Dashboard/__tests__/Dashboard.k8s.test.tsx b/frontend-modern/src/components/Dashboard/__tests__/Dashboard.k8s.test.tsxindex 03d5e5d63c..e1cb2aa444 100644--- a/frontend-modern/src/components/Dashboard/__tests__/Dashboard.k8s.test.tsx+++ b/frontend-modern/src/components/Dashboard/__tests__/Dashboard.k8s.test.tsx@@ -64,7 +64,7 @@ vi.mock('@solidjs/router', async () => {};});-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({connected: () => true,activeAlerts: () => ({}),diff --git a/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx b/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsxindex 3db59b4515..a92d9b4c85 100644--- a/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx+++ b/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx@@ -96,7 +96,7 @@ vi.mock('@solidjs/router', async () => {};});-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({connected: () => wsConnected,activeAlerts: () => ({}),diff --git a/frontend-modern/src/components/Dashboard/useDashboardState.ts b/frontend-modern/src/components/Dashboard/useDashboardState.tsindex dfc7033451..4c6bc814c9 100644--- a/frontend-modern/src/components/Dashboard/useDashboardState.ts+++ b/frontend-modern/src/components/Dashboard/useDashboardState.ts@@ -2,7 +2,7 @@ import { createEffect, createMemo } from 'solid-js';import { useNavigate } from '@solidjs/router';import type { VM, Container, Node } from '@/types/api';import type { WorkloadGuest } from '@/types/workloads';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { useAlertsActivation } from '@/stores/alertsActivation';import { usePersistentSignal } from '@/hooks/usePersistentSignal';import { useWorkloads } from '@/hooks/useWorkloads';diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsxindex 2f93ed8f62..deb72438b5 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx@@ -55,7 +55,7 @@ const aiIntelligenceMock = vi.hoisted(() => ({}),}));-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: { pmg: [] as any[] },connected: () => true,diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsxindex 669269770f..d67b2021fb 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx@@ -10,7 +10,7 @@ import {const wsState = vi.hoisted(() => ({ pmg: [] as any[] }));const reconnectSpy = vi.hoisted(() => vi.fn());-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: wsState,connected: () => true,diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsxindex 257ee4f4dd..223d574ee4 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsx@@ -7,7 +7,7 @@ import { ResourceDetailDrawer } from '@/components/Infrastructure/ResourceDetailconst wsState = vi.hoisted(() => ({ pmg: [] as any[] }));const reconnectSpy = vi.hoisted(() => vi.fn());-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: wsState,connected: () => true,diff --git a/frontend-modern/src/components/PMG/MailGateway.tsx b/frontend-modern/src/components/PMG/MailGateway.tsxindex 9d00b431c1..e62761c890 100644--- a/frontend-modern/src/components/PMG/MailGateway.tsx+++ b/frontend-modern/src/components/PMG/MailGateway.tsx@@ -1,7 +1,7 @@import { Component, Show, For, createMemo, createSignal } from 'solid-js';import { useTooltip } from '@/hooks/useTooltip';import { TooltipPortal } from '@/components/shared/TooltipPortal';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { Card } from '@/components/shared/Card';import {Table,diff --git a/frontend-modern/src/components/Recovery/RecoveryPointDetails.test.tsx b/frontend-modern/src/components/Recovery/RecoveryPointDetails.test.tsxindex 6b9e902b83..6001967905 100644--- a/frontend-modern/src/components/Recovery/RecoveryPointDetails.test.tsx+++ b/frontend-modern/src/components/Recovery/RecoveryPointDetails.test.tsx@@ -6,7 +6,7 @@ import { RecoveryPointDetails } from './RecoveryPointDetails';const wsState = vi.hoisted(() => ({ resources: [] as Resource[] }));-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: wsState,}),diff --git a/frontend-modern/src/components/Recovery/RecoveryPointDetails.tsx b/frontend-modern/src/components/Recovery/RecoveryPointDetails.tsxindex 148b39caec..c61b4b5679 100644--- a/frontend-modern/src/components/Recovery/RecoveryPointDetails.tsx+++ b/frontend-modern/src/components/Recovery/RecoveryPointDetails.tsx@@ -1,6 +1,6 @@import type { Component } from 'solid-js';import { For, Show, createMemo, createSignal } from 'solid-js';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { getSourcePlatformBadge } from '@/components/shared/sourcePlatformBadges';import type { PBSDatastore } from '@/types/api';import type { RecoveryExternalRef, RecoveryPoint } from '@/types/recovery';diff --git a/frontend-modern/src/components/Recovery/__tests__/Recovery.test.tsx b/frontend-modern/src/components/Recovery/__tests__/Recovery.test.tsxindex 9c26a8ad94..f3265d838c 100644--- a/frontend-modern/src/components/Recovery/__tests__/Recovery.test.tsx+++ b/frontend-modern/src/components/Recovery/__tests__/Recovery.test.tsx@@ -99,7 +99,7 @@ vi.mock('@/utils/apiClient', () => ({apiFetchJSON: apiFetchMock,}));-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: wsState,}),diff --git a/frontend-modern/src/components/Settings/Settings.tsx b/frontend-modern/src/components/Settings/Settings.tsxindex 511a319d5c..4d2f2f0578 100644--- a/frontend-modern/src/components/Settings/Settings.tsx+++ b/frontend-modern/src/components/Settings/Settings.tsx@@ -1,7 +1,7 @@import { Component, createSignal, onMount, Show, Suspense, createMemo } from 'solid-js';import { Dynamic } from 'solid-js/web';import { useNavigate, useLocation } from '@solidjs/router';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { SettingsDialogs } from './SettingsDialogs';import { SettingsPageShell } from './SettingsPageShell';import { eventBus } from '@/stores/events';diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsxindex 8abe86a091..6eeb8550f2 100644--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx@@ -54,7 +54,7 @@ vi.mock('@/utils/url', () => ({getPulseBaseUrl: () => 'https://pulse.example.com',}));-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({markDockerRuntimesTokenRevoked: (...args: unknown[]) =>markDockerRuntimesTokenRevokedMock(...args),diff --git a/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsxindex ecb4725746..4e551aa6b6 100644--- a/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AgentProfilesPanel.test.tsx@@ -24,7 +24,7 @@ vi.mock('@/hooks/useResources', () => ({}),}));-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => mockWsStore,}));diff --git a/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsController.test.tsx b/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsController.test.tsxindex 615cb37c74..7e187bc61c 100644--- a/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsController.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsController.test.tsx@@ -219,7 +219,7 @@ describe('InfrastructurePlatformConnectionsSummaryCard', () => {});});-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => mockWsStore,}));diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex d0d227f9d2..b5f60cff08 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -392,6 +392,15 @@ const canonicalShellTitleExpectations = [] as const;describe('Settings architecture guardrails', () => {+ it('keeps shell-level runtime hooks on the shared app runtime context', () => {+ expect(settingsSource).toContain("from '@/contexts/appRuntime'");+ expect(settingsSource).not.toContain("from '@/App'");+ expect(apiTokenManagerStateSource).toContain("from '@/contexts/appRuntime'");+ expect(apiTokenManagerStateSource).not.toContain("from '@/App'");+ expect(infrastructureReportingStateSource).toContain("from '@/contexts/appRuntime'");+ expect(infrastructureReportingStateSource).not.toContain("from '@/App'");+ });+it('keeps extracted settings modules present on disk', () => {const settingsModuleFiles = {...import.meta.glob('../*.ts'),diff --git a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts b/frontend-modern/src/components/Settings/useAPITokenManagerState.tsindex 291a2bd272..00664a37a4 100644--- a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts+++ b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts@@ -7,7 +7,7 @@ import {} from 'solid-js';import type { APITokenRecord } from '@/api/security';import { SecurityAPI } from '@/api/security';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { MONITORING_READ_SCOPE, API_SCOPE_LABELS } from '@/constants/apiScopes';import { useResources } from '@/hooks/useResources';import { notificationStore } from '@/stores/notifications';diff --git a/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts b/frontend-modern/src/components/Settings/useAgentProfilesPanelState.tsindex 203450f451..715a3cc8ff 100644--- a/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts+++ b/frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts@@ -1,5 +1,5 @@import { createEffect, createMemo, createSignal, onMount } from 'solid-js';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { AIAPI } from '@/api/ai';import {AgentProfilesAPI,diff --git a/frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx b/frontend-modern/src/components/Settings/useInfrastructureReportingState.tsxindex 953b60afb9..1bad916b82 100644--- a/frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx+++ b/frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx@@ -1,5 +1,5 @@import { createEffect, createMemo, createSignal, For, onMount, Show } from 'solid-js';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import {MonitoringAPI,type RemovedDockerHost,diff --git a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsxindex f8720ff43e..4f9ce2c753 100644--- a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx+++ b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx@@ -250,7 +250,7 @@ vi.mock('@solidjs/router', async () => {};});-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: wsState,activeAlerts: wsActiveAlerts,diff --git a/frontend-modern/src/components/Storage/useStoragePageResources.ts b/frontend-modern/src/components/Storage/useStoragePageResources.tsindex a324bf3bc0..53ed5af570 100644--- a/frontend-modern/src/components/Storage/useStoragePageResources.ts+++ b/frontend-modern/src/components/Storage/useStoragePageResources.ts@@ -1,5 +1,5 @@import { createMemo } from 'solid-js';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { useResources } from '@/hooks/useResources';import { useStorageRecoveryResources } from '@/hooks/useUnifiedResources';import { useAlertsActivation } from '@/stores/alertsActivation';diff --git a/frontend-modern/src/components/shared/TagBadges.tsx b/frontend-modern/src/components/shared/TagBadges.tsxindex 4f13dabf98..fdfc45672d 100644--- a/frontend-modern/src/components/shared/TagBadges.tsx+++ b/frontend-modern/src/components/shared/TagBadges.tsx@@ -1,6 +1,6 @@import { Component, For, Show } from 'solid-js';import { getTagColorWithSpecial } from '@/utils/tagColors';-import { useDarkMode } from '@/App';+import { useDarkMode } from '@/contexts/appRuntime';import { showTooltip, hideTooltip } from '@/components/shared/Tooltip';interface TagBadgesProps {diff --git a/frontend-modern/src/components/shared/__tests__/InfrastructureSummaryTable.test.tsx b/frontend-modern/src/components/shared/__tests__/InfrastructureSummaryTable.test.tsxindex 7940477075..36a93b42cc 100644--- a/frontend-modern/src/components/shared/__tests__/InfrastructureSummaryTable.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/InfrastructureSummaryTable.test.tsx@@ -19,7 +19,7 @@ if (typeof globalThis.ResizeObserver === 'undefined') {} as unknown as typeof ResizeObserver;}-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({activeAlerts: [],}),diff --git a/frontend-modern/src/components/shared/__tests__/TagBadges.test.tsx b/frontend-modern/src/components/shared/__tests__/TagBadges.test.tsxindex 94177baa59..dd8e0c5eff 100644--- a/frontend-modern/src/components/shared/__tests__/TagBadges.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/TagBadges.test.tsx@@ -12,7 +12,7 @@ const { darkModeMock, showTooltipMock, hideTooltipMock } = vi.hoisted(() => {// ── Module mocks ───────────────────────────────────────────────────────-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useDarkMode: () => darkModeMock,}));diff --git a/frontend-modern/src/components/shared/useInfrastructureSummaryTableState.ts b/frontend-modern/src/components/shared/useInfrastructureSummaryTableState.tsindex 215ed712d3..3c30be876d 100644--- a/frontend-modern/src/components/shared/useInfrastructureSummaryTableState.ts+++ b/frontend-modern/src/components/shared/useInfrastructureSummaryTableState.ts@@ -1,5 +1,5 @@import { createMemo, createSignal } from 'solid-js';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { useBreakpoint } from '@/hooks/useBreakpoint';import { useAlertsActivation } from '@/stores/alertsActivation';import {diff --git a/frontend-modern/src/contexts/appRuntime.ts b/frontend-modern/src/contexts/appRuntime.tsnew file mode 100644index 0000000000..c855adfd16--- /dev/null+++ b/frontend-modern/src/contexts/appRuntime.ts@@ -0,0 +1,24 @@+import { createContext, useContext } from 'solid-js';+import { getGlobalWebSocketStore } from '@/stores/websocket-global';++export type WebSocketStore = ReturnType<typeof getGlobalWebSocketStore>;++export const WebSocketContext = createContext<WebSocketStore>();++export const useWebSocket = () => {+ const context = useContext(WebSocketContext);+ if (!context) {+ throw new Error('useWebSocket must be used within WebSocketContext.Provider');+ }+ return context;+};++export const DarkModeContext = createContext<() => boolean>();++export const useDarkMode = () => {+ const context = useContext(DarkModeContext);+ if (!context) {+ throw new Error('useDarkMode must be used within DarkModeContext.Provider');+ }+ return context;+};diff --git a/frontend-modern/src/features/alerts/__tests__/HistoryTab.test.tsx b/frontend-modern/src/features/alerts/__tests__/HistoryTab.test.tsxindex 74d693830e..039bfa6911 100644--- a/frontend-modern/src/features/alerts/__tests__/HistoryTab.test.tsx+++ b/frontend-modern/src/features/alerts/__tests__/HistoryTab.test.tsx@@ -9,7 +9,7 @@ vi.mock('@solidjs/router', () => ({}),}));-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({activeAlerts: {},}),diff --git a/frontend-modern/src/features/alerts/tabs/HistoryTab.tsx b/frontend-modern/src/features/alerts/tabs/HistoryTab.tsxindex ba83b79919..ade7012eaa 100644--- a/frontend-modern/src/features/alerts/tabs/HistoryTab.tsx+++ b/frontend-modern/src/features/alerts/tabs/HistoryTab.tsx@@ -2,7 +2,7 @@ import { createSignal, onCleanup, createEffect } from 'solid-js';import { useLocation } from '@solidjs/router';import type { Resource } from '@/types/resource';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { useBreakpoint } from '@/hooks/useBreakpoint';import { AlertHistoryAdministrationCard } from '../AlertHistoryAdministrationCard';diff --git a/frontend-modern/src/pages/Alerts.tsx b/frontend-modern/src/pages/Alerts.tsxindex 2116eeb24f..4ce312a140 100644--- a/frontend-modern/src/pages/Alerts.tsx+++ b/frontend-modern/src/pages/Alerts.tsx@@ -16,7 +16,7 @@ import { SectionHeader } from '@/components/shared/SectionHeader';import { notificationStore } from '@/stores/notifications';import Calendar from 'lucide-solid/icons/calendar';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { useResources } from '@/hooks/useResources';import { aiChatStore } from '@/stores/aiChat';import { trackPaywallViewed } from '@/utils/upgradeMetrics';diff --git a/frontend-modern/src/pages/Ceph.tsx b/frontend-modern/src/pages/Ceph.tsxindex 22f8966e72..6878d88dd2 100644--- a/frontend-modern/src/pages/Ceph.tsx+++ b/frontend-modern/src/pages/Ceph.tsx@@ -1,6 +1,6 @@import { Component, For, Show, createMemo, createSignal } from 'solid-js';import { Portal } from 'solid-js/web';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { useResources } from '@/hooks/useResources';import { Card } from '@/components/shared/Card';import {diff --git a/frontend-modern/src/pages/Dashboard.tsx b/frontend-modern/src/pages/Dashboard.tsxindex fe2028fb41..af6580047a 100644--- a/frontend-modern/src/pages/Dashboard.tsx+++ b/frontend-modern/src/pages/Dashboard.tsx@@ -9,7 +9,7 @@ import {onCleanup,} from 'solid-js';import { useNavigate } from '@solidjs/router';-import { useWebSocket } from '@/App';+import { useWebSocket } from '@/contexts/appRuntime';import { buildInfrastructureWorkspacePath } from '@/components/Settings/infrastructureWorkspaceModel';import { useUnifiedResources } from '@/hooks/useUnifiedResources';import { useDashboardOverview } from '@/hooks/useDashboardOverview';diff --git a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.tsindex 7066650608..225137d0b5 100644--- a/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts+++ b/frontend-modern/src/pages/__tests__/Alerts.helpers.test.ts@@ -608,6 +608,13 @@ describe('tab path helpers', () => {);expect(thresholdsOverrideMutationModelSource).toContain('export const stripStateKeys =');});++ it('keeps alerts websocket access on the shared app runtime context', () => {+ expect(alertsPageSource).toContain("from '@/contexts/appRuntime'");+ expect(alertsPageSource).not.toContain("from '@/App'");+ expect(alertHistoryTabSource).toContain("from '@/contexts/appRuntime'");+ expect(alertHistoryTabSource).not.toContain("from '@/App'");+ });});describe('default schedule helpers', () => {@@ -987,7 +994,7 @@ describe('Unified selector parity', () => {['docker-host', 'Container Runtime'],['k8s-cluster', 'K8s Cluster'],['k8s-node', 'K8s Node'],- ['truenas', 'TrueNAS'],+ ['truenas', 'Agent'],['vm', 'VM'],['system-container', 'Container'],['oci-container', 'Container'],diff --git a/frontend-modern/src/pages/__tests__/DashboardPage.test.tsx b/frontend-modern/src/pages/__tests__/DashboardPage.test.tsxindex 3002f82636..e4004a69f4 100644--- a/frontend-modern/src/pages/__tests__/DashboardPage.test.tsx+++ b/frontend-modern/src/pages/__tests__/DashboardPage.test.tsx@@ -54,7 +54,7 @@ const overviewMock: DashboardOverview = {problemResources: [],};-vi.mock('@/App', () => ({+vi.mock('@/contexts/appRuntime', () => ({useWebSocket: () => ({state: { resources: [] },activeAlerts: {},diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex 9dd80e5d2e..344a0c4c19 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -336,17 +336,27 @@ func TestAISettingsHandler_UpdateSettings_QuickstartRequiresActivationBeforeEnabassert.Contains(t, rec.Body.String(), ai.QuickstartActivationRequiredReason())}-func TestAISettingsHandler_UpdateSettings_QuickstartBootstrapBeforeEnable(t *testing.T) {+func TestAISettingsHandler_UpdateSettings_QuickstartBootstrapBeforeEnableUsesActivationIdentity(t *testing.T) {tmp := t.TempDir()cfg := &config.Config{DataPath: tmp}persistence := config.NewConfigPersistence(tmp)- handler := newTestAISettingsHandler(cfg, persistence, nil)+ persistQuickstartActivationState(t, persistence)+ useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {+ assert.Equal(t, "Bearer pit_live_test", strings.TrimSpace(r.Header.Get("Authorization")))+ instanceFingerprint, _ := reqBody["instance_fingerprint"].(string)+ assert.Equal(t, "fp-live-test", instanceFingerprint)+ assert.Equal(t, "patrol", reqBody["use_case"])+ })- quickstartMgr := &stubQuickstartCreditManager{- remaining: 25,- total: 25,- }- handler.defaultAIService.SetQuickstartCredits(quickstartMgr)+ handler := newTestAISettingsHandler(cfg, persistence, nil)+ handler.defaultAIService.SetQuickstartCredits(ai.NewPersistentQuickstartCreditManager(+ persistence,+ "default",+ func() *config.AIConfig {+ cfg, _ := persistence.LoadAIConfig()+ return cfg+ },+ ))body, _ := json.Marshal(AISettingsUpdateRequest{Enabled: ptr(true),@@ -361,6 +371,7 @@ func TestAISettingsHandler_UpdateSettings_QuickstartBootstrapBeforeEnable(t *tesrequire.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))assert.True(t, resp.Enabled)assert.Equal(t, config.DefaultModelForProvider(config.AIProviderQuickstart), resp.Model)+ assert.True(t, resp.UsingQuickstart)assert.Equal(t, 25, resp.QuickstartCreditsRemaining)assert.Equal(t, 25, resp.QuickstartCreditsTotal)}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 7bf47f32c3..6d1b8844ef 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -126,6 +126,202 @@ func TestContract_AIQuickstartPayloadFieldsRemainCanonical(t *testing.T) {}}+func TestContract_AISettingsUpdateQuickstartBootstrapJSONSnapshot(t *testing.T) {+ tmp := t.TempDir()+ cfg := &config.Config{DataPath: tmp}+ persistence := config.NewConfigPersistence(tmp)+ persistQuickstartActivationState(t, persistence)+ useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {+ if got := strings.TrimSpace(r.Header.Get("Authorization")); got != "Bearer pit_live_test" {+ t.Fatalf("authorization=%q want Bearer pit_live_test", got)+ }+ instanceFingerprint, _ := reqBody["instance_fingerprint"].(string)+ if instanceFingerprint != "fp-live-test" {+ t.Fatalf("instance_fingerprint=%q want fp-live-test", instanceFingerprint)+ }+ if reqBody["use_case"] != "patrol" {+ t.Fatalf("use_case=%v want patrol", reqBody["use_case"])+ }+ })+ handler := newTestAISettingsHandler(cfg, persistence, nil)+ handler.defaultAIService.SetQuickstartCredits(ai.NewPersistentQuickstartCreditManager(+ persistence,+ "default",+ func() *config.AIConfig {+ cfg, _ := persistence.LoadAIConfig()+ return cfg+ },+ ))++ req := httptest.NewRequest(http.MethodPut, "/api/settings/ai/update", strings.NewReader(`{+ "enabled": true+ }`))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())+ }++ const want = `{+ "enabled":true,+ "model":"quickstart:minimax-2.5m",+ "chat_model":"quickstart:minimax-2.5m",+ "patrol_model":"quickstart:minimax-2.5m",+ "configured":true,+ "custom_context":"",+ "auth_method":"api_key",+ "oauth_connected":false,+ "patrol_interval_minutes":360,+ "patrol_enabled":true,+ "patrol_auto_fix":false,+ "alert_triggered_analysis":true,+ "patrol_event_triggers_enabled":true,+ "patrol_alert_triggers_enabled":true,+ "patrol_anomaly_triggers_enabled":true,+ "use_proactive_thresholds":false,+ "available_models":[],+ "anthropic_configured":false,+ "openai_configured":false,+ "openrouter_configured":false,+ "deepseek_configured":false,+ "gemini_configured":false,+ "ollama_configured":false,+ "ollama_base_url":"http://localhost:11434",+ "ollama_password_set":false,+ "configured_providers":[],+ "control_level":"read_only",+ "protected_guests":[],+ "discovery_enabled":false,+ "quickstart_credits_total":25,+ "quickstart_credits_used":0,+ "quickstart_credits_remaining":25,+ "quickstart_credits_available":true,+ "using_quickstart":true+ }`++ assertJSONSnapshot(t, rec.Body.Bytes(), want)+}++func TestContract_PatrolStatusActivationRequiredSurface(t *testing.T) {+ handler, _, _, _ := setupAIHandlerWithPatrol(t)+ persistence := handler.defaultPersistence+ aiCfg := config.NewDefaultAIConfig()+ aiCfg.Enabled = true+ if err := persistence.SaveAIConfig(*aiCfg); err != nil {+ t.Fatalf("SaveAIConfig: %v", err)+ }++ handler.defaultAIService.SetQuickstartCredits(ai.NewPersistentQuickstartCreditManager(+ persistence,+ "default",+ func() *config.AIConfig {+ cfg, _ := persistence.LoadAIConfig()+ return cfg+ },+ ))+ if err := handler.defaultAIService.LoadConfig(); err != nil {+ t.Fatalf("LoadConfig: %v", err)+ }++ req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/status", nil)+ rec := httptest.NewRecorder()+ handler.HandleGetPatrolStatus(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())+ }++ var resp PatrolStatusResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode patrol status: %v", err)+ }+ if resp.RuntimeState != ai.PatrolRuntimeStateBlocked {+ t.Fatalf("runtime_state=%q want %q", resp.RuntimeState, ai.PatrolRuntimeStateBlocked)+ }+ if !resp.Enabled {+ t.Fatal("expected patrol status to remain enabled while activation is required")+ }+ if resp.Healthy {+ t.Fatal("expected activation-required patrol status to report healthy=false")+ }+ if resp.BlockedReason != ai.QuickstartActivationRequiredReason() {+ t.Fatalf("blocked_reason=%q want %q", resp.BlockedReason, ai.QuickstartActivationRequiredReason())+ }+ if resp.QuickstartCreditsRemaining != 0 || resp.QuickstartCreditsTotal != 0 {+ t.Fatalf("quickstart credits=%d/%d want 0/0", resp.QuickstartCreditsRemaining, resp.QuickstartCreditsTotal)+ }+ if resp.UsingQuickstart {+ t.Fatal("expected using_quickstart=false while activation is required")+ }+}++func TestContract_AISettingsBYOKOverrideRetainsQuickstartInventoryJSONSnapshot(t *testing.T) {+ tmp := t.TempDir()+ cfg := &config.Config{DataPath: tmp}+ persistence := config.NewConfigPersistence(tmp)++ aiCfg := config.NewDefaultAIConfig()+ aiCfg.Enabled = true+ aiCfg.Model = "openai:gpt-4o"+ aiCfg.OpenAIAPIKey = "sk-openai-test"+ if err := persistence.SaveAIConfig(*aiCfg); err != nil {+ t.Fatalf("SaveAIConfig: %v", err)+ }++ handler := newTestAISettingsHandler(cfg, persistence, nil)+ handler.defaultAIService.SetQuickstartCredits(&stubQuickstartCreditManager{+ remaining: 12,+ total: pkglicensing.QuickstartCreditsTotal,+ })++ req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ rec := httptest.NewRecorder()+ handler.HandleGetAISettings(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())+ }++ const want = `{+ "enabled":true,+ "model":"openai:gpt-4o",+ "configured":true,+ "custom_context":"",+ "auth_method":"api_key",+ "oauth_connected":false,+ "patrol_interval_minutes":360,+ "patrol_enabled":true,+ "patrol_auto_fix":false,+ "alert_triggered_analysis":true,+ "patrol_event_triggers_enabled":true,+ "patrol_alert_triggers_enabled":true,+ "patrol_anomaly_triggers_enabled":true,+ "use_proactive_thresholds":false,+ "available_models":[],+ "anthropic_configured":false,+ "openai_configured":true,+ "openrouter_configured":false,+ "deepseek_configured":false,+ "gemini_configured":false,+ "ollama_configured":false,+ "ollama_base_url":"http://localhost:11434",+ "ollama_password_set":false,+ "configured_providers":["openai"],+ "control_level":"read_only",+ "protected_guests":[],+ "discovery_enabled":false,+ "quickstart_credits_total":25,+ "quickstart_credits_used":13,+ "quickstart_credits_remaining":12,+ "quickstart_credits_available":true,+ "using_quickstart":false+ }`++ assertJSONSnapshot(t, rec.Body.Bytes(), want)+}+func TestContract_ChartMetricPointsPreserveMillisecondPrecision(t *testing.T) {pointTime := time.Date(2026, time.March, 31, 12, 0, 0, 987_000_000, time.UTC)diff --git a/tests/integration/tests/18-patrol-runtime-state.spec.ts b/tests/integration/tests/18-patrol-runtime-state.spec.tsindex 85ce407920..aaf73097f0 100644--- a/tests/integration/tests/18-patrol-runtime-state.spec.ts+++ b/tests/integration/tests/18-patrol-runtime-state.spec.ts@@ -494,7 +494,7 @@ test.describe("Patrol runtime-state browser contract", () => {await expect(page.getByRole("button", { name: "Run Patrol" }),).toBeDisabled();- await expect(page.getByText(/Credits exhausted/)).toBeVisible();+ await expect(page.getByText("Patrol quickstart exhausted")).toBeVisible();await expect(page.getByText("Health A · 100/100")).toHaveCount(0);});diff --git a/tests/integration/tests/51-quickstart-cross-surface.spec.ts b/tests/integration/tests/51-quickstart-cross-surface.spec.tsnew file mode 100644index 0000000000..c657022485--- /dev/null+++ b/tests/integration/tests/51-quickstart-cross-surface.spec.ts@@ -0,0 +1,661 @@+import { expect, test, type Page } from "@playwright/test";++import { ensureAuthenticated } from "./helpers";++const QUICKSTART_EXHAUSTED_REASON =+ "Quickstart credits exhausted. Connect your API key to continue using AI Patrol.";+const QUICKSTART_ACTIVATION_REQUIRED_REASON =+ "Activate this install or start a trial to use AI Patrol quickstart. Otherwise connect your API key.";+const QUICKSTART_OFFLINE_REASON =+ "Quickstart credits require internet access. Connect your API key for offline AI Patrol.";++type AISettingsPayload = {+ enabled: boolean;+ model: string;+ chat_model?: string;+ patrol_model?: string;+ configured: boolean;+ custom_context: string;+ auth_method: string;+ oauth_connected: boolean;+ patrol_interval_minutes: number;+ patrol_enabled: boolean;+ patrol_auto_fix: boolean;+ alert_triggered_analysis: boolean;+ patrol_event_triggers_enabled: boolean;+ patrol_alert_triggers_enabled: boolean;+ patrol_anomaly_triggers_enabled: boolean;+ use_proactive_thresholds: boolean;+ available_models: Array<{ id: string; name: string }>;+ anthropic_configured: boolean;+ openai_configured: boolean;+ openrouter_configured: boolean;+ deepseek_configured: boolean;+ gemini_configured: boolean;+ ollama_configured: boolean;+ ollama_base_url: string;+ ollama_password_set: boolean;+ configured_providers: string[];+ control_level: string;+ protected_guests: string[];+ discovery_enabled: boolean;+ quickstart_credits_total: number;+ quickstart_credits_used: number;+ quickstart_credits_remaining: number;+ quickstart_credits_available: boolean;+ using_quickstart: boolean;+};++type PatrolStatusPayload = {+ runtime_state: string;+ running: boolean;+ enabled: boolean;+ last_patrol_at: string;+ next_patrol_at: string;+ last_duration_ms: number;+ resources_checked: number;+ findings_count: number;+ error_count: number;+ healthy: boolean;+ interval_ms: number;+ fixed_count: number;+ blocked_reason: string;+ blocked_at: string;+ license_required: boolean;+ license_status: string;+ summary: {+ critical: number;+ warning: number;+ watch: number;+ info: number;+ };+ using_quickstart: boolean;+ quickstart_credits_total: number;+ quickstart_credits_remaining: number;+};++type PatrolSurfaceOverrides = {+ settings?: Partial<AISettingsPayload>;+ patrolStatus?: Partial<PatrolStatusPayload>;+ intelligenceSummary?: Record<string, unknown>;+};++const baseAISettings = (): AISettingsPayload => ({+ enabled: true,+ model: "quickstart:minimax-2.5m",+ chat_model: "quickstart:minimax-2.5m",+ patrol_model: "quickstart:minimax-2.5m",+ configured: true,+ custom_context: "",+ auth_method: "api_key",+ oauth_connected: false,+ patrol_interval_minutes: 360,+ patrol_enabled: true,+ patrol_auto_fix: false,+ alert_triggered_analysis: true,+ patrol_event_triggers_enabled: true,+ patrol_alert_triggers_enabled: true,+ patrol_anomaly_triggers_enabled: true,+ use_proactive_thresholds: false,+ available_models: [],+ anthropic_configured: false,+ openai_configured: false,+ openrouter_configured: false,+ deepseek_configured: false,+ gemini_configured: false,+ ollama_configured: false,+ ollama_base_url: "http://localhost:11434",+ ollama_password_set: false,+ configured_providers: [],+ control_level: "read_only",+ protected_guests: [],+ discovery_enabled: false,+ quickstart_credits_total: 25,+ quickstart_credits_used: 0,+ quickstart_credits_remaining: 25,+ quickstart_credits_available: true,+ using_quickstart: true,+});++const basePatrolStatus = (): PatrolStatusPayload => ({+ runtime_state: "active",+ running: false,+ enabled: true,+ last_patrol_at: "2026-03-25T08:55:00Z",+ next_patrol_at: "2026-03-25T14:55:00Z",+ last_duration_ms: 42000,+ resources_checked: 24,+ findings_count: 0,+ error_count: 0,+ healthy: true,+ interval_ms: 21600000,+ fixed_count: 0,+ blocked_reason: "",+ blocked_at: "",+ license_required: false,+ license_status: "active",+ summary: {+ critical: 0,+ warning: 0,+ watch: 0,+ info: 0,+ },+ using_quickstart: true,+ quickstart_credits_total: 25,+ quickstart_credits_remaining: 25,+});++const healthyIntelligenceSummary = () => ({+ timestamp: "2026-03-25T09:05:00Z",+ overall_health: {+ score: 100,+ grade: "A",+ trend: "stable",+ factors: [],+ prediction: "Infrastructure is healthy with no significant issues detected.",+ },+ findings_count: {+ critical: 0,+ warning: 0,+ watch: 0,+ info: 0,+ total: 0,+ },+ predictions_count: 0,+ recent_changes_count: 0,+ recent_changes: [],+ learning: {+ resources_with_knowledge: 0,+ total_notes: 0,+ resources_with_baselines: 0,+ patterns_detected: 0,+ correlations_learned: 0,+ incidents_tracked: 0,+ },+});++const baseRunHistory = () => [+ {+ id: "run-healthy-before-quickstart",+ started_at: "2026-03-25T08:55:00Z",+ completed_at: "2026-03-25T08:55:42Z",+ duration_ms: 42000,+ type: "full",+ trigger_reason: "scheduled",+ resources_checked: 24,+ nodes_checked: 2,+ guests_checked: 8,+ docker_checked: 4,+ storage_checked: 3,+ hosts_checked: 2,+ pbs_checked: 1,+ pmg_checked: 0,+ kubernetes_checked: 4,+ new_findings: 0,+ existing_findings: 0,+ rejected_findings: 0,+ resolved_findings: 0,+ auto_fix_count: 0,+ findings_summary: "No active findings",+ finding_ids: [],+ error_count: 0,+ status: "healthy",+ triage_flags: 0,+ tool_call_count: 0,+ },+];++function clone<T>(value: T): T {+ return JSON.parse(JSON.stringify(value)) as T;+}++async function browserApiRequest(+ page: Page,+ endpoint: string,+ method = "GET",+ data?: Record<string, unknown>,+): Promise<{ ok: boolean; status: number; body: unknown }> {+ return page.evaluate(+ async ({ endpoint: path, method: httpMethod, data: requestBody }) => {+ const headers: Record<string, string> = {};+ if (requestBody !== undefined) {+ headers["Content-Type"] = "application/json";+ }+ if (!["GET", "HEAD", "OPTIONS"].includes(httpMethod)) {+ const csrf = document.cookie+ .split("; ")+ .find((cookie) => cookie.startsWith("pulse_csrf="))+ ?.split("=")[1];+ if (csrf) {+ headers["X-CSRF-Token"] = decodeURIComponent(csrf);+ }+ }++ const response = await fetch(path, {+ method: httpMethod,+ headers,+ body: requestBody === undefined ? undefined : JSON.stringify(requestBody),+ });+ const text = await response.text();+ let body: unknown = text;+ if (text) {+ try {+ body = JSON.parse(text);+ } catch {+ body = text;+ }+ }+ return { ok: response.ok, status: response.status, body };+ },+ { endpoint, method, data },+ );+}++async function mockQuickstartPatrolSurface(page: Page, overrides: PatrolSurfaceOverrides = {}) {+ const settings = {+ ...baseAISettings(),+ ...clone(overrides.settings ?? {}),+ };+ const patrolStatus = {+ ...basePatrolStatus(),+ ...clone(overrides.patrolStatus ?? {}),+ };+ const intelligenceSummary = {+ ...healthyIntelligenceSummary(),+ ...clone(overrides.intelligenceSummary ?? {}),+ };+ const runHistory = baseRunHistory();+ const updateRequests: Array<Record<string, unknown>> = [];+ const patrolRunRequests: Array<Record<string, unknown>> = [];++ await page.route("**/api/settings/ai", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(settings),+ });+ });++ await page.route("**/api/settings/ai/update", async (route) => {+ const body = (route.request().postDataJSON() as Record<string, unknown> | null) ?? {};+ updateRequests.push(body);++ if (typeof body.enabled === "boolean") {+ settings.enabled = body.enabled;+ settings.patrol_enabled = body.enabled;+ patrolStatus.enabled = body.enabled;+ if (body.enabled && settings.quickstart_credits_available && settings.configured_providers.length === 0) {+ settings.configured = true;+ settings.model = "quickstart:minimax-2.5m";+ settings.chat_model = "quickstart:minimax-2.5m";+ settings.patrol_model = "quickstart:minimax-2.5m";+ settings.using_quickstart = true;+ patrolStatus.runtime_state = "active";+ patrolStatus.using_quickstart = true;+ patrolStatus.blocked_reason = "";+ patrolStatus.blocked_at = "";+ patrolStatus.healthy = true;+ }+ }++ if (typeof body.openai_api_key === "string" && body.openai_api_key.trim().length > 0) {+ settings.configured = true;+ settings.model = "openai:gpt-4o";+ settings.chat_model = "";+ settings.patrol_model = "";+ settings.openai_configured = true;+ settings.configured_providers = ["openai"];+ settings.using_quickstart = false;+ patrolStatus.using_quickstart = false;+ patrolStatus.runtime_state = "active";+ patrolStatus.blocked_reason = "";+ patrolStatus.blocked_at = "";+ patrolStatus.healthy = true;+ }++ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(settings),+ });+ });++ await page.route("**/api/ai/patrol/status", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(patrolStatus),+ });+ });++ await page.route("**/api/ai/patrol/run", async (route) => {+ const body = (route.request().postDataJSON() as Record<string, unknown> | null) ?? {};+ patrolRunRequests.push(body);++ if (!patrolStatus.enabled || patrolStatus.runtime_state === "blocked") {+ await route.fulfill({+ status: 403,+ contentType: "application/json",+ body: JSON.stringify({ success: false, message: patrolStatus.blocked_reason }),+ });+ return;+ }++ if (patrolStatus.using_quickstart && patrolStatus.quickstart_credits_remaining > 0) {+ patrolStatus.quickstart_credits_remaining -= 1;+ settings.quickstart_credits_remaining = patrolStatus.quickstart_credits_remaining;+ settings.quickstart_credits_used =+ settings.quickstart_credits_total - patrolStatus.quickstart_credits_remaining;+ }++ runHistory.unshift({+ ...baseRunHistory()[0],+ id: `run-manual-${patrolRunRequests.length}`,+ started_at: "2026-03-25T09:15:00Z",+ completed_at: "2026-03-25T09:15:36Z",+ trigger_reason: "manual",+ });++ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ success: true, message: "Patrol started" }),+ });+ });++ await page.route("**/api/ai/patrol/runs*", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(runHistory),+ });+ });++ await page.route("**/api/ai/patrol/autonomy", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ autonomy_level: "monitor",+ full_mode_unlocked: false,+ investigation_budget: 15,+ investigation_timeout_sec: 300,+ }),+ });+ });++ await page.route("**/api/ai/models", async (route) => {+ const models = settings.openai_configured+ ? [{ id: "openai:gpt-4o", name: "GPT-4o" }]+ : [];+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ models }),+ });+ });++ await page.route("**/api/ai/unified/findings*", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ findings: [], count: 0, active_count: 0 }),+ });+ });++ await page.route("**/api/ai/intelligence/correlations*", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ correlations: [], count: 0 }),+ });+ });++ await page.route("**/api/ai/intelligence", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(intelligenceSummary),+ });+ });++ await page.route("**/api/ai/circuit/status", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ state: "closed",+ can_patrol: patrolStatus.runtime_state !== "blocked",+ consecutive_failures: 0,+ total_successes: 42,+ total_failures: 0,+ }),+ });+ });++ await page.route("**/api/ai/approvals", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ approvals: [] }),+ });+ });++ await page.route("**/api/ai/remediation/plans", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ plans: [] }),+ });+ });++ return { settings, patrolStatus, updateRequests, patrolRunRequests };+}++test.describe("Quickstart cross-surface browser contract", () => {+ test("activated install first AI enable surfaces quickstart-backed Patrol without BYOK", async ({+ page,+ }, testInfo) => {+ test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only quickstart coverage");++ await ensureAuthenticated(page);+ const surface = await mockQuickstartPatrolSurface(page, {+ settings: {+ enabled: false,+ configured: false,+ model: "",+ chat_model: "",+ patrol_model: "",+ using_quickstart: false,+ },+ patrolStatus: {+ runtime_state: "blocked",+ enabled: false,+ healthy: false,+ using_quickstart: false,+ blocked_reason: "Awaiting AI provider configuration",+ },+ });++ await page.goto("/settings/system-ai", { waitUntil: "domcontentloaded" });+ await expect(page.getByRole("heading", { name: "AI Services", level: 1 })).toBeVisible();++ const response = await browserApiRequest(page, "/api/settings/ai/update", "PUT", {+ enabled: true,+ });+ expect(response.ok).toBe(true);+ expect(surface.updateRequests).toHaveLength(1);++ await page.goto("/ai", { waitUntil: "domcontentloaded" });+ await expect(page.getByText("Patrol enabled")).toBeVisible();+ await expect(page.getByText("Patrol quickstart: 25/25 runs left")).toBeVisible();+ await expect(page.getByRole("button", { name: "Run Patrol" })).toBeEnabled();+ });++ test("unactivated Community surfaces activation-or-BYOK messaging instead of quickstart", async ({+ page,+ }, testInfo) => {+ test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only quickstart coverage");++ await ensureAuthenticated(page);+ await mockQuickstartPatrolSurface(page, {+ settings: {+ enabled: true,+ configured: false,+ model: "",+ chat_model: "",+ patrol_model: "",+ quickstart_credits_total: 0,+ quickstart_credits_used: 0,+ quickstart_credits_remaining: 0,+ quickstart_credits_available: false,+ using_quickstart: false,+ },+ patrolStatus: {+ runtime_state: "blocked",+ enabled: true,+ healthy: false,+ using_quickstart: false,+ quickstart_credits_total: 0,+ quickstart_credits_remaining: 0,+ blocked_reason: QUICKSTART_ACTIVATION_REQUIRED_REASON,+ blocked_at: "2026-03-25T09:00:00Z",+ },+ });++ await page.goto("/ai", { waitUntil: "domcontentloaded" });++ await expect(page.getByText("Patrol paused").first()).toBeVisible();+ await expect(page.getByText(QUICKSTART_ACTIVATION_REQUIRED_REASON).first()).toBeVisible();+ await expect(page.getByRole("button", { name: "Run Patrol" })).toBeDisabled();+ await expect(page.getByText(/Patrol quickstart:/)).toHaveCount(0);+ });++ test("successful quickstart Patrol run refreshes the credit badge from server state", async ({+ page,+ }, testInfo) => {+ test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only quickstart coverage");++ await ensureAuthenticated(page);+ const surface = await mockQuickstartPatrolSurface(page, {+ settings: {+ quickstart_credits_remaining: 12,+ quickstart_credits_used: 13,+ },+ patrolStatus: {+ quickstart_credits_remaining: 12,+ },+ });++ await page.goto("/ai", { waitUntil: "domcontentloaded" });+ await expect(page.getByText("Patrol quickstart: 12/25 runs left")).toBeVisible();++ const response = await browserApiRequest(page, "/api/ai/patrol/run", "POST", {});+ expect(response.ok).toBe(true);+ expect(surface.patrolRunRequests).toHaveLength(1);++ await page.getByRole("button", { name: "Refresh" }).click();+ await expect(page.getByText("Patrol quickstart: 11/25 runs left")).toBeVisible();+ });++ test("BYOK override suppresses exhausted quickstart copy once Patrol is no longer using quickstart", async ({+ page,+ }, testInfo) => {+ test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only quickstart coverage");++ await ensureAuthenticated(page);+ await mockQuickstartPatrolSurface(page, {+ settings: {+ model: "openai:gpt-4o",+ chat_model: "",+ patrol_model: "",+ openai_configured: true,+ configured_providers: ["openai"],+ using_quickstart: false,+ quickstart_credits_remaining: 0,+ quickstart_credits_used: 25,+ },+ patrolStatus: {+ using_quickstart: false,+ quickstart_credits_remaining: 0,+ healthy: true,+ },+ });++ await page.goto("/ai", { waitUntil: "domcontentloaded" });++ await expect(page.getByText("Patrol enabled")).toBeVisible();+ await expect(page.getByText("Health A · 100/100")).toBeVisible();+ await expect(page.getByText("Patrol quickstart exhausted")).toHaveCount(0);+ await expect(page.getByText(QUICKSTART_EXHAUSTED_REASON)).toHaveCount(0);+ });++ test("unreachable quickstart proxy pauses Patrol with accurate offline guidance", async ({+ page,+ }, testInfo) => {+ test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only quickstart coverage");++ await ensureAuthenticated(page);+ await mockQuickstartPatrolSurface(page, {+ settings: {+ enabled: true,+ configured: false,+ model: "",+ chat_model: "",+ patrol_model: "",+ using_quickstart: false,+ quickstart_credits_remaining: 25,+ quickstart_credits_used: 0,+ },+ patrolStatus: {+ runtime_state: "blocked",+ healthy: false,+ using_quickstart: false,+ blocked_reason: QUICKSTART_OFFLINE_REASON,+ blocked_at: "2026-03-25T09:00:00Z",+ },+ });++ await page.goto("/ai", { waitUntil: "domcontentloaded" });++ await expect(page.getByText("Patrol Paused").first()).toBeVisible();+ await expect(page.getByText("Patrol paused").first()).toBeVisible();+ await expect(page.getByText(QUICKSTART_OFFLINE_REASON).first()).toBeVisible();+ await expect(page.getByRole("button", { name: "Run Patrol" })).toBeDisabled();+ await expect(page.getByText("Patrol quickstart exhausted")).toHaveCount(0);+ await expect(page.getByText("Health A · 100/100")).toHaveCount(0);+ });++ test.fail("activated-install first AI enable toggle should not force BYOK setup when quickstart credits are available", async ({+ page,+ }, testInfo) => {+ test.skip(testInfo.project.name.startsWith("mobile-"), "Desktop-only quickstart coverage");++ await ensureAuthenticated(page);+ const surface = await mockQuickstartPatrolSurface(page, {+ settings: {+ enabled: false,+ configured: false,+ model: "",+ chat_model: "",+ patrol_model: "",+ using_quickstart: false,+ },+ patrolStatus: {+ runtime_state: "blocked",+ enabled: false,+ healthy: false,+ using_quickstart: false,+ blocked_reason: "Awaiting AI provider configuration",+ },+ });++ await page.goto("/settings/system-ai", { waitUntil: "domcontentloaded" });+ await expect(page.getByRole("heading", { name: "AI Services", level: 1 })).toBeVisible();++ await page.locator("button[aria-pressed]").first().click();++ expect(surface.updateRequests).toHaveLength(1);+ await expect(page.getByText("Choose a provider to get started")).toHaveCount(0);+ });+});