Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add monitored-system admission previews for platform connections

rcourtman38c8237a4fed
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d955f88e40..4c67a0c7a7 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -91,7 +91,8 @@ management, and fleet control surfaces.
67. `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`
68. `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`
69. `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`
-70. `internal/hostagent/proxmox_setup.go`
+70. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`
+71. `internal/hostagent/proxmox_setup.go`
## Shared Boundaries
@@ -99,6 +100,7 @@ management, and fleet control surfaces.
2. `frontend-modern/src/api/nodes.ts` shared with `api-contracts`: the shared Proxmox node client is both an agent lifecycle setup/install control surface and a canonical API payload contract boundary.
3. `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx` shared with `api-contracts`: the infrastructure operations controller is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.
4. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx` shared with `api-contracts`: the pure infrastructure operations inventory/install model is both an agent fleet lifecycle control surface and an API token, lookup, assignment, and reporting/install contract boundary.
+5. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx` shared with `cloud-paid`: the monitored-system admission preview is both a platform-connections lifecycle surface and a canonical cloud-paid monitored-system presentation boundary.
5. `frontend-modern/src/components/Settings/NodeModal.tsx` shared with `api-contracts`: the node setup modal render shell is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.
6. `frontend-modern/src/components/Settings/NodeModalAuthenticationSection.tsx` shared with `api-contracts`: the node setup authentication section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.
7. `frontend-modern/src/components/Settings/NodeModalBasicInfoSection.tsx` shared with `api-contracts`: the node setup basic-info section is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary.
@@ -174,7 +176,7 @@ management, and fleet control surfaces.
The same shared-helper rule now covers SSO outbound discovery and metadata fetches plus credential-file loads in `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`: lifecycle-adjacent setup or auth work may depend on that shared trust boundary, but it must not fork a second HTTP client, redirect policy, or file-read rule inside lifecycle-local flows.
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`.
+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, the shared monitored-system admission preview shell for those platform connections, 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/MonitoredSystemAdmissionPreview.tsx`, `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.
Agent-profile suggestion affordances remain adjacent assistant UX, not a
second AI settings reader. `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`
@@ -1038,6 +1040,13 @@ lifecycle-local counter, drift on source priority, or treat missing monitored-
system usage as zero; when an active cap is present and usage cannot be
resolved, the route must fail closed with retryable unavailable guidance
instead of silently admitting a net-new monitored system.
+When lifecycle-adjacent setup or support surfaces need to explain why a
+candidate would count or dedupe, they must consume the shared monitored-system
+ledger preview contract rather than rebuilding a second preview model from
+setup-local transport fields. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`
+is the shared shell for that explanation inside platform-connections settings,
+so provider-specific panels must not fork their own monitored-system preview
+copy or inline projected-usage rendering.
That same commercial readiness boundary now also assumes settled canonical
usage, not the first non-nil monitor view. Lifecycle-owned setup or first-host
surfaces may not seal migrated-v5 continuity, display counted-system totals as
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 7ff93c68ea..12abf13628 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -898,6 +898,13 @@ must update the canonical TrueNAS poll summary owner so subsequent
`/api/truenas/connections` reads reflect refreshed last-success or last-error
state instead of leaving settings health disconnected from manual operator
tests.
+That same route family now also owns pre-save monitored-system admission
+preview. `POST /api/truenas/connections/preview` and
+`POST /api/truenas/connections/{id}/preview` must return the shared
+monitored-system ledger preview contract sourced from canonical
+unified-resource projection, including current/projected grouped systems and
+enforced limit verdicts, rather than page-local settings estimates or
+provider-local counters.
That same `/api/truenas/connections` list boundary now also owns the
operator-facing runtime summary for those configured connections. The list
response must carry the canonical redacted config together with poll health
@@ -960,6 +967,13 @@ remains the saved connection retest surface. The explicit disabled path also
stays on this boundary: `404 vmware_disabled` means the operator or runtime has
opted out of the default-on VMware candidate, not that the platform requires a
different onboarding contract.
+That same route family now also owns source-native monitored-system admission
+preview. `POST /api/vmware/connections/preview` and
+`POST /api/vmware/connections/{id}/preview` must project the discovered
+provider-backed record set through the shared monitored-system ledger preview
+contract before persistence, including current/projected grouped systems and
+enforced limit verdicts, rather than collapsing a vCenter add or edit to one
+handler-local candidate estimate.
That same TrueNAS and VMware platform-connections contract now also owns
runtime mock continuity. When `/api/system/mock-mode` flips on a running
server, `/api/truenas/connections` and `/api/vmware/connections` must
@@ -1048,6 +1062,18 @@ directly rather than keeping flat alias fallback for
`latest_included_signal_at`, `latest_included_signal_source`, or `last_seen`.
The canonical nested status-reason timestamp is `reported_at`, and the
normalized client contract must expose only that field.
+That same monitored-system ledger contract now also owns prospective
+explanation. `POST /api/license/monitored-system-ledger/preview` must accept
+one canonical candidate plus an optional structured replacement selector, fail
+closed when monitored-system usage is unavailable, and return the canonical
+current/projected count delta, enforced limit verdict, effect label, and
+current/projected ledger entries produced by the shared monitored-system
+projection layer instead of by handler-local heuristics.
+Provider-backed preview routes such as `/api/truenas/connections/preview`,
+`/api/truenas/connections/{id}/preview`, `/api/vmware/connections/preview`,
+and `/api/vmware/connections/{id}/preview` must serialize that same canonical
+preview shape directly; they may not down-scope the response to local counts or
+hide current/projected grouped systems from the governed contract.
That client contract must also fail closed when older or partial payloads omit
the nested explanation object: the frontend may normalize missing explanation
fields to empty reasons/surfaces plus a safe default summary, but it must not
@@ -1238,6 +1264,11 @@ registration or update routes must project candidates or preview records
through the canonical monitored-system resolver before persistence, including
replacement of one existing source-owned surface, instead of rebuilding
handler-local priority tables or platform-specific counters.
+That same admission contract now also owns replacement identity. Shared API
+handlers may keep source-local request decoding, but the replacement they pass
+into monitored-system projection must travel as one canonical structured
+selector contract rather than as per-handler opaque match logic, so support
+preview, limit enforcement, and final runtime grouping stay aligned.
When an active monitored-system cap is present and current usage cannot be
resolved, those API contracts must fail closed for net-new admissions rather
than serializing a fake zero. `/api/license/entitlements` therefore carries
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 4c56932401..05347652c5 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -61,34 +61,36 @@ agreement, and cloud-specific enforcement rules.
39. `frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx`
40. `frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx`
41. `frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx`
-42. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`
-43. `frontend-modern/src/components/Settings/ProLicensePlanSection.tsx`
-44. `frontend-modern/src/components/Settings/CommercialBillingSections.tsx`
-45. `frontend-modern/src/components/Settings/SelfHostedCommercialRecoverySection.tsx`
-46. `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`
-47. `frontend-modern/src/components/Settings/RelayPairingSection.tsx`
-48. `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`
-49. `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`
-50. `frontend-modern/src/components/Settings/useProLicensePanelState.ts`
-51. `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`
-52. `frontend-modern/src/pages/CloudPricing.tsx`
-53. `frontend-modern/src/pages/HostedSignup.tsx`
-54. `frontend-modern/src/pages/PricingHandoff.tsx`
-55. `frontend-modern/src/utils/apiClient.ts`
-56. `frontend-modern/src/utils/cloudPlans.ts`
-57. `frontend-modern/src/utils/commercialBillingModel.ts`
-58. `frontend-modern/src/utils/licensePresentation.ts`
-59. `frontend-modern/src/utils/monitoredSystemPresentation.ts`
-60. `frontend-modern/src/utils/pricingHandoff.ts`
-61. `frontend-modern/src/utils/selfHostedPlans.ts`
-62. `frontend-modern/src/utils/upgradePresentation.ts`
+42. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`
+43. `frontend-modern/src/components/Settings/ProLicensePanel.tsx`
+44. `frontend-modern/src/components/Settings/ProLicensePlanSection.tsx`
+45. `frontend-modern/src/components/Settings/CommercialBillingSections.tsx`
+46. `frontend-modern/src/components/Settings/SelfHostedCommercialRecoverySection.tsx`
+47. `frontend-modern/src/components/Settings/RelaySettingsPanel.tsx`
+48. `frontend-modern/src/components/Settings/RelayPairingSection.tsx`
+49. `frontend-modern/src/components/Settings/useBillingAdminPanelState.ts`
+50. `frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts`
+51. `frontend-modern/src/components/Settings/useProLicensePanelState.ts`
+52. `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`
+53. `frontend-modern/src/pages/CloudPricing.tsx`
+54. `frontend-modern/src/pages/HostedSignup.tsx`
+55. `frontend-modern/src/pages/PricingHandoff.tsx`
+56. `frontend-modern/src/utils/apiClient.ts`
+57. `frontend-modern/src/utils/cloudPlans.ts`
+58. `frontend-modern/src/utils/commercialBillingModel.ts`
+59. `frontend-modern/src/utils/licensePresentation.ts`
+60. `frontend-modern/src/utils/monitoredSystemPresentation.ts`
+61. `frontend-modern/src/utils/pricingHandoff.ts`
+62. `frontend-modern/src/utils/selfHostedPlans.ts`
+63. `frontend-modern/src/utils/upgradePresentation.ts`
## Shared Boundaries
-1. `internal/api/licensing_bridge.go` shared with `api-contracts`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
-2. `internal/api/licensing_handlers.go` shared with `api-contracts`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
-3. `internal/api/payments_webhook_handlers.go` shared with `api-contracts`: commercial payment webhook handlers carry both API payload contract and cloud-paid billing boundary ownership.
-4. `internal/api/public_signup_handlers.go` shared with `api-contracts`: hosted signup handlers carry both API payload contract and cloud-paid hosted provisioning boundary ownership.
+1. `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx` shared with `agent-lifecycle`: the monitored-system admission preview is both a platform-connections lifecycle surface and a canonical cloud-paid monitored-system presentation boundary.
+2. `internal/api/licensing_bridge.go` shared with `api-contracts`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
+3. `internal/api/licensing_handlers.go` shared with `api-contracts`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
+4. `internal/api/payments_webhook_handlers.go` shared with `api-contracts`: commercial payment webhook handlers carry both API payload contract and cloud-paid billing boundary ownership.
+5. `internal/api/public_signup_handlers.go` shared with `api-contracts`: hosted signup handlers carry both API payload contract and cloud-paid hosted provisioning boundary ownership.
## Extension Points
@@ -632,6 +634,11 @@ That same helper also owns preview-impact copy and current/projected
source-label wording for pre-save monitored-system admission UI, so the
TrueNAS and VMware settings panels do not drift into provider-local billing
phrasing when they surface canonical preview results before save.
+That same helper also owns grouped preview attribution and multi-source labels.
+When a current or projected monitored system represents several included
+surfaces, the admission preview must render canonical helper-owned labels such
+as `Multiple Sources` and helper-owned effect copy instead of provider-local
+source names, raw type/source slugs, or ad hoc billing phrasing.
That same disclosure surface must not accept arbitrary caller-supplied
monitored-system summary strings as its primary API. When the disclosure needs
to show brief summary copy, it should render the canonical helper-owned brief
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index ea85a4323e..e2ac2041e8 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -225,6 +225,14 @@
"api-contracts"
]
},
+ {
+ "path": "frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx",
+ "rationale": "the monitored-system admission preview is both a platform-connections lifecycle surface and a canonical cloud-paid monitored-system presentation boundary",
+ "subsystems": [
+ "agent-lifecycle",
+ "cloud-paid"
+ ]
+ },
{
"path": "frontend-modern/src/components/Settings/NodeModal.tsx",
"rationale": "the node setup modal render shell is both an agent lifecycle control surface and a shared API-backed install/setup contract boundary",
@@ -598,6 +606,7 @@
"frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx",
"frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx",
"frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts",
+ "frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx",
"frontend-modern/src/components/Settings/NodeModal.tsx",
"frontend-modern/src/components/Settings/NodeModalAuthenticationSection.tsx",
"frontend-modern/src/components/Settings/NodeModalBasicInfoSection.tsx",
@@ -627,6 +636,8 @@
"frontend-modern/src/components/Settings/useNodeModalState.ts",
"frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts",
"frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts",
+ "frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts",
+ "frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx",
"frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx",
"frontend-modern/src/utils/agentCapabilityPresentation.ts",
"frontend-modern/src/utils/agentInstallCommand.ts",
@@ -874,6 +885,7 @@
"frontend-modern/src/components/Settings/infrastructureSettingsModel.ts",
"frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx",
"frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts",
+ "frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx",
"frontend-modern/src/components/Settings/platformConnectionsModel.ts",
"frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx",
"frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx",
@@ -891,6 +903,8 @@
"frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts",
"frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts",
"frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts",
+ "frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts",
+ "frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx",
"frontend-modern/src/utils/clusterEndpointPresentation.ts",
"frontend-modern/src/utils/proxmoxSettingsPresentation.ts"
],
@@ -904,9 +918,13 @@
"frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts",
"frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx",
"frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/useVMwareSettingsPanelState.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx",
"frontend-modern/src/utils/__tests__/clusterEndpointPresentation.test.ts",
"frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",
- "frontend-modern/src/utils/__tests__/proxmoxSettingsPresentation.test.ts"
+ "frontend-modern/src/utils/__tests__/proxmoxSettingsPresentation.test.ts",
+ "tests/integration/tests/21-truenas-settings-platform-connections.spec.ts",
+ "tests/integration/tests/22-vmware-settings-platform-connections.spec.ts"
]
},
{
@@ -1651,6 +1669,7 @@
"frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx",
"frontend-modern/src/components/Settings/BillingAdminPanel.tsx",
"frontend-modern/src/components/Settings/CommercialBillingSections.tsx",
+ "frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx",
"frontend-modern/src/components/Settings/MonitoredSystemLedgerPanel.tsx",
"frontend-modern/src/components/Settings/OrganizationBillingLoadingState.tsx",
"frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx",
@@ -2158,15 +2177,20 @@
},
{
"id": "monitored-system-presentation-helper",
- "label": "monitored system presentation helper proof",
+ "label": "monitored system presentation and admission preview proof",
"match_prefixes": [],
"match_files": [
+ "frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx",
"frontend-modern/src/utils/monitoredSystemPresentation.ts"
],
"allow_same_subsystem_tests": false,
"test_prefixes": [],
"exact_files": [
- "frontend-modern/src/utils/__tests__/monitoredSystemPresentation.test.ts"
+ "frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx",
+ "frontend-modern/src/utils/__tests__/monitoredSystemPresentation.test.ts",
+ "tests/integration/tests/21-truenas-settings-platform-connections.spec.ts",
+ "tests/integration/tests/22-vmware-settings-platform-connections.spec.ts"
]
},
{
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d351c377bb..95403ce9bc 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -147,6 +147,7 @@ querying, and the operator-facing storage health presentation layer.
26. Keep cross-surface recovery handoffs on the shared route-helper contract. When infrastructure or other unified-resource consumers expose TrueNAS recovery links, they must reuse the canonical `frontend-modern/src/routing/resourceLinks.ts` recovery builder with owned `platform` and `node` queries instead of inventing drawer-local recovery URLs or treating PBS services as the only infrastructure-to-recovery path.
27. Keep alert-side recovery drill-ins on that same shared route-helper contract. When alert investigation surfaces such as resource-incident panels expose recovery follow-up links for TrueNAS or future API-backed platforms, they must route through the canonical `frontend-modern/src/routing/resourceLinks.ts` recovery builder instead of freezing alert-local recovery URLs or introducing another provider-shaped recovery handoff vocabulary.
28. Keep VMware onboarding runtime and recovery semantics separate on that same adjacent platform-connections contract. When `internal/api/router.go`, `internal/api/router_routes_registration.go`, or `internal/api/vmware_handlers.go` evolve VMware connection CRUD, poller-owned `poll` / `observed` summary payloads, saved-test refresh, or observed datastore/VM snapshot visibility, storage and recovery may consume the resulting shared context but must not treat those onboarding/runtime payloads as canonical recovery artifacts, restore capability, or recovery-local control transport.
+ That same adjacent platform-connections boundary also owns pre-save monitored-system admission preview. When `internal/api/monitored_system_ledger.go`, `internal/api/router_routes_registration.go`, `internal/api/truenas_handlers.go`, or `internal/api/vmware_handlers.go` expose current/projected grouped systems and limit-enforcement verdicts before a provider connection is saved, storage and recovery may consume that context only as adjacent onboarding evidence; they must not reinterpret those preview groups as protected inventory, restore readiness, backup coverage, or recovery-local capacity truth.
29. Keep VMware datastore projection on the shared unified-resource and storage-source contracts. When `frontend-modern/src/hooks/useUnifiedResources.ts` or shared `internal/api/router.go` wiring starts surfacing VMware-backed canonical `storage` resources, storage and recovery may expose those datastores through the owned `vmware-vsphere` source/platform vocabulary for inventory, capacity, and handoff flows only; they must not reinterpret that projection as VMware recovery support, restore semantics, or a provider-local protection surface.
30. Keep VMware placement and guest-detail enrichment descriptive on that same shared unified-resource contract. When `internal/vmware/provider.go`, `internal/unifiedresources/types.go`, and `frontend-modern/src/hooks/useUnifiedResources.ts` project datacenter, cluster, folder, runtime-host, datastore-attachment, guest-hostname, or guest-IP metadata onto canonical VMware `agent` / `vm` / `storage` resources, storage and recovery may use that detail for labeling and navigation only; they must not promote those topology or guest fields into recovery ownership, restore targeting, protection grouping, or a VMware-local recovery taxonomy without a separately governed slice.
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.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 283a1930c3..a7e17ab4ea 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -132,7 +132,17 @@ phrases for `sensitive` and `restricted` resources, so the backend policy
contract controls those strings instead of duplicating them inside the summary
assembly branch.
4. Add metrics-target normalization or synthetic metrics support through `internal/unifiedresources/metrics_targets.go` and `internal/unifiedresources/metrics.go`
-5. Add platform registry, resolution, or host-dedup behavior through `internal/unifiedresources/registry.go`, `internal/unifiedresources/resolve.go`, `internal/unifiedresources/resolved_host_set.go`, `internal/unifiedresources/snapshot_source_filter.go`, `internal/unifiedresources/store.go`, `internal/unifiedresources/kubernetes_capabilities.go`, and `internal/unifiedresources/pbs_rollups.go`
+5. Add platform registry, resolution, host-dedup, or monitored-system
+ projection behavior through `internal/unifiedresources/registry.go`,
+ `internal/unifiedresources/resolve.go`,
+ `internal/unifiedresources/resolved_host_set.go`,
+ `internal/unifiedresources/snapshot_source_filter.go`,
+ `internal/unifiedresources/store.go`,
+ `internal/unifiedresources/kubernetes_capabilities.go`,
+ `internal/unifiedresources/pbs_rollups.go`,
+ `internal/unifiedresources/monitored_systems.go`,
+ `internal/unifiedresources/monitored_system_projection.go`, and
+ `internal/unifiedresources/top_level_systems.go`
6. Add canonical governed name-resolution or policy-aware resource lookup behavior through `internal/unifiedresources/resolve.go` and `internal/unifiedresources/resolve_context.go`
7. Add or change resource drawer timeline/facet presentation through `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`, `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`, `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`, `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`, and the governed `internal/api/resources.go` facet/timeline contract together
8. Add or change discovery-support runtime under the resource drawer through `frontend-modern/src/components/Discovery/DiscoveryTab.tsx` for shell/presentation ownership and `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts` for fetch, websocket-progress, and notes-mutation ownership
@@ -1384,6 +1394,16 @@ source replacement. Add/update handlers must project candidates or preview
records through shared monitored-system projection helpers, including the
delta from replacing one existing source-owned surface, instead of guessing
from handler-local priority rules or transport-specific counters.
+That same projection contract now also owns structured replacement selectors
+and detailed previews. Shared callers may serialize source-native selector
+fields such as hostname, host URL, machine or agent identity, and source-owned
+resource identifiers, but they must not invent preview-only matcher logic or
+hide source replacement behind handler-local closures once the request crosses
+into unified-resource ownership.
+Source-native record-set preview is required for provider-backed onboarding
+that can discover multiple top-level systems from one saved connection, so
+TrueNAS, VMware, and future multi-record providers stay on the same canonical
+projection boundary for both explanation and enforcement.
VMware host previews are part of that same contract: canonical host identity
must honor VMware host UUID plus normalized hostnames so a vCenter add or
update cannot bypass the monitored-system cap by discovering host-backed
@@ -1532,6 +1552,11 @@ must remove only the replaced source from that grouped root and preserve any
remaining canonical source ownership that still keeps the monitored system
counted, so replacement-aware admission stays aligned with final runtime
counting.
+When support or onboarding needs to explain that same change, unified
+resources must be able to return both the current grouped monitored system and
+the projected grouped monitored system for the candidate being evaluated, not
+just the numeric count delta, so explainability and enforcement stay on one
+canonical projection boundary.
Canonical unified resources now also own first-class policy metadata for the
v6 bridge release. Cloned and API-exported resources must carry
diff --git a/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts b/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts
index dae7a2e3fb..37e84d7cb1 100644
--- a/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts
+++ b/frontend-modern/src/api/__tests__/monitoredSystemLedger.test.ts
@@ -29,6 +29,124 @@ describe('MonitoredSystemLedgerAPI', () => {
});
});
+ it('fetches the canonical monitored-system ledger preview endpoint', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({
+ current_count: 1,
+ projected_count: 1,
+ additional_count: 0,
+ limit: 5,
+ would_exceed_limit: false,
+ effect: 'attaches_existing',
+ current_systems: [
+ {
+ name: 'Tower',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ },
+ ],
+ projected_systems: [
+ {
+ name: 'tower',
+ type: 'vmware-host',
+ status: 'online',
+ source: 'vmware',
+ },
+ ],
+ current_system: {
+ name: 'Tower',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ },
+ projected_system: {
+ name: 'tower',
+ type: 'vmware-host',
+ status: 'online',
+ source: 'vmware',
+ },
+ });
+
+ const request = {
+ candidate: {
+ source: 'vmware',
+ hostname: 'tower.local',
+ resource_id: 'vc-1',
+ },
+ };
+ const result = await MonitoredSystemLedgerAPI.preview(request);
+
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/license/monitored-system-ledger/preview', {
+ method: 'POST',
+ body: JSON.stringify(request),
+ });
+ expect(result.current_system?.source).toBe('agent');
+ expect(result.projected_system?.source).toBe('vmware');
+ expect(result.current_systems).toHaveLength(1);
+ expect(result.projected_systems).toHaveLength(1);
+ expect(result.effect).toBe('attaches_existing');
+ });
+
+ it('fetches the canonical monitored-system explanation endpoint', async () => {
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({
+ ledger: {
+ systems: [
+ {
+ name: 'Tower',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ },
+ ],
+ total: 1,
+ limit: 5,
+ },
+ preview: {
+ current_count: 1,
+ projected_count: 1,
+ additional_count: 0,
+ limit: 5,
+ would_exceed_limit: false,
+ effect: 'attaches_existing',
+ current_systems: [
+ {
+ name: 'Tower',
+ type: 'host',
+ status: 'online',
+ source: 'agent',
+ },
+ ],
+ projected_systems: [
+ {
+ name: 'tower',
+ type: 'vmware-host',
+ status: 'online',
+ source: 'vmware',
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ });
+
+ const request = {
+ candidate: {
+ source: 'vmware',
+ hostname: 'tower.local',
+ resource_id: 'vc-1',
+ },
+ };
+ const result = await MonitoredSystemLedgerAPI.explain(request);
+
+ expect(apiFetchJSON).toHaveBeenCalledWith('/api/license/monitored-system-ledger/explain', {
+ method: 'POST',
+ body: JSON.stringify(request),
+ });
+ expect(result.ledger.total).toBe(1);
+ expect(result.preview?.effect).toBe('attaches_existing');
+ expect(result.preview?.projected_systems).toHaveLength(1);
+ });
+
it('preserves grouping explanation payloads from the API contract', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce({
systems: [
@@ -95,7 +213,9 @@ describe('MonitoredSystemLedgerAPI', () => {
const result = await MonitoredSystemLedgerAPI.getLedger();
- expect(result.systems[0]?.explanation.summary).toContain('counts this top-level collection path');
+ expect(result.systems[0]?.explanation.summary).toContain(
+ 'counts this top-level collection path',
+ );
expect(result.systems[0]?.status_explanation?.summary).toContain('currently report online');
expect(result.systems[0]?.status_explanation?.reasons).toEqual([]);
expect(result.systems[0]?.explanation.reasons).toEqual([]);
@@ -201,7 +321,8 @@ describe('MonitoredSystemLedgerAPI', () => {
type: 'host',
status: 'warning',
status_explanation: {
- summary: 'At least one included source is stale, so Pulse marks this monitored system as warning.',
+ summary:
+ 'At least one included source is stale, so Pulse marks this monitored system as warning.',
reasons: [
{
kind: 'source-stale',
diff --git a/frontend-modern/src/api/monitoredSystemLedger.ts b/frontend-modern/src/api/monitoredSystemLedger.ts
index 91f45da3fe..0dbbeb8bca 100644
--- a/frontend-modern/src/api/monitoredSystemLedger.ts
+++ b/frontend-modern/src/api/monitoredSystemLedger.ts
@@ -29,11 +29,7 @@ export interface MonitoredSystemLedgerStatusExplanation {
reasons: MonitoredSystemLedgerStatusReason[];
}
-export type MonitoredSystemLedgerStatusReasonStatus =
- | 'online'
- | 'stale'
- | 'offline'
- | 'unknown';
+export type MonitoredSystemLedgerStatusReasonStatus = 'online' | 'stale' | 'offline' | 'unknown';
export interface MonitoredSystemLedgerStatusReason {
kind: string;
@@ -68,6 +64,61 @@ export interface MonitoredSystemLedgerResponse {
limit: number; // 0 = unlimited
}
+export interface MonitoredSystemLedgerExplainRequest {
+ candidate?: MonitoredSystemLedgerPreviewCandidate | null;
+ replacement?: MonitoredSystemLedgerPreviewReplacement | null;
+}
+
+export interface MonitoredSystemLedgerPreviewCandidate {
+ source: string;
+ type?: string;
+ name?: string;
+ hostname?: string;
+ host_url?: string;
+ agent_id?: string;
+ machine_id?: string;
+ resource_id?: string;
+}
+
+export interface MonitoredSystemLedgerPreviewReplacement {
+ source?: string;
+ name?: string;
+ hostname?: string;
+ host_url?: string;
+ agent_id?: string;
+ machine_id?: string;
+ resource_id?: string;
+}
+
+export interface MonitoredSystemLedgerPreviewRequest {
+ candidate: MonitoredSystemLedgerPreviewCandidate;
+ replacement?: MonitoredSystemLedgerPreviewReplacement | null;
+}
+
+export type MonitoredSystemLedgerPreviewEffect =
+ | 'creates_new'
+ | 'attaches_existing'
+ | 'replaces_existing'
+ | 'splits_existing';
+
+export interface MonitoredSystemLedgerPreviewResponse {
+ current_count: number;
+ projected_count: number;
+ additional_count: number;
+ limit: number;
+ would_exceed_limit: boolean;
+ effect: MonitoredSystemLedgerPreviewEffect | string;
+ current_systems: MonitoredSystemLedgerEntry[];
+ projected_systems: MonitoredSystemLedgerEntry[];
+ current_system: MonitoredSystemLedgerEntry | null;
+ projected_system: MonitoredSystemLedgerEntry | null;
+}
+
+export interface MonitoredSystemLedgerExplainResponse {
+ ledger: MonitoredSystemLedgerResponse;
+ preview: MonitoredSystemLedgerPreviewResponse | null;
+}
+
type MonitoredSystemLedgerRawEntry = Omit<
MonitoredSystemLedgerEntry,
'status_explanation' | 'latest_included_signal' | 'explanation'
@@ -81,13 +132,32 @@ type MonitoredSystemLedgerRawResponse = Omit<MonitoredSystemLedgerResponse, 'sys
systems?: MonitoredSystemLedgerRawEntry[];
};
-interface MonitoredSystemLedgerRawStatusExplanation
- extends Omit<MonitoredSystemLedgerStatusExplanation, 'reasons'> {
+type MonitoredSystemLedgerRawExplainResponse = {
+ ledger?: MonitoredSystemLedgerRawResponse;
+ preview?: MonitoredSystemLedgerRawPreviewResponse | null;
+};
+
+export type MonitoredSystemLedgerRawPreviewResponse = Omit<
+ MonitoredSystemLedgerPreviewResponse,
+ 'current_systems' | 'projected_systems' | 'current_system' | 'projected_system'
+> & {
+ current_systems?: MonitoredSystemLedgerRawEntry[];
+ projected_systems?: MonitoredSystemLedgerRawEntry[];
+ current_system?: MonitoredSystemLedgerRawEntry | null;
+ projected_system?: MonitoredSystemLedgerRawEntry | null;
+};
+
+interface MonitoredSystemLedgerRawStatusExplanation extends Omit<
+ MonitoredSystemLedgerStatusExplanation,
+ 'reasons'
+> {
reasons?: MonitoredSystemLedgerRawStatusReason[];
}
-interface MonitoredSystemLedgerRawStatusReason
- extends Omit<MonitoredSystemLedgerStatusReason, 'reported_at'> {
+interface MonitoredSystemLedgerRawStatusReason extends Omit<
+ MonitoredSystemLedgerStatusReason,
+ 'reported_at'
+> {
reported_at?: string;
}
@@ -96,13 +166,88 @@ export class MonitoredSystemLedgerAPI {
static async getLedger(): Promise<MonitoredSystemLedgerResponse> {
const response = await apiFetchJSON<MonitoredSystemLedgerRawResponse>(this.baseUrl);
- return {
- ...response,
- systems: (response.systems ?? []).map(normalizeMonitoredSystemLedgerEntry),
- };
+ return normalizeMonitoredSystemLedgerResponse(response);
+ }
+
+ static async preview(
+ request: MonitoredSystemLedgerPreviewRequest,
+ ): Promise<MonitoredSystemLedgerPreviewResponse> {
+ const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
+ `${this.baseUrl}/preview`,
+ {
+ method: 'POST',
+ body: JSON.stringify(request),
+ },
+ );
+ return normalizeMonitoredSystemLedgerPreviewResponse(response);
+ }
+
+ static async explain(
+ request: MonitoredSystemLedgerExplainRequest = {},
+ ): Promise<MonitoredSystemLedgerExplainResponse> {
+ const response = await apiFetchJSON<MonitoredSystemLedgerRawExplainResponse>(
+ `${this.baseUrl}/explain`,
+ {
+ method: 'POST',
+ body: JSON.stringify(request),
+ },
+ );
+ return normalizeMonitoredSystemLedgerExplainResponse(response);
}
}
+export function normalizeMonitoredSystemLedgerResponse(
+ response: MonitoredSystemLedgerRawResponse,
+): MonitoredSystemLedgerResponse {
+ return {
+ ...response,
+ systems: (response.systems ?? []).map(normalizeMonitoredSystemLedgerEntry),
+ };
+}
+
+export function normalizeMonitoredSystemLedgerPreviewResponse(
+ response: MonitoredSystemLedgerRawPreviewResponse,
+): MonitoredSystemLedgerPreviewResponse {
+ const currentSystems = (response.current_systems ?? []).map(normalizeMonitoredSystemLedgerEntry);
+ const projectedSystems = (response.projected_systems ?? []).map(
+ normalizeMonitoredSystemLedgerEntry,
+ );
+ return {
+ ...response,
+ current_systems: currentSystems,
+ projected_systems: projectedSystems,
+ current_system:
+ response.current_system != null
+ ? normalizeMonitoredSystemLedgerEntry(response.current_system)
+ : currentSystems.length === 1
+ ? currentSystems[0]
+ : null,
+ projected_system:
+ response.projected_system != null
+ ? normalizeMonitoredSystemLedgerEntry(response.projected_system)
+ : projectedSystems.length === 1
+ ? projectedSystems[0]
+ : null,
+ };
+}
+
+export function normalizeMonitoredSystemLedgerExplainResponse(
+ response: MonitoredSystemLedgerRawExplainResponse,
+): MonitoredSystemLedgerExplainResponse {
+ const rawLedger: MonitoredSystemLedgerRawResponse = response.ledger ?? {
+ systems: [],
+ total: 0,
+ limit: 0,
+ };
+ return {
+ ledger: normalizeMonitoredSystemLedgerResponse(rawLedger),
+ preview:
+ response.preview != null
+ ? normalizeMonitoredSystemLedgerPreviewResponse(response.preview)
+ : null,
+ };
+}
+
function normalizeMonitoredSystemLedgerEntry(
entry: MonitoredSystemLedgerRawEntry,
): MonitoredSystemLedgerEntry {
@@ -120,7 +265,9 @@ function normalizeMonitoredSystemLedgerEntry(
latest_included_signal: latestIncludedSignal,
status_explanation: {
summary: entry.status_explanation?.summary ?? getMonitoredSystemStatusFallbackSummary(status),
- reasons: (entry.status_explanation?.reasons ?? []).map(normalizeMonitoredSystemLedgerStatusReason),
+ reasons: (entry.status_explanation?.reasons ?? []).map(
+ normalizeMonitoredSystemLedgerStatusReason,
+ ),
},
explanation: {
summary: explanation?.summary ?? getMonitoredSystemExplanationFallbackSummary(),
@@ -183,6 +330,7 @@ function normalizeMonitoredSystemLedgerSource(
case 'pmg':
case 'proxmox':
case 'truenas':
+ case 'vmware':
return source?.trim().toLowerCase();
default:
return undefined;
diff --git a/frontend-modern/src/api/truenas.ts b/frontend-modern/src/api/truenas.ts
index be8d5e2304..1bec372695 100644
--- a/frontend-modern/src/api/truenas.ts
+++ b/frontend-modern/src/api/truenas.ts
@@ -1,4 +1,9 @@
import { apiFetchJSON } from '@/utils/apiClient';
+import {
+ normalizeMonitoredSystemLedgerPreviewResponse,
+ type MonitoredSystemLedgerPreviewResponse,
+ type MonitoredSystemLedgerRawPreviewResponse,
+} from './monitoredSystemLedger';
import {
arrayOrUndefined,
finiteNumberOrUndefined,
@@ -220,4 +225,33 @@ export class TrueNASAPI {
success: strictBoolean(response.success),
};
}
+
+ static async previewConnection(
+ input: TrueNASConnectionInput,
+ ): Promise<MonitoredSystemLedgerPreviewResponse> {
+ const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
+ `${TRUE_NAS_CONNECTIONS_PATH}/preview`,
+ {
+ method: 'POST',
+ body: JSON.stringify(serializeTrueNASConnectionInput(input)),
+ },
+ );
+ return normalizeMonitoredSystemLedgerPreviewResponse(response);
+ }
+
+ static async previewSavedConnection(
+ id: string,
+ input?: TrueNASConnectionInput,
+ ): Promise<MonitoredSystemLedgerPreviewResponse> {
+ const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
+ `${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}/preview`,
+ {
+ method: 'POST',
+ ...(input !== undefined
+ ? { body: JSON.stringify(serializeTrueNASConnectionInput(input)) }
+ : {}),
+ },
+ );
+ return normalizeMonitoredSystemLedgerPreviewResponse(response);
+ }
}
diff --git a/frontend-modern/src/api/vmware.ts b/frontend-modern/src/api/vmware.ts
index 5e5c2d9be5..21dd179f3e 100644
--- a/frontend-modern/src/api/vmware.ts
+++ b/frontend-modern/src/api/vmware.ts
@@ -1,4 +1,9 @@
import { apiFetchJSON } from '@/utils/apiClient';
+import {
+ normalizeMonitoredSystemLedgerPreviewResponse,
+ type MonitoredSystemLedgerPreviewResponse,
+ type MonitoredSystemLedgerRawPreviewResponse,
+} from './monitoredSystemLedger';
import {
arrayOrUndefined,
finiteNumberOrUndefined,
@@ -216,4 +221,33 @@ export class VMwareAPI {
success: strictBoolean(response.success),
};
}
+
+ static async previewConnection(
+ input: VMwareConnectionInput,
+ ): Promise<MonitoredSystemLedgerPreviewResponse> {
+ const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
+ `${VMWARE_CONNECTIONS_PATH}/preview`,
+ {
+ method: 'POST',
+ body: JSON.stringify(serializeVMwareConnectionInput(input)),
+ },
+ );
+ return normalizeMonitoredSystemLedgerPreviewResponse(response);
+ }
+
+ static async previewSavedConnection(
+ id: string,
+ input?: VMwareConnectionInput,
+ ): Promise<MonitoredSystemLedgerPreviewResponse> {
+ const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(
+ `${VMWARE_CONNECTIONS_PATH}/${encodeURIComponent(id)}/preview`,
+ {
+ method: 'POST',
+ ...(input !== undefined
+ ? { body: JSON.stringify(serializeVMwareConnectionInput(input)) }
+ : {}),
+ },
+ );
+ return normalizeMonitoredSystemLedgerPreviewResponse(response);
+ }
}
diff --git a/frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx b/frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx
new file mode 100644
index 0000000000..e448518f9d
--- /dev/null
+++ b/frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx
@@ -0,0 +1,111 @@
+import { For, Show, type Component } from 'solid-js';
+import type { MonitoredSystemLedgerPreviewResponse } from '@/api/monitoredSystemLedger';
+import { CalloutCard } from '@/components/shared/CalloutCard';
+import { formatMonitoredSystemSurfaceAttribution } from '@/utils/monitoredSystemPresentation';
+
+interface MonitoredSystemAdmissionPreviewProps {
+ preview: MonitoredSystemLedgerPreviewResponse | null;
+ loading?: boolean;
+ error?: string | null;
+}
+
+const formatUsage = (count: number, limit: number): string =>
+ limit > 0 ? `${count} / ${limit}` : `${count}`;
+
+const formatDelta = (count: number): string => {
+ if (count > 0) return `+${count}`;
+ return `${count}`;
+};
+
+const previewTone = (preview: MonitoredSystemLedgerPreviewResponse | null) =>
+ preview?.would_exceed_limit ? 'warning' : 'info';
+
+const previewTitle = (preview: MonitoredSystemLedgerPreviewResponse | null) => {
+ if (!preview) return 'Monitored-system impact';
+ if (preview.would_exceed_limit) {
+ return 'This change exceeds your monitored-system limit';
+ }
+ if (preview.additional_count > 0) {
+ return 'This change adds monitored systems';
+ }
+ return 'This change reuses your current monitored-system capacity';
+};
+
+const previewSummary = (preview: MonitoredSystemLedgerPreviewResponse): string => {
+ const before = formatUsage(preview.current_count, preview.limit);
+ const after = formatUsage(preview.projected_count, preview.limit);
+ if (preview.additional_count > 0) {
+ return `Current usage ${before}. Saving this change would move usage to ${after} (${formatDelta(
+ preview.additional_count,
+ )}).`;
+ }
+ return `Current usage ${before}. Saving this change keeps usage at ${after}.`;
+};
+
+export const MonitoredSystemAdmissionPreview: Component<
+ MonitoredSystemAdmissionPreviewProps
+> = (props) => {
+ return (
+ <>
+ <Show when={props.loading}>
+ <div class="rounded-md border border-border bg-surface-alt px-4 py-3 text-sm text-muted">
+ Calculating monitored-system impact…
+ </div>
+ </Show>
+
+ <Show when={!props.loading && props.error}>
+ {(error) => (
+ <CalloutCard
+ tone="warning"
+ title="Could not preview monitored-system impact"
+ description={<p>{error()}</p>}
+ />
+ )}
+ </Show>
+
+ <Show when={!props.loading && props.preview}>
+ {(preview) => (
+ <CalloutCard
+ tone={previewTone(preview())}
+ title={previewTitle(preview())}
+ description={
+ <div class="space-y-3 text-sm">
+ <p>{previewSummary(preview())}</p>
+ <Show when={preview().current_systems.length > 0}>
+ <div class="space-y-1">
+ <p class="text-xs font-medium uppercase tracking-wide text-muted">
+ Current matched systems
+ </p>
+ <ul class="space-y-1 text-sm text-base-content">
+ <For each={preview().current_systems}>
+ {(system) => (
+ <li>{formatMonitoredSystemSurfaceAttribution(system)}</li>
+ )}
+ </For>
+ </ul>
+ </div>
+ </Show>
+ <Show when={preview().projected_systems.length > 0}>
+ <div class="space-y-1">
+ <p class="text-xs font-medium uppercase tracking-wide text-muted">
+ Projected systems
+ </p>
+ <ul class="space-y-1 text-sm text-base-content">
+ <For each={preview().projected_systems}>
+ {(system) => (
+ <li>{formatMonitoredSystemSurfaceAttribution(system)}</li>
+ )}
+ </For>
+ </ul>
+ </div>
+ </Show>
+ </div>
+ }
+ />
+ )}
+ </Show>
+ </>
+ );
+};
+
+export default MonitoredSystemAdmissionPreview;
diff --git a/frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx b/frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx
index 0206648911..646fc6976f 100644
--- a/frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx
+++ b/frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx
@@ -22,6 +22,7 @@ import {
formSelect,
} from '@/components/shared/Form';
import { getSettingsConfigurationLoadingState } from '@/utils/settingsShellPresentation';
+import { MonitoredSystemAdmissionPreview } from './MonitoredSystemAdmissionPreview';
import type { TrueNASSettingsPanelState } from './useTrueNASSettingsPanelState';
const buttonClass =
@@ -584,6 +585,12 @@ export const TrueNASSettingsPanel: Component<TrueNASSettingsPanelProps> = (props
</div>
</div>
+ <MonitoredSystemAdmissionPreview
+ preview={state.monitoredSystemPreview()}
+ loading={state.previewing()}
+ error={state.monitoredSystemPreviewError()}
+ />
+
<div class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<button
type="button"
@@ -601,11 +608,24 @@ export const TrueNASSettingsPanel: Component<TrueNASSettingsPanelProps> = (props
>
{state.testing() ? 'Testing…' : 'Test connection'}
</button>
+ <button
+ type="button"
+ class={buttonClass}
+ onClick={() => void state.previewCurrentForm()}
+ disabled={state.saving() || state.testing() || state.previewing()}
+ >
+ {state.previewing() ? 'Previewing…' : 'Preview impact'}
+ </button>
<button
type="button"
class={primaryButtonClass}
onClick={() => void state.saveCurrentForm()}
- disabled={state.saving() || state.testing()}
+ disabled={
+ state.saving() ||
+ state.testing() ||
+ state.previewing() ||
+ state.monitoredSystemPreview()?.would_exceed_limit
+ }
>
{state.saving()
? state.editingConnection()
diff --git a/frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx b/frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx
index 6482d79709..d448eac199 100644
--- a/frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx
+++ b/frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx
@@ -15,6 +15,7 @@ import {
formLabel,
} from '@/components/shared/Form';
import { getSettingsConfigurationLoadingState } from '@/utils/settingsShellPresentation';
+import { MonitoredSystemAdmissionPreview } from './MonitoredSystemAdmissionPreview';
import type { VMwareSettingsPanelState } from './useVMwareSettingsPanelState';
import { buildVMwareConnectionFailurePresentation } from './vmwareConnectionFailurePresentation';
@@ -524,6 +525,12 @@ export const VMwareSettingsPanel: Component<VMwareSettingsPanelProps> = (props)
</label>
</div>
+ <MonitoredSystemAdmissionPreview
+ preview={state.monitoredSystemPreview()}
+ loading={state.previewing()}
+ error={state.monitoredSystemPreviewError()}
+ />
+
<div class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<button
type="button"
@@ -541,11 +548,24 @@ export const VMwareSettingsPanel: Component<VMwareSettingsPanelProps> = (props)
>
{state.testing() ? 'Testing…' : 'Test connection'}
</button>
+ <button
+ type="button"
+ class={buttonClass}
+ onClick={() => void state.previewCurrentForm()}
+ disabled={state.saving() || state.testing() || state.previewing()}
+ >
+ {state.previewing() ? 'Previewing…' : 'Preview impact'}
+ </button>
<button
type="button"
class={primaryButtonClass}
onClick={() => void state.saveCurrentForm()}
- disabled={state.saving() || state.testing()}
+ disabled={
+ state.saving() ||
+ state.testing() ||
+ state.previewing() ||
+ state.monitoredSystemPreview()?.would_exceed_limit
+ }
>
{state.saving()
? state.editingConnection()
diff --git a/frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx
index 8044ba8a45..b058f2b78c 100644
--- a/frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx
@@ -37,6 +37,10 @@ const mockState = vi.hoisted(() => ({
openDeleteDialog: vi.fn(),
openEditDialog: vi.fn(),
pendingDeleteConnection: vi.fn(() => null),
+ monitoredSystemPreview: vi.fn(() => null),
+ monitoredSystemPreviewError: vi.fn(() => null),
+ previewCurrentForm: vi.fn(),
+ previewing: vi.fn(() => false),
saveCurrentForm: vi.fn(),
saving: vi.fn(() => false),
testCurrentForm: vi.fn(),
@@ -78,6 +82,9 @@ describe('TrueNASSettingsPanel', () => {
mockState.loading.mockReturnValue(false);
mockState.loadingError.mockReturnValue(null);
mockState.pendingDeleteConnection.mockReturnValue(null);
+ mockState.monitoredSystemPreview.mockReturnValue(null);
+ mockState.monitoredSystemPreviewError.mockReturnValue(null);
+ mockState.previewing.mockReturnValue(false);
mockState.saving.mockReturnValue(false);
mockState.testing.mockReturnValue(false);
});
@@ -179,4 +186,39 @@ describe('TrueNASSettingsPanel', () => {
expect(screen.getByText(/PULSE_ENABLE_TRUENAS=false/)).toBeInTheDocument();
expect(screen.queryByText('TrueNAS connections')).not.toBeInTheDocument();
});
+
+ it('renders monitored-system preview inside the dialog and blocks save over the limit', () => {
+ mockState.dialogOpen.mockReturnValue(true);
+ mockState.monitoredSystemPreview.mockReturnValue({
+ current_count: 9,
+ projected_count: 11,
+ additional_count: 2,
+ limit: 10,
+ would_exceed_limit: true,
+ effect: 'splits_existing',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'tower',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'truenas',
+ status_explanation: { summary: '', reasons: [] },
+ latest_included_signal: { name: '', type: '', at: '' },
+ explanation: { summary: '', reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ });
+
+ renderPanel();
+
+ expect(screen.getByText('This change exceeds your monitored-system limit')).toBeInTheDocument();
+ expect(screen.getByText(/Current usage 9 \/ 10/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Add connection' })).toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Preview impact' }));
+ expect(mockState.previewCurrentForm).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx
index 19842329ed..b4a034875f 100644
--- a/frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx
@@ -33,6 +33,10 @@ const mockState = vi.hoisted(() => ({
openDeleteDialog: vi.fn(),
openEditDialog: vi.fn(),
pendingDeleteConnection: vi.fn((): VMwareConnection | null => null),
+ monitoredSystemPreview: vi.fn(() => null),
+ monitoredSystemPreviewError: vi.fn(() => null),
+ previewCurrentForm: vi.fn(),
+ previewing: vi.fn(() => false),
saveCurrentForm: vi.fn(),
saving: vi.fn(() => false),
testCurrentForm: vi.fn(),
@@ -69,6 +73,9 @@ describe('VMwareSettingsPanel', () => {
mockState.loading.mockReturnValue(false);
mockState.loadingError.mockReturnValue(null);
mockState.pendingDeleteConnection.mockReturnValue(null);
+ mockState.monitoredSystemPreview.mockReturnValue(null);
+ mockState.monitoredSystemPreviewError.mockReturnValue(null);
+ mockState.previewing.mockReturnValue(false);
mockState.saving.mockReturnValue(false);
mockState.testing.mockReturnValue(false);
});
@@ -239,4 +246,39 @@ describe('VMwareSettingsPanel', () => {
),
).toBeInTheDocument();
});
+
+ it('renders monitored-system preview inside the dialog and blocks save over the limit', () => {
+ mockState.dialogOpen.mockReturnValue(true);
+ mockState.monitoredSystemPreview.mockReturnValue({
+ current_count: 5,
+ projected_count: 7,
+ additional_count: 2,
+ limit: 6,
+ would_exceed_limit: true,
+ effect: 'creates_multiple',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'esxi-01',
+ type: 'host',
+ status: 'online',
+ source: 'vmware',
+ status_explanation: { summary: '', reasons: [] },
+ latest_included_signal: { name: '', type: '', at: '' },
+ explanation: { summary: '', reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ });
+
+ renderPanel();
+
+ expect(screen.getByText('This change exceeds your monitored-system limit')).toBeInTheDocument();
+ expect(screen.getByText(/Current usage 5 \/ 6/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Add connection' })).toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Preview impact' }));
+ expect(mockState.previewCurrentForm).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts b/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts
index 7bb6076a9d..fc5916f40b 100644
--- a/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts
@@ -29,6 +29,7 @@ import systemSettingsStateSource from '../useSystemSettingsState.ts?raw';
import infrastructureSettingsStateSource from '../useInfrastructureSettingsState.ts?raw';
import infrastructureWorkspaceSource from '../InfrastructureWorkspace.tsx?raw';
import infrastructureWorkspaceModelSource from '../infrastructureWorkspaceModel.ts?raw';
+import monitoredSystemAdmissionPreviewSource from '../MonitoredSystemAdmissionPreview.tsx?raw';
import settingsPanelRegistrySource from '../useSettingsPanelRegistry.tsx?raw';
import settingsSystemPanelsSource from '../useSettingsSystemPanels.tsx?raw';
import infrastructureSummarySource from '@/components/Infrastructure/InfrastructureSummary.tsx?raw';
@@ -185,6 +186,12 @@ import proxmoxNodeModalStackSource from '../ProxmoxNodeModalStack.tsx?raw';
import proxmoxSettingsPanelSource from '../ProxmoxSettingsPanel.tsx?raw';
import proxmoxSettingsModelSource from '../proxmoxSettingsModel.ts?raw';
import proxmoxDirectWorkspaceStateSource from '../useProxmoxDirectWorkspaceState.ts?raw';
+import trueNASApiSource from '@/api/truenas.ts?raw';
+import trueNASSettingsPanelSource from '../TrueNASSettingsPanel.tsx?raw';
+import trueNASSettingsPanelStateSource from '../useTrueNASSettingsPanelState.ts?raw';
+import vmwareApiSource from '@/api/vmware.ts?raw';
+import vmwareSettingsPanelSource from '../VMwareSettingsPanel.tsx?raw';
+import vmwareSettingsPanelStateSource from '../useVMwareSettingsPanelState.ts?raw';
import relayOnboardingCardSource from '@/components/Dashboard/RelayOnboardingCard.tsx?raw';
import relayOnboardingCardStateSource from '@/components/Dashboard/useRelayOnboardingCardState.ts?raw';
import generalSettingsPanelSource from '../GeneralSettingsPanel.tsx?raw';
@@ -278,6 +285,44 @@ describe('monitored-system model guardrails', () => {
expect(agentLedgerPanelSource).not.toContain('function systemStatusExplanation(');
});
+ it('keeps platform-connection admission preview on the shared monitored-system model', () => {
+ expect(monitoredSystemAdmissionPreviewSource).toContain(
+ "import { formatMonitoredSystemSurfaceAttribution }",
+ );
+ expect(monitoredSystemAdmissionPreviewSource).toContain('Current matched systems');
+ expect(monitoredSystemAdmissionPreviewSource).toContain('Projected systems');
+ expect(monitoredSystemAdmissionPreviewSource).not.toContain('TrueNASAPI.');
+ expect(monitoredSystemAdmissionPreviewSource).not.toContain('VMwareAPI.');
+
+ expect(trueNASSettingsPanelSource).toContain(
+ "import { MonitoredSystemAdmissionPreview } from './MonitoredSystemAdmissionPreview';",
+ );
+ expect(trueNASSettingsPanelSource).toContain('<MonitoredSystemAdmissionPreview');
+ expect(trueNASSettingsPanelSource).toContain('Preview impact');
+ expect(trueNASSettingsPanelStateSource).toContain('const [previewing, setPreviewing]');
+ expect(trueNASSettingsPanelStateSource).toContain('const previewCurrentForm = async () =>');
+ expect(trueNASSettingsPanelStateSource).toContain('TrueNASAPI.previewConnection(payload)');
+ expect(trueNASSettingsPanelStateSource).toContain(
+ 'TrueNASAPI.previewSavedConnection(editingConnectionId()!, payload)',
+ );
+ expect(trueNASApiSource).toContain('static async previewConnection(');
+ expect(trueNASApiSource).toContain('static async previewSavedConnection(');
+
+ expect(vmwareSettingsPanelSource).toContain(
+ "import { MonitoredSystemAdmissionPreview } from './MonitoredSystemAdmissionPreview';",
+ );
+ expect(vmwareSettingsPanelSource).toContain('<MonitoredSystemAdmissionPreview');
+ expect(vmwareSettingsPanelSource).toContain('Preview impact');
+ expect(vmwareSettingsPanelStateSource).toContain('const [previewing, setPreviewing]');
+ expect(vmwareSettingsPanelStateSource).toContain('const previewCurrentForm = async () =>');
+ expect(vmwareSettingsPanelStateSource).toContain('VMwareAPI.previewConnection(payload)');
+ expect(vmwareSettingsPanelStateSource).toContain(
+ 'VMwareAPI.previewSavedConnection(editingConnectionId()!, payload)',
+ );
+ expect(vmwareApiSource).toContain('static async previewConnection(');
+ expect(vmwareApiSource).toContain('static async previewSavedConnection(');
+ });
+
it('keeps APITokenManager runtime usage mapped from unified resources', () => {
expect(apiTokenManagerSource).toContain('import { useAPITokenManagerState }');
expect(apiTokenManagerSource).toContain('useAPITokenManagerState(props)');
diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx
index b1197ed06c..6357fd1fc3 100644
--- a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx
@@ -10,10 +10,13 @@ vi.mock('@/api/truenas', () => ({
createConnection: vi.fn(),
updateConnection: vi.fn(),
deleteConnection: vi.fn(),
+ previewConnection: vi.fn(),
+ previewSavedConnection: vi.fn(),
testConnection: vi.fn(),
testSavedConnection: vi.fn(),
},
- isRedactedTrueNASSecret: (value: string | null | undefined) => (value || '').trim() === '********',
+ isRedactedTrueNASSecret: (value: string | null | undefined) =>
+ (value || '').trim() === '********',
}));
vi.mock('@/stores/notifications', () => ({
@@ -188,4 +191,106 @@ describe('useTrueNASSettingsPanelState', () => {
expect(TrueNASAPI.testConnection).not.toHaveBeenCalled();
expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection successful');
});
+
+ it('previews monitored-system impact through the canonical TrueNAS preview path', async () => {
+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValueOnce([] as never);
+ vi.mocked(TrueNASAPI.previewConnection).mockResolvedValueOnce({
+ current_count: 4,
+ projected_count: 4,
+ additional_count: 0,
+ limit: 10,
+ would_exceed_limit: false,
+ effect: 'attaches_existing',
+ current_systems: [
+ {
+ name: 'tower',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'agent',
+ status_explanation: { summary: '', reasons: [] },
+ latest_included_signal: { name: '', type: '', at: '' },
+ explanation: { summary: '', reasons: [], surfaces: [] },
+ },
+ ],
+ projected_systems: [
+ {
+ name: 'tower',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'multiple',
+ status_explanation: { summary: '', reasons: [] },
+ latest_included_signal: { name: '', type: '', at: '' },
+ explanation: { summary: '', reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ } as never);
+
+ const { result } = renderHook(() => useTrueNASSettingsPanelState());
+ await waitFor(() => expect(result.loading()).toBe(false));
+
+ result.openCreateDialog();
+ result.updateForm({
+ host: 'tower.local',
+ apiKey: 'secret',
+ });
+ const preview = await result.previewCurrentForm();
+
+ expect(TrueNASAPI.previewConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: 'tower.local',
+ apiKey: 'secret',
+ }),
+ );
+ expect(preview?.additional_count).toBe(0);
+ expect(result.monitoredSystemPreview()?.effect).toBe('attaches_existing');
+ });
+
+ it('reuses the canonical monitored-system preview when a save is denied by the backend', async () => {
+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValueOnce([] as never);
+ vi.mocked(TrueNASAPI.createConnection).mockRejectedValueOnce(
+ Object.assign(new Error('Monitored-system limit reached (10/9)'), {
+ status: 402,
+ feature: 'max_monitored_systems',
+ monitored_system_preview: {
+ current_count: 9,
+ projected_count: 10,
+ additional_count: 1,
+ limit: 9,
+ would_exceed_limit: true,
+ effect: 'creates_new',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'tower',
+ type: 'truenas-system',
+ status: 'online',
+ source: 'truenas',
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useTrueNASSettingsPanelState());
+ await waitFor(() => expect(result.loading()).toBe(false));
+
+ result.openCreateDialog();
+ result.updateForm({
+ host: 'tower.local',
+ apiKey: 'secret',
+ });
+ await result.saveCurrentForm();
+
+ expect(notificationStore.error).toHaveBeenCalledWith('Monitored-system limit reached (10/9)');
+ expect(result.monitoredSystemPreview()).toMatchObject({
+ would_exceed_limit: true,
+ projected_count: 10,
+ effect: 'creates_new',
+ });
+ expect(result.dialogOpen()).toBe(true);
+ });
});
diff --git a/frontend-modern/src/components/Settings/__tests__/useVMwareSettingsPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useVMwareSettingsPanelState.test.tsx
index 5d8191158d..d00e42c5fa 100644
--- a/frontend-modern/src/components/Settings/__tests__/useVMwareSettingsPanelState.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/useVMwareSettingsPanelState.test.tsx
@@ -10,6 +10,8 @@ vi.mock('@/api/vmware', () => ({
createConnection: vi.fn(),
updateConnection: vi.fn(),
deleteConnection: vi.fn(),
+ previewConnection: vi.fn(),
+ previewSavedConnection: vi.fn(),
testConnection: vi.fn(),
testSavedConnection: vi.fn(),
},
@@ -355,4 +357,112 @@ describe('useVMwareSettingsPanelState', () => {
expect(result.connections()[0].poll?.lastError?.category).toBe('auth');
expect(result.connections()[0].poll?.lastError?.message).toBe(authError);
});
+
+ it('previews monitored-system impact through the canonical VMware preview path', async () => {
+ vi.mocked(VMwareAPI.listConnections).mockResolvedValueOnce([] as never);
+ vi.mocked(VMwareAPI.previewConnection).mockResolvedValueOnce({
+ current_count: 1,
+ projected_count: 3,
+ additional_count: 2,
+ limit: 5,
+ would_exceed_limit: false,
+ effect: 'creates_multiple',
+ current_systems: [],
+ projected_systems: [
+ {
+ name: 'esxi-01',
+ type: 'host',
+ status: 'online',
+ source: 'vmware',
+ status_explanation: { summary: '', reasons: [] },
+ latest_included_signal: { name: '', type: '', at: '' },
+ explanation: { summary: '', reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ } as never);
+
+ const { result } = renderHook(() => useVMwareSettingsPanelState());
+ await waitFor(() => expect(result.loading()).toBe(false));
+
+ result.openCreateDialog();
+ result.updateForm({
+ host: 'vcsa.lab.local',
+ username: '[email protected]',
+ password: 'secret',
+ });
+ const preview = await result.previewCurrentForm();
+
+ expect(VMwareAPI.previewConnection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: 'vcsa.lab.local',
+ username: '[email protected]',
+ password: 'secret',
+ }),
+ );
+ expect(preview?.additional_count).toBe(2);
+ expect(result.monitoredSystemPreview()?.projected_count).toBe(3);
+ });
+
+ it('reuses the canonical monitored-system preview when a save is denied by the backend', async () => {
+ vi.mocked(VMwareAPI.listConnections).mockResolvedValueOnce([] as never);
+ vi.mocked(VMwareAPI.createConnection).mockRejectedValueOnce(
+ Object.assign(new Error('Monitored-system limit reached (7/6)'), {
+ status: 402,
+ feature: 'max_monitored_systems',
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 7,
+ additional_count: 2,
+ limit: 6,
+ would_exceed_limit: true,
+ effect: 'mixed_existing_and_new',
+ current_systems: [
+ {
+ name: 'esxi-01',
+ type: 'agent',
+ status: 'online',
+ source: 'agent',
+ },
+ ],
+ projected_systems: [
+ {
+ name: 'esxi-01',
+ type: 'agent',
+ status: 'online',
+ source: 'vmware',
+ },
+ {
+ name: 'esxi-02',
+ type: 'agent',
+ status: 'online',
+ source: 'vmware',
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useVMwareSettingsPanelState());
+ await waitFor(() => expect(result.loading()).toBe(false));
+
+ result.openCreateDialog();
+ result.updateForm({
+ host: 'vcsa.lab.local',
+ username: '[email protected]',
+ password: 'secret',
+ });
+ await result.saveCurrentForm();
+
+ expect(notificationStore.error).toHaveBeenCalledWith('Monitored-system limit reached (7/6)');
+ expect(result.monitoredSystemPreview()).toMatchObject({
+ would_exceed_limit: true,
+ projected_count: 7,
+ effect: 'mixed_existing_and_new',
+ });
+ expect(result.dialogOpen()).toBe(true);
+ });
});
diff --git a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts
index b943692702..69ebbf6123 100644
--- a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts
+++ b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts
@@ -1,7 +1,8 @@
import { createMemo, createSignal, onMount } from 'solid-js';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
-import { apiErrorStatus } from '@/api/responseUtils';
+import type { MonitoredSystemLedgerPreviewResponse } from '@/api/monitoredSystemLedger';
+import { apiErrorMonitoredSystemPreview, apiErrorStatus } from '@/api/responseUtils';
import {
TrueNASAPI,
isRedactedTrueNASSecret,
@@ -47,7 +48,9 @@ const createEmptyFormState = (): TrueNASConnectionFormState => ({
hasStoredPassword: false,
});
-const buildFormStateFromConnection = (connection: TrueNASConnection): TrueNASConnectionFormState => {
+const buildFormStateFromConnection = (
+ connection: TrueNASConnection,
+): TrueNASConnectionFormState => {
const hasStoredAPIKey = isRedactedTrueNASSecret(connection.apiKey);
const hasStoredPassword = isRedactedTrueNASSecret(connection.password);
const authMode: TrueNASAuthMode =
@@ -149,16 +152,21 @@ export function useTrueNASSettingsPanelState() {
const [dialogOpen, setDialogOpen] = createSignal(false);
const [deleteDialogOpen, setDeleteDialogOpen] = createSignal(false);
const [editingConnectionId, setEditingConnectionId] = createSignal<string | null>(null);
- const [pendingDeleteConnection, setPendingDeleteConnection] = createSignal<TrueNASConnection | null>(
- null,
- );
+ const [pendingDeleteConnection, setPendingDeleteConnection] =
+ createSignal<TrueNASConnection | null>(null);
const [form, setForm] = createSignal<TrueNASConnectionFormState>(createEmptyFormState());
const [saving, setSaving] = createSignal(false);
const [testing, setTesting] = createSignal(false);
const [deleting, setDeleting] = createSignal(false);
+ const [previewing, setPreviewing] = createSignal(false);
+ const [monitoredSystemPreview, setMonitoredSystemPreview] =
+ createSignal<MonitoredSystemLedgerPreviewResponse | null>(null);
+ const [monitoredSystemPreviewError, setMonitoredSystemPreviewError] = createSignal<string | null>(
+ null,
+ );
- const editingConnection = createMemo(() =>
- connections().find((connection) => connection.id === editingConnectionId()) ?? null,
+ const editingConnection = createMemo(
+ () => connections().find((connection) => connection.id === editingConnectionId()) ?? null,
);
const loadConnections = async () => {
@@ -193,12 +201,16 @@ export function useTrueNASSettingsPanelState() {
const openCreateDialog = () => {
setEditingConnectionId(null);
setForm(createEmptyFormState());
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
setDialogOpen(true);
};
const openEditDialog = (connection: TrueNASConnection) => {
setEditingConnectionId(connection.id);
setForm(buildFormStateFromConnection(connection));
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
setDialogOpen(true);
};
@@ -206,6 +218,8 @@ export function useTrueNASSettingsPanelState() {
setDialogOpen(false);
setEditingConnectionId(null);
setForm(createEmptyFormState());
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
};
const closeDialog = () => {
@@ -228,8 +242,11 @@ export function useTrueNASSettingsPanelState() {
resetDeleteDialogState();
};
- const updateForm = (patch: Partial<TrueNASConnectionFormState>) =>
+ const updateForm = (patch: Partial<TrueNASConnectionFormState>) => {
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
setForm((current) => ({ ...current, ...patch }));
+ };
const testCurrentForm = async () => {
setTesting(true);
@@ -256,7 +273,9 @@ export function useTrueNASSettingsPanelState() {
setTesting(true);
try {
await TrueNASAPI.testSavedConnection(connection.id);
- notificationStore.success(`TrueNAS connection successful for ${connection.name || connection.host}`);
+ notificationStore.success(
+ `TrueNAS connection successful for ${connection.name || connection.host}`,
+ );
} catch (error) {
const message = getErrorMessage(error, 'TrueNAS connection failed');
notificationStore.error(message);
@@ -267,7 +286,32 @@ export function useTrueNASSettingsPanelState() {
}
};
+ const previewCurrentForm = async () => {
+ setPreviewing(true);
+ setMonitoredSystemPreviewError(null);
+ try {
+ const payload = buildConnectionInput(form());
+ const preview = editingConnectionId()
+ ? await TrueNASAPI.previewSavedConnection(editingConnectionId()!, payload)
+ : await TrueNASAPI.previewConnection(payload);
+ setMonitoredSystemPreview(preview);
+ return preview;
+ } catch (error) {
+ const message = getErrorMessage(error, 'Could not preview monitored-system impact');
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(message);
+ logger.error('[TrueNAS Settings] Preview failed', error);
+ return null;
+ } finally {
+ setPreviewing(false);
+ }
+ };
+
const saveCurrentForm = async () => {
+ if (monitoredSystemPreview()?.would_exceed_limit) {
+ notificationStore.error('This change would exceed your monitored-system limit');
+ return;
+ }
setSaving(true);
try {
const payload = buildConnectionInput(form());
@@ -281,6 +325,11 @@ export function useTrueNASSettingsPanelState() {
resetDialogState();
await loadConnections();
} catch (error) {
+ const preview = apiErrorMonitoredSystemPreview(error);
+ if (preview) {
+ setMonitoredSystemPreview(preview);
+ setMonitoredSystemPreviewError(null);
+ }
const message = getErrorMessage(error, 'Failed to save TrueNAS connection');
notificationStore.error(message);
logger.error('[TrueNAS Settings] Save failed', error);
@@ -326,6 +375,10 @@ export function useTrueNASSettingsPanelState() {
openDeleteDialog,
openEditDialog,
pendingDeleteConnection,
+ previewCurrentForm,
+ monitoredSystemPreview,
+ monitoredSystemPreviewError,
+ previewing,
saveCurrentForm,
saving,
testCurrentForm,
diff --git a/frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts b/frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts
index 6b7bab8707..8e387833e5 100644
--- a/frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts
+++ b/frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts
@@ -1,11 +1,17 @@
import { createMemo, createSignal, onMount } from 'solid-js';
+import type { MonitoredSystemLedgerPreviewResponse } from '@/api/monitoredSystemLedger';
import {
VMwareAPI,
isRedactedVMwareSecret,
type VMwareConnection,
type VMwareConnectionInput,
} from '@/api/vmware';
-import { apiErrorCode, apiErrorDetailField, apiErrorStatus } from '@/api/responseUtils';
+import {
+ apiErrorCode,
+ apiErrorDetailField,
+ apiErrorMonitoredSystemPreview,
+ apiErrorStatus,
+} from '@/api/responseUtils';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
import {
@@ -111,8 +117,14 @@ export function useVMwareSettingsPanelState() {
const [saving, setSaving] = createSignal(false);
const [testing, setTesting] = createSignal(false);
const [deleting, setDeleting] = createSignal(false);
+ const [previewing, setPreviewing] = createSignal(false);
const [connectionFailure, setConnectionFailure] =
createSignal<VMwareConnectionFailurePresentation | null>(null);
+ const [monitoredSystemPreview, setMonitoredSystemPreview] =
+ createSignal<MonitoredSystemLedgerPreviewResponse | null>(null);
+ const [monitoredSystemPreviewError, setMonitoredSystemPreviewError] = createSignal<string | null>(
+ null,
+ );
const editingConnection = createMemo(
() => connections().find((connection) => connection.id === editingConnectionId()) ?? null,
@@ -151,6 +163,8 @@ export function useVMwareSettingsPanelState() {
setEditingConnectionId(null);
setForm(createEmptyFormState());
setConnectionFailure(null);
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
setDialogOpen(true);
};
@@ -158,6 +172,8 @@ export function useVMwareSettingsPanelState() {
setEditingConnectionId(connection.id);
setForm(buildFormStateFromConnection(connection));
setConnectionFailure(null);
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
setDialogOpen(true);
};
@@ -166,6 +182,8 @@ export function useVMwareSettingsPanelState() {
setEditingConnectionId(null);
setForm(createEmptyFormState());
setConnectionFailure(null);
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
};
const closeDialog = () => {
@@ -190,6 +208,8 @@ export function useVMwareSettingsPanelState() {
const updateForm = (patch: Partial<VMwareConnectionFormState>) => {
setConnectionFailure(null);
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(null);
setForm((current) => ({ ...current, ...patch }));
};
@@ -246,7 +266,44 @@ export function useVMwareSettingsPanelState() {
}
};
+ const previewCurrentForm = async () => {
+ setPreviewing(true);
+ setConnectionFailure(null);
+ setMonitoredSystemPreviewError(null);
+ try {
+ const payload = buildConnectionInput(form());
+ const preview = editingConnectionId()
+ ? await VMwareAPI.previewSavedConnection(editingConnectionId()!, payload)
+ : await VMwareAPI.previewConnection(payload);
+ setMonitoredSystemPreview(preview);
+ return preview;
+ } catch (error) {
+ const failure = buildVMwareConnectionFailurePresentation({
+ code: apiErrorCode(error),
+ category: apiErrorDetailField(error, 'category'),
+ message: getVMwareErrorMessage(error, 'Could not preview monitored-system impact'),
+ fallback: 'Could not preview monitored-system impact',
+ });
+ setMonitoredSystemPreview(null);
+ setMonitoredSystemPreviewError(failure.message);
+ if (
+ apiErrorCode(error) === 'vmware_connection_failed' ||
+ apiErrorCode(error) === 'vmware_invalid_config'
+ ) {
+ setConnectionFailure(failure);
+ }
+ logger.error('[VMware Settings] Preview failed', error);
+ return null;
+ } finally {
+ setPreviewing(false);
+ }
+ };
+
const saveCurrentForm = async () => {
+ if (monitoredSystemPreview()?.would_exceed_limit) {
+ notificationStore.error('This change would exceed your monitored-system limit');
+ return;
+ }
setSaving(true);
try {
const payload = buildConnectionInput(form());
@@ -260,6 +317,11 @@ export function useVMwareSettingsPanelState() {
resetDialogState();
await loadConnections();
} catch (error) {
+ const preview = apiErrorMonitoredSystemPreview(error);
+ if (preview) {
+ setMonitoredSystemPreview(preview);
+ setMonitoredSystemPreviewError(null);
+ }
const message = getErrorMessage(error, 'Failed to save VMware connection');
notificationStore.error(message);
logger.error('[VMware Settings] Save failed', error);
@@ -306,6 +368,10 @@ export function useVMwareSettingsPanelState() {
openDeleteDialog,
openEditDialog,
pendingDeleteConnection,
+ previewCurrentForm,
+ monitoredSystemPreview,
+ monitoredSystemPreviewError,
+ previewing,
saveCurrentForm,
saving,
testCurrentForm,
diff --git a/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.test.ts b/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.test.ts
index 45e8037685..987123c721 100644
--- a/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.test.ts
@@ -139,8 +139,11 @@ describe('monitoredSystemPresentation', () => {
it('returns customer-facing source and type labels', () => {
expect(getMonitoredSystemSourceLabel('agent')).toBe('Agent');
+ expect(getMonitoredSystemSourceLabel('multiple')).toBe('Multiple Sources');
expect(getMonitoredSystemSourceLabel('pbs')).toBe('PBS');
+ expect(getMonitoredSystemSourceLabel('vmware')).toBe('VMware');
expect(getMonitoredSystemSourceLabel('')).toBe('');
+ expect(getMonitoredSystemSurfaceTypeLabel('agent')).toBe('Host');
expect(getMonitoredSystemSurfaceTypeLabel('docker-host')).toBe('Docker Host');
expect(getMonitoredSystemSurfaceTypeLabel('proxmox-node')).toBe('Proxmox Node');
expect(getMonitoredSystemSurfaceTypeLabel(undefined)).toBe('System');
@@ -162,6 +165,20 @@ describe('monitoredSystemPresentation', () => {
source: 'host',
}),
).toBe('tower (Host)');
+ expect(
+ formatMonitoredSystemSurfaceAttribution({
+ name: 'esxi-01',
+ type: 'host',
+ source: 'vmware',
+ }),
+ ).toBe('esxi-01 (Host via VMware)');
+ expect(
+ formatMonitoredSystemSurfaceAttribution({
+ name: 'tower',
+ type: 'truenas-system',
+ source: 'multiple',
+ }),
+ ).toBe('tower (TrueNAS System via Multiple Sources)');
expect(
formatMonitoredSystemLatestIncludedSignalSentence({
attribution: 'tower (PBS Server via PBS)',
diff --git a/frontend-modern/src/utils/monitoredSystemPresentation.ts b/frontend-modern/src/utils/monitoredSystemPresentation.ts
index 315f00a990..6066881292 100644
--- a/frontend-modern/src/utils/monitoredSystemPresentation.ts
+++ b/frontend-modern/src/utils/monitoredSystemPresentation.ts
@@ -185,12 +185,16 @@ export function getMonitoredSystemSourceLabel(source: string | undefined): strin
return 'Docker';
case 'kubernetes':
return 'Kubernetes';
+ case 'multiple':
+ return 'Multiple Sources';
case 'pbs':
return 'PBS';
case 'pmg':
return 'PMG';
case 'proxmox':
return 'Proxmox';
+ case 'vmware':
+ return 'VMware';
case 'truenas':
return 'TrueNAS';
case '':
@@ -203,6 +207,8 @@ export function getMonitoredSystemSourceLabel(source: string | undefined): strin
export function getMonitoredSystemSurfaceTypeLabel(type: string | undefined): string {
switch (normalizeMonitoredSystemValue(type)) {
+ case 'agent':
+ return 'Host';
case 'docker-host':
return 'Docker Host';
case 'host':
diff --git a/internal/api/monitored_system_ledger.go b/internal/api/monitored_system_ledger.go
index bf491512a5..eda04a4131 100644
--- a/internal/api/monitored_system_ledger.go
+++ b/internal/api/monitored_system_ledger.go
@@ -1,12 +1,13 @@
package api
import (
+ "context"
"encoding/json"
+ "io"
"net/http"
+ "strings"
"time"
- "github.com/rs/zerolog/log"
-
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -69,6 +70,63 @@ type MonitoredSystemLedgerResponse struct {
Limit int `json:"limit"` // 0 = unlimited
}
+// MonitoredSystemLedgerExplainRequest describes an optional monitored-system
+// preview to explain alongside the current counted ledger.
+type MonitoredSystemLedgerExplainRequest struct {
+ Candidate *MonitoredSystemLedgerPreviewCandidate `json:"candidate"`
+ Replacement *MonitoredSystemLedgerPreviewReplacement `json:"replacement"`
+}
+
+// MonitoredSystemLedgerExplainResponse is the response for
+// POST /api/license/monitored-system-ledger/explain.
+type MonitoredSystemLedgerExplainResponse struct {
+ Ledger MonitoredSystemLedgerResponse `json:"ledger"`
+ Preview *MonitoredSystemLedgerPreviewResponse `json:"preview"`
+}
+
+// MonitoredSystemLedgerPreviewRequest describes one prospective monitored-system
+// add or replacement to project through the canonical grouped ledger.
+type MonitoredSystemLedgerPreviewRequest struct {
+ Candidate MonitoredSystemLedgerPreviewCandidate `json:"candidate"`
+ Replacement *MonitoredSystemLedgerPreviewReplacement `json:"replacement"`
+}
+
+type MonitoredSystemLedgerPreviewCandidate struct {
+ Source string `json:"source"`
+ Type string `json:"type"`
+ Name string `json:"name"`
+ Hostname string `json:"hostname"`
+ HostURL string `json:"host_url"`
+ AgentID string `json:"agent_id"`
+ MachineID string `json:"machine_id"`
+ ResourceID string `json:"resource_id"`
+}
+
+type MonitoredSystemLedgerPreviewReplacement struct {
+ Source string `json:"source"`
+ Name string `json:"name"`
+ Hostname string `json:"hostname"`
+ HostURL string `json:"host_url"`
+ AgentID string `json:"agent_id"`
+ MachineID string `json:"machine_id"`
+ ResourceID string `json:"resource_id"`
+}
+
+// MonitoredSystemLedgerPreviewResponse is the response for
+// POST /api/license/monitored-system-ledger/preview.
+type MonitoredSystemLedgerPreviewResponse struct {
+ CurrentCount int `json:"current_count"`
+ ProjectedCount int `json:"projected_count"`
+ AdditionalCount int `json:"additional_count"`
+ Limit int `json:"limit"`
+ WouldExceedLimit bool `json:"would_exceed_limit"`
+ Effect string `json:"effect"`
+ CurrentSystems []MonitoredSystemLedgerEntry `json:"current_systems"`
+ ProjectedSystems []MonitoredSystemLedgerEntry `json:"projected_systems"`
+ CurrentSystem *MonitoredSystemLedgerEntry `json:"current_system"`
+ ProjectedSystem *MonitoredSystemLedgerEntry `json:"projected_system"`
+}
+
func EmptyMonitoredSystemLedgerResponse() MonitoredSystemLedgerResponse {
return MonitoredSystemLedgerResponse{}.NormalizeCollections()
}
@@ -83,6 +141,15 @@ func (r MonitoredSystemLedgerResponse) NormalizeCollections() MonitoredSystemLed
return r
}
+func (r MonitoredSystemLedgerExplainResponse) NormalizeCollections() MonitoredSystemLedgerExplainResponse {
+ r.Ledger = r.Ledger.NormalizeCollections()
+ if r.Preview != nil {
+ preview := r.Preview.NormalizeCollections()
+ r.Preview = &preview
+ }
+ return r
+}
+
func (e MonitoredSystemLedgerEntry) NormalizeCollections() MonitoredSystemLedgerEntry {
if e.LatestIncludedSignal.Name == "" {
e.LatestIncludedSignal.Name = "Unnamed source"
@@ -103,46 +170,148 @@ func (e MonitoredSystemLedgerEntry) NormalizeCollections() MonitoredSystemLedger
}
func (r *Router) handleMonitoredSystemLedger(w http.ResponseWriter, req *http.Request) {
- orgID := GetOrgID(req.Context())
-
- // Get canonical monitored systems from the unified ReadState surface.
- var systems []unifiedresources.MonitoredSystemRecord
- var monitorResolved bool
- if r.mtMonitor != nil {
- monitor, monErr := r.mtMonitor.GetMonitor(orgID)
- if monErr != nil {
- log.Warn().Err(monErr).Str("org", orgID).Msg("monitored-system-ledger: failed to resolve tenant monitor")
- }
- if monitor != nil {
- if rs := monitor.GetUnifiedReadState(); rs != nil {
- systems = unifiedresources.MonitoredSystems(rs)
- }
- monitorResolved = true
- }
+ usage := monitoredSystemUsage(r.getTenantMonitor(req.Context()))
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
}
- // Fallback to the default monitor only for the default org to avoid cross-tenant data leaks.
- if !monitorResolved && orgID == "default" && r.monitor != nil {
- if rs := r.monitor.GetUnifiedReadState(); rs != nil {
- systems = unifiedresources.MonitoredSystems(rs)
+
+ resp := monitoredSystemLedgerResponseFromReadState(req.Context(), usage.readState)
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp.NormalizeCollections())
+}
+
+func (r *Router) handleMonitoredSystemLedgerPreview(w http.ResponseWriter, req *http.Request) {
+ var previewReq MonitoredSystemLedgerPreviewRequest
+ decoder := json.NewDecoder(req.Body)
+ if err := decoder.Decode(&previewReq); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
+ return
+ }
+
+ candidate, err := previewReq.Candidate.toUnifiedCandidate()
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+
+ monitor := r.getTenantMonitor(req.Context())
+ usage := monitoredSystemUsage(monitor)
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
+ }
+
+ var preview unifiedresources.MonitoredSystemProjectionPreview
+ if previewReq.Replacement != nil {
+ replacement, err := previewReq.Replacement.toUnifiedReplacement(candidate.Source)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
}
+ preview = unifiedresources.PreviewMonitoredSystemCandidateReplacement(usage.readState, replacement, candidate)
+ } else {
+ preview = unifiedresources.PreviewMonitoredSystemCandidate(usage.readState, candidate)
}
- entries := make([]MonitoredSystemLedgerEntry, 0, len(systems))
- for _, system := range systems {
- entries = append(entries, monitoredSystemLedgerEntry(system))
+ if len(preview.ProjectedSystems) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Candidate did not resolve to a canonical monitored system preview", nil)
+ return
}
- limit := maxMonitoredSystemsLimitForContext(req.Context())
+ resp := monitoredSystemLedgerPreviewResponse(req.Context(), previewReq.Replacement != nil, preview)
- resp := EmptyMonitoredSystemLedgerResponse()
- resp.Systems = entries
- resp.Total = len(entries)
- resp.Limit = limit
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(resp.NormalizeCollections())
+}
+
+func (r *Router) handleMonitoredSystemLedgerExplain(w http.ResponseWriter, req *http.Request) {
+ var explainReq MonitoredSystemLedgerExplainRequest
+ decoder := json.NewDecoder(req.Body)
+ if err := decoder.Decode(&explainReq); err != nil && err != io.EOF {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
+ return
+ }
+ if explainReq.Candidate == nil && explainReq.Replacement != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "candidate is required when replacement is provided", nil)
+ return
+ }
+
+ usage := monitoredSystemUsage(r.getTenantMonitor(req.Context()))
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
+ }
+
+ resp := MonitoredSystemLedgerExplainResponse{
+ Ledger: monitoredSystemLedgerResponseFromReadState(req.Context(), usage.readState),
+ }
+
+ if explainReq.Candidate != nil {
+ candidate, err := explainReq.Candidate.toUnifiedCandidate()
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+
+ var preview unifiedresources.MonitoredSystemProjectionPreview
+ if explainReq.Replacement != nil {
+ replacement, err := explainReq.Replacement.toUnifiedReplacement(candidate.Source)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+ preview = unifiedresources.PreviewMonitoredSystemCandidateReplacement(
+ usage.readState,
+ replacement,
+ candidate,
+ )
+ } else {
+ preview = unifiedresources.PreviewMonitoredSystemCandidate(usage.readState, candidate)
+ }
+
+ if len(preview.ProjectedSystems) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Candidate did not resolve to a canonical monitored system preview", nil)
+ return
+ }
+
+ previewResp := monitoredSystemLedgerPreviewResponse(
+ req.Context(),
+ explainReq.Replacement != nil,
+ preview,
+ ).NormalizeCollections()
+ resp.Preview = &previewResp
+ }
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp.NormalizeCollections())
}
+func (r MonitoredSystemLedgerPreviewResponse) NormalizeCollections() MonitoredSystemLedgerPreviewResponse {
+ if r.CurrentSystems == nil {
+ r.CurrentSystems = []MonitoredSystemLedgerEntry{}
+ }
+ if r.ProjectedSystems == nil {
+ r.ProjectedSystems = []MonitoredSystemLedgerEntry{}
+ }
+ for i := range r.CurrentSystems {
+ r.CurrentSystems[i] = r.CurrentSystems[i].NormalizeCollections()
+ }
+ for i := range r.ProjectedSystems {
+ r.ProjectedSystems[i] = r.ProjectedSystems[i].NormalizeCollections()
+ }
+ if r.CurrentSystem != nil {
+ entry := r.CurrentSystem.NormalizeCollections()
+ r.CurrentSystem = &entry
+ }
+ if r.ProjectedSystem != nil {
+ entry := r.ProjectedSystem.NormalizeCollections()
+ r.ProjectedSystem = &entry
+ }
+ return r
+}
+
func monitoredSystemLedgerEntry(system unifiedresources.MonitoredSystemRecord) MonitoredSystemLedgerEntry {
status := normalizeStatus(string(system.Status))
latestIncludedSignal := monitoredSystemLedgerLatestSignal(system.LatestIncludedSignal)
@@ -157,6 +326,71 @@ func monitoredSystemLedgerEntry(system unifiedresources.MonitoredSystemRecord) M
}
}
+func monitoredSystemLedgerEntryPointer(system *unifiedresources.MonitoredSystemRecord) *MonitoredSystemLedgerEntry {
+ if system == nil {
+ return nil
+ }
+ entry := monitoredSystemLedgerEntry(*system)
+ return &entry
+}
+
+func monitoredSystemLedgerEntries(
+ systems []unifiedresources.MonitoredSystemRecord,
+) []MonitoredSystemLedgerEntry {
+ if len(systems) == 0 {
+ return []MonitoredSystemLedgerEntry{}
+ }
+ entries := make([]MonitoredSystemLedgerEntry, 0, len(systems))
+ for _, system := range systems {
+ entries = append(entries, monitoredSystemLedgerEntry(system))
+ }
+ return entries
+}
+
+func monitoredSystemLedgerResponseFromReadState(
+ ctx context.Context,
+ rs unifiedresources.ReadState,
+) MonitoredSystemLedgerResponse {
+ systems := unifiedresources.MonitoredSystems(rs)
+ entries := monitoredSystemLedgerEntries(systems)
+ return MonitoredSystemLedgerResponse{
+ Systems: entries,
+ Total: len(entries),
+ Limit: maxMonitoredSystemsLimitForContext(ctx),
+ }
+}
+
+func monitoredSystemLedgerPreviewResponse(
+ ctx context.Context,
+ hasReplacement bool,
+ preview unifiedresources.MonitoredSystemProjectionPreview,
+) MonitoredSystemLedgerPreviewResponse {
+ limit := maxMonitoredSystemsLimitForContext(ctx)
+ decision := monitoredSystemLimitDecisionFromAdditional(ctx, limit, preview.CurrentCount, preview.AdditionalCount)
+ currentSystems := monitoredSystemLedgerEntries(preview.CurrentSystems)
+ projectedSystems := monitoredSystemLedgerEntries(preview.ProjectedSystems)
+
+ resp := MonitoredSystemLedgerPreviewResponse{
+ CurrentCount: preview.CurrentCount,
+ ProjectedCount: preview.ProjectedCount,
+ AdditionalCount: preview.AdditionalCount,
+ Limit: limit,
+ WouldExceedLimit: decision.exceeded,
+ Effect: monitoredSystemLedgerPreviewEffect(hasReplacement, preview),
+ CurrentSystems: currentSystems,
+ ProjectedSystems: projectedSystems,
+ }
+ if len(currentSystems) == 1 {
+ entry := currentSystems[0]
+ resp.CurrentSystem = &entry
+ }
+ if len(projectedSystems) == 1 {
+ entry := projectedSystems[0]
+ resp.ProjectedSystem = &entry
+ }
+ return resp
+}
+
// ---------------------------------------------------------------------------
// Status helpers
// ---------------------------------------------------------------------------
@@ -222,7 +456,7 @@ func normalizeMonitoredSystemLedgerReasonStatus(status string) string {
func normalizeMonitoredSystemLedgerSource(source string) string {
switch source {
- case "agent", "docker", "kubernetes", "pbs", "pmg", "proxmox", "truenas":
+ case "agent", "docker", "kubernetes", "pbs", "pmg", "proxmox", "truenas", "vmware":
return source
default:
return ""
@@ -274,3 +508,113 @@ func monitoredSystemLedgerExplanation(
Surfaces: surfaces,
}
}
+
+func (c MonitoredSystemLedgerPreviewCandidate) toUnifiedCandidate() (unifiedresources.MonitoredSystemCandidate, error) {
+ source := normalizedMonitoredSystemLedgerDataSource(c.Source)
+ if source == "" {
+ return unifiedresources.MonitoredSystemCandidate{}, errMonitoredSystemLedgerValidation("candidate.source is required")
+ }
+ if strings.TrimSpace(c.Name) == "" &&
+ strings.TrimSpace(c.Hostname) == "" &&
+ strings.TrimSpace(c.HostURL) == "" &&
+ strings.TrimSpace(c.ResourceID) == "" &&
+ strings.TrimSpace(c.AgentID) == "" &&
+ strings.TrimSpace(c.MachineID) == "" {
+ return unifiedresources.MonitoredSystemCandidate{}, errMonitoredSystemLedgerValidation("candidate must include at least one canonical identifier or display field")
+ }
+
+ return unifiedresources.MonitoredSystemCandidate{
+ Source: source,
+ Type: unifiedresources.ResourceType(strings.TrimSpace(c.Type)),
+ Name: strings.TrimSpace(c.Name),
+ Hostname: strings.TrimSpace(c.Hostname),
+ HostURL: strings.TrimSpace(c.HostURL),
+ AgentID: strings.TrimSpace(c.AgentID),
+ MachineID: strings.TrimSpace(c.MachineID),
+ ResourceID: strings.TrimSpace(c.ResourceID),
+ }, nil
+}
+
+func (r MonitoredSystemLedgerPreviewReplacement) toUnifiedReplacement(
+ fallbackSource unifiedresources.DataSource,
+) (unifiedresources.MonitoredSystemReplacement, error) {
+ source := normalizedMonitoredSystemLedgerDataSource(r.Source)
+ if source == "" {
+ source = fallbackSource
+ }
+ if source == "" {
+ return unifiedresources.MonitoredSystemReplacement{}, errMonitoredSystemLedgerValidation("replacement.source is required")
+ }
+ if strings.TrimSpace(r.Name) == "" &&
+ strings.TrimSpace(r.Hostname) == "" &&
+ strings.TrimSpace(r.HostURL) == "" &&
+ strings.TrimSpace(r.ResourceID) == "" &&
+ strings.TrimSpace(r.AgentID) == "" &&
+ strings.TrimSpace(r.MachineID) == "" {
+ return unifiedresources.MonitoredSystemReplacement{}, errMonitoredSystemLedgerValidation("replacement must include at least one canonical selector field")
+ }
+
+ return unifiedresources.MonitoredSystemReplacement{
+ Source: source,
+ Selector: unifiedresources.MonitoredSystemReplacementSelector{
+ Name: strings.TrimSpace(r.Name),
+ Hostname: strings.TrimSpace(r.Hostname),
+ HostURL: strings.TrimSpace(r.HostURL),
+ AgentID: strings.TrimSpace(r.AgentID),
+ MachineID: strings.TrimSpace(r.MachineID),
+ ResourceID: strings.TrimSpace(r.ResourceID),
+ },
+ }, nil
+}
+
+func normalizedMonitoredSystemLedgerDataSource(source string) unifiedresources.DataSource {
+ normalized := normalizeMonitoredSystemLedgerSource(strings.ToLower(strings.TrimSpace(source)))
+ if normalized == "" {
+ return ""
+ }
+ return unifiedresources.DataSource(normalized)
+}
+
+func monitoredSystemLedgerPreviewEffect(
+ hasReplacement bool,
+ preview unifiedresources.MonitoredSystemProjectionPreview,
+) string {
+ currentCount := len(preview.CurrentSystems)
+ projectedCount := len(preview.ProjectedSystems)
+
+ if !hasReplacement {
+ if preview.AdditionalCount == 0 && currentCount > 0 {
+ return "attaches_existing"
+ }
+ if projectedCount > 1 && currentCount > 0 {
+ return "mixed_existing_and_new"
+ }
+ if projectedCount > 1 {
+ return "creates_multiple"
+ }
+ return "creates_new"
+ }
+ if currentCount == 0 {
+ if projectedCount > 1 {
+ return "creates_multiple"
+ }
+ return "creates_new"
+ }
+ if preview.AdditionalCount > 0 {
+ return "splits_existing"
+ }
+ if currentCount > 1 || projectedCount > 1 {
+ return "replaces_multiple"
+ }
+ return "replaces_existing"
+}
+
+func errMonitoredSystemLedgerValidation(message string) error {
+ return monitoredSystemLedgerValidationError(message)
+}
+
+type monitoredSystemLedgerValidationError string
+
+func (e monitoredSystemLedgerValidationError) Error() string {
+ return string(e)
+}
diff --git a/internal/api/monitored_system_ledger_test.go b/internal/api/monitored_system_ledger_test.go
index 9006b69743..7e56d2490c 100644
--- a/internal/api/monitored_system_ledger_test.go
+++ b/internal/api/monitored_system_ledger_test.go
@@ -1,12 +1,15 @@
package api
import (
+ "bytes"
"encoding/json"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
@@ -326,3 +329,215 @@ func TestHandleMonitoredSystemLedgerHTTP(t *testing.T) {
t.Errorf("expected explanation summary, got %+v", decoded.Systems[0].Explanation)
}
}
+
+func TestHandleMonitoredSystemLedgerPreviewHTTP(t *testing.T) {
+ setMaxMonitoredSystemsLicenseForTests(t, 1)
+
+ monitor, state, _ := newTestMonitor(t)
+ state.Hosts = []models.Host{
+ {
+ ID: "host-1",
+ Hostname: "tower.local",
+ DisplayName: "Tower",
+ Status: "online",
+ LastSeen: time.Date(2026, 4, 8, 10, 0, 0, 0, time.UTC),
+ MachineID: "machine-1",
+ AgentVersion: "1.0.0",
+ },
+ }
+ syncTestResourceStore(t, monitor, state)
+
+ body := bytes.NewBufferString(`{
+ "candidate":{
+ "source":"proxmox",
+ "name":"tower",
+ "hostname":"tower.local",
+ "host_url":"https://tower.local:8006"
+ }
+ }`)
+ req := httptest.NewRequest(http.MethodPost, "/api/license/monitored-system-ledger/preview", body)
+ rec := httptest.NewRecorder()
+
+ router := &Router{monitor: monitor}
+ router.handleMonitoredSystemLedgerPreview(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var decoded MonitoredSystemLedgerPreviewResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if decoded.CurrentCount != 1 || decoded.ProjectedCount != 1 || decoded.AdditionalCount != 0 {
+ t.Fatalf("unexpected counts: %+v", decoded)
+ }
+ if decoded.Limit != 1 {
+ t.Fatalf("Limit = %d, want 1", decoded.Limit)
+ }
+ if decoded.WouldExceedLimit {
+ t.Fatalf("expected attach preview to stay within limit, got %+v", decoded)
+ }
+ if decoded.Effect != "attaches_existing" {
+ t.Fatalf("Effect = %q, want attaches_existing", decoded.Effect)
+ }
+ if decoded.CurrentSystem == nil {
+ t.Fatal("expected current system payload")
+ }
+ if decoded.ProjectedSystem == nil {
+ t.Fatal("expected projected system payload")
+ }
+ if len(decoded.CurrentSystems) != 1 {
+ t.Fatalf("len(CurrentSystems) = %d, want 1", len(decoded.CurrentSystems))
+ }
+ if len(decoded.ProjectedSystems) != 1 {
+ t.Fatalf("len(ProjectedSystems) = %d, want 1", len(decoded.ProjectedSystems))
+ }
+ if decoded.CurrentSystem.Source != "agent" {
+ t.Fatalf("CurrentSystem.Source = %q, want agent", decoded.CurrentSystem.Source)
+ }
+ if decoded.ProjectedSystem.Source != "multiple" {
+ t.Fatalf("ProjectedSystem.Source = %q, want multiple", decoded.ProjectedSystem.Source)
+ }
+ if len(decoded.ProjectedSystem.Explanation.Surfaces) != 2 {
+ t.Fatalf("expected projected system surfaces to normalize, got %+v", decoded.ProjectedSystem.Explanation.Surfaces)
+ }
+}
+
+func TestHandleMonitoredSystemLedgerPreviewUnavailableUsage(t *testing.T) {
+ setMaxMonitoredSystemsLicenseForTests(t, 1)
+
+ body := bytes.NewBufferString(`{
+ "candidate":{
+ "source":"proxmox",
+ "name":"tower",
+ "hostname":"tower.local",
+ "host_url":"https://tower.local:8006"
+ }
+ }`)
+ req := httptest.NewRequest(http.MethodPost, "/api/license/monitored-system-ledger/preview", body)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMonitoredSystemLedgerPreview(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("expected 503, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "monitored_system_usage_unavailable") {
+ t.Fatalf("expected unavailable usage error body, got %s", rec.Body.String())
+ }
+}
+
+func TestHandleMonitoredSystemLedgerUnavailableUsage(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/license/monitored-system-ledger", nil)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMonitoredSystemLedger(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("expected 503, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "monitored_system_usage_unavailable") {
+ t.Fatalf("expected unavailable usage error body, got %s", rec.Body.String())
+ }
+}
+
+func TestHandleMonitoredSystemLedgerExplainCurrentAndPreview(t *testing.T) {
+ setMaxMonitoredSystemsLicenseForTests(t, 1)
+
+ monitor, state, _ := newTestMonitor(t)
+ state.Hosts = []models.Host{
+ {
+ ID: "host-1",
+ Hostname: "tower.local",
+ DisplayName: "Tower",
+ Status: "online",
+ LastSeen: time.Date(2026, 4, 8, 10, 0, 0, 0, time.UTC),
+ MachineID: "machine-1",
+ AgentVersion: "1.0.0",
+ },
+ }
+ syncTestResourceStore(t, monitor, state)
+
+ body := bytes.NewBufferString(`{
+ "candidate":{
+ "source":"proxmox",
+ "name":"tower",
+ "hostname":"tower.local",
+ "host_url":"https://tower.local:8006"
+ }
+ }`)
+ req := httptest.NewRequest(http.MethodPost, "/api/license/monitored-system-ledger/explain", body)
+ rec := httptest.NewRecorder()
+
+ router := &Router{monitor: monitor}
+ router.handleMonitoredSystemLedgerExplain(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var decoded MonitoredSystemLedgerExplainResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if decoded.Ledger.Total != 1 {
+ t.Fatalf("Ledger.Total = %d, want 1", decoded.Ledger.Total)
+ }
+ if decoded.Ledger.Limit != 1 {
+ t.Fatalf("Ledger.Limit = %d, want 1", decoded.Ledger.Limit)
+ }
+ if len(decoded.Ledger.Systems) != 1 {
+ t.Fatalf("len(Ledger.Systems) = %d, want 1", len(decoded.Ledger.Systems))
+ }
+ if decoded.Preview == nil {
+ t.Fatal("expected preview payload")
+ }
+ if decoded.Preview.CurrentCount != 1 || decoded.Preview.ProjectedCount != 1 {
+ t.Fatalf("unexpected preview counts: %+v", decoded.Preview)
+ }
+ if decoded.Preview.Effect != "attaches_existing" {
+ t.Fatalf("Preview.Effect = %q, want attaches_existing", decoded.Preview.Effect)
+ }
+}
+
+func TestHandleMonitoredSystemLedgerExplainCurrentOnly(t *testing.T) {
+ setMaxMonitoredSystemsLicenseForTests(t, 2)
+
+ monitor, state, _ := newTestMonitor(t)
+ state.Hosts = []models.Host{
+ {
+ ID: "host-1",
+ Hostname: "tower.local",
+ DisplayName: "Tower",
+ Status: "online",
+ LastSeen: time.Date(2026, 4, 8, 10, 0, 0, 0, time.UTC),
+ MachineID: "machine-1",
+ AgentVersion: "1.0.0",
+ },
+ }
+ syncTestResourceStore(t, monitor, state)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/license/monitored-system-ledger/explain", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ router := &Router{monitor: monitor}
+ router.handleMonitoredSystemLedgerExplain(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var decoded MonitoredSystemLedgerExplainResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if decoded.Preview != nil {
+ t.Fatalf("expected nil preview, got %+v", decoded.Preview)
+ }
+ if decoded.Ledger.Total != 1 || decoded.Ledger.Limit != 2 {
+ t.Fatalf("unexpected ledger payload: %+v", decoded.Ledger)
+ }
+}
diff --git a/internal/api/monitored_system_limit_enforcement.go b/internal/api/monitored_system_limit_enforcement.go
index ed5778f5d8..5b7a5b1eb1 100644
--- a/internal/api/monitored_system_limit_enforcement.go
+++ b/internal/api/monitored_system_limit_enforcement.go
@@ -144,6 +144,7 @@ type monitoredSystemLimitDecision struct {
additional int
usageAvailable bool
exceeded bool
+ preview *MonitoredSystemLedgerPreviewResponse
}
func legacyConnectionCounts(monitor *monitoring.Monitor) legacyConnectionCountsModel {
@@ -154,12 +155,21 @@ func legacyConnectionCountsFromReadState(rs unifiedresources.ReadState) legacyCo
return legacyConnectionCountsModel{}
}
-func writeMaxMonitoredSystemsLimitExceeded(w http.ResponseWriter, current, limit int) {
- WriteLicenseRequired(
- w,
- maxMonitoredSystemsLicenseGateKey,
- monitoredSystemLimitExceededMessageFromLicensing(current, limit),
- )
+func monitoredSystemLimitExceededPayload(decision monitoredSystemLimitDecision) map[string]interface{} {
+ payload := map[string]interface{}{
+ "error": "license_required",
+ "message": monitoredSystemLimitExceededMessageFromLicensing(decision.current, decision.limit),
+ "feature": maxMonitoredSystemsLicenseGateKey,
+ "upgrade_url": upgradeURLForFeatureFromLicensing(maxMonitoredSystemsLicenseGateKey),
+ }
+ if decision.preview != nil {
+ payload["monitored_system_preview"] = decision.preview.NormalizeCollections()
+ }
+ return payload
+}
+
+func writeMaxMonitoredSystemsLimitExceeded(w http.ResponseWriter, decision monitoredSystemLimitDecision) {
+ writePaymentRequired(w, monitoredSystemLimitExceededPayload(decision))
}
func writeMonitoredSystemUsageUnavailable(w http.ResponseWriter) {
@@ -196,6 +206,23 @@ func monitoredSystemLimitDecisionFromAdditional(
}
}
+func monitoredSystemLimitDecisionFromPreview(
+ ctx context.Context,
+ limit int,
+ hasReplacement bool,
+ preview unifiedresources.MonitoredSystemProjectionPreview,
+) monitoredSystemLimitDecision {
+ decision := monitoredSystemLimitDecisionFromAdditional(
+ ctx,
+ limit,
+ preview.CurrentCount,
+ preview.AdditionalCount,
+ )
+ resp := monitoredSystemLedgerPreviewResponse(ctx, hasReplacement, preview).NormalizeCollections()
+ decision.preview = &resp
+ return decision
+}
+
func monitoredSystemLimitDecisionForCandidate(
ctx context.Context,
monitor *monitoring.Monitor,
@@ -216,8 +243,8 @@ func monitoredSystemLimitDecisionForCandidate(
}
}
- projection := unifiedresources.ProjectMonitoredSystemCandidate(usage.readState, candidate)
- return monitoredSystemLimitDecisionFromAdditional(ctx, limit, projection.CurrentCount, projection.AdditionalCount)
+ projection := unifiedresources.PreviewMonitoredSystemCandidate(usage.readState, candidate)
+ return monitoredSystemLimitDecisionFromPreview(ctx, limit, false, projection)
}
func monitoredSystemLimitDecisionForCandidateReplacement(
@@ -241,8 +268,12 @@ func monitoredSystemLimitDecisionForCandidateReplacement(
}
}
- projection := unifiedresources.ProjectMonitoredSystemCandidateReplacement(usage.readState, replacement, candidate)
- return monitoredSystemLimitDecisionFromAdditional(ctx, limit, projection.CurrentCount, projection.AdditionalCount)
+ projection := unifiedresources.PreviewMonitoredSystemCandidateReplacement(
+ usage.readState,
+ replacement,
+ candidate,
+ )
+ return monitoredSystemLimitDecisionFromPreview(ctx, limit, true, projection)
}
func monitoredSystemLimitDecisionForRecords(
@@ -265,8 +296,8 @@ func monitoredSystemLimitDecisionForRecords(
}
}
- projection := unifiedresources.ProjectMonitoredSystemRecords(usage.readState, recordsBySource)
- return monitoredSystemLimitDecisionFromAdditional(ctx, limit, projection.CurrentCount, projection.AdditionalCount)
+ projection := unifiedresources.PreviewMonitoredSystemRecords(usage.readState, recordsBySource)
+ return monitoredSystemLimitDecisionFromPreview(ctx, limit, false, projection)
}
func monitoredSystemLimitDecisionForRecordsReplacement(
@@ -290,8 +321,12 @@ func monitoredSystemLimitDecisionForRecordsReplacement(
}
}
- projection := unifiedresources.ProjectMonitoredSystemRecordsReplacement(usage.readState, replacement, recordsBySource)
- return monitoredSystemLimitDecisionFromAdditional(ctx, limit, projection.CurrentCount, projection.AdditionalCount)
+ projection := unifiedresources.PreviewMonitoredSystemRecordsReplacement(
+ usage.readState,
+ replacement,
+ recordsBySource,
+ )
+ return monitoredSystemLimitDecisionFromPreview(ctx, limit, true, projection)
}
func monitoredSystemLimitDecisionForAdditionalSlots(
@@ -335,7 +370,7 @@ func enforceMonitoredSystemLimitForConfigRegistration(
}
emitLimitBlockedEvent(ctx, decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -356,7 +391,7 @@ func enforceMonitoredSystemLimitForConfigReplacement(
}
emitLimitBlockedEvent(ctx, decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -393,7 +428,7 @@ func enforceMonitoredSystemLimitForHostReport(
}
emitLimitBlockedEvent(ctx, decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -473,7 +508,7 @@ func enforceMonitoredSystemLimitForDockerReport(
}
emitLimitBlockedEvent(ctx, decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -513,7 +548,7 @@ func enforceMonitoredSystemLimitForKubernetesReport(
}
emitLimitBlockedEvent(ctx, decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
diff --git a/internal/api/monitored_system_limit_enforcement_test.go b/internal/api/monitored_system_limit_enforcement_test.go
index 66ad5a7291..632db088e5 100644
--- a/internal/api/monitored_system_limit_enforcement_test.go
+++ b/internal/api/monitored_system_limit_enforcement_test.go
@@ -2,6 +2,7 @@ package api
import (
"context"
+ "encoding/json"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -11,6 +12,26 @@ import (
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
)
+type monitoredSystemLimitBlockedPayload struct {
+ Error string `json:"error"`
+ Feature string `json:"feature"`
+ Message string `json:"message"`
+ MonitoredSystemPreview MonitoredSystemLedgerPreviewResponse `json:"monitored_system_preview"`
+}
+
+func decodeMonitoredSystemLimitBlockedPayload(
+ t *testing.T,
+ body []byte,
+) monitoredSystemLimitBlockedPayload {
+ t.Helper()
+
+ var payload monitoredSystemLimitBlockedPayload
+ if err := json.Unmarshal(body, &payload); err != nil {
+ t.Fatalf("decode monitored-system limit blocked payload: %v", err)
+ }
+ return payload
+}
+
func TestMonitoredSystemCountNilMonitor(t *testing.T) {
got := monitoredSystemCount(nil)
if got != 0 {
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index fdb5933558..96eef85558 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -82,6 +82,7 @@ func TestRouterRouteInventory_VMwarePhase1ExclusionIntegrity(t *testing.T) {
expected := []string{
"/api/vmware/connections",
"/api/vmware/connections/",
+ "/api/vmware/connections/preview",
"/api/vmware/connections/test",
}
if strings.Join(vmwareRoutes, ",") != strings.Join(expected, ",") {
@@ -300,9 +301,11 @@ var bareRouteAllowlist = []string{
"/api/config/nodes/test-connection",
"/api/config/system",
"/api/truenas/connections",
+ "/api/truenas/connections/preview",
"/api/truenas/connections/test",
"/api/truenas/connections/",
"/api/vmware/connections",
+ "/api/vmware/connections/preview",
"/api/vmware/connections/test",
"/api/vmware/connections/",
"/api/health",
@@ -429,9 +432,11 @@ var allRouteAllowlist = []string{
"/api/config/nodes/test-connection",
"/api/config/nodes/",
"/api/truenas/connections",
+ "/api/truenas/connections/preview",
"/api/truenas/connections/test",
"/api/truenas/connections/",
"/api/vmware/connections",
+ "/api/vmware/connections/preview",
"/api/vmware/connections/test",
"/api/vmware/connections/",
"/api/admin/profiles/",
@@ -449,6 +454,8 @@ var allRouteAllowlist = []string{
"GET /api/license/entitlements",
"POST /api/license/trial/start",
"GET /api/license/monitored-system-ledger",
+ "POST /api/license/monitored-system-ledger/explain",
+ "POST /api/license/monitored-system-ledger/preview",
"POST /api/upgrade-metrics/events",
"GET /api/upgrade-metrics/stats",
"GET /api/upgrade-metrics/health",
diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.go
index d0bbb97288..8eefe519db 100644
--- a/internal/api/router_routes_licensing.go
+++ b/internal/api/router_routes_licensing.go
@@ -41,6 +41,8 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHan
r.mux.HandleFunc("GET /api/license/commercial-posture", RequireAuth(r.config, r.licenseHandlers.HandleCommercialPosture))
r.mux.HandleFunc("GET /api/license/entitlements", RequireAuth(r.config, r.licenseHandlers.HandleEntitlements))
r.mux.HandleFunc("GET /api/license/monitored-system-ledger", RequireAuth(r.config, r.handleMonitoredSystemLedger))
+ r.mux.HandleFunc("POST /api/license/monitored-system-ledger/explain", RequireAuth(r.config, r.handleMonitoredSystemLedgerExplain))
+ r.mux.HandleFunc("POST /api/license/monitored-system-ledger/preview", RequireAuth(r.config, r.handleMonitoredSystemLedgerPreview))
r.mux.HandleFunc("POST /api/license/trial/start", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.licenseHandlers.HandleStartTrial)))
// Local upgrade metrics (formerly "conversion" telemetry). Canonical routes:
diff --git a/internal/api/router_routes_registration.go b/internal/api/router_routes_registration.go
index fb9345de18..6706c9db0c 100644
--- a/internal/api/router_routes_registration.go
+++ b/internal/api/router_routes_registration.go
@@ -206,6 +206,19 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
}
})
+ r.mux.HandleFunc("/api/truenas/connections/preview", func(w http.ResponseWriter, req *http.Request) {
+ if r.trueNASHandlers == nil {
+ writeErrorResponse(w, http.StatusServiceUnavailable, "truenas_unavailable", "TrueNAS service unavailable", nil)
+ return
+ }
+
+ if req.Method == http.MethodPost {
+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandlePreviewConnection))(w, req)
+ } else {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+ })
+
r.mux.HandleFunc("/api/truenas/connections/", func(w http.ResponseWriter, req *http.Request) {
if r.trueNASHandlers == nil {
writeErrorResponse(w, http.StatusServiceUnavailable, "truenas_unavailable", "TrueNAS service unavailable", nil)
@@ -214,6 +227,8 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/test") {
RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleTestSavedConnection))(w, req)
+ } else if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/preview") {
+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandlePreviewSavedConnection))(w, req)
} else if req.Method == http.MethodDelete {
RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleDelete))(w, req)
} else if req.Method == http.MethodPut {
@@ -253,6 +268,19 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
}
})
+ r.mux.HandleFunc("/api/vmware/connections/preview", func(w http.ResponseWriter, req *http.Request) {
+ if r.vmwareHandlers == nil {
+ writeErrorResponse(w, http.StatusServiceUnavailable, "vmware_unavailable", "VMware service unavailable", nil)
+ return
+ }
+
+ if req.Method == http.MethodPost {
+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandlePreviewConnection))(w, req)
+ } else {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+ })
+
r.mux.HandleFunc("/api/vmware/connections/", func(w http.ResponseWriter, req *http.Request) {
if r.vmwareHandlers == nil {
writeErrorResponse(w, http.StatusServiceUnavailable, "vmware_unavailable", "VMware service unavailable", nil)
@@ -261,6 +289,8 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {
if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/test") {
RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleTestSavedConnection))(w, req)
+ } else if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/preview") {
+ RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandlePreviewSavedConnection))(w, req)
} else if req.Method == http.MethodDelete {
RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleDelete))(w, req)
} else if req.Method == http.MethodPut {
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 11955934a4..a52c64bc4f 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -1736,9 +1736,11 @@ func TestTrueNASConnectionMutationsRequireSettingsWriteScope(t *testing.T) {
body string
}{
{method: http.MethodPost, path: "/api/truenas/connections", body: `{}`},
+ {method: http.MethodPost, path: "/api/truenas/connections/preview", body: `{}`},
{method: http.MethodPost, path: "/api/truenas/connections/test", body: `{}`},
{method: http.MethodPut, path: "/api/truenas/connections/conn-1", body: `{}`},
{method: http.MethodDelete, path: "/api/truenas/connections/conn-1", body: ""},
+ {method: http.MethodPost, path: "/api/truenas/connections/conn-1/preview", body: ``},
{method: http.MethodPost, path: "/api/truenas/connections/conn-1/test", body: ""},
}
@@ -1768,9 +1770,11 @@ func TestVMwareConnectionMutationsRequireSettingsWriteScope(t *testing.T) {
body string
}{
{method: http.MethodPost, path: "/api/vmware/connections", body: `{}`},
+ {method: http.MethodPost, path: "/api/vmware/connections/preview", body: `{}`},
{method: http.MethodPost, path: "/api/vmware/connections/test", body: `{}`},
{method: http.MethodPut, path: "/api/vmware/connections/conn-1", body: `{}`},
{method: http.MethodDelete, path: "/api/vmware/connections/conn-1", body: ""},
+ {method: http.MethodPost, path: "/api/vmware/connections/conn-1/preview", body: ``},
{method: http.MethodPost, path: "/api/vmware/connections/conn-1/test", body: ""},
}
diff --git a/internal/api/truenas_handlers.go b/internal/api/truenas_handlers.go
index e6674db840..3b56255021 100644
--- a/internal/api/truenas_handlers.go
+++ b/internal/api/truenas_handlers.go
@@ -261,6 +261,121 @@ func (h *TrueNASHandlers) HandleUpdate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, instance.Redacted())
}
+// HandlePreviewConnection projects the monitored-system impact of a proposed
+// TrueNAS connection without persisting it.
+func (h *TrueNASHandlers) HandlePreviewConnection(w http.ResponseWriter, r *http.Request) {
+ if !h.featureEnabled(w) {
+ return
+ }
+
+ r.Body = http.MaxBytesReader(w, r.Body, 32*1024)
+ defer r.Body.Close()
+
+ var instance config.TrueNASInstance
+ if err := json.NewDecoder(r.Body).Decode(&instance); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
+ return
+ }
+
+ normalizeTrueNASInstance(&instance)
+ if err := instance.Validate(); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+
+ monitor := h.monitorForRequest(r.Context())
+ usage := monitoredSystemUsage(monitor)
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
+ }
+
+ preview := unifiedresources.PreviewMonitoredSystemCandidate(usage.readState, trueNASMonitoredSystemCandidate(instance))
+ if len(preview.ProjectedSystems) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "TrueNAS connection did not resolve to a canonical monitored system preview", nil)
+ return
+ }
+
+ writeJSON(w, http.StatusOK, monitoredSystemLedgerPreviewResponse(r.Context(), false, preview).NormalizeCollections())
+}
+
+// HandlePreviewSavedConnection projects the monitored-system impact of an edit
+// to one saved TrueNAS connection using the same secret-preservation path as
+// update and saved test flows.
+func (h *TrueNASHandlers) HandlePreviewSavedConnection(w http.ResponseWriter, r *http.Request) {
+ if !h.featureEnabled(w) {
+ return
+ }
+
+ connectionID, ok := trueNASConnectionIDFromPreviewPath(r.URL.Path)
+ if !ok {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_connection_id", "Connection ID is required", nil)
+ return
+ }
+
+ persistence := h.persistenceForRequest(w, r.Context())
+ if persistence == nil {
+ return
+ }
+
+ instances, err := persistence.LoadTrueNASConfig()
+ if err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "truenas_load_failed", "Failed to load TrueNAS configuration", map[string]string{"error": err.Error()})
+ return
+ }
+
+ for i := range instances {
+ current := instances[i]
+ if strings.TrimSpace(current.ID) != connectionID {
+ continue
+ }
+
+ payload, hasPayload, ok := decodeOptionalTrueNASInstanceRequest(w, r)
+ if !ok {
+ return
+ }
+ next := current
+ if hasPayload {
+ payload.ID = connectionID
+ normalizeTrueNASInstance(&payload)
+ payload.PreserveMaskedSecrets(current)
+ if err := payload.Validate(); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+ next = payload
+ }
+
+ monitor := h.monitorForRequest(r.Context())
+ usage := monitoredSystemUsage(monitor)
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
+ }
+
+ replacementHost := pulseTokenHostCandidate(current.Host)
+ preview := unifiedresources.PreviewMonitoredSystemCandidateReplacement(
+ usage.readState,
+ unifiedresources.MonitoredSystemReplacement{
+ Source: unifiedresources.SourceTrueNAS,
+ Selector: unifiedresources.MonitoredSystemReplacementSelector{
+ Hostname: replacementHost,
+ },
+ },
+ trueNASMonitoredSystemCandidate(next),
+ )
+ if len(preview.ProjectedSystems) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "TrueNAS connection did not resolve to a canonical monitored system preview", nil)
+ return
+ }
+
+ writeJSON(w, http.StatusOK, monitoredSystemLedgerPreviewResponse(r.Context(), true, preview).NormalizeCollections())
+ return
+ }
+
+ writeErrorResponse(w, http.StatusNotFound, "truenas_not_found", "Connection not found", nil)
+}
+
// HandleTestConnection validates connectivity for a proposed TrueNAS connection.
func (h *TrueNASHandlers) HandleTestConnection(w http.ResponseWriter, r *http.Request) {
if !h.featureEnabled(w) {
@@ -452,6 +567,13 @@ func (h *TrueNASHandlers) featureEnabled(w http.ResponseWriter) bool {
return false
}
+func (h *TrueNASHandlers) monitorForRequest(ctx context.Context) *monitoring.Monitor {
+ if h == nil || h.getMonitor == nil {
+ return nil
+ }
+ return h.getMonitor(ctx)
+}
+
func (h *TrueNASHandlers) persistenceForRequest(w http.ResponseWriter, ctx context.Context) *config.ConfigPersistence {
if h == nil || h.getPersistence == nil {
writeErrorResponse(w, http.StatusInternalServerError, "truenas_unavailable", "TrueNAS service unavailable", nil)
@@ -485,7 +607,7 @@ func (h *TrueNASHandlers) enforceMonitoredSystemLimit(
}
emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -503,8 +625,8 @@ func (h *TrueNASHandlers) enforceMonitoredSystemLimitReplacement(
replacementHost := pulseTokenHostCandidate(current.Host)
decision := monitoredSystemLimitDecisionForCandidateReplacement(r.Context(), monitor, unifiedresources.MonitoredSystemReplacement{
Source: unifiedresources.SourceTrueNAS,
- Matches: func(resource unifiedresources.Resource) bool {
- return resource.TrueNAS != nil && strings.EqualFold(strings.TrimSpace(resource.TrueNAS.Hostname), replacementHost)
+ Selector: unifiedresources.MonitoredSystemReplacementSelector{
+ Hostname: replacementHost,
},
}, trueNASMonitoredSystemCandidate(next))
if !decision.usageAvailable {
@@ -516,7 +638,7 @@ func (h *TrueNASHandlers) enforceMonitoredSystemLimitReplacement(
}
emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -553,14 +675,22 @@ func trueNASConnectionIDFromPath(path string) (string, bool) {
}
func trueNASConnectionIDFromTestPath(path string) (string, bool) {
+ return trueNASConnectionIDFromActionPath(path, "/test")
+}
+
+func trueNASConnectionIDFromPreviewPath(path string) (string, bool) {
+ return trueNASConnectionIDFromActionPath(path, "/preview")
+}
+
+func trueNASConnectionIDFromActionPath(path string, suffix string) (string, bool) {
if !strings.HasPrefix(path, trueNASConnectionsPathPrefix) {
return "", false
}
trimmed := strings.Trim(strings.TrimPrefix(path, trueNASConnectionsPathPrefix), "/")
- if !strings.HasSuffix(trimmed, "/test") {
+ if !strings.HasSuffix(trimmed, suffix) {
return "", false
}
- raw := strings.TrimSuffix(trimmed, "/test")
+ raw := strings.TrimSuffix(trimmed, suffix)
if raw == "" || strings.Contains(raw, "/") {
return "", false
}
diff --git a/internal/api/truenas_handlers_test.go b/internal/api/truenas_handlers_test.go
index 4e676ecd94..8ad8e49e60 100644
--- a/internal/api/truenas_handlers_test.go
+++ b/internal/api/truenas_handlers_test.go
@@ -162,6 +162,25 @@ func TestTrueNASHandlers_HandleAdd_BlocksNewCountedSystemAtLimit(t *testing.T) {
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("expected 402 once monitored-system cap is full, got %d: %s", rec.Code, rec.Body.String())
}
+ payload := decodeMonitoredSystemLimitBlockedPayload(t, rec.Body.Bytes())
+ if payload.Error != "license_required" {
+ t.Fatalf("error=%q, want license_required", payload.Error)
+ }
+ if payload.Feature != maxMonitoredSystemsLicenseGateKey {
+ t.Fatalf("feature=%q, want %q", payload.Feature, maxMonitoredSystemsLicenseGateKey)
+ }
+ if !payload.MonitoredSystemPreview.WouldExceedLimit {
+ t.Fatalf("expected monitored_system_preview.would_exceed_limit=true, got %+v", payload.MonitoredSystemPreview)
+ }
+ if payload.MonitoredSystemPreview.Effect != "creates_new" {
+ t.Fatalf("effect=%q, want creates_new", payload.MonitoredSystemPreview.Effect)
+ }
+ if payload.MonitoredSystemPreview.AdditionalCount != 1 {
+ t.Fatalf("additional_count=%d, want 1", payload.MonitoredSystemPreview.AdditionalCount)
+ }
+ if len(payload.MonitoredSystemPreview.ProjectedSystems) != 1 {
+ t.Fatalf("len(projected_systems)=%d, want 1", len(payload.MonitoredSystemPreview.ProjectedSystems))
+ }
stored, err := persistence.LoadTrueNASConfig()
if err != nil {
@@ -565,6 +584,22 @@ func TestTrueNASHandlers_HandleUpdate_BlocksProjectedNetNewSystemAtLimit(t *test
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("expected 402 when update would add a new monitored system, got %d: %s", rec.Code, rec.Body.String())
}
+ payload := decodeMonitoredSystemLimitBlockedPayload(t, rec.Body.Bytes())
+ if !payload.MonitoredSystemPreview.WouldExceedLimit {
+ t.Fatalf("expected monitored_system_preview.would_exceed_limit=true, got %+v", payload.MonitoredSystemPreview)
+ }
+ if payload.MonitoredSystemPreview.Effect != "splits_existing" {
+ t.Fatalf("effect=%q, want splits_existing", payload.MonitoredSystemPreview.Effect)
+ }
+ if payload.MonitoredSystemPreview.AdditionalCount != 1 {
+ t.Fatalf("additional_count=%d, want 1", payload.MonitoredSystemPreview.AdditionalCount)
+ }
+ if len(payload.MonitoredSystemPreview.CurrentSystems) != 1 {
+ t.Fatalf("len(current_systems)=%d, want 1", len(payload.MonitoredSystemPreview.CurrentSystems))
+ }
+ if len(payload.MonitoredSystemPreview.ProjectedSystems) != 1 {
+ t.Fatalf("len(projected_systems)=%d, want 1", len(payload.MonitoredSystemPreview.ProjectedSystems))
+ }
stored, err := persistence.LoadTrueNASConfig()
if err != nil {
@@ -707,6 +742,143 @@ func TestTrueNASHandlers_HandleTestSavedConnection_UsesStoredSecrets(t *testing.
}
}
+func TestTrueNASHandlers_HandlePreviewConnection_ReturnsCanonicalImpact(t *testing.T) {
+ setTrueNASFeatureForTest(t, true)
+
+ handler, _, monitor := newTrueNASHandlersForTest(t, nil)
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestRecords(unifiedresources.SourceAgent, []unifiedresources.IngestRecord{
+ {
+ SourceID: "host-1",
+ Resource: unifiedresources.Resource{
+ ID: "host-1",
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "tower.local",
+ Status: unifiedresources.StatusOnline,
+ Agent: &unifiedresources.AgentData{
+ AgentID: "agent-1",
+ Hostname: "tower.local",
+ MachineID: "machine-1",
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"tower.local"},
+ },
+ },
+ },
+ })
+ setUnexportedField(t, monitor, "resourceStore", monitoring.ResourceStoreInterface(unifiedresources.NewMonitorAdapter(registry)))
+
+ body := marshalTrueNASRequest(t, map[string]any{
+ "name": "tower",
+ "host": "tower.local",
+ "apiKey": "super-secret",
+ })
+ req := httptest.NewRequest(http.MethodPost, "/api/truenas/connections/preview", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandlePreviewConnection(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var preview MonitoredSystemLedgerPreviewResponse
+ if err := json.NewDecoder(rec.Body).Decode(&preview); err != nil {
+ t.Fatalf("decode preview response: %v", err)
+ }
+ if preview.CurrentCount != 1 || preview.ProjectedCount != 1 || preview.AdditionalCount != 0 {
+ t.Fatalf("unexpected preview counts: %+v", preview)
+ }
+ if preview.Effect != "attaches_existing" {
+ t.Fatalf("Effect = %q, want attaches_existing", preview.Effect)
+ }
+ if len(preview.CurrentSystems) != 1 || len(preview.ProjectedSystems) != 1 {
+ t.Fatalf("unexpected affected systems: %+v", preview)
+ }
+}
+
+func TestTrueNASHandlers_HandlePreviewSavedConnection_UsesReplacementProjection(t *testing.T) {
+ setTrueNASFeatureForTest(t, true)
+
+ handler, persistence, monitor := newTrueNASHandlersForTest(t, nil)
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestRecords(unifiedresources.SourceAgent, []unifiedresources.IngestRecord{
+ {
+ SourceID: "host-1",
+ Resource: unifiedresources.Resource{
+ ID: "host-1",
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "archive.local",
+ Status: unifiedresources.StatusOnline,
+ Agent: &unifiedresources.AgentData{
+ AgentID: "agent-1",
+ Hostname: "archive.local",
+ MachineID: "machine-1",
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"archive.local"},
+ },
+ },
+ },
+ })
+ registry.IngestRecords(unifiedresources.SourceTrueNAS, []unifiedresources.IngestRecord{
+ {
+ SourceID: "system:archive.local",
+ Resource: unifiedresources.Resource{
+ ID: "truenas-1",
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "archive",
+ Status: unifiedresources.StatusOnline,
+ TrueNAS: &unifiedresources.TrueNASData{
+ Hostname: "archive.local",
+ },
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"archive.local"},
+ },
+ },
+ })
+ setUnexportedField(t, monitor, "resourceStore", monitoring.ResourceStoreInterface(unifiedresources.NewMonitorAdapter(registry)))
+ if err := persistence.SaveTrueNASConfig([]config.TrueNASInstance{
+ {
+ ID: "conn-1",
+ Name: "archive",
+ Host: "archive.local",
+ APIKey: "super-secret",
+ Enabled: true,
+ UseHTTPS: true,
+ },
+ }); err != nil {
+ t.Fatalf("seed truenas config: %v", err)
+ }
+
+ body := marshalTrueNASRequest(t, map[string]any{
+ "name": "backup",
+ "host": "backup.local",
+ "apiKey": "********",
+ })
+ req := httptest.NewRequest(http.MethodPost, "/api/truenas/connections/conn-1/preview", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandlePreviewSavedConnection(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var preview MonitoredSystemLedgerPreviewResponse
+ if err := json.NewDecoder(rec.Body).Decode(&preview); err != nil {
+ t.Fatalf("decode preview response: %v", err)
+ }
+ if preview.ProjectedCount != 2 || preview.AdditionalCount != 1 {
+ t.Fatalf("unexpected preview counts: %+v", preview)
+ }
+ if preview.Effect != "splits_existing" {
+ t.Fatalf("Effect = %q, want splits_existing", preview.Effect)
+ }
+}
+
func TestTrueNASHandlers_HandleTestSavedConnection_UpdatesPollSummaryFailure(t *testing.T) {
setTrueNASFeatureForTest(t, true)
diff --git a/internal/api/vmware_handlers.go b/internal/api/vmware_handlers.go
index 4ab5d7181f..0fc2d66657 100644
--- a/internal/api/vmware_handlers.go
+++ b/internal/api/vmware_handlers.go
@@ -275,6 +275,136 @@ func (h *VMwareHandlers) HandleUpdate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, instance.Redacted())
}
+// HandlePreviewConnection projects the monitored-system impact of a proposed
+// VMware vCenter connection without persisting it.
+func (h *VMwareHandlers) HandlePreviewConnection(w http.ResponseWriter, r *http.Request) {
+ if !h.featureEnabled(w) {
+ return
+ }
+
+ r.Body = http.MaxBytesReader(w, r.Body, 32*1024)
+ defer r.Body.Close()
+
+ var instance config.VMwareVCenterInstance
+ if err := json.NewDecoder(r.Body).Decode(&instance); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
+ return
+ }
+
+ normalizeVMwareInstance(&instance)
+ if err := instance.Validate(); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+
+ monitor := h.monitorForRequest(r.Context())
+ usage := monitoredSystemUsage(monitor)
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
+ }
+
+ records, invalidConfig, err := h.previewMonitoredSystemRecords(r.Context(), instance)
+ if err != nil {
+ h.writeConnectionFailure(w, invalidConfig, err)
+ return
+ }
+
+ preview := unifiedresources.PreviewMonitoredSystemRecords(usage.readState, map[unifiedresources.DataSource][]unifiedresources.IngestRecord{
+ unifiedresources.SourceVMware: records,
+ })
+ if len(preview.ProjectedSystems) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "VMware connection did not resolve to a canonical monitored system preview", nil)
+ return
+ }
+
+ writeJSON(w, http.StatusOK, monitoredSystemLedgerPreviewResponse(r.Context(), false, preview).NormalizeCollections())
+}
+
+// HandlePreviewSavedConnection projects the monitored-system impact of editing
+// one saved VMware connection using the same secret-preservation path as
+// update and saved test flows.
+func (h *VMwareHandlers) HandlePreviewSavedConnection(w http.ResponseWriter, r *http.Request) {
+ if !h.featureEnabled(w) {
+ return
+ }
+
+ connectionID, ok := vmwareConnectionIDFromPreviewPath(r.URL.Path)
+ if !ok {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_connection_id", "Connection ID is required", nil)
+ return
+ }
+
+ persistence := h.persistenceForRequest(w, r.Context())
+ if persistence == nil {
+ return
+ }
+
+ instances, err := persistence.LoadVMwareConfig()
+ if err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "vmware_load_failed", "Failed to load VMware configuration", map[string]string{"error": err.Error()})
+ return
+ }
+
+ for i := range instances {
+ current := instances[i]
+ if strings.TrimSpace(current.ID) != connectionID {
+ continue
+ }
+
+ payload, hasPayload, ok := decodeOptionalVMwareInstanceRequest(w, r)
+ if !ok {
+ return
+ }
+ next := current
+ if hasPayload {
+ payload.ID = connectionID
+ normalizeVMwareInstance(&payload)
+ payload.PreserveMaskedSecrets(current)
+ if err := payload.Validate(); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)
+ return
+ }
+ next = payload
+ }
+
+ monitor := h.monitorForRequest(r.Context())
+ usage := monitoredSystemUsage(monitor)
+ if !usage.available {
+ writeMonitoredSystemUsageUnavailable(w)
+ return
+ }
+
+ records, invalidConfig, err := h.previewMonitoredSystemRecords(r.Context(), next)
+ if err != nil {
+ h.writeConnectionFailure(w, invalidConfig, err)
+ return
+ }
+
+ preview := unifiedresources.PreviewMonitoredSystemRecordsReplacement(
+ usage.readState,
+ unifiedresources.MonitoredSystemReplacement{
+ Source: unifiedresources.SourceVMware,
+ Selector: unifiedresources.MonitoredSystemReplacementSelector{
+ ResourceID: connectionID,
+ },
+ },
+ map[unifiedresources.DataSource][]unifiedresources.IngestRecord{
+ unifiedresources.SourceVMware: records,
+ },
+ )
+ if len(preview.ProjectedSystems) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "VMware connection did not resolve to a canonical monitored system preview", nil)
+ return
+ }
+
+ writeJSON(w, http.StatusOK, monitoredSystemLedgerPreviewResponse(r.Context(), true, preview).NormalizeCollections())
+ return
+ }
+
+ writeErrorResponse(w, http.StatusNotFound, "vmware_not_found", "Connection not found", nil)
+}
+
// HandleTestConnection validates connectivity for a proposed VMware vCenter connection.
func (h *VMwareHandlers) HandleTestConnection(w http.ResponseWriter, r *http.Request) {
if !h.featureEnabled(w) {
@@ -551,7 +681,7 @@ func (h *VMwareHandlers) enforceMonitoredSystemLimit(
}
emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -581,8 +711,8 @@ func (h *VMwareHandlers) enforceMonitoredSystemLimitReplacement(
replacementID := strings.TrimSpace(current.ID)
decision := monitoredSystemLimitDecisionForRecordsReplacement(r.Context(), monitor, unifiedresources.MonitoredSystemReplacement{
Source: unifiedresources.SourceVMware,
- Matches: func(resource unifiedresources.Resource) bool {
- return resource.VMware != nil && strings.TrimSpace(resource.VMware.ConnectionID) == replacementID
+ Selector: unifiedresources.MonitoredSystemReplacementSelector{
+ ResourceID: replacementID,
},
}, map[unifiedresources.DataSource][]unifiedresources.IngestRecord{
unifiedresources.SourceVMware: records,
@@ -596,7 +726,7 @@ func (h *VMwareHandlers) enforceMonitoredSystemLimitReplacement(
}
emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
- writeMaxMonitoredSystemsLimitExceeded(w, decision.current, decision.limit)
+ writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -778,15 +908,23 @@ func vmwareConnectionIDFromPath(path string) (string, bool) {
}
func vmwareConnectionIDFromTestPath(path string) (string, bool) {
+ return vmwareConnectionIDFromActionPath(path, "/test")
+}
+
+func vmwareConnectionIDFromPreviewPath(path string) (string, bool) {
+ return vmwareConnectionIDFromActionPath(path, "/preview")
+}
+
+func vmwareConnectionIDFromActionPath(path string, suffix string) (string, bool) {
if !strings.HasPrefix(path, vmwareConnectionsPathPrefix) {
return "", false
}
raw := strings.Trim(strings.TrimPrefix(path, vmwareConnectionsPathPrefix), "/")
- if !strings.HasSuffix(raw, "/test") {
+ if !strings.HasSuffix(raw, suffix) {
return "", false
}
- raw = strings.TrimSuffix(raw, "/test")
+ raw = strings.TrimSuffix(raw, suffix)
if raw == "" || strings.Contains(raw, "/") {
return "", false
}
diff --git a/internal/api/vmware_handlers_test.go b/internal/api/vmware_handlers_test.go
index 4ea2256623..6ed8988402 100644
--- a/internal/api/vmware_handlers_test.go
+++ b/internal/api/vmware_handlers_test.go
@@ -189,6 +189,25 @@ func TestVMwareHandlers_HandleAdd_BlocksProjectedNetNewSystemsAtLimit(t *testing
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("expected 402 once projected VMware inventory exceeds the cap, got %d: %s", rec.Code, rec.Body.String())
}
+ payload := decodeMonitoredSystemLimitBlockedPayload(t, rec.Body.Bytes())
+ if payload.Error != "license_required" {
+ t.Fatalf("error=%q, want license_required", payload.Error)
+ }
+ if payload.Feature != maxMonitoredSystemsLicenseGateKey {
+ t.Fatalf("feature=%q, want %q", payload.Feature, maxMonitoredSystemsLicenseGateKey)
+ }
+ if !payload.MonitoredSystemPreview.WouldExceedLimit {
+ t.Fatalf("expected monitored_system_preview.would_exceed_limit=true, got %+v", payload.MonitoredSystemPreview)
+ }
+ if payload.MonitoredSystemPreview.Effect != "creates_new" {
+ t.Fatalf("effect=%q, want creates_new", payload.MonitoredSystemPreview.Effect)
+ }
+ if payload.MonitoredSystemPreview.AdditionalCount != 1 {
+ t.Fatalf("additional_count=%d, want 1", payload.MonitoredSystemPreview.AdditionalCount)
+ }
+ if len(payload.MonitoredSystemPreview.ProjectedSystems) != 1 {
+ t.Fatalf("len(projected_systems)=%d, want 1", len(payload.MonitoredSystemPreview.ProjectedSystems))
+ }
stored, err := persistence.LoadVMwareConfig()
if err != nil {
@@ -648,6 +667,22 @@ func TestVMwareHandlers_HandleUpdate_BlocksProjectedNetNewSystemsAtLimit(t *test
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("expected 402 when update would add a new monitored system, got %d: %s", rec.Code, rec.Body.String())
}
+ payload := decodeMonitoredSystemLimitBlockedPayload(t, rec.Body.Bytes())
+ if !payload.MonitoredSystemPreview.WouldExceedLimit {
+ t.Fatalf("expected monitored_system_preview.would_exceed_limit=true, got %+v", payload.MonitoredSystemPreview)
+ }
+ if payload.MonitoredSystemPreview.Effect != "splits_existing" {
+ t.Fatalf("effect=%q, want splits_existing", payload.MonitoredSystemPreview.Effect)
+ }
+ if payload.MonitoredSystemPreview.AdditionalCount != 1 {
+ t.Fatalf("additional_count=%d, want 1", payload.MonitoredSystemPreview.AdditionalCount)
+ }
+ if len(payload.MonitoredSystemPreview.CurrentSystems) != 1 {
+ t.Fatalf("len(current_systems)=%d, want 1", len(payload.MonitoredSystemPreview.CurrentSystems))
+ }
+ if len(payload.MonitoredSystemPreview.ProjectedSystems) != 1 {
+ t.Fatalf("len(projected_systems)=%d, want 1", len(payload.MonitoredSystemPreview.ProjectedSystems))
+ }
stored, err := persistence.LoadVMwareConfig()
if err != nil {
@@ -768,6 +803,170 @@ func TestVMwareHandlers_HandleTestConnection_PreservesUnsupportedVersionCategory
}
}
+func TestVMwareHandlers_HandlePreviewConnection_ReturnsCanonicalMultiSystemImpact(t *testing.T) {
+ setVMwareFeatureForTest(t, true)
+ setMaxMonitoredSystemsLicenseForTests(t, 1)
+
+ handler, _ := newVMwareHandlersForTest(t)
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestRecords(unifiedresources.SourceAgent, []unifiedresources.IngestRecord{
+ {
+ SourceID: "agent-host-1",
+ Resource: unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: unifiedresources.StatusOnline,
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ })
+ monitor := &monitoring.Monitor{}
+ monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(registry))
+ handler.getMonitor = func(context.Context) *monitoring.Monitor { return monitor }
+ handler.previewRecords = func(context.Context, config.VMwareVCenterInstance) ([]unifiedresources.IngestRecord, error) {
+ return []unifiedresources.IngestRecord{
+ {
+ SourceID: "vc-1:host:host-101",
+ Resource: unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: unifiedresources.StatusOnline,
+ VMware: &unifiedresources.VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ {
+ SourceID: "vc-1:host:host-102",
+ Resource: unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "esxi-02.lab.local",
+ Status: unifiedresources.StatusOnline,
+ VMware: &unifiedresources.VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-102",
+ EntityType: "host",
+ HostUUID: "uuid-host-2",
+ },
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ DMIUUID: "uuid-host-2",
+ Hostnames: []string{"esxi-02.lab.local"},
+ },
+ },
+ }, nil
+ }
+
+ body := marshalVMwareRequest(t, map[string]any{
+ "host": "vcsa.lab.local",
+ "username": "[email protected]",
+ "password": "super-secret",
+ })
+ req := httptest.NewRequest(http.MethodPost, "/api/vmware/connections/preview", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandlePreviewConnection(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var preview MonitoredSystemLedgerPreviewResponse
+ if err := json.NewDecoder(rec.Body).Decode(&preview); err != nil {
+ t.Fatalf("decode preview response: %v", err)
+ }
+ if preview.CurrentCount != 1 || preview.ProjectedCount != 2 || preview.AdditionalCount != 1 {
+ t.Fatalf("unexpected preview counts: %+v", preview)
+ }
+ if !preview.WouldExceedLimit {
+ t.Fatalf("expected preview to report limit overrun, got %+v", preview)
+ }
+ if len(preview.CurrentSystems) != 1 {
+ t.Fatalf("len(CurrentSystems) = %d, want 1", len(preview.CurrentSystems))
+ }
+ if len(preview.ProjectedSystems) != 2 {
+ t.Fatalf("len(ProjectedSystems) = %d, want 2", len(preview.ProjectedSystems))
+ }
+}
+
+func TestVMwareHandlers_HandlePreviewSavedConnection_PreservesStoredSecrets(t *testing.T) {
+ setVMwareFeatureForTest(t, true)
+
+ handler, persistence := newVMwareHandlersForTest(t)
+ monitor, _, _ := newTestMonitor(t)
+ handler.getMonitor = func(context.Context) *monitoring.Monitor { return monitor }
+ if err := persistence.SaveVMwareConfig([]config.VMwareVCenterInstance{
+ {
+ ID: "conn-1",
+ Name: "lab-vcenter",
+ Host: "vcsa.lab.local",
+ Username: "[email protected]",
+ Password: "super-secret",
+ Enabled: true,
+ },
+ }); err != nil {
+ t.Fatalf("seed vmware config: %v", err)
+ }
+
+ var previewed config.VMwareVCenterInstance
+ handler.previewRecords = func(_ context.Context, instance config.VMwareVCenterInstance) ([]unifiedresources.IngestRecord, error) {
+ previewed = instance
+ return []unifiedresources.IngestRecord{
+ {
+ SourceID: "vc-1:host:host-101",
+ Resource: unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: unifiedresources.StatusOnline,
+ VMware: &unifiedresources.VMwareData{
+ ConnectionID: "conn-1",
+ ConnectionName: "lab-vcenter",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ }, nil
+ }
+
+ body := marshalVMwareRequest(t, map[string]any{
+ "host": "edited.lab.local",
+ "username": "[email protected]",
+ "password": "********",
+ "insecureSkipVerify": true,
+ "enabled": true,
+ })
+ req := httptest.NewRequest(http.MethodPost, "/api/vmware/connections/conn-1/preview", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandlePreviewSavedConnection(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if previewed.Password != "super-secret" {
+ t.Fatalf("expected stored password to be reused, got %+v", previewed)
+ }
+ if previewed.Host != "edited.lab.local" {
+ t.Fatalf("expected edited host to be previewed, got %+v", previewed)
+ }
+}
+
func TestVMwareHandlers_HandleTestSavedConnection_UsesStoredSecretsAndUpdatesRuntimeSummary(t *testing.T) {
setVMwareFeatureForTest(t, true)
diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.go
index 90f3444497..af0f96716b 100644
--- a/internal/monitoring/truenas_poller_test.go
+++ b/internal/monitoring/truenas_poller_test.go
@@ -1331,13 +1331,24 @@ func TestTrueNASPollerPollAllLogsStructuredContextOnRefreshFailure(t *testing.T)
poller := NewTrueNASPoller(nil, time.Second, nil)
poller.mu.Lock()
+ if poller.configsByOrg == nil {
+ poller.configsByOrg = make(map[string]map[string]config.TrueNASInstance)
+ }
+ if poller.configsByOrg["default"] == nil {
+ poller.configsByOrg["default"] = make(map[string]config.TrueNASInstance)
+ }
+ connection := config.NewTrueNASInstance()
+ connection.ID = "conn-refresh-fail"
+ connection.Host = "nas-refresh-fail.lab.local"
+ connection.APIKey = "api-key"
+ poller.configsByOrg["default"][connection.ID] = connection
if poller.providersByOrg == nil {
poller.providersByOrg = make(map[string]map[string]*truenas.Provider)
}
if poller.providersByOrg["default"] == nil {
poller.providersByOrg["default"] = make(map[string]*truenas.Provider)
}
- poller.providersByOrg["default"]["conn-refresh-fail"] = truenas.NewLiveProvider(failingTrueNASFetcher{err: fmt.Errorf("refresh exploded")})
+ poller.providersByOrg["default"][connection.ID] = truenas.NewLiveProvider(failingTrueNASFetcher{err: fmt.Errorf("refresh exploded")})
poller.mu.Unlock()
poller.pollAll(context.Background())
diff --git a/internal/unifiedresources/monitored_system_projection.go b/internal/unifiedresources/monitored_system_projection.go
index 03fd743357..e8600b2325 100644
--- a/internal/unifiedresources/monitored_system_projection.go
+++ b/internal/unifiedresources/monitored_system_projection.go
@@ -10,12 +10,46 @@ type MonitoredSystemProjection struct {
AdditionalCount int
}
+// MonitoredSystemProjectionPreview describes how a prospective change affects
+// canonical monitored-system counting and which current/projected systems are
+// involved in that change.
+type MonitoredSystemProjectionPreview struct {
+ CurrentCount int
+ ProjectedCount int
+ AdditionalCount int
+ CurrentSystems []MonitoredSystemRecord
+ ProjectedSystems []MonitoredSystemRecord
+ CurrentSystem *MonitoredSystemRecord
+ ProjectedSystem *MonitoredSystemRecord
+}
+
+// MonitoredSystemReplacementSelector identifies one source-owned top-level
+// monitored-system surface using canonical source-specific fields.
+type MonitoredSystemReplacementSelector struct {
+ Name string
+ Hostname string
+ HostURL string
+ AgentID string
+ MachineID string
+ ResourceID string
+}
+
// MonitoredSystemReplacement describes one existing monitored-system surface to
// replace while preserving any other source ownership already attached to the
// same top-level resource.
type MonitoredSystemReplacement struct {
- Source DataSource
- Matches func(Resource) bool
+ Source DataSource
+ Selector MonitoredSystemReplacementSelector
+ Matches func(Resource) bool
+}
+
+// MatchesResource reports whether the replacement targets the provided
+// source-owned top-level resource.
+func (r MonitoredSystemReplacement) MatchesResource(resource Resource) bool {
+ if r.Matches != nil {
+ return r.Matches(resource)
+ }
+ return monitoredSystemReplacementSelectorMatches(r.Source, r.Selector, resource)
}
// ProjectMonitoredSystemCandidate projects one prospective monitored-system
@@ -31,6 +65,20 @@ func ProjectMonitoredSystemCandidate(
return projectMonitoredSystemResources(rs, []Resource{*resource}, nil, nil)
}
+// PreviewMonitoredSystemCandidate projects one prospective monitored-system
+// candidate through the canonical top-level resolver and returns the affected
+// current/projected monitored-system records.
+func PreviewMonitoredSystemCandidate(
+ rs ReadState,
+ candidate MonitoredSystemCandidate,
+) MonitoredSystemProjectionPreview {
+ resource := monitoredSystemCandidateResource(candidate)
+ if resource == nil {
+ return previewMonitoredSystemResources(rs, nil, nil, nil)
+ }
+ return previewMonitoredSystemResources(rs, []Resource{*resource}, nil, nil)
+}
+
// ProjectMonitoredSystemCandidateReplacement projects a prospective monitored-system
// candidate while replacing one existing source-owned surface in the canonical
// top-level resolver.
@@ -46,6 +94,42 @@ func ProjectMonitoredSystemCandidateReplacement(
return projectMonitoredSystemResources(rs, []Resource{*resource}, nil, &replacement)
}
+// PreviewMonitoredSystemCandidateReplacement projects a prospective monitored-system
+// candidate while replacing one existing source-owned surface and returns the
+// affected current/projected monitored-system records.
+func PreviewMonitoredSystemCandidateReplacement(
+ rs ReadState,
+ replacement MonitoredSystemReplacement,
+ candidate MonitoredSystemCandidate,
+) MonitoredSystemProjectionPreview {
+ resource := monitoredSystemCandidateResource(candidate)
+ if resource == nil {
+ return previewMonitoredSystemResources(rs, nil, nil, &replacement)
+ }
+ return previewMonitoredSystemResources(rs, []Resource{*resource}, nil, &replacement)
+}
+
+// PreviewMonitoredSystemRecords projects source-native records through the
+// canonical top-level resolver and returns the affected current/projected
+// monitored-system records.
+func PreviewMonitoredSystemRecords(
+ rs ReadState,
+ recordsBySource map[DataSource][]IngestRecord,
+) MonitoredSystemProjectionPreview {
+ return previewMonitoredSystemResources(rs, nil, recordsBySource, nil)
+}
+
+// PreviewMonitoredSystemRecordsReplacement projects source-native records while
+// replacing one existing source-owned surface and returns the affected
+// current/projected monitored-system records.
+func PreviewMonitoredSystemRecordsReplacement(
+ rs ReadState,
+ replacement MonitoredSystemReplacement,
+ recordsBySource map[DataSource][]IngestRecord,
+) MonitoredSystemProjectionPreview {
+ return previewMonitoredSystemResources(rs, nil, recordsBySource, &replacement)
+}
+
// ProjectMonitoredSystemRecords projects source-native records through the
// canonical top-level resolver before they are admitted into runtime state.
func ProjectMonitoredSystemRecords(
@@ -92,17 +176,60 @@ func projectMonitoredSystemResources(
}
}
+func previewMonitoredSystemResources(
+ rs ReadState,
+ additionalResources []Resource,
+ recordsBySource map[DataSource][]IngestRecord,
+ replacement *MonitoredSystemReplacement,
+) MonitoredSystemProjectionPreview {
+ currentRoots := monitoredSystemRootResources(rs)
+ currentResolver := ResolveTopLevelSystems(currentRoots)
+
+ recordRoots := monitoredSystemRootsFromRecords(recordsBySource)
+ projectedRoots := monitoredSystemRootsWithReplacement(currentRoots, replacement)
+ projectedRoots = append(projectedRoots, additionalResources...)
+ projectedRoots = append(projectedRoots, recordRoots...)
+ projectedResolver := ResolveTopLevelSystems(projectedRoots)
+ projectedResourceIDs := monitoredSystemResourceIDs(additionalResources, recordRoots)
+
+ currentCount := currentResolver.Count()
+ projectedCount := projectedResolver.Count()
+ additionalCount := projectedCount - currentCount
+ if additionalCount < 0 {
+ additionalCount = 0
+ }
+
+ currentSystems := previewCurrentMonitoredSystems(
+ currentResolver,
+ currentRoots,
+ replacement,
+ projectedResolver,
+ projectedResourceIDs,
+ )
+ projectedSystems := previewProjectedMonitoredSystems(projectedResolver, projectedResourceIDs)
+
+ return MonitoredSystemProjectionPreview{
+ CurrentCount: currentCount,
+ ProjectedCount: projectedCount,
+ AdditionalCount: additionalCount,
+ CurrentSystems: currentSystems,
+ ProjectedSystems: projectedSystems,
+ CurrentSystem: firstMonitoredSystemRecord(currentSystems),
+ ProjectedSystem: firstMonitoredSystemRecord(projectedSystems),
+ }
+}
+
func monitoredSystemRootsWithReplacement(
currentRoots []Resource,
replacement *MonitoredSystemReplacement,
) []Resource {
- if replacement == nil || replacement.Matches == nil {
+ if replacement == nil {
return append([]Resource(nil), currentRoots...)
}
projected := make([]Resource, 0, len(currentRoots))
for _, root := range currentRoots {
- if !replacement.Matches(root) {
+ if !replacement.MatchesResource(root) {
projected = append(projected, root)
continue
}
@@ -115,6 +242,377 @@ func monitoredSystemRootsWithReplacement(
return projected
}
+func previewCurrentMonitoredSystems(
+ currentResolver TopLevelSystemResolver,
+ currentRoots []Resource,
+ replacement *MonitoredSystemReplacement,
+ projectedResolver TopLevelSystemResolver,
+ projectedResourceIDs []string,
+) []MonitoredSystemRecord {
+ if replacement != nil {
+ groupIDs := make(map[string]struct{})
+ for _, root := range currentRoots {
+ if !replacement.MatchesResource(root) {
+ continue
+ }
+ if groupID := currentResolver.GroupIDForResource(root); strings.TrimSpace(groupID) != "" {
+ groupIDs[groupID] = struct{}{}
+ }
+ }
+ return monitoredSystemRecordsForGroupIDs(currentResolver, groupIDs)
+ }
+
+ if len(projectedResourceIDs) == 0 {
+ return []MonitoredSystemRecord{}
+ }
+
+ currentGroupIDs := make(map[string]struct{})
+ excludedProjectedIDs := make(map[string]struct{}, len(projectedResourceIDs))
+ for _, resourceID := range projectedResourceIDs {
+ resourceID = strings.TrimSpace(resourceID)
+ if resourceID == "" {
+ continue
+ }
+ if group := currentResolver.groupForResourceID(resourceID); group != nil {
+ currentGroupIDs[group.id] = struct{}{}
+ continue
+ }
+ excludedProjectedIDs[resourceID] = struct{}{}
+ }
+
+ seenProjectedGroups := make(map[string]struct{})
+ for _, projectedResourceID := range projectedResourceIDs {
+ projectedGroup := projectedResolver.groupForResourceID(projectedResourceID)
+ if projectedGroup == nil {
+ continue
+ }
+ if _, seen := seenProjectedGroups[projectedGroup.id]; seen {
+ continue
+ }
+ seenProjectedGroups[projectedGroup.id] = struct{}{}
+
+ projectedIDs := monitoredSystemGroupResourceIDsExcluding(projectedGroup.resources, excludedProjectedIDs)
+ if len(projectedIDs) == 0 {
+ continue
+ }
+
+ for _, group := range currentResolver.groups {
+ if monitoredSystemGroupMatchesResourceIDs(group.resources, projectedIDs) {
+ currentGroupIDs[group.id] = struct{}{}
+ break
+ }
+ }
+ }
+
+ return monitoredSystemRecordsForGroupIDs(currentResolver, currentGroupIDs)
+}
+
+func previewProjectedMonitoredSystems(
+ projectedResolver TopLevelSystemResolver,
+ projectedResourceIDs []string,
+) []MonitoredSystemRecord {
+ if len(projectedResourceIDs) == 0 {
+ return []MonitoredSystemRecord{}
+ }
+
+ groupIDs := make(map[string]struct{})
+ for _, projectedResourceID := range projectedResourceIDs {
+ if groupID := projectedResolver.GroupIDForResource(Resource{ID: projectedResourceID}); strings.TrimSpace(groupID) != "" {
+ groupIDs[groupID] = struct{}{}
+ }
+ }
+ return monitoredSystemRecordsForGroupIDs(projectedResolver, groupIDs)
+}
+
+func monitoredSystemRecordForGroupID(resolver TopLevelSystemResolver, groupID string) *MonitoredSystemRecord {
+ groupID = strings.TrimSpace(groupID)
+ if groupID == "" {
+ return nil
+ }
+ for _, group := range resolver.groups {
+ if group.id != groupID {
+ continue
+ }
+ record := monitoredSystemRecordForResolvedGroup(group)
+ return &record
+ }
+ return nil
+}
+
+func monitoredSystemRecordsForGroupIDs(
+ resolver TopLevelSystemResolver,
+ groupIDs map[string]struct{},
+) []MonitoredSystemRecord {
+ if len(groupIDs) == 0 {
+ return []MonitoredSystemRecord{}
+ }
+
+ records := make([]MonitoredSystemRecord, 0, len(groupIDs))
+ for _, group := range resolver.groups {
+ if _, ok := groupIDs[group.id]; !ok {
+ continue
+ }
+ records = append(records, monitoredSystemRecordForResolvedGroup(group))
+ }
+ return records
+}
+
+func firstMonitoredSystemRecord(records []MonitoredSystemRecord) *MonitoredSystemRecord {
+ if len(records) != 1 {
+ return nil
+ }
+ record := records[0]
+ return &record
+}
+
+func monitoredSystemRecordForResolvedGroup(group topLevelSystemResolvedGroup) MonitoredSystemRecord {
+ return monitoredSystemRecord(monitoredSystemGroup{
+ keys: cloneStringSet(group.strongIDs),
+ resources: group.resources,
+ explanation: group.explanation,
+ })
+}
+
+func (r TopLevelSystemResolver) groupForResourceID(resourceID string) *topLevelSystemResolvedGroup {
+ groupID := r.resourceToGroup[strings.TrimSpace(resourceID)]
+ if groupID == "" {
+ return nil
+ }
+ for i := range r.groups {
+ if r.groups[i].id != groupID {
+ continue
+ }
+ return &r.groups[i]
+ }
+ return nil
+}
+
+func monitoredSystemGroupResourceIDs(resources []*Resource, excludeID string) map[string]struct{} {
+ excluded := make(map[string]struct{})
+ if excludeID = strings.TrimSpace(excludeID); excludeID != "" {
+ excluded[excludeID] = struct{}{}
+ }
+ return monitoredSystemGroupResourceIDsExcluding(resources, excluded)
+}
+
+func monitoredSystemGroupResourceIDsExcluding(
+ resources []*Resource,
+ excluded map[string]struct{},
+) map[string]struct{} {
+ ids := make(map[string]struct{})
+ for _, resource := range resources {
+ if resource == nil {
+ continue
+ }
+ resourceID := strings.TrimSpace(resource.ID)
+ if resourceID == "" {
+ continue
+ }
+ if _, skip := excluded[resourceID]; skip {
+ continue
+ }
+ ids[resourceID] = struct{}{}
+ }
+ return ids
+}
+
+func monitoredSystemGroupMatchesResourceIDs(resources []*Resource, ids map[string]struct{}) bool {
+ count := 0
+ for _, resource := range resources {
+ if resource == nil {
+ continue
+ }
+ resourceID := strings.TrimSpace(resource.ID)
+ if resourceID == "" {
+ continue
+ }
+ if _, ok := ids[resourceID]; !ok {
+ return false
+ }
+ count++
+ }
+ return count == len(ids)
+}
+
+func monitoredSystemReplacementSelectorMatches(
+ source DataSource,
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ switch source {
+ case SourceAgent:
+ return monitoredSystemReplacementSelectorMatchesAgent(selector, resource)
+ case SourceDocker:
+ return monitoredSystemReplacementSelectorMatchesDocker(selector, resource)
+ case SourceProxmox:
+ return monitoredSystemReplacementSelectorMatchesProxmox(selector, resource)
+ case SourceTrueNAS:
+ return monitoredSystemReplacementSelectorMatchesTrueNAS(selector, resource)
+ case SourcePBS:
+ return monitoredSystemReplacementSelectorMatchesPBS(selector, resource)
+ case SourcePMG:
+ return monitoredSystemReplacementSelectorMatchesPMG(selector, resource)
+ case SourceK8s:
+ return monitoredSystemReplacementSelectorMatchesK8s(selector, resource)
+ case SourceVMware:
+ return monitoredSystemReplacementSelectorMatchesVMware(selector, resource)
+ default:
+ return false
+ }
+}
+
+func monitoredSystemReplacementSelectorMatchesAgent(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.Agent == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.AgentID, resource.Agent.AgentID) ||
+ trimmedEqualFold(selector.MachineID, resource.Identity.MachineID) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.Agent.Hostname, resource.Name)
+}
+
+func monitoredSystemReplacementSelectorMatchesDocker(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.Docker == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.ResourceID, resource.Docker.HostSourceID) ||
+ trimmedEqualFold(selector.AgentID, resource.Docker.AgentID) ||
+ trimmedEqualFold(selector.MachineID, resource.Docker.MachineID) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.Docker.Hostname, resource.Name)
+}
+
+func monitoredSystemReplacementSelectorMatchesProxmox(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.Proxmox == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.ResourceID, resource.Proxmox.SourceID) ||
+ trimmedEqualFold(selector.Name, resource.Proxmox.Instance) ||
+ trimmedEqualFold(selector.Name, resource.Proxmox.NodeName) ||
+ trimmedEqualFold(selector.HostURL, resource.Proxmox.HostURL) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.Proxmox.HostURL, resource.Proxmox.NodeName, resource.Name)
+}
+
+func monitoredSystemReplacementSelectorMatchesTrueNAS(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.TrueNAS == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.MachineID, resource.Identity.MachineID) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.TrueNAS.Hostname, resource.Name)
+}
+
+func monitoredSystemReplacementSelectorMatchesPBS(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.PBS == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.ResourceID, resource.PBS.InstanceID) ||
+ trimmedEqualFold(selector.HostURL, resource.PBS.HostURL) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.PBS.Hostname, resource.PBS.HostURL, resource.Name)
+}
+
+func monitoredSystemReplacementSelectorMatchesPMG(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.PMG == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.ResourceID, resource.PMG.InstanceID) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.PMG.Hostname, resource.Name)
+}
+
+func monitoredSystemReplacementSelectorMatchesK8s(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.Kubernetes == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.ResourceID, resource.Kubernetes.ClusterID) ||
+ trimmedEqualFold(selector.Name, resource.Kubernetes.ClusterName) ||
+ trimmedEqualFold(selector.Name, resource.Kubernetes.SourceName) ||
+ trimmedEqualFold(selector.HostURL, resource.Kubernetes.Server) ||
+ trimmedEqualFold(selector.AgentID, resource.Kubernetes.AgentID)
+}
+
+func monitoredSystemReplacementSelectorMatchesVMware(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if resource.VMware == nil {
+ return false
+ }
+ return monitoredSystemSelectorMatchesCanonicalResourceID(selector, resource) ||
+ trimmedEqualFold(selector.ResourceID, resource.VMware.ConnectionID) ||
+ trimmedEqualFold(selector.ResourceID, resource.VMware.HostUUID) ||
+ trimmedEqualFold(selector.Name, resource.Name) ||
+ monitoredSystemSelectorMatchesHost(selector, resource.VMware.RuntimeHostName, resource.VMware.VCenterHost, resource.Name)
+}
+
+func monitoredSystemSelectorMatchesCanonicalResourceID(
+ selector MonitoredSystemReplacementSelector,
+ resource Resource,
+) bool {
+ if trimmedEqualFold(selector.ResourceID, resource.ID) {
+ return true
+ }
+ return false
+}
+
+func monitoredSystemSelectorMatchesHost(
+ selector MonitoredSystemReplacementSelector,
+ candidates ...string,
+) bool {
+ selectorHosts := make(map[string]struct{})
+ for _, value := range []string{selector.Hostname, extractHostname(selector.HostURL)} {
+ if normalized := topLevelSystemNormalizeHost(value); normalized != "" {
+ selectorHosts[normalized] = struct{}{}
+ }
+ }
+ if len(selectorHosts) == 0 {
+ return false
+ }
+ for _, candidate := range candidates {
+ if normalized := topLevelSystemNormalizeHost(candidate); normalized != "" {
+ if _, ok := selectorHosts[normalized]; ok {
+ return true
+ }
+ }
+ if normalized := topLevelSystemNormalizeHost(extractHostname(candidate)); normalized != "" {
+ if _, ok := selectorHosts[normalized]; ok {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func trimmedEqualFold(left, right string) bool {
+ left = strings.TrimSpace(left)
+ right = strings.TrimSpace(right)
+ return left != "" && right != "" && strings.EqualFold(left, right)
+}
+
func stripMonitoredSystemSource(resource Resource, source DataSource) (Resource, bool) {
stripped := cloneResource(&resource)
stripped.Sources = removeMonitoredSystemSource(stripped.Sources, source)
@@ -208,6 +706,25 @@ func monitoredSystemRootsFromRecords(recordsBySource map[DataSource][]IngestReco
return monitoredSystemRootResources(registry)
}
+func monitoredSystemResourceIDs(resourceSets ...[]Resource) []string {
+ ids := make([]string, 0)
+ seen := make(map[string]struct{})
+ for _, resources := range resourceSets {
+ for _, resource := range resources {
+ resourceID := strings.TrimSpace(resource.ID)
+ if resourceID == "" {
+ continue
+ }
+ if _, ok := seen[resourceID]; ok {
+ continue
+ }
+ seen[resourceID] = struct{}{}
+ ids = append(ids, resourceID)
+ }
+ }
+ return ids
+}
+
func monitoredSystemCandidateResource(candidate MonitoredSystemCandidate) *Resource {
source := normalizeMonitoredSystemCandidateSource(candidate)
diff --git a/internal/unifiedresources/monitored_systems_test.go b/internal/unifiedresources/monitored_systems_test.go
index f64f1f25a2..270f7264f3 100644
--- a/internal/unifiedresources/monitored_systems_test.go
+++ b/internal/unifiedresources/monitored_systems_test.go
@@ -321,8 +321,8 @@ func TestProjectMonitoredSystemCandidateReplacementPreservesOverlappingSources(t
projection := ProjectMonitoredSystemCandidateReplacement(registry, MonitoredSystemReplacement{
Source: SourceTrueNAS,
- Matches: func(resource Resource) bool {
- return resource.TrueNAS != nil && resource.TrueNAS.Hostname == "archive.local"
+ Selector: MonitoredSystemReplacementSelector{
+ Hostname: "archive.local",
},
}, MonitoredSystemCandidate{
Source: SourceTrueNAS,
@@ -364,8 +364,8 @@ func TestProjectMonitoredSystemCandidateReplacementRemovesStandaloneSource(t *te
projection := ProjectMonitoredSystemCandidateReplacement(registry, MonitoredSystemReplacement{
Source: SourcePBS,
- Matches: func(resource Resource) bool {
- return resource.PBS != nil && resource.PBS.InstanceID == "pbs-a"
+ Selector: MonitoredSystemReplacementSelector{
+ ResourceID: "pbs-a",
},
}, MonitoredSystemCandidate{
Source: SourcePBS,
@@ -385,3 +385,232 @@ func TestProjectMonitoredSystemCandidateReplacementRemovesStandaloneSource(t *te
t.Fatalf("AdditionalCount = %d, want 0", projection.AdditionalCount)
}
}
+
+func TestPreviewMonitoredSystemCandidateReturnsCurrentAndProjectedSystems(t *testing.T) {
+ registry := NewRegistry(nil)
+ registry.IngestRecords(SourceAgent, []IngestRecord{
+ {
+ SourceID: "host-1",
+ Resource: Resource{
+ ID: "host-1",
+ Type: ResourceTypeAgent,
+ Name: "tower.local",
+ Status: StatusOnline,
+ Agent: &AgentData{
+ AgentID: "agent-1",
+ Hostname: "tower.local",
+ MachineID: "machine-1",
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"tower.local"},
+ },
+ },
+ },
+ })
+
+ preview := PreviewMonitoredSystemCandidate(registry, MonitoredSystemCandidate{
+ Source: SourceProxmox,
+ Type: ResourceTypeAgent,
+ Name: "tower",
+ Hostname: "tower.local",
+ HostURL: "https://tower.local:8006",
+ })
+
+ if preview.CurrentCount != 1 {
+ t.Fatalf("CurrentCount = %d, want 1", preview.CurrentCount)
+ }
+ if preview.ProjectedCount != 1 {
+ t.Fatalf("ProjectedCount = %d, want 1", preview.ProjectedCount)
+ }
+ if preview.AdditionalCount != 0 {
+ t.Fatalf("AdditionalCount = %d, want 0", preview.AdditionalCount)
+ }
+ if preview.CurrentSystem == nil {
+ t.Fatal("expected current system preview")
+ }
+ if preview.ProjectedSystem == nil {
+ t.Fatal("expected projected system preview")
+ }
+ if len(preview.CurrentSystems) != 1 {
+ t.Fatalf("len(CurrentSystems) = %d, want 1", len(preview.CurrentSystems))
+ }
+ if len(preview.ProjectedSystems) != 1 {
+ t.Fatalf("len(ProjectedSystems) = %d, want 1", len(preview.ProjectedSystems))
+ }
+ if preview.CurrentSystem.Source != "agent" {
+ t.Fatalf("CurrentSystem.Source = %q, want agent", preview.CurrentSystem.Source)
+ }
+ if preview.ProjectedSystem.Source != "multiple" {
+ t.Fatalf("ProjectedSystem.Source = %q, want multiple", preview.ProjectedSystem.Source)
+ }
+ if len(preview.ProjectedSystem.Explanation.Surfaces) != 2 {
+ t.Fatalf("expected projected system to include 2 grouped surfaces, got %+v", preview.ProjectedSystem.Explanation.Surfaces)
+ }
+}
+
+func TestPreviewMonitoredSystemCandidateReplacementReturnsAffectedSystems(t *testing.T) {
+ registry := NewRegistry(nil)
+ registry.IngestRecords(SourceAgent, []IngestRecord{
+ {
+ SourceID: "host-1",
+ Resource: Resource{
+ ID: "host-1",
+ Type: ResourceTypeAgent,
+ Name: "archive.local",
+ Status: StatusOnline,
+ Agent: &AgentData{
+ AgentID: "agent-1",
+ Hostname: "archive.local",
+ MachineID: "machine-1",
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"archive.local"},
+ },
+ },
+ },
+ })
+ registry.IngestRecords(SourceTrueNAS, []IngestRecord{
+ {
+ SourceID: "system:archive.local",
+ Resource: Resource{
+ ID: "truenas-1",
+ Type: ResourceTypeAgent,
+ Name: "archive",
+ Status: StatusOnline,
+ TrueNAS: &TrueNASData{
+ Hostname: "archive.local",
+ },
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"archive.local"},
+ },
+ },
+ })
+
+ preview := PreviewMonitoredSystemCandidateReplacement(registry, MonitoredSystemReplacement{
+ Source: SourceTrueNAS,
+ Selector: MonitoredSystemReplacementSelector{
+ Hostname: "archive.local",
+ },
+ }, MonitoredSystemCandidate{
+ Source: SourceTrueNAS,
+ Type: ResourceTypeAgent,
+ Name: "backup",
+ Hostname: "backup.local",
+ HostURL: "https://backup.local",
+ })
+
+ if preview.CurrentCount != 1 {
+ t.Fatalf("CurrentCount = %d, want 1", preview.CurrentCount)
+ }
+ if preview.ProjectedCount != 2 {
+ t.Fatalf("ProjectedCount = %d, want 2", preview.ProjectedCount)
+ }
+ if preview.AdditionalCount != 1 {
+ t.Fatalf("AdditionalCount = %d, want 1", preview.AdditionalCount)
+ }
+ if preview.CurrentSystem == nil {
+ t.Fatal("expected current system preview")
+ }
+ if preview.ProjectedSystem == nil {
+ t.Fatal("expected projected system preview")
+ }
+ if len(preview.CurrentSystems) != 1 {
+ t.Fatalf("len(CurrentSystems) = %d, want 1", len(preview.CurrentSystems))
+ }
+ if len(preview.ProjectedSystems) != 1 {
+ t.Fatalf("len(ProjectedSystems) = %d, want 1", len(preview.ProjectedSystems))
+ }
+ if preview.CurrentSystem.Source != "multiple" {
+ t.Fatalf("CurrentSystem.Source = %q, want multiple", preview.CurrentSystem.Source)
+ }
+ if preview.ProjectedSystem.Source != "truenas" {
+ t.Fatalf("ProjectedSystem.Source = %q, want truenas", preview.ProjectedSystem.Source)
+ }
+ if preview.ProjectedSystem.Name != "backup" {
+ t.Fatalf("ProjectedSystem.Name = %q, want backup", preview.ProjectedSystem.Name)
+ }
+}
+
+func TestPreviewMonitoredSystemRecordsReturnsAffectedSystems(t *testing.T) {
+ registry := NewRegistry(nil)
+ registry.IngestRecords(SourceAgent, []IngestRecord{
+ {
+ SourceID: "agent-host-1",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: StatusOnline,
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ })
+
+ preview := PreviewMonitoredSystemRecords(registry, map[DataSource][]IngestRecord{
+ SourceVMware: {
+ {
+ SourceID: "vc-1:host:host-101",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: StatusOnline,
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ {
+ SourceID: "vc-1:host:host-102",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-02.lab.local",
+ Status: StatusOnline,
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-102",
+ EntityType: "host",
+ HostUUID: "uuid-host-2",
+ },
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-2",
+ Hostnames: []string{"esxi-02.lab.local"},
+ },
+ },
+ },
+ })
+
+ if preview.CurrentCount != 1 {
+ t.Fatalf("CurrentCount = %d, want 1", preview.CurrentCount)
+ }
+ if preview.ProjectedCount != 2 {
+ t.Fatalf("ProjectedCount = %d, want 2", preview.ProjectedCount)
+ }
+ if preview.AdditionalCount != 1 {
+ t.Fatalf("AdditionalCount = %d, want 1", preview.AdditionalCount)
+ }
+ if len(preview.CurrentSystems) != 1 {
+ t.Fatalf("len(CurrentSystems) = %d, want 1", len(preview.CurrentSystems))
+ }
+ if len(preview.ProjectedSystems) != 2 {
+ t.Fatalf("len(ProjectedSystems) = %d, want 2", len(preview.ProjectedSystems))
+ }
+ if preview.CurrentSystems[0].Source != "agent" {
+ t.Fatalf("CurrentSystems[0].Source = %q, want agent", preview.CurrentSystems[0].Source)
+ }
+}
diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.go
index 49f4feecc8..ad5bd8ed7c 100644
--- a/internal/unifiedresources/registry_test.go
+++ b/internal/unifiedresources/registry_test.go
@@ -2115,6 +2115,91 @@ func TestProjectMonitoredSystemRecords_DedupesVMwareHostAgainstExistingAgentCoun
}
}
+func TestPreviewMonitoredSystemRecords_ReturnsCurrentAndProjectedSystemsForVMwareAdmission(t *testing.T) {
+ rr := NewRegistry(nil)
+ now := time.Date(2026, 4, 7, 12, 0, 0, 0, time.UTC)
+
+ rr.IngestRecords(SourceAgent, []IngestRecord{
+ {
+ SourceID: "agent-host-1",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: StatusOnline,
+ LastSeen: now,
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ })
+
+ preview := PreviewMonitoredSystemRecords(rr, map[DataSource][]IngestRecord{
+ SourceVMware: {
+ {
+ SourceID: "vc-1:host:host-101",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: StatusOnline,
+ LastSeen: now,
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ {
+ SourceID: "vc-1:host:host-102",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-02.lab.local",
+ Status: StatusOnline,
+ LastSeen: now,
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-102",
+ EntityType: "host",
+ HostUUID: "uuid-host-2",
+ },
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-2",
+ Hostnames: []string{"esxi-02.lab.local"},
+ },
+ },
+ },
+ })
+
+ if preview.CurrentCount != 1 {
+ t.Fatalf("CurrentCount = %d, want 1", preview.CurrentCount)
+ }
+ if preview.ProjectedCount != 2 {
+ t.Fatalf("ProjectedCount = %d, want 2", preview.ProjectedCount)
+ }
+ if preview.AdditionalCount != 1 {
+ t.Fatalf("AdditionalCount = %d, want 1", preview.AdditionalCount)
+ }
+ if len(preview.CurrentSystems) != 1 {
+ t.Fatalf("len(CurrentSystems) = %d, want 1", len(preview.CurrentSystems))
+ }
+ if len(preview.ProjectedSystems) != 2 {
+ t.Fatalf("len(ProjectedSystems) = %d, want 2", len(preview.ProjectedSystems))
+ }
+ if preview.CurrentSystems[0].Source != "agent" {
+ t.Fatalf("CurrentSystems[0].Source = %q, want agent", preview.CurrentSystems[0].Source)
+ }
+}
+
func TestResourceRegistry_WorkloadsIncludeCanonicalAppContainers(t *testing.T) {
rr := NewRegistry(nil)
now := time.Date(2026, 3, 29, 12, 0, 0, 0, time.UTC)
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 8d8b6b7aa3..1b97f521ac 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -29,12 +29,16 @@ PLATFORM_CONNECTIONS_WORKSPACE_EXACT_FILES = [
"frontend-modern/src/components/Settings/__tests__/InfrastructureWorkspace.test.tsx",
"frontend-modern/src/components/Settings/__tests__/PlatformConnectionsWorkspace.test.tsx",
"frontend-modern/src/components/Settings/__tests__/TrueNASSettingsPanel.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/VMwareSettingsPanel.test.tsx",
"frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts",
"frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts",
"frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/useVMwareSettingsPanelState.test.tsx",
"frontend-modern/src/utils/__tests__/clusterEndpointPresentation.test.ts",
"frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",
"frontend-modern/src/utils/__tests__/proxmoxSettingsPresentation.test.ts",
+ "tests/integration/tests/21-truenas-settings-platform-connections.spec.ts",
+ "tests/integration/tests/22-vmware-settings-platform-connections.spec.ts",
]
diff --git a/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts b/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts
index 54389e2989..f1c7b7c6ae 100644
--- a/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts
+++ b/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts
@@ -1,8 +1,8 @@
-import fs from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { test as base, expect } from '@playwright/test';
-import { createAuthenticatedStorageState } from './helpers';
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { test as base, expect } from "@playwright/test";
+import { createAuthenticatedStorageState } from "./helpers";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -12,84 +12,87 @@ type WorkerFixtures = {
const SCREENSHOT_PATH = path.resolve(
__dirname,
- '..',
- '..',
- 'tmp',
- 'truenas-settings-platform-connections.png',
+ "..",
+ "..",
+ "tmp",
+ "truenas-settings-platform-connections.png",
);
const OPERATIONS_SCREENSHOT_PATH = path.resolve(
__dirname,
- '..',
- '..',
- 'tmp',
- 'truenas-settings-operations-summary.png',
+ "..",
+ "..",
+ "tmp",
+ "truenas-settings-operations-summary.png",
);
const WORKFLOW_SCREENSHOT_PATH = path.resolve(
__dirname,
- '..',
- '..',
- 'tmp',
- 'truenas-settings-platform-workflow.png',
+ "..",
+ "..",
+ "tmp",
+ "truenas-settings-platform-workflow.png",
);
const HEALTH_REFRESH_SCREENSHOT_PATH = path.resolve(
__dirname,
- '..',
- '..',
- 'tmp',
- 'truenas-settings-health-refresh.png',
+ "..",
+ "..",
+ "tmp",
+ "truenas-settings-health-refresh.png",
);
const test = base.extend<{}, WorkerFixtures>({
storageState: async ({ authStorageStatePath }, use) => {
await use(authStorageStatePath);
},
- authStorageStatePath: [async ({ browser }, use, workerInfo) => {
- const storageStatePath = path.resolve(
- __dirname,
- '..',
- '..',
- 'tmp',
- 'playwright-auth',
- `truenas-settings-platform-connections-${workerInfo.project.name}.json`,
- );
- fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
- await createAuthenticatedStorageState(browser, storageStatePath);
- try {
- await use(storageStatePath);
- } finally {
- fs.rmSync(storageStatePath, { force: true });
- }
- }, { scope: 'worker' }],
+ authStorageStatePath: [
+ async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ "..",
+ "..",
+ "tmp",
+ "playwright-auth",
+ `truenas-settings-platform-connections-${workerInfo.project.name}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ },
+ { scope: "worker" },
+ ],
});
-test.describe('TrueNAS platform connections settings', () => {
+test.describe("TrueNAS platform connections settings", () => {
test.setTimeout(180_000);
- test('renders the platform-connections workspace with the TrueNAS integration shell', async ({
+ test("renders the platform-connections workspace with the TrueNAS integration shell", async ({
page,
}) => {
const healthyAt = new Date(Date.now() - 5 * 60_000).toISOString();
const failingAt = new Date(Date.now() - 2 * 60_000).toISOString();
- await page.route('**/api/truenas/connections', async (route) => {
- if (route.request().method() !== 'GET') {
+ await page.route("**/api/truenas/connections", async (route) => {
+ if (route.request().method() !== "GET") {
await route.continue();
return;
}
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify([
{
- id: 'truenas-1',
- name: 'Tower NAS',
- host: 'tower.local',
+ id: "truenas-1",
+ name: "Tower NAS",
+ host: "tower.local",
port: 443,
- apiKey: '********',
+ apiKey: "********",
useHttps: true,
insecureSkipVerify: false,
- fingerprint: '',
+ fingerprint: "",
enabled: true,
pollIntervalSeconds: 60,
poll: {
@@ -97,8 +100,8 @@ test.describe('TrueNAS platform connections settings', () => {
lastSuccessAt: healthyAt,
},
observed: {
- host: 'tower',
- resourceId: 'tower',
+ host: "tower",
+ resourceId: "tower",
collectedAt: healthyAt,
systems: 1,
storagePools: 2,
@@ -109,15 +112,15 @@ test.describe('TrueNAS platform connections settings', () => {
},
},
{
- id: 'truenas-2',
- name: 'Backup Vault',
- host: 'vault.local',
+ id: "truenas-2",
+ name: "Backup Vault",
+ host: "vault.local",
port: 443,
- username: 'admin',
- password: '********',
+ username: "admin",
+ password: "********",
useHttps: true,
insecureSkipVerify: true,
- fingerprint: 'sha256:example',
+ fingerprint: "sha256:example",
enabled: false,
pollIntervalSeconds: 300,
poll: {
@@ -126,13 +129,13 @@ test.describe('TrueNAS platform connections settings', () => {
consecutiveFailures: 2,
lastError: {
at: failingAt,
- message: 'authentication failed',
- category: 'auth',
+ message: "authentication failed",
+ category: "auth",
},
},
observed: {
- host: 'vault',
- resourceId: 'vault',
+ host: "vault",
+ resourceId: "vault",
collectedAt: healthyAt,
systems: 1,
storagePools: 1,
@@ -146,63 +149,66 @@ test.describe('TrueNAS platform connections settings', () => {
});
});
- await page.goto('/settings/infrastructure/platforms/truenas', {
- waitUntil: 'domcontentloaded',
+ await page.goto("/settings/infrastructure/platforms/truenas", {
+ waitUntil: "domcontentloaded",
});
await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {
timeout: 15_000,
});
await expect(
- page.getByRole('heading', { level: 1, name: 'Infrastructure Operations' }),
+ page.getByRole("heading", {
+ level: 1,
+ name: "Infrastructure Operations",
+ }),
).toBeVisible();
- await expect(page.getByRole('tab', { name: 'Platform connections' })).toHaveAttribute(
- 'aria-selected',
- 'true',
- );
- await expect(page.getByRole('tab', { name: 'TrueNAS' })).toHaveAttribute(
- 'aria-selected',
- 'true',
+ await expect(
+ page.getByRole("tab", { name: "Platform connections" }),
+ ).toHaveAttribute("aria-selected", "true");
+ await expect(page.getByRole("tab", { name: "TrueNAS" })).toHaveAttribute(
+ "aria-selected",
+ "true",
);
- await expect(page.getByRole('tab', { name: 'Proxmox' })).toHaveAttribute(
- 'aria-selected',
- 'false',
+ await expect(page.getByRole("tab", { name: "Proxmox" })).toHaveAttribute(
+ "aria-selected",
+ "false",
);
- await expect(page.getByText('TrueNAS platform integration')).toBeVisible();
- await expect(page.getByRole('button', { name: 'Add TrueNAS connection' })).toBeVisible();
- await expect(page.getByText('Tower NAS')).toBeVisible();
- await expect(page.getByText('Backup Vault')).toBeVisible();
- await expect(page.getByText('API key auth')).toBeVisible();
- await expect(page.getByText('Username/password auth')).toBeVisible();
- await expect(page.getByText('Healthy')).toBeVisible();
- await expect(page.getByText('Paused', { exact: true })).toBeVisible();
- await expect(page.getByText('Poll every 1 minute')).toBeVisible();
- await expect(page.getByText('Poll every 5 minutes')).toBeVisible();
- await expect(page.getByText('2 pools')).toBeVisible();
- await expect(page.getByText('12 datasets')).toBeVisible();
- await expect(page.getByTestId('truenas-connection-truenas-1-infrastructure')).toHaveAttribute(
- 'href',
- '/infrastructure?source=truenas&resource=tower',
- );
- await expect(page.getByTestId('truenas-connection-truenas-1-workloads')).toHaveAttribute(
- 'href',
- '/workloads?type=app-container&platform=truenas&agent=tower',
- );
- await expect(page.getByTestId('truenas-connection-truenas-1-storage')).toHaveAttribute(
- 'href',
- '/storage?source=truenas&node=tower',
- );
- await expect(page.getByTestId('truenas-connection-truenas-1-recovery')).toHaveAttribute(
- 'href',
- '/recovery?platform=truenas&node=tower',
+ await expect(page.getByText("TrueNAS platform integration")).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "Add TrueNAS connection" }),
+ ).toBeVisible();
+ await expect(page.getByText("Tower NAS")).toBeVisible();
+ await expect(page.getByText("Backup Vault")).toBeVisible();
+ await expect(page.getByText("API key auth")).toBeVisible();
+ await expect(page.getByText("Username/password auth")).toBeVisible();
+ await expect(page.getByText("Healthy")).toBeVisible();
+ await expect(page.getByText("Paused", { exact: true })).toBeVisible();
+ await expect(page.getByText("Poll every 1 minute")).toBeVisible();
+ await expect(page.getByText("Poll every 5 minutes")).toBeVisible();
+ await expect(page.getByText("2 pools")).toBeVisible();
+ await expect(page.getByText("12 datasets")).toBeVisible();
+ await expect(
+ page.getByTestId("truenas-connection-truenas-1-infrastructure"),
+ ).toHaveAttribute("href", "/infrastructure?source=truenas&resource=tower");
+ await expect(
+ page.getByTestId("truenas-connection-truenas-1-workloads"),
+ ).toHaveAttribute(
+ "href",
+ "/workloads?type=app-container&platform=truenas&agent=tower",
);
+ await expect(
+ page.getByTestId("truenas-connection-truenas-1-storage"),
+ ).toHaveAttribute("href", "/storage?source=truenas&node=tower");
+ await expect(
+ page.getByTestId("truenas-connection-truenas-1-recovery"),
+ ).toHaveAttribute("href", "/recovery?platform=truenas&node=tower");
fs.mkdirSync(path.dirname(SCREENSHOT_PATH), { recursive: true });
await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true });
});
- test('adds, edits, retests, and deletes TrueNAS connections through the canonical settings workflow', async ({
+ test("adds, edits, retests, and deletes TrueNAS connections through the canonical settings workflow", async ({
page,
}) => {
const syncedAt = new Date(Date.now() - 60_000).toISOString();
@@ -211,43 +217,46 @@ test.describe('TrueNAS platform connections settings', () => {
let createPayload: Record<string, unknown> | null = null;
let updatePayload: Record<string, unknown> | null = null;
let draftTestCalls = 0;
- const savedTestRequests: Array<{ path: string; payload: Record<string, unknown> | null }> = [];
+ const savedTestRequests: Array<{
+ path: string;
+ payload: Record<string, unknown> | null;
+ }> = [];
const deletePaths: string[] = [];
- await page.route('**/api/truenas/connections**', async (route) => {
+ await page.route("**/api/truenas/connections**", async (route) => {
const request = route.request();
const method = request.method();
const pathname = new URL(request.url()).pathname;
- if (pathname === '/api/truenas/connections' && method === 'GET') {
+ if (pathname === "/api/truenas/connections" && method === "GET") {
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify(connections),
});
return;
}
- if (pathname === '/api/truenas/connections/test' && method === 'POST') {
+ if (pathname === "/api/truenas/connections/test" && method === "POST") {
draftTestCalls += 1;
- draftTestPayload = JSON.parse(request.postData() || '{}');
+ draftTestPayload = JSON.parse(request.postData() || "{}");
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify({ success: true }),
});
return;
}
- if (pathname === '/api/truenas/connections' && method === 'POST') {
- createPayload = JSON.parse(request.postData() || '{}');
+ if (pathname === "/api/truenas/connections" && method === "POST") {
+ createPayload = JSON.parse(request.postData() || "{}");
connections = [
{
- id: 'conn-1',
+ id: "conn-1",
name: createPayload.name,
host: createPayload.host,
port: createPayload.port,
- apiKey: '********',
+ apiKey: "********",
useHttps: createPayload.useHttps,
insecureSkipVerify: createPayload.insecureSkipVerify,
fingerprint: createPayload.fingerprint,
@@ -258,8 +267,8 @@ test.describe('TrueNAS platform connections settings', () => {
lastSuccessAt: syncedAt,
},
observed: {
- host: 'tower',
- resourceId: 'tower',
+ host: "tower",
+ resourceId: "tower",
collectedAt: syncedAt,
systems: 1,
storagePools: 2,
@@ -272,34 +281,39 @@ test.describe('TrueNAS platform connections settings', () => {
];
await route.fulfill({
status: 201,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify(connections[0]),
});
return;
}
- if (pathname === '/api/truenas/connections/conn-1/test' && method === 'POST') {
+ if (
+ pathname === "/api/truenas/connections/conn-1/test" &&
+ method === "POST"
+ ) {
savedTestRequests.push({
path: pathname,
- payload: request.postData() ? JSON.parse(request.postData() || '{}') : null,
+ payload: request.postData()
+ ? JSON.parse(request.postData() || "{}")
+ : null,
});
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify({ success: true }),
});
return;
}
- if (pathname === '/api/truenas/connections/conn-1' && method === 'PUT') {
- updatePayload = JSON.parse(request.postData() || '{}');
+ if (pathname === "/api/truenas/connections/conn-1" && method === "PUT") {
+ updatePayload = JSON.parse(request.postData() || "{}");
connections = [
{
- id: 'conn-1',
+ id: "conn-1",
name: updatePayload.name,
host: updatePayload.host,
port: updatePayload.port,
- apiKey: '********',
+ apiKey: "********",
useHttps: updatePayload.useHttps,
insecureSkipVerify: updatePayload.insecureSkipVerify,
fingerprint: updatePayload.fingerprint,
@@ -310,8 +324,8 @@ test.describe('TrueNAS platform connections settings', () => {
lastSuccessAt: syncedAt,
},
observed: {
- host: 'tower',
- resourceId: 'tower',
+ host: "tower",
+ resourceId: "tower",
collectedAt: syncedAt,
systems: 1,
storagePools: 2,
@@ -324,19 +338,22 @@ test.describe('TrueNAS platform connections settings', () => {
];
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify(connections[0]),
});
return;
}
- if (pathname === '/api/truenas/connections/conn-1' && method === 'DELETE') {
+ if (
+ pathname === "/api/truenas/connections/conn-1" &&
+ method === "DELETE"
+ ) {
deletePaths.push(pathname);
connections = [];
await route.fulfill({
status: 200,
- contentType: 'application/json',
- body: JSON.stringify({ success: true, id: 'conn-1' }),
+ contentType: "application/json",
+ body: JSON.stringify({ success: true, id: "conn-1" }),
});
return;
}
@@ -344,77 +361,84 @@ test.describe('TrueNAS platform connections settings', () => {
await route.continue();
});
- await page.goto('/settings/infrastructure/platforms/truenas', {
- waitUntil: 'domcontentloaded',
+ await page.goto("/settings/infrastructure/platforms/truenas", {
+ waitUntil: "domcontentloaded",
});
await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {
timeout: 15_000,
});
- await expect(page.getByText('No TrueNAS connections yet')).toBeVisible();
+ await expect(page.getByText("No TrueNAS connections yet")).toBeVisible();
- await page.getByRole('button', { name: 'Add TrueNAS connection' }).click();
- const dialog = page.getByRole('dialog', { name: 'Add TrueNAS connection' });
+ await page.getByRole("button", { name: "Add TrueNAS connection" }).click();
+ const dialog = page.getByRole("dialog", { name: "Add TrueNAS connection" });
await expect(dialog).toBeVisible();
- await dialog.getByPlaceholder('tower').fill('Tower NAS');
- await dialog.getByPlaceholder('truenas.local').fill('tower.local');
- await dialog.getByPlaceholder('443').fill('443');
- await dialog.getByPlaceholder('60').fill('90');
- await dialog.locator('input[type="password"]').first().fill('secret-api-key');
+ await dialog.getByPlaceholder("tower").fill("Tower NAS");
+ await dialog.getByPlaceholder("truenas.local").fill("tower.local");
+ await dialog.getByPlaceholder("443").fill("443");
+ await dialog.getByPlaceholder("60").fill("90");
+ await dialog
+ .locator('input[type="password"]')
+ .first()
+ .fill("secret-api-key");
- await dialog.getByRole('button', { name: 'Test connection' }).click();
+ await dialog.getByRole("button", { name: "Test connection" }).click();
await expect
.poll(() => draftTestPayload)
.toMatchObject({
- name: 'Tower NAS',
- host: 'tower.local',
+ name: "Tower NAS",
+ host: "tower.local",
port: 443,
- apiKey: 'secret-api-key',
+ apiKey: "secret-api-key",
useHttps: true,
enabled: true,
pollIntervalSeconds: 90,
});
- await dialog.getByRole('button', { name: 'Add connection' }).click();
+ await dialog.getByRole("button", { name: "Add connection" }).click();
- const connectionCard = page.getByTestId('truenas-connection-conn-1');
+ const connectionCard = page.getByTestId("truenas-connection-conn-1");
await expect(connectionCard).toBeVisible();
- await expect(connectionCard).toContainText('Tower NAS');
- await expect(connectionCard).toContainText('Healthy');
+ await expect(connectionCard).toContainText("Tower NAS");
+ await expect(connectionCard).toContainText("Healthy");
await expect
.poll(() => createPayload)
.toMatchObject({
- name: 'Tower NAS',
- host: 'tower.local',
+ name: "Tower NAS",
+ host: "tower.local",
port: 443,
- apiKey: 'secret-api-key',
+ apiKey: "secret-api-key",
useHttps: true,
enabled: true,
pollIntervalSeconds: 90,
});
- await connectionCard.getByRole('button', { name: 'Edit' }).click();
- const editDialog = page.getByRole('dialog', { name: 'Edit TrueNAS connection' });
+ await connectionCard.getByRole("button", { name: "Edit" }).click();
+ const editDialog = page.getByRole("dialog", {
+ name: "Edit TrueNAS connection",
+ });
await expect(editDialog).toBeVisible();
await expect(
- editDialog.getByPlaceholder('Saved API key retained unless replaced'),
+ editDialog.getByPlaceholder("Saved API key retained unless replaced"),
).toBeVisible();
- await editDialog.getByPlaceholder('tower').fill('Tower NAS Edited');
- await editDialog.getByPlaceholder('truenas.local').fill('tower-edited.local');
- await editDialog.getByPlaceholder('60').fill('120');
+ await editDialog.getByPlaceholder("tower").fill("Tower NAS Edited");
+ await editDialog
+ .getByPlaceholder("truenas.local")
+ .fill("tower-edited.local");
+ await editDialog.getByPlaceholder("60").fill("120");
- await editDialog.getByRole('button', { name: 'Test connection' }).click();
+ await editDialog.getByRole("button", { name: "Test connection" }).click();
await expect
.poll(() => savedTestRequests[0])
.toMatchObject({
- path: '/api/truenas/connections/conn-1/test',
+ path: "/api/truenas/connections/conn-1/test",
payload: {
- name: 'Tower NAS Edited',
- host: 'tower-edited.local',
+ name: "Tower NAS Edited",
+ host: "tower-edited.local",
port: 443,
- apiKey: '********',
+ apiKey: "********",
useHttps: true,
enabled: true,
pollIntervalSeconds: 120,
@@ -422,53 +446,299 @@ test.describe('TrueNAS platform connections settings', () => {
});
await expect.poll(() => draftTestCalls).toBe(1);
- await editDialog.getByRole('button', { name: 'Save connection' }).click();
+ await editDialog.getByRole("button", { name: "Save connection" }).click();
await expect
.poll(() => updatePayload)
.toMatchObject({
- name: 'Tower NAS Edited',
- host: 'tower-edited.local',
+ name: "Tower NAS Edited",
+ host: "tower-edited.local",
port: 443,
- apiKey: '********',
+ apiKey: "********",
useHttps: true,
enabled: true,
pollIntervalSeconds: 120,
});
- await expect(connectionCard).toContainText('Tower NAS Edited');
-
- await connectionCard.getByRole('button', { name: 'Test' }).click();
- await expect.poll(() => savedTestRequests).toEqual([
- expect.objectContaining({
- path: '/api/truenas/connections/conn-1/test',
- payload: expect.objectContaining({
- host: 'tower-edited.local',
- apiKey: '********',
- pollIntervalSeconds: 120,
+ await expect(connectionCard).toContainText("Tower NAS Edited");
+
+ await connectionCard.getByRole("button", { name: "Test" }).click();
+ await expect
+ .poll(() => savedTestRequests)
+ .toEqual([
+ expect.objectContaining({
+ path: "/api/truenas/connections/conn-1/test",
+ payload: expect.objectContaining({
+ host: "tower-edited.local",
+ apiKey: "********",
+ pollIntervalSeconds: 120,
+ }),
}),
- }),
- { path: '/api/truenas/connections/conn-1/test', payload: null },
- ]);
+ { path: "/api/truenas/connections/conn-1/test", payload: null },
+ ]);
await expect.poll(() => draftTestCalls).toBe(1);
- await connectionCard.getByRole('button', { name: 'Delete' }).click();
- await page.getByRole('button', { name: 'Delete connection' }).click();
- await expect.poll(() => deletePaths).toEqual(['/api/truenas/connections/conn-1']);
- await expect(page.getByText('No TrueNAS connections yet')).toBeVisible();
+ await connectionCard.getByRole("button", { name: "Delete" }).click();
+ await page.getByRole("button", { name: "Delete connection" }).click();
+ await expect
+ .poll(() => deletePaths)
+ .toEqual(["/api/truenas/connections/conn-1"]);
+ await expect(page.getByText("No TrueNAS connections yet")).toBeVisible();
fs.mkdirSync(path.dirname(WORKFLOW_SCREENSHOT_PATH), { recursive: true });
await page.screenshot({ path: WORKFLOW_SCREENSHOT_PATH, fullPage: true });
});
- test('saved connection tests refresh runtime health in the settings card', async ({ page }) => {
+ test("previews monitored-system impact before creating a TrueNAS connection", async ({
+ page,
+ }) => {
+ let previewPayload: Record<string, unknown> | null = null;
+ let createCalls = 0;
+
+ await page.route("**/api/truenas/connections**", async (route) => {
+ const request = route.request();
+ const method = request.method();
+ const pathname = new URL(request.url()).pathname;
+
+ if (pathname === "/api/truenas/connections" && method === "GET") {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify([]),
+ });
+ return;
+ }
+
+ if (
+ pathname === "/api/truenas/connections/preview" &&
+ method === "POST"
+ ) {
+ previewPayload = JSON.parse(request.postData() || "{}");
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ current_count: 9,
+ projected_count: 10,
+ additional_count: 1,
+ limit: 9,
+ would_exceed_limit: true,
+ effect: "creates_new",
+ current_systems: [
+ {
+ name: "tower-agent",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "tower-agent",
+ type: "agent",
+ source: "agent",
+ at: new Date(Date.now() - 60_000).toISOString(),
+ },
+ source: "agent",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ projected_systems: [
+ {
+ name: "tower",
+ type: "truenas-system",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "tower",
+ type: "truenas-system",
+ source: "truenas",
+ at: new Date().toISOString(),
+ },
+ source: "truenas",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ }),
+ });
+ return;
+ }
+
+ if (pathname === "/api/truenas/connections" && method === "POST") {
+ createCalls += 1;
+ await route.fulfill({
+ status: 201,
+ contentType: "application/json",
+ body: JSON.stringify({}),
+ });
+ return;
+ }
+
+ await route.continue();
+ });
+
+ await page.goto("/settings/infrastructure/platforms/truenas", {
+ waitUntil: "domcontentloaded",
+ });
+ await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {
+ timeout: 15_000,
+ });
+
+ await page.getByRole("button", { name: "Add TrueNAS connection" }).click();
+ const dialog = page.getByRole("dialog", { name: "Add TrueNAS connection" });
+ await expect(dialog).toBeVisible();
+
+ await dialog.getByPlaceholder("tower").fill("Tower NAS");
+ await dialog.getByPlaceholder("truenas.local").fill("tower.local");
+ await dialog.getByPlaceholder("443").fill("443");
+ await dialog
+ .locator('input[type="password"]')
+ .first()
+ .fill("secret-api-key");
+
+ await dialog.getByRole("button", { name: "Preview impact" }).click();
+
+ await expect
+ .poll(() => previewPayload)
+ .toMatchObject({
+ name: "Tower NAS",
+ host: "tower.local",
+ port: 443,
+ apiKey: "secret-api-key",
+ useHttps: true,
+ enabled: true,
+ });
+ await expect(
+ dialog.getByText("This change exceeds your monitored-system limit"),
+ ).toBeVisible();
+ await expect(dialog.getByText(/Current usage 9 \/ 9/)).toBeVisible();
+ await expect(dialog.getByText("Current matched systems")).toBeVisible();
+ await expect(
+ dialog.getByText("tower-agent (Host via Agent)"),
+ ).toBeVisible();
+ await expect(dialog.getByText("Projected systems")).toBeVisible();
+ await expect(
+ dialog.getByText("tower (TrueNAS System via TrueNAS)"),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole("button", { name: "Add connection" }),
+ ).toBeDisabled();
+ expect(createCalls).toBe(0);
+ });
+
+ test("reuses the canonical monitored-system explanation when a TrueNAS save is denied", async ({
+ page,
+ }) => {
+ let createPayload: Record<string, unknown> | null = null;
+
+ await page.route("**/api/truenas/connections**", async (route) => {
+ const request = route.request();
+ const method = request.method();
+ const pathname = new URL(request.url()).pathname;
+
+ if (pathname === "/api/truenas/connections" && method === "GET") {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify([]),
+ });
+ return;
+ }
+
+ if (pathname === "/api/truenas/connections" && method === "POST") {
+ createPayload = JSON.parse(request.postData() || "{}");
+ await route.fulfill({
+ status: 402,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: "license_required",
+ message: "Monitored-system limit reached (10/9)",
+ feature: "max_monitored_systems",
+ monitored_system_preview: {
+ current_count: 9,
+ projected_count: 10,
+ additional_count: 1,
+ limit: 9,
+ would_exceed_limit: true,
+ effect: "creates_new",
+ current_systems: [],
+ projected_systems: [
+ {
+ name: "tower",
+ type: "truenas-system",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "tower",
+ type: "truenas-system",
+ source: "truenas",
+ at: new Date().toISOString(),
+ },
+ source: "truenas",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ }),
+ });
+ return;
+ }
+
+ await route.continue();
+ });
+
+ await page.goto("/settings/infrastructure/platforms/truenas", {
+ waitUntil: "domcontentloaded",
+ });
+ await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {
+ timeout: 15_000,
+ });
+
+ await page.getByRole("button", { name: "Add TrueNAS connection" }).click();
+ const dialog = page.getByRole("dialog", { name: "Add TrueNAS connection" });
+ await expect(dialog).toBeVisible();
+
+ await dialog.getByPlaceholder("tower").fill("Tower NAS");
+ await dialog.getByPlaceholder("truenas.local").fill("tower.local");
+ await dialog
+ .locator('input[type="password"]')
+ .first()
+ .fill("secret-api-key");
+ await dialog.getByRole("button", { name: "Add connection" }).click();
+
+ await expect
+ .poll(() => createPayload)
+ .toMatchObject({
+ name: "Tower NAS",
+ host: "tower.local",
+ apiKey: "secret-api-key",
+ useHttps: true,
+ enabled: true,
+ });
+ await expect(
+ dialog.getByText("This change exceeds your monitored-system limit"),
+ ).toBeVisible();
+ await expect(dialog.getByText(/Current usage 9 \/ 9/)).toBeVisible();
+ await expect(dialog.getByText("Projected systems")).toBeVisible();
+ await expect(
+ dialog.getByText("tower (TrueNAS System via TrueNAS)"),
+ ).toBeVisible();
+ await expect(
+ dialog.getByRole("button", { name: "Add connection" }),
+ ).toBeDisabled();
+ });
+
+ test("saved connection tests refresh runtime health in the settings card", async ({
+ page,
+ }) => {
const failedAt = new Date(Date.now() - 5 * 60_000).toISOString();
const recoveredAt = new Date().toISOString();
let savedTestCalls = 0;
let connection = {
- id: 'conn-1',
- name: 'Tower NAS',
- host: 'tower.local',
+ id: "conn-1",
+ name: "Tower NAS",
+ host: "tower.local",
port: 443,
- apiKey: '********',
+ apiKey: "********",
useHttps: true,
insecureSkipVerify: false,
enabled: true,
@@ -479,13 +749,13 @@ test.describe('TrueNAS platform connections settings', () => {
consecutiveFailures: 2,
lastError: {
at: failedAt,
- message: 'authentication failed',
- category: 'auth',
+ message: "authentication failed",
+ category: "auth",
},
},
observed: {
- host: 'tower',
- resourceId: 'tower',
+ host: "tower",
+ resourceId: "tower",
collectedAt: failedAt,
systems: 1,
storagePools: 2,
@@ -496,21 +766,24 @@ test.describe('TrueNAS platform connections settings', () => {
},
};
- await page.route('**/api/truenas/connections**', async (route) => {
+ await page.route("**/api/truenas/connections**", async (route) => {
const request = route.request();
const method = request.method();
const pathname = new URL(request.url()).pathname;
- if (pathname === '/api/truenas/connections' && method === 'GET') {
+ if (pathname === "/api/truenas/connections" && method === "GET") {
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify([connection]),
});
return;
}
- if (pathname === '/api/truenas/connections/conn-1/test' && method === 'POST') {
+ if (
+ pathname === "/api/truenas/connections/conn-1/test" &&
+ method === "POST"
+ ) {
savedTestCalls += 1;
connection = {
...connection,
@@ -521,7 +794,7 @@ test.describe('TrueNAS platform connections settings', () => {
};
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify({ success: true }),
});
return;
@@ -530,125 +803,130 @@ test.describe('TrueNAS platform connections settings', () => {
await route.continue();
});
- await page.goto('/settings/infrastructure/platforms/truenas', {
- waitUntil: 'domcontentloaded',
+ await page.goto("/settings/infrastructure/platforms/truenas", {
+ waitUntil: "domcontentloaded",
});
await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {
timeout: 15_000,
});
- const connectionCard = page.getByTestId('truenas-connection-conn-1');
- await expect(connectionCard).toContainText('Sync failing');
- await expect(connectionCard).toContainText('authentication failed');
+ const connectionCard = page.getByTestId("truenas-connection-conn-1");
+ await expect(connectionCard).toContainText("Sync failing");
+ await expect(connectionCard).toContainText("authentication failed");
- await connectionCard.getByRole('button', { name: 'Test' }).click();
+ await connectionCard.getByRole("button", { name: "Test" }).click();
await expect.poll(() => savedTestCalls).toBe(1);
- await expect(connectionCard).toContainText('Healthy');
- await expect(connectionCard).not.toContainText('authentication failed');
+ await expect(connectionCard).toContainText("Healthy");
+ await expect(connectionCard).not.toContainText("authentication failed");
- fs.mkdirSync(path.dirname(HEALTH_REFRESH_SCREENSHOT_PATH), { recursive: true });
- await page.screenshot({ path: HEALTH_REFRESH_SCREENSHOT_PATH, fullPage: true });
+ fs.mkdirSync(path.dirname(HEALTH_REFRESH_SCREENSHOT_PATH), {
+ recursive: true,
+ });
+ await page.screenshot({
+ path: HEALTH_REFRESH_SCREENSHOT_PATH,
+ fullPage: true,
+ });
});
- test('counts TrueNAS alongside the other platform connections on the operations summary', async ({
+ test("counts TrueNAS alongside the other platform connections on the operations summary", async ({
page,
}) => {
- await page.route('**/api/config/nodes', async (route) => {
- if (route.request().method() !== 'GET') {
+ await page.route("**/api/config/nodes", async (route) => {
+ if (route.request().method() !== "GET") {
await route.continue();
return;
}
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify([
{
- id: 'pve-1',
- type: 'pve',
- name: 'pve-main',
- host: 'pve-main.local',
- user: 'root@pam',
+ id: "pve-1",
+ type: "pve",
+ name: "pve-main",
+ host: "pve-main.local",
+ user: "root@pam",
verifySSL: true,
monitorVMs: true,
monitorContainers: true,
monitorStorage: true,
monitorBackups: true,
monitorPhysicalDisks: true,
- status: 'connected',
+ status: "connected",
},
{
- id: 'pbs-1',
- type: 'pbs',
- name: 'pbs-main',
- host: 'pbs-main.local',
- user: 'root@pam',
+ id: "pbs-1",
+ type: "pbs",
+ name: "pbs-main",
+ host: "pbs-main.local",
+ user: "root@pam",
verifySSL: true,
monitorDatastores: true,
monitorSyncJobs: true,
monitorVerifyJobs: true,
monitorPruneJobs: true,
monitorGarbageJobs: true,
- status: 'connected',
+ status: "connected",
},
{
- id: 'pbs-2',
- type: 'pbs',
- name: 'pbs-vault',
- host: 'pbs-vault.local',
- user: 'root@pam',
+ id: "pbs-2",
+ type: "pbs",
+ name: "pbs-vault",
+ host: "pbs-vault.local",
+ user: "root@pam",
verifySSL: true,
monitorDatastores: true,
monitorSyncJobs: true,
monitorVerifyJobs: true,
monitorPruneJobs: true,
monitorGarbageJobs: true,
- status: 'connected',
+ status: "connected",
},
{
- id: 'pmg-1',
- type: 'pmg',
- name: 'pmg-main',
- host: 'pmg-main.local',
- user: 'root@pam',
+ id: "pmg-1",
+ type: "pmg",
+ name: "pmg-main",
+ host: "pmg-main.local",
+ user: "root@pam",
verifySSL: true,
monitorMailStats: true,
monitorQueues: true,
monitorQuarantine: true,
monitorDomainStats: true,
- status: 'connected',
+ status: "connected",
},
]),
});
});
- await page.route('**/api/truenas/connections', async (route) => {
- if (route.request().method() !== 'GET') {
+ await page.route("**/api/truenas/connections", async (route) => {
+ if (route.request().method() !== "GET") {
await route.continue();
return;
}
await route.fulfill({
status: 200,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify([
{
- id: 'truenas-1',
- name: 'Tower NAS',
- host: 'tower.local',
+ id: "truenas-1",
+ name: "Tower NAS",
+ host: "tower.local",
port: 443,
- apiKey: '********',
+ apiKey: "********",
useHttps: true,
insecureSkipVerify: false,
enabled: true,
},
{
- id: 'truenas-2',
- name: 'Backup Vault',
- host: 'vault.local',
+ id: "truenas-2",
+ name: "Backup Vault",
+ host: "vault.local",
port: 443,
- apiKey: '********',
+ apiKey: "********",
useHttps: true,
insecureSkipVerify: false,
enabled: true,
@@ -657,62 +935,81 @@ test.describe('TrueNAS platform connections settings', () => {
});
});
- await page.goto('/settings/infrastructure/operations', {
- waitUntil: 'domcontentloaded',
+ await page.goto("/settings/infrastructure/operations", {
+ waitUntil: "domcontentloaded",
});
await page.waitForURL(/\/settings\/infrastructure\/operations/, {
timeout: 15_000,
});
await expect(
- page.getByRole('heading', { level: 1, name: 'Infrastructure Operations' }),
+ page.getByRole("heading", {
+ level: 1,
+ name: "Infrastructure Operations",
+ }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("heading", { level: 3, name: "Platform connections" }),
).toBeVisible();
- await expect(page.getByRole('heading', { level: 3, name: 'Platform connections' })).toBeVisible();
- await expect(page.getByTestId('platform-connections-pve')).toContainText('1');
- await expect(page.getByTestId('platform-connections-pbs')).toContainText('2');
- await expect(page.getByTestId('platform-connections-pmg')).toContainText('1');
- await expect(page.getByTestId('platform-connections-truenas')).toContainText('2');
- await expect(page.getByTestId('platform-connections-truenas')).toContainText(
- 'API-backed NAS connections',
+ await expect(page.getByTestId("platform-connections-pve")).toContainText(
+ "1",
);
+ await expect(page.getByTestId("platform-connections-pbs")).toContainText(
+ "2",
+ );
+ await expect(page.getByTestId("platform-connections-pmg")).toContainText(
+ "1",
+ );
+ await expect(
+ page.getByTestId("platform-connections-truenas"),
+ ).toContainText("2");
+ await expect(
+ page.getByTestId("platform-connections-truenas"),
+ ).toContainText("API-backed NAS connections");
fs.mkdirSync(path.dirname(OPERATIONS_SCREENSHOT_PATH), { recursive: true });
await page.screenshot({ path: OPERATIONS_SCREENSHOT_PATH, fullPage: true });
});
- test('treats disabled TrueNAS as an explicit opt-out instead of a setup prerequisite', async ({
+ test("treats disabled TrueNAS as an explicit opt-out instead of a setup prerequisite", async ({
page,
}) => {
- await page.route('**/api/truenas/connections', async (route) => {
- if (route.request().method() !== 'GET') {
+ await page.route("**/api/truenas/connections", async (route) => {
+ if (route.request().method() !== "GET") {
await route.continue();
return;
}
await route.fulfill({
status: 404,
- contentType: 'application/json',
+ contentType: "application/json",
body: JSON.stringify({
- error: 'truenas_disabled',
- message: 'TrueNAS integration has been explicitly disabled',
+ error: "truenas_disabled",
+ message: "TrueNAS integration has been explicitly disabled",
}),
});
});
- await page.goto('/settings/infrastructure/platforms/truenas', {
- waitUntil: 'domcontentloaded',
+ await page.goto("/settings/infrastructure/platforms/truenas", {
+ waitUntil: "domcontentloaded",
});
await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {
timeout: 15_000,
});
- await expect(page.getByText('TrueNAS integration is disabled')).toBeVisible();
await expect(
- page.getByText('TrueNAS integration has been explicitly disabled'),
+ page.getByText("TrueNAS integration is disabled"),
+ ).toBeVisible();
+ await expect(
+ page.getByText("TrueNAS integration has been explicitly disabled"),
).toBeVisible();
await expect(page.getByText(/PULSE_ENABLE_TRUENAS=false/)).toBeVisible();
await expect(page.getByText(/set it back to true/i)).toBeVisible();
- await expect(page.getByRole('button', { name: 'Add TrueNAS connection' })).not.toBeVisible();
- await expect(page.locator('[data-testid^=\"truenas-connection-\"]')).toHaveCount(0);
+ await expect(
+ page.getByRole("button", { name: "Add TrueNAS connection" }),
+ ).not.toBeVisible();
+ await expect(
+ page.locator('[data-testid^=\"truenas-connection-\"]'),
+ ).toHaveCount(0);
});
});
diff --git a/tests/integration/tests/22-vmware-settings-platform-connections.spec.ts b/tests/integration/tests/22-vmware-settings-platform-connections.spec.ts
index 13a501c326..85d79079c0 100644
--- a/tests/integration/tests/22-vmware-settings-platform-connections.spec.ts
+++ b/tests/integration/tests/22-vmware-settings-platform-connections.spec.ts
@@ -339,7 +339,8 @@ test.describe("VMware platform connections settings", () => {
}
if (pathname === "/api/vmware/connections/test" && method === "POST") {
- const scenario = scenarios[Math.min(draftFailureIndex, scenarios.length - 1)];
+ const scenario =
+ scenarios[Math.min(draftFailureIndex, scenarios.length - 1)];
draftFailureIndex += 1;
await route.fulfill({
status: 400,
@@ -385,7 +386,9 @@ test.describe("VMware platform connections settings", () => {
}
});
- test("surfaces saved runtime guidance when a VMware retest fails", async ({ page }) => {
+ test("surfaces saved runtime guidance when a VMware retest fails", async ({
+ page,
+ }) => {
const authError =
"VMware authentication failed while creating the VI JSON API session";
const healthyAt = new Date(Date.now() - 5 * 60_000).toISOString();
@@ -427,7 +430,10 @@ test.describe("VMware platform connections settings", () => {
return;
}
- if (pathname === "/api/vmware/connections/conn-1/test" && method === "POST") {
+ if (
+ pathname === "/api/vmware/connections/conn-1/test" &&
+ method === "POST"
+ ) {
connections = [
{
...connections[0],
@@ -755,4 +761,280 @@ test.describe("VMware platform connections settings", () => {
fs.mkdirSync(path.dirname(WORKFLOW_SCREENSHOT_PATH), { recursive: true });
await page.screenshot({ path: WORKFLOW_SCREENSHOT_PATH, fullPage: true });
});
+
+ test("previews canonical multi-system impact before creating a VMware connection", async ({
+ page,
+ }) => {
+ let previewPayload: Record<string, unknown> | null = null;
+ let createCalls = 0;
+
+ await page.route("**/api/vmware/connections**", async (route) => {
+ const request = route.request();
+ const method = request.method();
+ const pathname = new URL(request.url()).pathname;
+
+ if (pathname === "/api/vmware/connections" && method === "GET") {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify([]),
+ });
+ return;
+ }
+
+ if (pathname === "/api/vmware/connections/preview" && method === "POST") {
+ previewPayload = JSON.parse(request.postData() || "{}");
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ current_count: 5,
+ projected_count: 7,
+ additional_count: 2,
+ limit: 6,
+ would_exceed_limit: true,
+ effect: "mixed_existing_and_new",
+ current_systems: [
+ {
+ name: "esxi-01",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "esxi-01",
+ type: "agent",
+ source: "agent",
+ at: new Date(Date.now() - 60_000).toISOString(),
+ },
+ source: "agent",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ projected_systems: [
+ {
+ name: "esxi-01",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "esxi-01",
+ type: "agent",
+ source: "vmware",
+ at: new Date().toISOString(),
+ },
+ source: "vmware",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ {
+ name: "esxi-02",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "esxi-02",
+ type: "agent",
+ source: "vmware",
+ at: new Date().toISOString(),
+ },
+ source: "vmware",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ }),
+ });
+ return;
+ }
+
+ if (pathname === "/api/vmware/connections" && method === "POST") {
+ createCalls += 1;
+ await route.fulfill({
+ status: 201,
+ contentType: "application/json",
+ body: JSON.stringify({}),
+ });
+ return;
+ }
+
+ await route.continue();
+ });
+
+ await page.goto("/settings/infrastructure/platforms/vmware", {
+ waitUntil: "domcontentloaded",
+ });
+ await page.waitForURL(/\/settings\/infrastructure\/platforms\/vmware/, {
+ timeout: 15_000,
+ });
+
+ await page.getByRole("button", { name: "Add VMware connection" }).click();
+ const dialog = page.getByRole("dialog", { name: "Add VMware connection" });
+ await expect(dialog).toBeVisible();
+
+ await dialog.getByPlaceholder("lab-vcenter").fill("Lab VC");
+ await dialog.getByPlaceholder("vcsa.lab.local").fill("vcsa.lab.local");
+ await dialog
+ .getByPlaceholder("[email protected]")
+ .fill("[email protected]");
+ await dialog.locator('input[type="password"]').first().fill("super-secret");
+
+ await dialog.getByRole("button", { name: "Preview impact" }).click();
+
+ await expect
+ .poll(() => previewPayload)
+ .toMatchObject({
+ name: "Lab VC",
+ host: "vcsa.lab.local",
+ username: "[email protected]",
+ password: "super-secret",
+ enabled: true,
+ });
+ await expect(
+ dialog.getByText("This change exceeds your monitored-system limit"),
+ ).toBeVisible();
+ await expect(dialog.getByText(/Current usage 5 \/ 6/)).toBeVisible();
+ await expect(dialog.getByText("Current matched systems")).toBeVisible();
+ await expect(dialog.getByText("esxi-01 (Host via Agent)")).toBeVisible();
+ await expect(dialog.getByText("Projected systems")).toBeVisible();
+ await expect(dialog.getByText("esxi-01 (Host via VMware)")).toBeVisible();
+ await expect(dialog.getByText("esxi-02 (Host via VMware)")).toBeVisible();
+ await expect(
+ dialog.getByRole("button", { name: "Add connection" }),
+ ).toBeDisabled();
+ expect(createCalls).toBe(0);
+ });
+
+ test("reuses the canonical monitored-system explanation when a VMware save is denied", async ({
+ page,
+ }) => {
+ let createPayload: Record<string, unknown> | null = null;
+
+ await page.route("**/api/vmware/connections**", async (route) => {
+ const request = route.request();
+ const method = request.method();
+ const pathname = new URL(request.url()).pathname;
+
+ if (pathname === "/api/vmware/connections" && method === "GET") {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify([]),
+ });
+ return;
+ }
+
+ if (pathname === "/api/vmware/connections" && method === "POST") {
+ createPayload = JSON.parse(request.postData() || "{}");
+ await route.fulfill({
+ status: 402,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: "license_required",
+ message: "Monitored-system limit reached (7/6)",
+ feature: "max_monitored_systems",
+ monitored_system_preview: {
+ current_count: 5,
+ projected_count: 7,
+ additional_count: 2,
+ limit: 6,
+ would_exceed_limit: true,
+ effect: "mixed_existing_and_new",
+ current_systems: [
+ {
+ name: "esxi-01",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "esxi-01",
+ type: "agent",
+ source: "agent",
+ at: new Date(Date.now() - 60_000).toISOString(),
+ },
+ source: "agent",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ projected_systems: [
+ {
+ name: "esxi-01",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "esxi-01",
+ type: "agent",
+ source: "vmware",
+ at: new Date().toISOString(),
+ },
+ source: "vmware",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ {
+ name: "esxi-02",
+ type: "agent",
+ status: "online",
+ status_explanation: { summary: "", reasons: [] },
+ latest_included_signal: {
+ name: "esxi-02",
+ type: "agent",
+ source: "vmware",
+ at: new Date().toISOString(),
+ },
+ source: "vmware",
+ explanation: { summary: "", reasons: [], surfaces: [] },
+ },
+ ],
+ current_system: null,
+ projected_system: null,
+ },
+ }),
+ });
+ return;
+ }
+
+ await route.continue();
+ });
+
+ await page.goto("/settings/infrastructure/platforms/vmware", {
+ waitUntil: "domcontentloaded",
+ });
+ await page.waitForURL(/\/settings\/infrastructure\/platforms\/vmware/, {
+ timeout: 15_000,
+ });
+
+ await page.getByRole("button", { name: "Add VMware connection" }).click();
+ const dialog = page.getByRole("dialog", { name: "Add VMware connection" });
+ await expect(dialog).toBeVisible();
+
+ await dialog.getByPlaceholder("lab-vcenter").fill("Lab VC");
+ await dialog.getByPlaceholder("vcsa.lab.local").fill("vcsa.lab.local");
+ await dialog
+ .getByPlaceholder("[email protected]")
+ .fill("[email protected]");
+ await dialog.locator('input[type="password"]').first().fill("super-secret");
+ await dialog.getByRole("button", { name: "Add connection" }).click();
+
+ await expect
+ .poll(() => createPayload)
+ .toMatchObject({
+ name: "Lab VC",
+ host: "vcsa.lab.local",
+ username: "[email protected]",
+ password: "super-secret",
+ enabled: true,
+ });
+ await expect(
+ dialog.getByText("This change exceeds your monitored-system limit"),
+ ).toBeVisible();
+ await expect(dialog.getByText(/Current usage 5 \/ 6/)).toBeVisible();
+ await expect(dialog.getByText("Current matched systems")).toBeVisible();
+ await expect(dialog.getByText("esxi-01 (Host via Agent)")).toBeVisible();
+ await expect(dialog.getByText("Projected systems")).toBeVisible();
+ await expect(dialog.getByText("esxi-01 (Host via VMware)")).toBeVisible();
+ await expect(dialog.getByText("esxi-02 (Host via VMware)")).toBeVisible();
+ await expect(
+ dialog.getByRole("button", { name: "Add connection" }),
+ ).toBeDisabled();
+ });
});