Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Cover the connection ledger and agent update branches the fresh drop left cold
rcourtmanf109aac93f14
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentUpdateCommandsModel.branchcov0722am.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentUpdateCommandsModel.branchcov0722am.test.tsnew file mode 100644index 0000000000..e3eeb9238e--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentUpdateCommandsModel.branchcov0722am.test.ts@@ -0,0 +1,377 @@+import { describe, expect, it } from 'vitest';+import type { Connection } from '@/api/connections';+import type {+ AgentFleetAgentDiagnostic,+ AgentFleetDiagnosticReason,+ AgentFleetDiagnosticStatus,+} from '@/api/agentDiagnostics';+import type { InfrastructureSystemRow } from '../connectionsTableModel';+import {+ collectInfrastructureAgentDoctorTargets,+ collectInfrastructureAgentUpdateTargets,+} from '../infrastructureAgentUpdateCommandsModel';+import type { InfrastructureAgentDoctorOptions } from '../infrastructureAgentUpdateCommandsModel';++// ---- Fixtures ---------------------------------------------------------------+// Mirrors the sibling infrastructureAgentUpdateCommandsModel.branchcov0720pm.test.ts+// factories so every module-private branch is driven through the two exported+// orchestrators (collectInfrastructureAgentUpdateTargets /+// collectInfrastructureAgentDoctorTargets). This file targets the arms V8 still+// reported as zero-hit after the three sibling suites ran.++const agentConnection = (overrides: Partial<Connection> = {}): Connection => ({+ id: 'agent:host-1',+ type: 'agent',+ name: 'host-1',+ address: 'host-1.lab',+ state: 'active',+ stateReason: '',+ enabled: true,+ surfaces: ['host'],+ scope: { host: true },+ lastSeen: '2026-07-22T09:00:00Z',+ lastError: null,+ source: 'agent',+ agentVersion: '6.1.0',+ expectedAgentVersion: '6.2.0',+ agentUpdateAvailable: true,+ agentIdentity: { hostname: 'host-1', platform: 'ubuntu', architecture: 'amd64' },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ ...overrides,+});++const emptyFleetRow = {+ fleetSignals: [],+ fleetHighlights: [],+} satisfies Pick<InfrastructureSystemRow, 'fleetSignals' | 'fleetHighlights'>;++const row = (overrides: Partial<InfrastructureSystemRow> = {}): InfrastructureSystemRow => {+ const primary = agentConnection();+ return {+ id: primary.id,+ ownerType: 'agent',+ name: primary.name,+ subtitle: 'via Pulse Agent',+ source: 'agent',+ host: primary.address,+ coverageLabels: ['Host telemetry'],+ statusLabel: 'Active',+ statusClassName: 'bg-green-100',+ agentUpdateCount: 0,+ lastActivityText: '1m ago',+ ...emptyFleetRow,+ enabled: true,+ canEdit: false,+ canPause: false,+ canRemove: true,+ isAgent: true,+ isCluster: false,+ attachedConnections: [],+ members: [],+ connection: primary,+ ...overrides,+ };+};++// A non-agent primary so collectInfrastructureAgentUpdateTargets only builds+// targets from attachedConnections (isolates pushTarget shaping).+const pvePrimaryRow = (overrides: Partial<InfrastructureSystemRow> = {}): InfrastructureSystemRow =>+ row({+ id: 'pve:node',+ ownerType: 'pve',+ isAgent: false,+ name: 'node',+ connection: agentConnection({+ id: 'pve:node',+ type: 'pve',+ name: 'node',+ agentUpdateAvailable: false,+ }),+ ...overrides,+ });++const diagnostic = (+ overrides: Partial<AgentFleetAgentDiagnostic> = {},+): AgentFleetAgentDiagnostic => ({+ connectionId: 'agent:host-1',+ rowKey: 'host-1',+ id: 'host-1',+ agentId: 'host-1',+ name: 'host-1',+ hostname: 'host-1',+ types: ['host'],+ status: 'warning',+ version: '6.1.0',+ profileId: 'profile-linux',+ profileName: 'Linux servers',+ profileVersion: 4,+ deployedProfileVersion: 3,+ reasons: [+ {+ code: 'agent_version_stale',+ severity: 'warning',+ message: 'Agent is behind the supported server version.',+ },+ ],+ repairActions: [+ {+ code: 'copy_upgrade_command',+ label: 'Copy upgrade command',+ description: 'Run on the affected host.',+ supported: true,+ scope: 'local_admin_shell',+ },+ ],+ ...overrides,+});++// An orphan diagnostic: no ledger connection binds to its connectionId, so the+// doctor surfaces it via diagnosticOnlyDoctorTarget (the diagnostic-only path).+const orphanDiagnostic = (+ overrides: Partial<AgentFleetAgentDiagnostic> = {},+): AgentFleetAgentDiagnostic =>+ diagnostic({+ connectionId: 'agent:orphan',+ rowKey: 'orphan-row',+ id: 'orphan-id',+ agentId: 'orphan-id',+ name: 'orphan',+ hostname: 'orphan-host',+ status: 'warning',+ types: ['host'],+ ...overrides,+ });++const runDoctor = (+ agents: readonly Connection[],+ options: Partial<InfrastructureAgentDoctorOptions> = {},+) =>+ collectInfrastructureAgentDoctorTargets({+ rows: [],+ connections: agents,+ diagnosticsAvailable: false,+ ...options,+ });++// Run with only orphan diagnostics (no ledger bindings at all).+const runOrphans = (+ diagnostics: readonly AgentFleetAgentDiagnostic[],+ options: Partial<InfrastructureAgentDoctorOptions> = {},+) =>+ runDoctor([], {+ diagnostics,+ diagnosticsAvailable: true,+ ...options,+ });++// ---- pushTarget: currentVersion optional-chain fallback ---------------------++describe('collectInfrastructureAgentUpdateTargets (currentVersion fallback)', () => {+ it('reports undefined currentVersion when a pushed target has no agentVersion', () => {+ // agentUpdateAvailable short-circuits connectionNeedsUpdate so the agent is+ // still pushed; agentVersion undefined forces `agentVersion?.trim() ||+ // undefined` to its right operand.+ const agent = agentConnection({+ id: 'agent:no-version',+ name: 'no-version',+ agentVersion: undefined,+ agentUpdateAvailable: true,+ agentIdentity: { hostname: 'no-version', platform: 'linux' },+ });++ const [target] = collectInfrastructureAgentUpdateTargets([+ pvePrimaryRow({ attachedConnections: [agent] }),+ ]);++ expect(target?.key).toBe('agent:no-version');+ expect(target?.currentVersion).toBeUndefined();+ });+});++// ---- collectAgentConnectionBindings: integrationSource guard ----------------++describe('collectInfrastructureAgentDoctorTargets (integrationSource guard)', () => {+ it('excludes platform-integrated agents from the doctor bindings', () => {+ // An agent whose telemetry comes from a platform integration (vSphere,+ // TrueNAS, ...) has no Pulse Agent to diagnose; the binding guard returns+ // early so no target is produced.+ const integrated = agentConnection({+ id: 'agent:integrated',+ name: 'integrated',+ integrationSource: 'vmware',+ agentUpdateAvailable: false,+ });++ expect(runDoctor([integrated])).toEqual([]);+ });+});++// ---- ledgerFallbackReasons: state/module ternary arms -----------------------++describe('collectInfrastructureAgentDoctorTargets (ledgerFallbackReasons ternary arms)', () => {+ it('emits ledger_unauthorized with empty evidence when stateReason is blank', () => {+ // The sibling suite only exercises unauthorized with a stateReason; the+ // `stateReason ? [...] : []` alternate (blank reason) was unhit.+ const [target] = runDoctor([+ agentConnection({ state: 'unauthorized', stateReason: '', agentUpdateAvailable: false }),+ ]);++ expect(target?.status).toBe('critical');+ expect(target?.reasons.find((r) => r.code === 'ledger_unauthorized')?.evidence).toEqual([]);+ });++ it('emits ledger_unreachable with evidence when stateReason is present', () => {+ // The sibling suite only exercises unreachable with a blank stateReason;+ // the consequent `[stateReason]` arm was unhit.+ const [target] = runDoctor([+ agentConnection({+ state: 'unreachable',+ stateReason: 'dial tcp: connection refused',+ agentUpdateAvailable: false,+ }),+ ]);++ expect(target?.reasons.find((r) => r.code === 'ledger_unreachable')?.evidence).toEqual([+ 'dial tcp: connection refused',+ ]);+ });++ it('emits ledger_module_degraded with empty evidence when lastError is absent', () => {+ // The sibling suite only exercises a degraded module carrying a lastError;+ // the `lastError ? [...] : []` alternate was unhit.+ const [target] = runDoctor([+ agentConnection({+ agentUpdateAvailable: false,+ agentVersion: '6.2.0',+ expectedAgentVersion: '6.2.0',+ agentModules: [+ { name: 'docker', enabled: true, state: 'retrying', updatedAt: '2026-07-22T00:00:00Z' },+ ],+ }),+ ]);++ const reason = target?.reasons.find((r) => r.code === 'ledger_module_degraded');+ expect(reason?.message).toBe('docker is enabled but retrying.');+ expect(reason?.evidence).toEqual([]);+ });+});++// ---- doctorTargetFromBinding: diagnostic.reasons fallback -------------------++describe('collectInfrastructureAgentDoctorTargets (matching diagnostic reasons fallback)', () => {+ it('defaults to an empty reasons list when a matching diagnostic omits reasons', () => {+ // diagnosticsAvailable + matching diagnostic selects the diagnostic branch;+ // a nullish reasons exercises `diagnostic.reasons ?? []`.+ const [target] = runDoctor([agentConnection()], {+ diagnostics: [diagnostic({ reasons: undefined as unknown as AgentFleetDiagnosticReason[] })],+ diagnosticsAvailable: true,+ targetVersion: '6.2.0',+ });++ expect(target?.source).toBe('diagnostics');+ expect(target?.reasons).toEqual([]);+ });+});++// ---- doctorTargetFromBinding: currentVersion from diagnostic ----------------++describe('collectInfrastructureAgentDoctorTargets (currentVersion from diagnostic)', () => {+ it('derives currentVersion from the diagnostic when the ledger version is absent', () => {+ // agentVersion undefined forces the `|| diagnostic?.version?.trim()` arm.+ const [target] = runDoctor(+ [+ agentConnection({+ agentVersion: undefined,+ agentUpdateAvailable: true,+ expectedAgentVersion: '6.2.0',+ }),+ ],+ {+ diagnostics: [diagnostic({ version: '6.1.5' })],+ diagnosticsAvailable: true,+ targetVersion: '6.2.0',+ },+ );++ expect(target?.currentVersion).toBe('6.1.5');+ });++ it('reports undefined currentVersion when neither ledger nor diagnostic carry a version', () => {+ // agentVersion undefined AND diagnostic.version undefined forces the final+ // `|| undefined` arm.+ const [target] = runDoctor(+ [+ agentConnection({+ agentVersion: undefined,+ agentUpdateAvailable: true,+ expectedAgentVersion: '6.2.0',+ }),+ ],+ {+ diagnostics: [diagnostic({ version: undefined })],+ diagnosticsAvailable: true,+ targetVersion: '6.2.0',+ },+ );++ expect(target?.currentVersion).toBeUndefined();+ });+});++// ---- diagnosticOnlyDoctorTarget: non-removed orphan shaping -----------------++describe('collectInfrastructureAgentDoctorTargets (diagnostic-only orphan shaping)', () => {+ it('classifies an out-of-set diagnostic status as unknown', () => {+ // diagnosticDoctorStatus fails closed to 'unknown' for any status outside+ // {healthy, warning, critical, removed}. The schema type is closed, so an+ // unexpected value is injected via cast (defensive resolver behaviour).+ const [target] = runOrphans([+ orphanDiagnostic({+ status: 'waiting' as unknown as AgentFleetDiagnosticStatus,+ }),+ ]);++ expect(target?.status).toBe('unknown');+ expect(target?.source).toBe('diagnostics');+ });++ it("falls back to the 'Agent' context label for a non-removed orphan with nullish types", () => {+ // Nullish types + non-removed exercises both the `types ?? []` fallback and+ // the `removed ? 'Removed agent' : 'Agent'` alternate arm.+ const [target] = runOrphans([orphanDiagnostic({ types: undefined as unknown as string[] })]);++ expect(target?.contextLabel).toBe('Agent');+ });++ it('falls back to the diagnostic id in the key when rowKey is blank', () => {+ // `diagnostic.rowKey || diagnostic.id` right operand.+ const [target] = runOrphans([orphanDiagnostic({ rowKey: '', id: 'fallback-id' })]);++ expect(target?.key).toBe('diagnostic:fallback-id');+ });++ it('passes an unrecognised diagnostic type through verbatim in the context label', () => {+ // `DIAGNOSTIC_TYPE_LABELS[type] ?? type` alternate arm.+ const [target] = runOrphans([orphanDiagnostic({ types: ['lxc'] })]);++ expect(target?.contextLabel).toBe('lxc agent');+ });++ it('defaults to an empty reasons list when the orphan diagnostic omits reasons', () => {+ // `diagnostic.reasons ?? []` alternate arm on the diagnostic-only path.+ const [target] = runOrphans([+ orphanDiagnostic({ reasons: undefined as unknown as AgentFleetDiagnosticReason[] }),+ ]);++ expect(target?.reasons).toEqual([]);+ });++ it('defaults deployedProfileVersion to 0 in the orphan profileVersionLabel', () => {+ // `deployedProfileVersion || 0` alternate arm on the diagnostic-only path.+ const [target] = runOrphans([+ orphanDiagnostic({ profileVersion: 7, deployedProfileVersion: undefined }),+ ]);++ expect(target?.profileVersionLabel).toBe('Expected v7 · deployed v0');+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/useConnectionsLedger.branchcov0722am.test.ts b/frontend-modern/src/components/Settings/__tests__/useConnectionsLedger.branchcov0722am.test.tsnew file mode 100644index 0000000000..c1cef7d215--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/useConnectionsLedger.branchcov0722am.test.ts@@ -0,0 +1,702 @@+import { renderHook, waitFor } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ ConnectionsAPI,+ type Connection,+ type ConnectionState,+ type ConnectionSystem,+} from '@/api/connections';+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';+import { connectionToRow, useConnectionsLedger } from '../useConnectionsLedger';++// ---- Fixtures ---------------------------------------------------------------+// Minimal valid factories mirroring the sibling suite. connectionToRow is a+// pure (non-reactive) export, so its cases call it directly; the hook-driven+// cases (findById, systems, error, cache) mirror useConnectionsLedger.test.ts.++const connectionFixture = (overrides: Partial<Connection> = {}): Connection => ({+ id: 'pve:node-1',+ type: 'pve',+ name: 'node-1',+ address: 'https://node-1:8006',+ state: 'active',+ stateReason: '',+ enabled: true,+ surfaces: ['vms', 'containers'],+ scope: { vms: true, containers: true },+ lastSeen: '2026-07-22T12:00:00Z',+ lastError: null,+ source: 'manual',+ capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },+ ...overrides,+});++const PINNED_NOW = new Date('2026-07-22T12:00:00.000Z');++// Reset the retained non-suspending query cache around every hook-driven case+// so each render starts from the empty initial snapshot, exactly as the+// sibling suite does.+const useLedgerHarness = () => {+ beforeEach(() => {+ resetCreateNonSuspendingQueryCacheForTest();+ });+ afterEach(() => {+ resetCreateNonSuspendingQueryCacheForTest();+ vi.restoreAllMocks();+ });+};++const renderLedger = (connections: Connection[], systems: ConnectionSystem[]) => {+ vi.spyOn(ConnectionsAPI, 'list').mockResolvedValue({ connections, systems });+ return renderHook(() => useConnectionsLedger());+};++// ---- findById ---------------------------------------------------------------+// findById had ZERO hits in the measured coverage. Exercise every arm of the+// `connections().find((conn) => conn.id === id)` lookup through the live hook.++describe('useConnectionsLedger.findById', () => {+ useLedgerHarness();++ it('returns the matching connection when the id exists', async () => {+ const alpha = connectionFixture({ id: 'agent:alpha', name: 'alpha' });+ const { result } = renderLedger([alpha], []);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.findById('agent:alpha')?.name).toBe('alpha');+ });++ it('returns undefined when the id does not match any connection', async () => {+ const alpha = connectionFixture({ id: 'agent:alpha', name: 'alpha' });+ const { result } = renderLedger([alpha], []);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.findById('agent:missing')).toBeUndefined();+ });++ it('returns undefined for an empty id', async () => {+ const alpha = connectionFixture({ id: 'agent:alpha', name: 'alpha' });+ const { result } = renderLedger([alpha], []);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.findById('')).toBeUndefined();+ });++ it('returns undefined for a whitespace-only id', async () => {+ const alpha = connectionFixture({ id: 'agent:alpha', name: 'alpha' });+ const { result } = renderLedger([alpha], []);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.findById(' ')).toBeUndefined();+ });++ it('returns the first match when two connections share an id', async () => {+ // Array.prototype.find is first-match-wins; a duplicate id must not silently+ // surface the newer record.+ const first = connectionFixture({ id: 'agent:dup', name: 'first', address: 'first' });+ const second = connectionFixture({ id: 'agent:dup', name: 'second', address: 'second' });+ const { result } = renderLedger([first, second], []);++ await waitFor(() => expect(result.rows()).toHaveLength(2));+ expect(result.findById('agent:dup')?.name).toBe('first');+ });++ it('returns undefined when the ledger is empty', async () => {+ const { result } = renderLedger([], []);++ await waitFor(() => expect(result.rows()).toHaveLength(0));+ expect(result.findById('agent:alpha')).toBeUndefined();+ expect(result.connections()).toEqual([]);+ });+});++// ---- connectionToRow (standalone buildRow arms) -----------------------------+// connectionToRow is exported and pure, so these exercise buildRow directly+// without the async query machinery. Each case targets an arm the sibling+// suite (which renders agents, truenas, pve clusters and vmware) leaves cold.++describe('connectionToRow (standalone buildRow arms)', () => {+ // --- name fallback chain (name || address || id) ---+ it('falls back to the address when the name is blank', () => {+ const row = connectionToRow(connectionFixture({ name: '', address: 'https://pve-blank:8006' }));+ expect(row.name).toBe('https://pve-blank:8006');+ });++ it('falls back to the id when both name and address are blank', () => {+ const row = connectionToRow(connectionFixture({ id: 'pve:id-only', name: '', address: '' }));+ expect(row.name).toBe('pve:id-only');+ });++ // --- host (non-agent, non-cluster) ---+ it('omits host when the address equals the name for a non-agent row', () => {+ const row = connectionToRow(connectionFixture({ name: 'node-1', address: 'node-1' }));+ expect(row.host).toBeUndefined();+ });++ it('exposes the address as host when it differs from the name', () => {+ const row = connectionToRow(+ connectionFixture({ name: 'node-1', address: 'https://node-1:8006' }),+ );+ expect(row.host).toBe('https://node-1:8006');+ });++ // --- sourceFor arms ---+ it('reports source "probe" for a contributing availability target', () => {+ const row = connectionToRow(+ connectionFixture({+ id: 'availability:probe-1',+ type: 'availability',+ name: 'probe-1',+ address: 'probe-1',+ surfaces: ['availability'],+ scope: { availability: true },+ }),+ );+ expect(row.source).toBe('probe');+ expect(row.subtitle).toBe('via availability probe');+ });++ it('falls back to configured "agent" source when the agent is not contributing', () => {+ // A stale agent is not active/paused, so the contributor path is empty and+ // sourceFor falls through to configured-presence (the distinct fallback arm).+ const row = connectionToRow(+ connectionFixture({+ id: 'agent:stale-1',+ type: 'agent',+ name: 'stale-1',+ address: 'stale-1',+ state: 'stale',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ }),+ );+ expect(row.source).toBe('agent');+ });++ it('reports source "unknown" when no contributing or configured path matches', () => {+ const row = connectionToRow(+ connectionFixture({+ id: 'docker:down',+ type: 'docker',+ name: 'down',+ address: 'down',+ state: 'unauthorized',+ surfaces: [],+ scope: {},+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ }),+ );+ expect(row.source).toBe('unknown');+ });++ // --- subtitleFor product-label fallback ---+ it('uses the product-label subtitle for a docker source', () => {+ const row = connectionToRow(+ connectionFixture({+ id: 'docker:host',+ type: 'docker',+ name: 'dock',+ address: 'dock',+ state: 'active',+ surfaces: [],+ scope: {},+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ }),+ );+ expect(row.subtitle).toBe('via Docker');+ });++ // --- canEdit / canRemove ---+ it.each([+ { type: 'docker' as const, name: 'docker-host' },+ { type: 'kubernetes' as const, name: 'k8s-cluster' },+ ])('disables edit and removal for $type connections', ({ type, name }) => {+ const row = connectionToRow(+ connectionFixture({+ type,+ name,+ address: name,+ surfaces: [],+ scope: {},+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ }),+ );+ expect(row.canEdit).toBe(false);+ expect(row.canRemove).toBe(false);+ });++ // --- coverageLabelsFor scope handling ---+ it('uses only active scope keys for coverage labels', () => {+ const row = connectionToRow(+ connectionFixture({+ surfaces: ['vms', 'containers', 'storage'],+ scope: { vms: true, containers: false },+ }),+ );+ expect(row.coverageLabels).toEqual(['VMs']);+ });++ it('falls back to surfaces when no scope key is active', () => {+ const row = connectionToRow(+ connectionFixture({+ surfaces: ['vms', 'containers'],+ scope: { vms: false, containers: false },+ }),+ );+ expect(row.coverageLabels).toEqual(['VMs', 'Containers']);+ });++ it('falls back to surfaces when scope is null', () => {+ const row = connectionToRow(+ connectionFixture({ surfaces: ['host'], scope: null as unknown as Connection['scope'] }),+ );+ expect(row.coverageLabels).toEqual(['Host telemetry']);+ });++ // --- status presentation fallback ---+ it('falls back to the Pending presentation for an unrecognized state', () => {+ const row = connectionToRow(+ connectionFixture({ state: 'bogus' as unknown as ConnectionState }),+ );+ expect(row.statusLabel).toBe('Pending');+ expect(row.statusClassName).toBe('bg-surface-alt text-base-content');+ });++ // --- lastErrorMessage (runs raw text through the error presenter) ---+ it('humanizes a raw timeout error for display', () => {+ const row = connectionToRow(+ connectionFixture({+ lastError: { message: 'context deadline exceeded', at: '2026-07-22T12:00:00Z' },+ }),+ );+ expect(row.lastErrorMessage).toBe(+ 'Connection timed out. Check the host is reachable, the port is correct, and the network path is open.',+ );+ });++ it('leaves lastErrorMessage undefined when there is no error', () => {+ const row = connectionToRow(connectionFixture({ lastError: null }));+ expect(row.lastErrorMessage).toBeUndefined();+ });+});++// ---- useConnectionsLedger (systemToRow & row-derivation arms) ---------------++describe('useConnectionsLedger (systemToRow & row-derivation arms)', () => {+ useLedgerHarness();++ it('drops a system whose primary connection is absent and falls back to standalone rows', async () => {+ // systemToRow returns null when connectionsByID.get(system.id) misses; with+ // every system dropped, groupedRows is empty and the memo falls back to+ // rendering raw connections as standalone rows.+ const solo = connectionFixture({+ id: 'agent:solo',+ type: 'agent',+ name: 'solo',+ address: 'solo',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const orphanSystem: ConnectionSystem = {+ id: 'pve:ghost',+ type: 'pve',+ components: [{ connectionId: 'pve:ghost', type: 'pve', role: 'primary' }],+ };+ const { result } = renderLedger([solo], [orphanSystem]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].id).toBe('agent:solo');+ });++ it('falls back to the primary connection when all component refs dangle', async () => {+ // componentConnections filters out missing refs; when none remain it pushes+ // the primary so the row still derives source/coverage from it.+ const primary = connectionFixture({+ id: 'pve:node',+ name: 'node',+ address: 'https://node:8006',+ });+ const system: ConnectionSystem = {+ id: 'pve:node',+ type: 'pve',+ components: [{ connectionId: 'pve:missing', type: 'pve', role: 'primary' }],+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].source).toBe('api');+ expect(result.rows()[0].coverageLabels).toEqual(['VMs', 'Containers']);+ });++ it('surfaces an unhealthy attached agent as the row problem on a non-agent system', async () => {+ const vmware = connectionFixture({+ id: 'vmware:vc-1',+ type: 'vmware',+ name: 'Lab vCenter',+ address: 'https://vcenter:443',+ surfaces: ['vms', 'hosts'],+ scope: { vms: true, hosts: true },+ });+ const staleAgent = connectionFixture({+ id: 'agent:stale-attached',+ type: 'agent',+ name: 'stale-attached',+ address: 'stale-attached',+ state: 'stale',+ stateReason: 'no keepalive',+ lastSeen: null,+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const system: ConnectionSystem = {+ id: 'vmware:vc-1',+ type: 'vmware',+ components: [+ { connectionId: 'vmware:vc-1', type: 'vmware', role: 'primary' },+ { connectionId: 'agent:stale-attached', type: 'agent', role: 'attachment' },+ ],+ members: [+ { id: 'host-1', name: 'esxi-01', state: 'active', lastSeen: '2026-07-22T12:00:00Z' },+ ],+ };+ const { result } = renderLedger([vmware, staleAgent], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].problem).toMatchObject({ label: 'Agent offline', tone: 'warning' });+ });++ it('drops a cluster member with a blank name and counts only valid members', async () => {+ // buildMemberRow returns null for a whitespace name; the member is filtered+ // out, leaving a single-node cluster (singular "node" subtitle).+ const primary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const system: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'node-good',+ name: 'good-node',+ state: 'active',+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ { id: 'node-blank', name: ' ', state: 'active', lastSeen: '2026-07-22T12:00:00Z' },+ ],+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].isCluster).toBe(true);+ expect(result.rows()[0].subtitle).toBe('Cluster · 1 node');+ expect(result.rows()[0].members).toHaveLength(1);+ expect(result.rows()[0].members[0].name).toBe('good-node');+ });++ it('derives the row error message from an attached connection when the primary has none', async () => {+ const primary = connectionFixture({+ id: 'pve:node',+ name: 'node',+ address: 'https://node:8006',+ lastError: null,+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const attached = connectionFixture({+ id: 'agent:attached',+ type: 'agent',+ name: 'attached',+ address: 'attached',+ state: 'active',+ lastError: { message: 'connection refused', at: '2026-07-22T12:00:00Z' },+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const system: ConnectionSystem = {+ id: 'pve:node',+ type: 'pve',+ components: [+ { connectionId: 'pve:node', type: 'pve', role: 'primary' },+ { connectionId: 'agent:attached', type: 'agent', role: 'attachment' },+ ],+ };+ const { result } = renderLedger([primary, attached], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].lastErrorMessage).toBe(+ 'Connection refused. The host is reachable but rejected the connection on this port. Check the port is correct and the service is running.',+ );+ });++ it('surfaces the fetch error and keeps rows empty', async () => {+ vi.spyOn(ConnectionsAPI, 'list').mockRejectedValue(new Error('network down'));+ const { result } = renderHook(() => useConnectionsLedger());++ await waitFor(() => expect(result.error()).toBeInstanceOf(Error));+ expect((result.error() as Error).message).toBe('network down');+ expect(result.rows()).toEqual([]);+ expect(result.loading()).toBe(false);+ });+});++// ---- standalone-agent dedupe vs cluster members ----------------------------++describe('useConnectionsLedger (standalone-agent cluster dedupe)', () => {+ useLedgerHarness();++ const clusterSystem = (memberName: string): ConnectionSystem => ({+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'm-delly',+ name: memberName,+ state: 'active',+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ ],+ });++ const agentSystem = (agentId: string): ConnectionSystem => ({+ id: agentId,+ type: 'agent',+ components: [{ connectionId: agentId, type: 'agent', role: 'primary' }],+ });++ it('dedupes a standalone agent system whose name matches a cluster member', async () => {+ const pvePrimary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const dupAgent = connectionFixture({+ id: 'agent:dup',+ type: 'agent',+ name: 'delly',+ address: 'delly',+ state: 'active',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const { result } = renderLedger(+ [pvePrimary, dupAgent],+ [clusterSystem('delly'), agentSystem('agent:dup')],+ );++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].id).toBe('pve:cluster');+ expect(result.rows().some((row) => row.id === 'agent:dup')).toBe(false);+ });++ it('keeps a standalone agent system whose host is not a cluster member', async () => {+ const pvePrimary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const distinctAgent = connectionFixture({+ id: 'agent:other',+ type: 'agent',+ name: 'other-host',+ address: 'other-host',+ state: 'active',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const { result } = renderLedger(+ [pvePrimary, distinctAgent],+ [clusterSystem('delly'), agentSystem('agent:other')],+ );++ await waitFor(() => expect(result.rows()).toHaveLength(2));+ expect(+ result+ .rows()+ .map((row) => row.id)+ .sort(),+ ).toEqual(['agent:other', 'pve:cluster']);+ });++ it('dedupes a standalone agent via a matching hostAlias', async () => {+ const pvePrimary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const aliasAgent = connectionFixture({+ id: 'agent:alias',+ type: 'agent',+ name: 'unrelated',+ address: 'unrelated',+ hostAliases: ['delly'],+ state: 'active',+ surfaces: ['host'],+ scope: { host: true },+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ });+ const { result } = renderLedger(+ [pvePrimary, aliasAgent],+ [clusterSystem('delly'), agentSystem('agent:alias')],+ );++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows().some((row) => row.id === 'agent:alias')).toBe(false);+ });+});++// ---- cluster rollup edge cases ---------------------------------------------+// oldestTimestamp (null/NaN skip + all-invalid -> undefined) and+// moreSevereState (left-wins + falsy-right arms). Only Date is faked so the+// testing-library waitFor polling keeps using real timers.++describe('useConnectionsLedger (cluster rollup edge cases)', () => {+ useLedgerHarness();++ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(PINNED_NOW);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('skips null and unparseable member timestamps and uses the oldest valid one', async () => {+ const primary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ lastSeen: null,+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const system: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ { id: 'm-bad', name: 'bad-node', state: 'active', lastSeen: 'not-a-date', primary: true },+ { id: 'm-good', name: 'good-node', state: 'active', lastSeen: '2026-07-22T11:00:00Z' },+ ],+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // null + 'not-a-date' skipped; '2026-07-22T11:00:00Z' is exactly 1h before now.+ expect(result.rows()[0].lastActivityText).toBe('1h ago');+ });++ it('reports "No activity yet" when every cluster timestamp is null or unparseable', async () => {+ const primary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ lastSeen: null,+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const system: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ { id: 'm-bad', name: 'bad-node', state: 'active', lastSeen: 'garbage', primary: true },+ ],+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ expect(result.rows()[0].lastActivityText).toBe('No activity yet');+ });++ it('keeps the more severe primary state when a member is healthier', async () => {+ const primary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ state: 'unreachable',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const system: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'm-active',+ name: 'active-node',+ state: 'active',+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ ],+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // primary unreachable (severity 5) vs member active (0): after the reduce+ // from 'active' the unreachable member wins, then active cannot overtake it+ // (left-wins arm of moreSevereState).+ expect(result.rows()[0].statusLabel).toBe('Unreachable');+ });++ it('tolerates a malformed member state by keeping the accumulated rollup', async () => {+ const primary = connectionFixture({+ id: 'pve:cluster',+ name: 'cluster',+ address: 'https://cluster:8006',+ state: 'active',+ surfaces: ['vms'],+ scope: { vms: true },+ });+ const system: ConnectionSystem = {+ id: 'pve:cluster',+ type: 'pve',+ clusterName: 'homelab',+ components: [{ connectionId: 'pve:cluster', type: 'pve', role: 'primary' }],+ members: [+ {+ id: 'm-undef',+ name: 'undef-node',+ state: undefined as unknown as ConnectionState,+ lastSeen: '2026-07-22T12:00:00Z',+ primary: true,+ },+ ],+ };+ const { result } = renderLedger([primary], [system]);++ await waitFor(() => expect(result.rows()).toHaveLength(1));+ // The undefined member state is falsy, so moreSevereState short-circuits+ // (!right) and the cluster stays Active; the member row itself falls back+ // to the Pending presentation.+ expect(result.rows()[0].statusLabel).toBe('Active');+ expect(result.rows()[0].members[0].statusLabel).toBe('Pending');+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsxnew file mode 100644index 0000000000..53ab40d6a7--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsx@@ -0,0 +1,396 @@+import { renderHook, waitFor } from '@solidjs/testing-library';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { TrueNASAPI, type TrueNASConnection } from '@/api/truenas';+import { notificationStore } from '@/stores/notifications';+import { logger } from '@/utils/logger';+import { useTrueNASSettingsPanelState } from '../useTrueNASSettingsPanelState';++vi.mock('@/api/truenas', () => ({+ TrueNASAPI: {+ listConnections: vi.fn(),+ 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() === '********',+}));++vi.mock('@/stores/notifications', () => ({+ notificationStore: {+ success: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock('@/utils/logger', () => ({+ logger: {+ error: vi.fn(),+ },+}));++const makeConnection = (overrides: Partial<TrueNASConnection> = {}): TrueNASConnection => ({+ id: 'conn-1',+ name: 'tower',+ host: 'truenas.local',+ port: undefined,+ apiKey: undefined,+ username: undefined,+ password: undefined,+ useHttps: true,+ insecureSkipVerify: false,+ fingerprint: undefined,+ enabled: true,+ pollIntervalSeconds: 60,+ monitorDatasets: true,+ monitorPools: true,+ monitorReplication: true,+ ...overrides,+});++describe('useTrueNASSettingsPanelState — error-message + dialog branch coverage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // ---------------------------------------------------------------------------+ // getTrueNASErrorMessage — exercised through testCurrentForm / testSavedConnection+ // / previewCurrentForm. Priority: apiErrorDetailField(error, 'error') first,+ // then getErrorMessage(error, fallback).+ // ---------------------------------------------------------------------------++ it('prefers a trimmed details.error cause over the top-level Error.message when testing a connection', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.testConnection).mockRejectedValueOnce(+ Object.assign(new Error('Failed to connect to TrueNAS'), {+ details: { error: ' x509: certificate signed by unknown authority ' },+ }),+ );++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openCreateDialog();+ result.updateForm({ host: 'tower.local', apiKey: 'secret' });+ const ok = await result.testCurrentForm();++ expect(ok).toBe(false);+ expect(notificationStore.error).toHaveBeenCalledWith(+ 'x509: certificate signed by unknown authority',+ );+ expect(notificationStore.success).not.toHaveBeenCalled();+ expect(logger.error).toHaveBeenCalledWith(+ '[TrueNAS Settings] Connection test failed',+ expect.anything(),+ );+ expect(result.testing()).toBe(false);+ });++ it('prefers details.error even when a sibling message field is also present', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.testConnection).mockRejectedValueOnce({+ message: 'ignored top-level message',+ status: 502,+ details: { error: 'actionable cause from details' },+ });++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openCreateDialog();+ result.updateForm({ host: 'tower.local', apiKey: 'secret' });+ await result.testCurrentForm();++ expect(notificationStore.error).toHaveBeenCalledWith('actionable cause from details');+ });++ it('falls back to Error.message (untrimmed) when no details.error is present', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.testConnection).mockRejectedValueOnce(new Error('connection refused'));++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openCreateDialog();+ result.updateForm({ host: 'tower.local', apiKey: 'secret' });+ await result.testCurrentForm();++ expect(notificationStore.error).toHaveBeenCalledWith('connection refused');+ });++ it('extracts and trims a plain-object message through testSavedConnection failure', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.testSavedConnection).mockRejectedValueOnce({ message: ' saved boom ' });++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ await result.testSavedConnection(makeConnection({ id: 'conn-saved', name: 'tower' }));++ expect(notificationStore.error).toHaveBeenCalledWith('saved boom');+ expect(logger.error).toHaveBeenCalledWith(+ '[TrueNAS Settings] Saved connection test failed',+ expect.anything(),+ );+ // finally clause reloads the list even on failure+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(2);+ expect(result.testing()).toBe(false);+ });++ const fallbackCases: ReadonlyArray<[string, unknown]> = [+ ['a whitespace-only Error message', new Error(' ')],+ ['an empty Error message', new Error('')],+ ['a plain object with an empty message', { message: '' }],+ ['a plain object with a whitespace message', { message: ' ' }],+ ['a plain object with a non-string message', { message: 42 }],+ ['a plain object without a message field', { status: 500, code: 'request_failed' }],+ ['a null error', null],+ ['an undefined error', undefined],+ ['a string primitive', 'network down'],+ ['a number primitive', 42],+ ];++ it.each(fallbackCases)(+ 'delegates to the fallback for %s when no extractable message exists',+ async (_label, error) => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.testConnection).mockRejectedValueOnce(error);++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openCreateDialog();+ result.updateForm({ host: 'tower.local', apiKey: 'secret' });+ const ok = await result.testCurrentForm();++ expect(ok).toBe(false);+ expect(notificationStore.error).toHaveBeenCalledWith('TrueNAS connection failed');+ },+ );++ it('routes a generic preview failure through getTrueNASErrorMessage without building an unavailable state', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ // No monitored_system_usage_unavailable code → unavailableState is null → else branch.+ vi.mocked(TrueNASAPI.previewConnection).mockRejectedValueOnce({+ status: 500,+ details: { error: 'preview-specific cause' },+ });++ 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(preview).toBeNull();+ expect(result.monitoredSystemPreview()).toBeNull();+ expect(result.monitoredSystemPreviewErrorTitle()).toBeNull();+ expect(result.monitoredSystemPreviewError()).toBe('preview-specific cause');+ expect(result.previewing()).toBe(false);+ });++ // ---------------------------------------------------------------------------+ // closeDialog — guarded by saving()/testing(); reset path clears all dialog state.+ // ---------------------------------------------------------------------------++ it('resets every piece of dialog state when closeDialog runs while idle', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([+ makeConnection({ id: 'conn-edit', name: 'tower' }),+ ] as never);++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.connections()).toHaveLength(1));++ result.openEditDialog(result.connections()[0]);+ expect(result.dialogOpen()).toBe(true);+ expect(result.form().name).toBe('tower');++ result.closeDialog();++ expect(result.dialogOpen()).toBe(false);+ expect(result.editingConnection()).toBeNull();+ expect(result.form().name).toBe('');+ expect(result.form().host).toBe('');+ expect(result.form().pollIntervalSeconds).toBe('60');+ expect(result.form().authMode).toBe('apiKey');+ expect(result.monitoredSystemPreview()).toBeNull();+ });++ it('keeps the dialog open when closeDialog is invoked while a connection test is in flight', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ let resolveTest!: (value: { success: boolean }) => void;+ vi.mocked(TrueNASAPI.testConnection).mockReturnValueOnce(+ new Promise<{ success: boolean }>((resolve) => {+ resolveTest = resolve;+ }),+ );++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openCreateDialog();+ result.updateForm({ host: 'tower.local', apiKey: 'secret' });+ const testPromise = result.testCurrentForm();+ await waitFor(() => expect(result.testing()).toBe(true));++ result.closeDialog();+ expect(result.dialogOpen()).toBe(true);++ resolveTest({ success: true });+ await testPromise;+ expect(result.testing()).toBe(false);+ expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection successful');+ });++ it('keeps the dialog open when closeDialog is invoked while a save is in flight', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ let resolveSave!: (value: TrueNASConnection) => void;+ vi.mocked(TrueNASAPI.createConnection).mockReturnValueOnce(+ new Promise<TrueNASConnection>((resolve) => {+ resolveSave = resolve;+ }),+ );++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openCreateDialog();+ result.updateForm({ host: 'tower.local', apiKey: 'secret' });+ const savePromise = result.saveCurrentForm();+ await waitFor(() => expect(result.saving()).toBe(true));++ result.closeDialog();+ expect(result.dialogOpen()).toBe(true);++ resolveSave(makeConnection({ id: 'conn-new' }));+ await savePromise;+ expect(result.saving()).toBe(false);+ // save success path resets the dialog itself+ expect(result.dialogOpen()).toBe(false);+ });++ // ---------------------------------------------------------------------------+ // openDeleteDialog / resetDeleteDialogState / closeDeleteDialog+ // ---------------------------------------------------------------------------++ it('opens the delete confirmation dialog with the pending connection and closes it while idle', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ const target = makeConnection({ id: 'conn-del', name: 'tower' });++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openDeleteDialog(target);+ expect(result.deleteDialogOpen()).toBe(true);+ expect(result.pendingDeleteConnection()).toEqual(target);++ result.closeDeleteDialog();+ expect(result.deleteDialogOpen()).toBe(false);+ expect(result.pendingDeleteConnection()).toBeNull();+ });++ it('keeps the delete dialog open when closeDeleteDialog is invoked while a delete is in flight', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ let resolveDelete!: (value: { success: boolean; id: string }) => void;+ vi.mocked(TrueNASAPI.deleteConnection).mockReturnValueOnce(+ new Promise<{ success: boolean; id: string }>((resolve) => {+ resolveDelete = resolve;+ }),+ );+ const target = makeConnection({ id: 'conn-del', name: 'tower' });++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openDeleteDialog(target);+ const deletePromise = result.deletePendingConnection();+ await waitFor(() => expect(result.deleting()).toBe(true));++ result.closeDeleteDialog();+ expect(result.deleteDialogOpen()).toBe(true);+ expect(result.pendingDeleteConnection()).toEqual(target);++ resolveDelete({ success: true, id: 'conn-del' });+ await deletePromise;+ expect(result.deleting()).toBe(false);+ expect(result.deleteDialogOpen()).toBe(false);+ });++ // ---------------------------------------------------------------------------+ // deletePendingConnection — success (name + host fallback), failure, null-pending no-op.+ // ---------------------------------------------------------------------------++ it('removes the pending connection, notifies by name, and reloads the list on delete success', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.deleteConnection).mockResolvedValueOnce({ success: true, id: 'conn-1' });++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openDeleteDialog(makeConnection({ id: 'conn-1', name: 'tower', host: 'truenas.local' }));+ await result.deletePendingConnection();++ expect(TrueNASAPI.deleteConnection).toHaveBeenCalledWith('conn-1');+ expect(notificationStore.success).toHaveBeenCalledWith('Removed tower');+ expect(result.deleteDialogOpen()).toBe(false);+ expect(result.pendingDeleteConnection()).toBeNull();+ expect(result.deleting()).toBe(false);+ // mount load + post-delete reload+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(2);+ });++ it('uses the connection host in the success notice when the name is empty', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.deleteConnection).mockResolvedValueOnce({ success: true, id: 'conn-2' });++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ result.openDeleteDialog(makeConnection({ id: 'conn-2', name: '', host: 'box.local' }));+ await result.deletePendingConnection();++ expect(notificationStore.success).toHaveBeenCalledWith('Removed box.local');+ });++ it('leaves the delete dialog open, notifies, and skips reload on delete failure', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.deleteConnection).mockRejectedValueOnce(new Error('server is down'));++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ const target = makeConnection({ id: 'conn-3', name: 'tower' });+ result.openDeleteDialog(target);+ await result.deletePendingConnection();++ expect(notificationStore.error).toHaveBeenCalledWith('server is down');+ expect(logger.error).toHaveBeenCalledWith(+ '[TrueNAS Settings] Delete failed',+ expect.anything(),+ );+ // failure path does not reset the dialog or reload+ expect(result.deleteDialogOpen()).toBe(true);+ expect(result.pendingDeleteConnection()).toEqual(target);+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(1);+ expect(result.deleting()).toBe(false);+ });++ it('is a no-op when deletePendingConnection runs with no pending connection', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);++ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await waitFor(() => expect(result.loading()).toBe(false));++ await result.deletePendingConnection();++ expect(TrueNASAPI.deleteConnection).not.toHaveBeenCalled();+ expect(notificationStore.success).not.toHaveBeenCalled();+ expect(result.deleting()).toBe(false);+ expect(result.deleteDialogOpen()).toBe(false);+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/useWorkloadGuestMetadataState.branchcov0722am.test.ts b/frontend-modern/src/components/Workloads/__tests__/useWorkloadGuestMetadataState.branchcov0722am.test.tsnew file mode 100644index 0000000000..40b7032c7c--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/useWorkloadGuestMetadataState.branchcov0722am.test.ts@@ -0,0 +1,361 @@+import { createRoot } from 'solid-js';+import { renderHook } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ RESOURCE_METADATA_CHANGED_EVENT,+ type ResourceMetadataChangedDetail,+} from '@/utils/resourceMetadataEvents';++import { useWorkloadGuestMetadataState } from '../useWorkloadGuestMetadataState';++// This suite targets the branch arms the base suite leaves cold: the+// metadata-changed event subscription (no/nil metadataId, missing kind or+// customUrl, docker kind), refresh (rejection + null payload), the org_switched+// subscription body, onMount teardown, the handleCustomUrlUpdate clearing/trim+// arms, and the localStorage persist queue. Each test is isolated by giving the+// hook a unique org scope (unique storage key) so the module-level metadata+// cache never leaks state across tests.++type OrgSwitchedHandler = (orgID?: string) => void;++const mocks = vi.hoisted(() => ({+ orgID: 'default',+ getAllMetadata: vi.fn().mockResolvedValue({}),+ unsubscribeOrgSwitched: vi.fn(),+ orgSwitchedHandler: { current: null as OrgSwitchedHandler | null },+}));++vi.mock('@/api/guestMetadata', () => ({+ GuestMetadataAPI: {+ getAllMetadata: () => mocks.getAllMetadata(),+ },+}));++vi.mock('@/utils/apiClient', () => ({+ getOrgID: () => mocks.orgID,+}));++vi.mock('@/stores/events', () => ({+ eventBus: {+ on: vi.fn((_event: unknown, handler: OrgSwitchedHandler) => {+ mocks.orgSwitchedHandler.current = handler;+ return mocks.unsubscribeOrgSwitched;+ }),+ },+}));++const STORAGE_PREFIX = 'pulseGuestMetadata.';+const keyFor = (orgScope: string) => `${STORAGE_PREFIX}${encodeURIComponent(orgScope)}`;+const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++const dispatchMetadataEvent = (detail?: ResourceMetadataChangedDetail) =>+ window.dispatchEvent(+ new CustomEvent<ResourceMetadataChangedDetail>(RESOURCE_METADATA_CHANGED_EVENT, { detail }),+ );++describe('useWorkloadGuestMetadataState (branch coverage 0722am)', () => {+ beforeEach(() => {+ window.localStorage.clear();+ mocks.orgID = 'default';+ mocks.getAllMetadata.mockReset();+ mocks.getAllMetadata.mockResolvedValue({});+ mocks.unsubscribeOrgSwitched.mockReset();+ mocks.orgSwitchedHandler.current = null;+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ describe('handleCustomUrlUpdate clearing / trim arms', () => {+ it('trims surrounding whitespace from the incoming url before storing it', () => {+ mocks.orgID = 'trim';+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ state.handleCustomUrlUpdate('guest:trim', ' https://trim.example ');+ expect(state.guestMetadata()['guest:trim']?.customUrl).toBe('https://trim.example');+ dispose();+ });+ });++ it('no-ops (keeps the same signal value reference) when re-applying the current url', () => {+ mocks.orgID = 'noop-same-url';+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ state.handleCustomUrlUpdate('guest:noop', 'https://a.example');+ const afterSet = state.guestMetadata();+ state.handleCustomUrlUpdate('guest:noop', 'https://a.example');+ expect(Object.is(state.guestMetadata(), afterSet)).toBe(true);+ dispose();+ });+ });++ it('omits a non-stable entry entirely when cleared and it only carried customUrl', () => {+ mocks.orgID = 'omit';+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ state.handleCustomUrlUpdate('guest:omit', 'https://o.example');+ expect(state.guestMetadata()['guest:omit']?.customUrl).toBe('https://o.example');+ state.handleCustomUrlUpdate('guest:omit', '');+ expect(state.guestMetadata()['guest:omit']).toBeUndefined();+ dispose();+ });+ });++ it('keeps a non-stable entry (dropping only customUrl) when it carries additional metadata', () => {+ mocks.orgID = 'keep-extra';+ window.localStorage.setItem(+ keyFor('keep-extra'),+ JSON.stringify({+ 'guest:keep': {+ id: 'guest:keep',+ customUrl: 'https://k.example',+ description: 'desc',+ tags: ['t'],+ },+ }),+ );+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ state.handleCustomUrlUpdate('guest:keep', '');+ expect(state.guestMetadata()['guest:keep']).toEqual({+ id: 'guest:keep',+ description: 'desc',+ tags: ['t'],+ });+ expect(state.guestMetadata()['guest:keep']?.customUrl).toBeUndefined();+ dispose();+ });+ });++ it('no-ops when clearing a non-stable id that has no entry at all', () => {+ mocks.orgID = 'clear-empty';+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ state.handleCustomUrlUpdate('guest:none', '');+ expect(state.guestMetadata()['guest:none']).toBeUndefined();+ expect(Object.keys(state.guestMetadata())).toHaveLength(0);+ dispose();+ });+ });++ it('detects a stable app-container id even with surrounding whitespace, keying the record by the raw id', () => {+ mocks.orgID = 'stable-ws';+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ const rawId = ' app-container:docker:name:grafana ';+ state.handleCustomUrlUpdate(rawId, '');+ const meta = state.guestMetadata();+ expect(meta[rawId]).toEqual({ id: rawId, customUrl: '' });+ expect(meta[rawId.trim()]).toBeUndefined();+ dispose();+ });+ });++ it('does not treat an app-container id lacking :name: as stable', () => {+ mocks.orgID = 'not-stable';+ createRoot((dispose) => {+ const state = useWorkloadGuestMetadataState();+ state.handleCustomUrlUpdate('app-container:docker:runtime-id', '');+ expect(state.guestMetadata()['app-container:docker:runtime-id']).toBeUndefined();+ dispose();+ });+ });+ });++ describe('handleMetadataChanged event subscription arms', () => {+ it('refreshes from the API when a metadata-changed event carries an empty metadataId', async () => {+ mocks.orgID = 'evt-no-id';+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ mocks.getAllMetadata.mockResolvedValue({+ 'guest:after': { id: 'guest:after', customUrl: 'https://after.example' },+ });+ mocks.getAllMetadata.mockClear();+ dispatchMetadataEvent({+ metadataKind: 'guest',+ metadataId: '',+ customUrl: 'https://ignored.example',+ });+ await flush();+ expect(mocks.getAllMetadata).toHaveBeenCalledTimes(1);+ expect(result.guestMetadata()['guest:after']?.customUrl).toBe('https://after.example');+ cleanup();+ });++ it('refreshes when a metadata-changed event has no detail payload at all', async () => {+ mocks.orgID = 'evt-nil-detail';+ const { cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ mocks.getAllMetadata.mockClear();+ dispatchMetadataEvent(undefined);+ await flush();+ expect(mocks.getAllMetadata).toHaveBeenCalledTimes(1);+ cleanup();+ });++ it('routes events with an undefined metadataKind through the non-agent path', () => {+ mocks.orgID = 'evt-no-kind';+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ dispatchMetadataEvent({+ metadataKind: undefined,+ metadataId: 'app-container:host:name:srv',+ customUrl: 'https://nk.example',+ } as unknown as ResourceMetadataChangedDetail);+ expect(result.guestMetadata()['app-container:host:name:srv']?.customUrl).toBe(+ 'https://nk.example',+ );+ cleanup();+ });++ it('applies docker-kind events via handleCustomUrlUpdate instead of refreshing', async () => {+ mocks.orgID = 'evt-docker';+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ mocks.getAllMetadata.mockClear();+ dispatchMetadataEvent({+ metadataKind: 'docker',+ metadataId: 'docker:ctr1',+ customUrl: 'https://d.example',+ });+ expect(result.guestMetadata()['docker:ctr1']?.customUrl).toBe('https://d.example');+ expect(mocks.getAllMetadata).not.toHaveBeenCalled();+ cleanup();+ });++ it('treats a missing customUrl on a metadata-changed event as an empty string', () => {+ mocks.orgID = 'evt-no-url';+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ dispatchMetadataEvent({+ metadataKind: 'guest',+ metadataId: 'app-container:host:name:clear',+ });+ expect(result.guestMetadata()['app-container:host:name:clear']).toEqual({+ id: 'app-container:host:name:clear',+ customUrl: '',+ });+ cleanup();+ });+ });++ describe('refreshGuestMetadata arms', () => {+ it('swallows a refresh failure without throwing and leaves state empty', async () => {+ mocks.orgID = 'refresh-err';+ mocks.getAllMetadata.mockRejectedValue(new Error('boom'));+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ expect(Object.keys(result.guestMetadata())).toHaveLength(0);+ cleanup();+ });++ it('coerces a null API payload to an empty record on refresh', async () => {+ mocks.orgID = 'refresh-null';+ window.localStorage.setItem(+ keyFor('refresh-null'),+ JSON.stringify({+ 'guest:seed': { id: 'guest:seed', customUrl: 'https://s.example' },+ }),+ );+ mocks.getAllMetadata.mockResolvedValue(null);+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ expect(result.guestMetadata()['guest:seed']?.customUrl).toBe('https://s.example');+ await flush();+ expect(result.guestMetadata()['guest:seed']).toBeUndefined();+ expect(result.guestMetadata()).toEqual({});+ cleanup();+ });+ });++ describe('org_switched subscription', () => {+ it('re-runs refresh when the org_switched event fires', async () => {+ mocks.orgID = 'orgswitch';+ const { cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ expect(mocks.orgSwitchedHandler.current).toBeTypeOf('function');+ mocks.getAllMetadata.mockClear();+ mocks.orgSwitchedHandler.current?.('org-2');+ await flush();+ expect(mocks.getAllMetadata).toHaveBeenCalledTimes(1);+ cleanup();+ });++ it('re-reads the cache under the new org scope on org_switched', async () => {+ mocks.orgID = 'scope-default';+ mocks.getAllMetadata.mockRejectedValue(new Error('no api'));+ window.localStorage.setItem(+ keyFor('org-target'),+ JSON.stringify({+ 'guest:target': { id: 'guest:target', customUrl: 'https://t.example' },+ }),+ );+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ expect(result.guestMetadata()['guest:target']).toBeUndefined();+ mocks.orgSwitchedHandler.current?.('org-target');+ await vi.waitFor(() => {+ expect(result.guestMetadata()['guest:target']?.customUrl).toBe('https://t.example');+ });+ cleanup();+ });+ });++ describe('onMount teardown', () => {+ it('removes the metadata-changed window listener on cleanup', async () => {+ mocks.orgID = 'teardown';+ const { cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ mocks.getAllMetadata.mockClear();+ cleanup();+ dispatchMetadataEvent({ metadataKind: 'guest', metadataId: 'whatever:id' });+ await flush();+ expect(mocks.getAllMetadata).not.toHaveBeenCalled();+ });++ it('invokes the org_switched unsubscribe returned by eventBus.on on cleanup', async () => {+ mocks.orgID = 'teardown-org';+ const { cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ await flush();+ expect(mocks.unsubscribeOrgSwitched).not.toHaveBeenCalled();+ cleanup();+ expect(mocks.unsubscribeOrgSwitched).toHaveBeenCalledTimes(1);+ });+ });++ describe('localStorage persist queue (no requestIdleCallback -> setTimeout fallback)', () => {+ it('persists queued metadata to localStorage via the setTimeout fallback', () => {+ vi.stubGlobal('requestIdleCallback', undefined);+ vi.stubGlobal('cancelIdleCallback', undefined);+ vi.useFakeTimers();+ mocks.orgID = 'persist-ok';+ mocks.getAllMetadata.mockReturnValue(new Promise(() => {}));+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ result.handleCustomUrlUpdate('guest:persist', 'https://p.example');+ vi.advanceTimersByTime(1);+ const raw = window.localStorage.getItem(keyFor('persist-ok'));+ expect(raw).not.toBeNull();+ expect(raw).toContain('guest:persist');+ expect(raw).toContain('https://p.example');+ cleanup();+ });++ it('swallows a localStorage.setItem failure during persist without throwing', () => {+ vi.stubGlobal('requestIdleCallback', undefined);+ vi.stubGlobal('cancelIdleCallback', undefined);+ vi.useFakeTimers();+ mocks.orgID = 'persist-err';+ mocks.getAllMetadata.mockReturnValue(new Promise(() => {}));+ const setItemSpy = vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {+ throw new Error('quota exceeded');+ });+ const { result, cleanup } = renderHook(() => useWorkloadGuestMetadataState());+ expect(() => {+ result.handleCustomUrlUpdate('guest:persist-err', 'https://pe.example');+ vi.advanceTimersByTime(1);+ }).not.toThrow();+ setItemSpy.mockRestore();+ cleanup();+ });+ });+});