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.

Cover the largest remaining frontend branch gaps

rcourtmanec6922b70275
diff --git a/frontend-modern/src/api/__tests__/truenas.branchcov0724pm.test.ts b/frontend-modern/src/api/__tests__/truenas.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..b97de612dc
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/truenas.branchcov0724pm.test.ts
@@ -0,0 +1,138 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { apiFetchJSON } from '@/utils/apiClient';
+import { TrueNASAPI, type TrueNASConnection } from '@/api/truenas';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+describe('TrueNASAPI branch coverage (0724pm)', () => {
+ const mock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ mock.mockReset();
+ });
+
+ describe('normalizeTrueNASConnection (response-shape fallbacks)', () => {
+ it('defaults a blank name to "", zeroes every absent observed count, keeps legacy-rest mode and surfaces a structured poll error', async () => {
+ mock.mockResolvedValueOnce([
+ {
+ id: 'c1',
+ host: 'truenas.local',
+ useHttps: true,
+ insecureSkipVerify: false,
+ enabled: true,
+ poll: {
+ lastError: {
+ at: ' 2026-01-01T00:00:00Z ',
+ message: ' boom ',
+ category: ' net ',
+ },
+ },
+ observed: {},
+ transport: {
+ mode: 'legacy-rest',
+ tls: false,
+ connected: false,
+ },
+ },
+ ]);
+
+ const [connection] = await TrueNASAPI.listConnections();
+
+ expect(connection.name).toBe('');
+ expect(connection.poll?.lastError).toEqual({
+ at: '2026-01-01T00:00:00Z',
+ message: 'boom',
+ category: 'net',
+ });
+ expect(connection.observed).toEqual({
+ host: undefined,
+ resourceId: undefined,
+ collectedAt: undefined,
+ systems: 0,
+ storagePools: 0,
+ datasets: 0,
+ apps: 0,
+ vms: 0,
+ shares: 0,
+ disks: 0,
+ recoveryArtifacts: 0,
+ });
+ expect(connection.transport).toEqual({
+ mode: 'legacy-rest',
+ endpoint: undefined,
+ tls: false,
+ connected: false,
+ authMechanism: undefined,
+ applianceVersion: undefined,
+ legacyReason: undefined,
+ reconnects: undefined,
+ lastError: undefined,
+ lastConnectedAt: undefined,
+ });
+ });
+
+ it('drops a non-object poll.lastError and collapses an unknown transport mode to negotiating', async () => {
+ mock.mockResolvedValueOnce([
+ {
+ id: 'c2',
+ host: 'truenas.local',
+ useHttps: true,
+ insecureSkipVerify: false,
+ enabled: true,
+ poll: { lastError: 'boom' },
+ transport: { mode: 'totally-bogus' },
+ },
+ ] as unknown as TrueNASConnection[]);
+
+ const [connection] = await TrueNASAPI.listConnections();
+
+ expect(connection.poll?.lastError).toBeUndefined();
+ expect(connection.transport?.mode).toBe('negotiating');
+ expect(connection.transport?.tls).toBe(false);
+ expect(connection.transport?.connected).toBe(false);
+ });
+
+ it('treats an absent transport mode as negotiating and drops a null poll.lastError', async () => {
+ mock.mockResolvedValueOnce([
+ {
+ id: 'c3',
+ host: 'truenas.local',
+ useHttps: true,
+ insecureSkipVerify: false,
+ enabled: true,
+ poll: { lastError: null },
+ transport: {},
+ },
+ ]);
+
+ const [connection] = await TrueNASAPI.listConnections();
+
+ expect(connection.transport?.mode).toBe('negotiating');
+ expect(connection.poll?.lastError).toBeUndefined();
+ });
+ });
+
+ describe('listConnections (non-array response)', () => {
+ it('returns an empty list when the backend answers with null', async () => {
+ mock.mockResolvedValueOnce(null);
+
+ await expect(TrueNASAPI.listConnections()).resolves.toEqual([]);
+ });
+ });
+
+ describe('testSavedConnection (no input override)', () => {
+ it('encodes the id and sends a bodyless POST when no input is supplied', async () => {
+ mock.mockResolvedValueOnce({ success: true });
+
+ await expect(TrueNASAPI.testSavedConnection('conn/with slash')).resolves.toEqual({
+ success: true,
+ });
+
+ expect(mock).toHaveBeenLastCalledWith('/api/truenas/connections/conn%2Fwith%20slash/test', {
+ method: 'POST',
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDiscoveryModel.branchcov0724pm.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDiscoveryModel.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..4f62ccee89
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDiscoveryModel.branchcov0724pm.test.ts
@@ -0,0 +1,298 @@
+import { describe, expect, it } from 'vitest';
+
+import { toDiscoveryConfig } from '@/components/Infrastructure/resourceDetailDiscoveryModel';
+import type { Resource, ResourceDiscoveryTarget } from '@/types/resource';
+
+/**
+ * Branch-coverage suite for the REMAINING uncovered arms of
+ * resourceDetailDiscoveryModel.ts (the 18 branches the existing
+ * resourceDetailDiscoveryModel.branchcov.test.ts and
+ * ResourceDetailDrawer.discovery.test.ts leave cold).
+ *
+ * Every private helper below (`getMetadataTarget`, `getHostMetadataTarget`,
+ * `getDockerContainerMetadataId`, `getPreferredHostLabel`) is driven through
+ * the single export `toDiscoveryConfig`, with assertions on the concrete
+ * returned values — never a delegate-equals-delegate tautology.
+ *
+ * The dominant cold pattern in the baseline is that the existing specs always
+ * set kubernetes/docker/proxmox identity directly on the resource and leave
+ * `platformData` absent, so every `platformData?.kubernetes?.X` and
+ * `platformData?.docker?.X` optional-chaining "defined" arm was never taken.
+ * These tests populate those nested platformData records to exercise them.
+ */
+
+const baseResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'res-1',
+ type: 'storage',
+ name: 'res-name',
+ displayName: 'Res Name',
+ platformId: 'platform-1',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+ }) as unknown as Resource;
+
+const discoveryTarget = (
+ overrides: Partial<ResourceDiscoveryTarget> = {},
+): ResourceDiscoveryTarget =>
+ ({
+ resourceType: 'agent',
+ agentId: 'agent-default',
+ resourceId: 'rid-default',
+ ...overrides,
+ }) as ResourceDiscoveryTarget;
+
+describe('getMetadataTarget — Kubernetes platformData-defined arms', () => {
+ it('builds the stable k8s guest id from platformData.kubernetes when resource.kubernetes is absent', () => {
+ // Drives the optional-chaining "defined" arms that the baseline leaves cold:
+ // - line 150 `kubernetesPlatformData?.clusterId`
+ // - line 153 `kubernetesPlatformData?.namespace`
+ // (baseline always passed resource.kubernetes with platformData undefined,
+ // so kubernetesPlatformData was always nullish here).
+ // Discriminator: the metadata id is keyed by the platformData cluster +
+ // namespace ('cl-a' / 'payments'), NOT by resource.id, proving the
+ // platformData arms supplied the values.
+ const resource = baseResource({
+ id: 'dep-runtime',
+ type: 'k8s-deployment',
+ name: 'checkout',
+ platformData: {
+ kubernetes: { clusterId: 'cl-a', namespace: 'payments' },
+ },
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'pod',
+ agentId: 'cl-a',
+ resourceId: 'payments/checkout',
+ metadataKind: 'guest',
+ metadataId: 'k8s-workload:cl-a:deployment:payments:checkout',
+ targetLabel: 'workload',
+ });
+ });
+});
+
+describe('getHostMetadataTarget — Kubernetes platformData-defined cluster arm', () => {
+ it('resolves the k8s-cluster host metadata id from platformData.kubernetes.clusterId', () => {
+ // Drives the "defined" arm of line 183
+ // `asString(kubernetesPlatformData?.clusterId)`. The baseline k8s-cluster
+ // spec set resource.kubernetes.clusterId with platformData undefined.
+ // Discriminator: metadataId is the platformData cluster id 'pd-cluster'
+ // (not resource.id), proving the platformData arm supplied it.
+ const resource = baseResource({
+ id: 'k8s-cluster-runtime',
+ type: 'k8s-cluster',
+ name: 'mycluster',
+ platformData: {
+ kubernetes: { clusterId: 'pd-cluster' },
+ },
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'agent',
+ agentId: 'pd-cluster',
+ resourceId: 'pd-cluster',
+ metadataKind: 'agent',
+ metadataId: 'pd-cluster',
+ targetLabel: 'host',
+ });
+ });
+});
+
+describe('getDockerContainerMetadataId — platformData.docker-defined arms', () => {
+ it('builds the runtime docker metadata id from platformData.docker when resource.docker is absent', () => {
+ // Drives the "defined" arms of:
+ // - line 99 `platformData?.docker`
+ // - line 101 `dockerPlatformData?.hostSourceId`
+ // - line 103 `dockerPlatformData?.containerId`
+ // (baseline only reached this helper with platformData undefined).
+ // name is blanked so the stable guest id (buildAppContainerMetadataId)
+ // returns null and execution falls through to getDockerContainerMetadataId
+ // with platformData.docker populated.
+ // Discriminator: metadataId is 'pd-host:container:pd-cont' (the
+ // platformData values), metadataKind 'docker' — not the resource id.
+ const resource = baseResource({
+ id: 'app-runtime',
+ type: 'app-container',
+ name: '',
+ platformId: 'app-platform',
+ platformData: {
+ docker: { hostSourceId: 'pd-host', containerId: 'pd-cont' },
+ },
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'app-container',
+ agentId: 'pd-host',
+ resourceId: 'pd-cont',
+ metadataKind: 'docker',
+ metadataId: 'pd-host:container:pd-cont',
+ targetLabel: 'container',
+ });
+ });
+});
+
+describe('getHostMetadataTarget — pmg branch (no existing pmg spec)', () => {
+ it('keys pmg host metadata by resource.pmg.instanceId', () => {
+ // Drives the previously-untaken `canonicalResourceType === 'pmg' && ...`
+ // branch (lines 211-213): with a pmg resource the left operand is finally
+ // truthy and the right operand (resource.pmg.instanceId) is evaluated.
+ // ALSO drives the "defined" arm of line 322
+ // `asString(resource.pmg?.instanceId)` in the agentLookupId chain — the
+ // baseline never had resource.pmg populated when this chain was computed.
+ // Discriminator: agentId/resourceId/metadataId all equal 'pmg-inst-1',
+ // targetLabel is 'host' (pmg != 'agent').
+ const resource = baseResource({
+ type: 'pmg',
+ name: 'pmg-node',
+ pmg: { instanceId: 'pmg-inst-1' } as Resource['pmg'],
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'agent',
+ agentId: 'pmg-inst-1',
+ resourceId: 'pmg-inst-1',
+ metadataKind: 'agent',
+ metadataId: 'pmg-inst-1',
+ targetLabel: 'host',
+ });
+ });
+
+ it('falls past the pmg branch when instanceId is missing and still produces a config', () => {
+ // Drives the `&&` short-circuit where canonicalResourceType === 'pmg' is
+ // true but `asString(resource.pmg?.instanceId)` is falsy (line 211 right
+ // operand false) — execution falls through to the generic agent fallback.
+ // Discriminator: with no other host id, agentLookupId bottoms out at the
+ // resource name 'pmg-node', so metadataId === 'pmg-node' (NOT null), and
+ // metadataKind stays 'agent'.
+ const resource = baseResource({
+ type: 'pmg',
+ name: 'pmg-node',
+ pmg: {} as Resource['pmg'],
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'agent',
+ agentId: 'pmg-node',
+ resourceId: 'pmg-node',
+ metadataKind: 'agent',
+ metadataId: 'pmg-node',
+ targetLabel: 'host',
+ });
+ });
+});
+
+describe('agentLookupId chain — lower-priority fallback arms', () => {
+ it('uses platformData.docker.hostname when no higher-priority host id resolves', () => {
+ // Drives the "defined" arm of line 325
+ // `asString(dockerPlatformData?.hostname)`. Requires platformData.docker
+ // to be present (with a hostname but no hostSourceId, so the actionable
+ // docker runtime id at line 318 stays falsy) and every earlier operand
+ // (docker/k8s/agent actionable ids, pbs, pmg.instanceId, proxmox node,
+ // platformData.agent.hostname) to be empty.
+ // Discriminator: agentId === 'docker-host-hint' (the platformData docker
+ // hostname), proving line 325 won the chain.
+ const resource = baseResource({
+ type: 'agent',
+ name: '',
+ platformId: '',
+ platformData: {
+ docker: { hostname: 'docker-host-hint' },
+ },
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'agent',
+ agentId: 'docker-host-hint',
+ resourceId: 'docker-host-hint',
+ metadataKind: 'agent',
+ metadataId: 'docker-host-hint',
+ targetLabel: 'agent',
+ });
+ });
+
+ it('falls through to getPreferredInfrastructureDisplayName (primary identity) when every hostname source is blank', () => {
+ // Drives line 327 `getPreferredInfrastructureDisplayName(resource)` as the
+ // winning operand: name/platformId/displayName and all platform hostnames
+ // are blank, so getPreferredResourceHostname (line 326) is falsy and the
+ // infra display name — which bottoms out at getPrimaryResourceIdentity →
+ // resource.id — wins.
+ // Discriminator: agentId === resource.id 'bare-agent-id', proving the
+ // infra-display-name operand (not name/platformId) supplied the value.
+ const resource = baseResource({
+ id: 'bare-agent-id',
+ type: 'agent',
+ name: '',
+ platformId: '',
+ displayName: '',
+ });
+ expect(toDiscoveryConfig(resource)).toMatchObject({
+ resourceType: 'agent',
+ agentId: 'bare-agent-id',
+ resourceId: 'bare-agent-id',
+ metadataKind: 'agent',
+ metadataId: 'bare-agent-id',
+ targetLabel: 'agent',
+ });
+ });
+
+ it('returns null for a malformed agent whose id and platformId are both empty', () => {
+ // Drives the genuinely-deep defensive arms only reachable when resource.id
+ // is empty (so getPrimaryResourceIdentity, and therefore
+ // getPreferredInfrastructureDisplayName, returns ''):
+ // - line 92 `|| resource.id` tail of getPreferredHostLabel
+ // - line 327 falsy arm of getPreferredInfrastructureDisplayName
+ // - line 328 `resource.platformId || resource.id` tail of agentLookupId
+ // With no id, hostMetadataTarget.metadataId resolves to '' and the agent
+ // case's isDiscoveryLookupValue guard rejects it.
+ // These arms are defensive fallbacks unreachable for any valid (non-empty
+ // id) resource; exercised here via a deliberately malformed input.
+ const resource = baseResource({
+ id: '',
+ type: 'agent',
+ name: '',
+ platformId: '',
+ displayName: '',
+ }) as unknown as Resource;
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+});
+
+describe('canonicalDiscoveryResourceType || resource.type defensive fallback', () => {
+ it('treats an empty type as unmapped and returns null even with rich platform data', () => {
+ // Drives the `|| resource.type` fallback at line 341 (main switch) and the
+ // same fallback at line 180 (inside getHostMetadataTarget).
+ // canonicalDiscoveryResourceType('') returns undefined, so the right
+ // operand (resource.type '') wins, canonicalResourceType becomes '' and
+ // the switch hits its default -> null. The fallback is unreachable for any
+ // non-empty type (canonicalDiscoveryResourceType always returns at least
+ // the lowercased type), so it is exercised here via an empty type cast.
+ // Discriminator: rich docker + kubernetes platform data is present yet the
+ // result is null, proving the empty-type canonicalization dominates.
+ const resource = baseResource({
+ id: 'empty-type-res',
+ type: '' as unknown as Resource['type'],
+ name: 'whatever',
+ platformData: {
+ docker: { hostSourceId: 'ignored-host' },
+ kubernetes: { clusterId: 'ignored-cluster' },
+ },
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it('drops an explicit discoveryTarget whose resourceType is unmapped and falls back to the main switch default', () => {
+ // Companion to the empty-type case above: an explicit discoveryTarget with
+ // a resourceType that canonicalizes to a value the explicit switch's
+ // `default` rejects (so resourceType becomes null) AND whose resource's own
+ // type is also unmapped -> main switch default -> null.
+ // Confirms the explicit resourceType guard's default arm and the main
+ // switch default compose to null without relying on platformData.
+ const resource = baseResource({
+ type: '' as unknown as Resource['type'],
+ discoveryTarget: discoveryTarget({
+ resourceType: 'storage' as ResourceDiscoveryTarget['resourceType'],
+ agentId: 'explicit-agent',
+ resourceId: 'explicit-rid',
+ }),
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerTrueNASModel.branchcov0724pm.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerTrueNASModel.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..8e1fe99478
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerTrueNASModel.branchcov0724pm.test.ts
@@ -0,0 +1,289 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildTrueNASDetailSections,
+ buildTrueNASDetailsSummary,
+ hasTrueNASDetailSections,
+ type ResourceDetailDrawerTrueNASRow,
+} from '@/components/Infrastructure/resourceDetailDrawerTrueNASModel';
+import type {
+ Resource,
+ ResourcePhysicalDiskMeta,
+ ResourceStorageMeta,
+ ResourceTrueNASAppMeta,
+} from '@/types/resource';
+
+// Every helper under test is module-private, so each case drives it through the
+// three public entry points (buildTrueNASDetailSections /
+// buildTrueNASDetailsSummary / hasTrueNASDetailSections) and asserts on the
+// rendered sections, rows, summaries or boolean verdict. Fixture builders and
+// accessors mirror the sibling `coverage2` spec's conventions. This file
+// targets ONLY the arms the existing specs leave uncovered.
+
+const baseResource = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: 'truenas-resource',
+ type: 'vm',
+ name: 'truenas-resource',
+ displayName: 'TrueNAS resource',
+ platformId: 'truenas-main',
+ platformType: 'truenas',
+ sourceType: 'api',
+ status: 'online',
+ ...overrides,
+ }) as Resource;
+
+const allRows = (resource: Resource): ResourceDetailDrawerTrueNASRow[] =>
+ buildTrueNASDetailSections(resource).flatMap((section) => section.rows);
+
+const findRow = (resource: Resource, label: string): ResourceDetailDrawerTrueNASRow | undefined =>
+ allRows(resource).find((row) => row.label === label);
+
+const storageRes = (
+ // `unknown` so deeply-nested deliberately-partial fixtures (zfsPool devices,
+ // scanDetails, poolHealth) bypass strict-null checks at the call site; the
+ // cast here is the sanctioned boundary for malformed inputs.
+ storage: unknown,
+ overrides: Partial<Resource> = {},
+): Resource => baseResource({ storage: storage as ResourceStorageMeta, ...overrides });
+
+const diskRes = (disk: Partial<ResourcePhysicalDiskMeta>): Resource =>
+ baseResource({ physicalDisk: disk });
+
+const appRes = (app: Partial<ResourceTrueNASAppMeta>): Resource =>
+ baseResource({ type: 'app-container', truenas: { app } });
+
+// =========================================================================
+// hasTrueNASDetailSections (previously zero hits)
+// =========================================================================
+
+describe('hasTrueNASDetailSections', () => {
+ it('returns true when a section builder produces at least one section', () => {
+ const resource = storageRes({ type: 'zfs-pool' });
+ expect(hasTrueNASDetailSections(resource)).toBe(true);
+ expect(buildTrueNASDetailSections(resource).map((s) => s.label)).toContain('Storage');
+ });
+
+ it('returns false for a resource that is not TrueNAS-scoped (falls through to [])', () => {
+ const resource = baseResource({ platformType: 'docker' });
+ expect(hasTrueNASDetailSections(resource)).toBe(false);
+ expect(buildTrueNASDetailSections(resource)).toEqual([]);
+ });
+
+ it('returns false when a builder yields only empty section arrays (bare app)', () => {
+ // An app with no fields routes to buildTrueNASAppSections, whose every
+ // section is compacted away because every row is null -> sections == [].
+ const resource = baseResource({ truenas: { app: {} } });
+ expect(hasTrueNASDetailSections(resource)).toBe(false);
+ expect(buildTrueNASDetailSections(resource)).toEqual([]);
+ });
+});
+
+// =========================================================================
+// isTrueNASScopedResource alternative scope arms (platformType short-circuits
+// the other four operands in every existing fixture)
+// =========================================================================
+
+describe('isTrueNASScopedResource alternative scoping arms', () => {
+ // Each resource is platformType 'docker' (so the first operand is false) and
+ // carries storage so it routes to buildTrueNASStorageSections; producing a
+ // 'Storage' section proves isTrueNASScopedResource returned true via the
+ // targeted alternative operand.
+
+ it('scopes via platformScopes containing "truenas"', () => {
+ const resource = baseResource({
+ platformType: 'docker',
+ platformScopes: ['truenas'],
+ storage: { type: 'zfs-pool' },
+ });
+ // platformType is 'docker' (first operand false), so isTrueNASScopedResource
+ // resolves true via platformScopes -> the Storage section is built at all.
+ expect(buildTrueNASDetailSections(resource).map((s) => s.label)).toContain('Storage');
+ });
+
+ it('scopes via sources containing "truenas"', () => {
+ const resource = baseResource({
+ platformType: 'docker',
+ sources: ['truenas'],
+ storage: { type: 'zfs-pool' },
+ });
+ expect(buildTrueNASDetailSections(resource).map((s) => s.label)).toContain('Storage');
+ });
+
+ it('scopes via storage.platform === "truenas"', () => {
+ const resource = baseResource({
+ platformType: 'docker',
+ storage: { platform: 'truenas', type: 'zfs-pool' },
+ });
+ expect(buildTrueNASDetailSections(resource).map((s) => s.label)).toContain('Storage');
+ });
+
+ it('scopes via tags containing "truenas"', () => {
+ const resource = baseResource({
+ platformType: 'docker',
+ tags: ['truenas'],
+ storage: { type: 'zfs-pool' },
+ });
+ expect(buildTrueNASDetailSections(resource).map((s) => s.label)).toContain('Storage');
+ });
+});
+
+// =========================================================================
+// zfsScanLabel fallback arms
+// =========================================================================
+
+describe('zfsScanLabel fallback arms (via Health "Scan / resilver" row)', () => {
+ it('returns the raw scan string when scanDetails is absent (early return)', () => {
+ // The early-return arm hands the scan straight to asString() without
+ // normalizeDelimitedLabel, so the original casing is preserved.
+ const resource = storageRes({ zfsPool: { scan: 'RESILVER' } });
+ expect(findRow(resource, 'Scan / resilver')?.value).toBe('RESILVER');
+ });
+
+ it('defaults the operation to "Scan" and drops progress when function/percentage are absent', () => {
+ const resource = storageRes({ zfsPool: { scanDetails: { state: 'SCANNING' } } });
+ const row = findRow(resource, 'Scan / resilver');
+ expect(row?.value).toBe('Scan Scanning');
+ expect(row?.tone).toBe('default');
+ });
+
+ it('formats error count and drops the state segment when state is absent', () => {
+ const resource = storageRes({ zfsPool: { scanDetails: { function: 'SCRUB', errors: 2 } } });
+ const row = findRow(resource, 'Scan / resilver');
+ expect(row?.value).toBe('Scrub · 2 errors');
+ expect(row?.tone).toBe('warning');
+ });
+});
+
+// =========================================================================
+// zfsDeviceEvidenceLabels: filter fall-through, name resolution, formatting
+// =========================================================================
+
+describe('zfsDeviceEvidenceLabels filter and formatting (via "Affected vdevs")', () => {
+ it('admits a device via the non-online state group and resolves name to Vdev with no errors', () => {
+ // missing is unset -> the `||` falls through to the state group; a
+ // non-empty state outside the ONLINE/AVAIL/INUSE allowlist passes the
+ // filter. With no disk/path/name the name resolves to the 'Vdev' fallback.
+ const resource = storageRes({
+ zfsPool: { devices: [{ state: 'DEGRADED', role: 'log', type: 'disk' }] },
+ });
+ expect(findRow(resource, 'Affected vdevs')?.value).toBe('Vdev (Log / Disk): DEGRADED');
+ });
+
+ it('admits a device via readErrors and formats the R/W/C evidence with no context', () => {
+ const resource = storageRes({
+ zfsPool: {
+ devices: [
+ { state: 'ONLINE', disk: 'sdb', readErrors: 1, writeErrors: 0, checksumErrors: 0 },
+ ],
+ },
+ });
+ expect(findRow(resource, 'Affected vdevs')?.value).toBe('sdb: ONLINE · R 1 W 0 C 0');
+ });
+
+ it('admits a device via writeErrors and resolves name via path', () => {
+ const resource = storageRes({
+ zfsPool: {
+ devices: [
+ { state: 'ONLINE', path: '/dev/sdc', readErrors: 0, writeErrors: 1, checksumErrors: 0 },
+ ],
+ },
+ });
+ expect(findRow(resource, 'Affected vdevs')?.value).toBe('/dev/sdc: ONLINE · R 0 W 1 C 0');
+ });
+
+ it('admits a device via checksumErrors and resolves name via the name field', () => {
+ const resource = storageRes({
+ zfsPool: {
+ devices: [
+ { state: 'ONLINE', name: 'sdd', readErrors: 0, writeErrors: 0, checksumErrors: 1 },
+ ],
+ },
+ });
+ expect(findRow(resource, 'Affected vdevs')?.value).toBe('sdd: ONLINE · R 0 W 0 C 1');
+ });
+
+ it('excludes a healthy online device with no errors from the evidence list', () => {
+ const resource = storageRes({
+ zfsPool: { devices: [{ state: 'ONLINE', role: 'data' }] },
+ });
+ expect(findRow(resource, 'Affected vdevs')).toBeUndefined();
+ });
+
+ it('falls back to the "Unknown" state label for an admitted device with no state string', () => {
+ // A device with no missing flag and no state still passes the state group
+ // (undefined !== '' is true), so its display state resolves through the
+ // asString(device.state) ?? 'Unknown' fallback.
+ const resource = storageRes({
+ zfsPool: { devices: [{ role: 'log' }] },
+ });
+ expect(findRow(resource, 'Affected vdevs')?.value).toBe('Vdev (Log): Unknown');
+ });
+});
+
+// =========================================================================
+// Canonical state tone (nested ternary in Health "Canonical state")
+// =========================================================================
+
+describe('poolHealth canonical state tone', () => {
+ it('tones success for canonicalState "ONLINE"', () => {
+ const resource = storageRes({ poolHealth: { canonicalState: 'ONLINE' } });
+ const row = findRow(resource, 'Canonical state');
+ expect(row?.value).toBe('ONLINE');
+ expect(row?.tone).toBe('success');
+ });
+
+ it('tones default for a canonicalState outside the known sets', () => {
+ const resource = storageRes({ poolHealth: { canonicalState: 'SUSPENDED' } });
+ const row = findRow(resource, 'Canonical state');
+ expect(row?.value).toBe('SUSPENDED');
+ expect(row?.tone).toBe('default');
+ });
+});
+
+// =========================================================================
+// SMART warning tones for offline/CRC/media error rows
+// =========================================================================
+
+describe('disk SMART warning tones', () => {
+ it('tones warning when offline uncorrectable, CRC and media errors are present', () => {
+ const resource = diskRes({
+ smart: { offlineUncorrectable: 1, udmaCrcErrors: 2, mediaErrors: 3 },
+ });
+ expect(findRow(resource, 'Offline uncorrectable')).toEqual({
+ label: 'Offline uncorrectable',
+ value: '1',
+ tone: 'warning',
+ });
+ expect(findRow(resource, 'CRC errors')).toEqual({
+ label: 'CRC errors',
+ value: '2',
+ tone: 'warning',
+ });
+ expect(findRow(resource, 'Media errors')).toEqual({
+ label: 'Media errors',
+ value: '3',
+ tone: 'warning',
+ });
+ });
+});
+
+// =========================================================================
+// buildTrueNASDetailsSummary edge arms
+// =========================================================================
+
+describe('buildTrueNASDetailsSummary edge arms', () => {
+ it('reads containers array length in the app summary when containerCount is absent', () => {
+ // Exercising app.containers?.length with a defined containers array so the
+ // optional-chain .length access is actually performed.
+ const resource = appRes({ containers: [{ id: 'c1' }] });
+ expect(buildTrueNASDetailsSummary(resource)).toBe('1 container, 0 ports');
+ });
+
+ it('returns null for a scoped storage resource whose summary is entirely empty', () => {
+ // No kind, no pool/array state, no usage, no risk summary, and a blank
+ // resource.status so storageStateLabel also resolves to null -> every
+ // summary element is nullish -> [] -> null.
+ const resource = baseResource({ status: undefined, storage: {} });
+ expect(buildTrueNASDetailsSummary(resource)).toBeNull();
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadSelectors.branchcov0724pm.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadSelectors.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..134d4fb363
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadSelectors.branchcov0724pm.test.ts
@@ -0,0 +1,247 @@
+import { describe, expect, it } from 'vitest';
+import type { WorkloadGuest } from '@/types/workloads';
+import {
+ computeWorkloadIOEmphasis,
+ createWorkloadSortComparator,
+ filterWorkloads,
+} from '@/components/Workloads/workloadSelectors';
+
+const makeGuest = (i: number, overrides?: Partial<WorkloadGuest>): WorkloadGuest => ({
+ id: `guest-${i}`,
+ vmid: 100 + i,
+ name: `workload-${i}`,
+ node: `node-${i % 5}`,
+ instance: `cluster-${i % 3}`,
+ status: 'running',
+ type: 'vm',
+ cpu: (i % 100) / 100,
+ cpus: 2,
+ memory: { total: 4096, used: ((i % 80) / 100) * 4096, free: 0, usage: (i % 80) / 100 },
+ disk: { total: 102400, used: ((i % 60) / 100) * 102400, free: 0, usage: (i % 60) / 100 },
+ networkIn: i * 100,
+ networkOut: i * 50,
+ diskRead: i * 10,
+ diskWrite: i * 5,
+ uptime: i * 3600,
+ template: false,
+ lastBackup: 0,
+ tags: [],
+ lock: '',
+ lastSeen: new Date().toISOString(),
+ workloadType: 'vm',
+ ...overrides,
+});
+
+const baseFilterParams = {
+ viewMode: 'all' as const,
+ statusMode: 'all',
+ searchTerm: '',
+ selectedNode: null,
+ selectedHostHint: null,
+ selectedKubernetesContext: null,
+};
+
+describe('workloadSelectors (branch coverage 0724pm)', () => {
+ describe('createWorkloadSortComparator - ?? / || fallback arms', () => {
+ it('coerces a non-numeric cpu to 0 via `getWorkloadCPUPercent(cpu) ?? 0` on both a and b', () => {
+ const nanCpu = makeGuest(1, {
+ id: 'nan',
+ name: 'nan-cpu',
+ cpu: undefined as unknown as number,
+ });
+ const realCpu = makeGuest(2, { id: 'real', name: 'real-cpu', cpu: 0.5 });
+ const cmp = createWorkloadSortComparator('cpu', 'asc')!;
+
+ // nan-cpu -> getWorkloadCPUPercent(undefined) -> undefined -> ?? 0 -> 0
+ // real-cpu -> 50. Ascending: nan (0) sorts before real (50).
+ expect(cmp(nanCpu, realCpu)).toBe(-1);
+ // Reversed orientation exercises bVal ?? 0 for the non-numeric guest.
+ expect(cmp(realCpu, nanCpu)).toBe(1);
+ });
+
+ it('falls back to 0 for missing diskRead/diskWrite on both a and b of the diskIo arm', () => {
+ const noIo = makeGuest(1, {
+ id: 'no-io',
+ name: 'no-io',
+ diskRead: undefined as unknown as number,
+ diskWrite: undefined as unknown as number,
+ });
+ const withIo = makeGuest(2, {
+ id: 'with-io',
+ name: 'with-io',
+ diskRead: 50,
+ diskWrite: 30,
+ });
+ const cmp = createWorkloadSortComparator('diskIo', 'asc')!;
+
+ // noIo -> max(0, undefined||0) + max(0, undefined||0) = 0 + 0 = 0
+ // withIo -> 50 + 30 = 80. Ascending: no-io (0) before with-io (80).
+ expect(cmp(noIo, withIo)).toBe(-1);
+ // Reversed orientation exercises the b-side diskRead||0 / diskWrite||0 fallbacks.
+ expect(cmp(withIo, noIo)).toBe(1);
+ });
+
+ it('falls back to 0 for missing networkIn/networkOut on both a and b of the netIo arm', () => {
+ const noNet = makeGuest(1, {
+ id: 'no-net',
+ name: 'no-net',
+ networkIn: undefined as unknown as number,
+ networkOut: undefined as unknown as number,
+ });
+ const withNet = makeGuest(2, {
+ id: 'with-net',
+ name: 'with-net',
+ networkIn: 20,
+ networkOut: 10,
+ });
+ const cmp = createWorkloadSortComparator('netIo', 'asc')!;
+
+ // noNet -> max(0, undefined||0) + max(0, undefined||0) = 0
+ // withNet -> 20 + 10 = 30. Ascending: no-net (0) before with-net (30).
+ expect(cmp(noNet, withNet)).toBe(-1);
+ // Reversed orientation exercises the b-side networkIn||0 / networkOut||0 fallbacks.
+ expect(cmp(withNet, noNet)).toBe(1);
+ });
+ });
+
+ describe('filterWorkloads - `(g.x || "")` missing-field fallback arms', () => {
+ it('treats a pod with no namespace as a non-match via `(g.namespace || "")` in the k8s namespace filter', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'pod-no-ns',
+ name: 'api',
+ type: 'pod',
+ workloadType: 'pod',
+ instance: 'ctx',
+ node: 'worker',
+ contextLabel: 'ctx',
+ namespace: undefined as unknown as string,
+ status: 'running',
+ }),
+ makeGuest(2, {
+ id: 'pod-with-ns',
+ name: 'web',
+ type: 'pod',
+ workloadType: 'pod',
+ instance: 'ctx',
+ node: 'worker',
+ contextLabel: 'ctx',
+ namespace: 'payments',
+ status: 'running',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ ...baseFilterParams,
+ guests,
+ viewMode: 'pod',
+ selectedKubernetesNamespace: 'payments',
+ });
+
+ // pod-no-ns: (undefined || '').trim() === 'payments' -> '' === 'payments' -> false (dropped)
+ // pod-with-ns: kept.
+ expect(result.map((g) => g.id)).toEqual(['pod-with-ns']);
+ });
+
+ it('treats a vm with no clusterName as a non-match via `(g.clusterName || "")` in the cluster filter', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'vm-no-cluster',
+ name: 'vm-a',
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst-a',
+ node: 'node-a',
+ clusterName: undefined as unknown as string,
+ }),
+ makeGuest(2, {
+ id: 'vm-with-cluster',
+ name: 'vm-b',
+ type: 'vm',
+ workloadType: 'vm',
+ instance: 'inst-b',
+ node: 'node-b',
+ clusterName: 'prod-cluster',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ ...baseFilterParams,
+ guests,
+ viewMode: 'vm',
+ selectedCluster: 'prod-cluster',
+ });
+
+ // vm-no-cluster: (undefined || '').trim() === 'prod-cluster' -> false (dropped)
+ // vm-with-cluster: kept.
+ expect(result.map((g) => g.id)).toEqual(['vm-with-cluster']);
+ });
+
+ it('treats an app-container with no containerRuntime as a non-match via `(g.containerRuntime || "")` in the runtime filter', () => {
+ const guests = [
+ makeGuest(1, {
+ id: 'no-runtime',
+ name: 'redis',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerRuntime: undefined as unknown as string,
+ contextLabel: 'host-a',
+ node: '',
+ instance: '',
+ }),
+ makeGuest(2, {
+ id: 'with-runtime',
+ name: 'nginx',
+ type: 'app-container',
+ workloadType: 'app-container',
+ containerRuntime: 'docker',
+ contextLabel: 'host-b',
+ node: '',
+ instance: '',
+ }),
+ ];
+
+ const result = filterWorkloads({
+ ...baseFilterParams,
+ guests,
+ viewMode: 'app-container',
+ containerRuntime: 'docker',
+ });
+
+ // no-runtime: (undefined || '').trim().toLowerCase() === 'docker' -> '' === 'docker' -> false (dropped)
+ // with-runtime: kept.
+ expect(result.map((g) => g.id)).toEqual(['with-runtime']);
+ });
+ });
+
+ describe('computeWorkloadIOEmphasis - `?? 0` nullish fallback arms', () => {
+ it('coerces null network/disk telemetry to 0 on every `guest.x ?? 0` arm and blends with real values', () => {
+ const nullTelemetry = makeGuest(1, {
+ id: 'null-io',
+ name: 'null-io',
+ networkIn: null as unknown as number,
+ networkOut: null as unknown as number,
+ diskRead: null as unknown as number,
+ diskWrite: null as unknown as number,
+ });
+ const realTelemetry = makeGuest(2, {
+ id: 'real-io',
+ name: 'real-io',
+ networkIn: 10,
+ networkOut: 6,
+ diskRead: 8,
+ diskWrite: 4,
+ });
+
+ const result = computeWorkloadIOEmphasis([nullTelemetry, realTelemetry]);
+
+ // nullTelemetry contributes 0 to both facets (null ?? 0 -> 0); realTelemetry
+ // contributes network 16 and disk 12. With the two-sample distribution
+ // [0, 16] / [0, 12]: median = midpoint, mad = midpoint, max/p97/p99 = upper.
+ expect(result).toEqual({
+ network: { median: 8, mad: 8, max: 16, p97: 16, p99: 16, count: 2 },
+ diskIO: { median: 6, mad: 6, max: 12, p97: 12, p99: 12, count: 2 },
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/components/shared/__tests__/webInterfaceUrlFieldModel.branchcov0724pm.test.ts b/frontend-modern/src/components/shared/__tests__/webInterfaceUrlFieldModel.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..a8d769dc25
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/webInterfaceUrlFieldModel.branchcov0724pm.test.ts
@@ -0,0 +1,250 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getWebInterfaceSuggestedUrlFallback,
+ shouldShowWebInterfaceSuggestedDiagnostic,
+ shouldShowWebInterfaceSuggestedUrl,
+} from '@/components/shared/webInterfaceUrlFieldModel';
+
+// Branch-coverage suite for the three still-zero-hit pure helpers in
+// webInterfaceUrlFieldModel.ts (the 0712 suite covers the validation and
+// target-label helpers; these three had no direct callers in specs).
+//
+// Every assertion is a concrete equality check against the real return shape /
+// primitive so it pins the exact arm taken. Where a falsy/whitespace input is
+// passed the cast is through `unknown` to satisfy strict null checks while
+// still exercising the real runtime coercion inside the source.
+
+describe('webInterfaceUrlFieldModel.branchcov0724pm', () => {
+ describe('shouldShowWebInterfaceSuggestedDiagnostic', () => {
+ // Source:
+ // return (
+ // !options.discoveryLoading &&
+ // !normalizeWebInterfaceUrl(options.currentUrl) &&
+ // !normalizeWebInterfaceUrl(options.suggestedUrl) &&
+ // Boolean(options.suggestedUrlDiagnostic)
+ // );
+ // The diagnostic banner is the "we have nothing to suggest but we can tell
+ // the user why" state, so it only shows once discovery has settled, the
+ // user has not typed anything, and we did not find a URL — i.e. all four
+ // guards must be true.
+
+ it('returns true when every guard passes (not loading, empty current, empty suggestion, diagnostic present)', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: '',
+ suggestedUrl: '',
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(true);
+ });
+
+ it('treats omitted discoveryLoading as not-loading (`!undefined` truthy arm) and still shows the diagnostic', () => {
+ // discoveryLoading is optional; omitting it must not suppress the banner.
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ currentUrl: undefined,
+ suggestedUrl: undefined,
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(true);
+ });
+
+ it('short-circuits to false while discovery is still loading (first guard false)', () => {
+ // Even with a diagnostic and no URL, we stay quiet until loading finishes.
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: true,
+ currentUrl: '',
+ suggestedUrl: '',
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false once the user has typed a currentUrl (second guard false)', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: 'https://198.51.100.100:8006',
+ suggestedUrl: '',
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(false);
+ });
+
+ it('treats a whitespace-only currentUrl as empty and still proceeds past the second guard', () => {
+ // normalizeWebInterfaceUrl trims, so ' ' === '' for this check — the
+ // banner can still show even though the raw field contains spaces.
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: ' ',
+ suggestedUrl: '',
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(true);
+ });
+
+ it('returns false when a suggestedUrl exists (third guard false) — the suggestion card wins over the diagnostic', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: '',
+ suggestedUrl: 'https://198.51.100.100:8006',
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(false);
+ });
+
+ it('treats a whitespace-only suggestedUrl as empty and still proceeds past the third guard', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: '',
+ suggestedUrl: '\t',
+ suggestedUrlDiagnostic: 'No web port detected',
+ }),
+ ).toBe(true);
+ });
+
+ it('returns false when the diagnostic is the empty string (fourth guard false via Boolean(""))', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: '',
+ suggestedUrl: '',
+ suggestedUrlDiagnostic: '',
+ }),
+ ).toBe(false);
+ });
+
+ it('treats a whitespace-only diagnostic as present and returns true — diagnostic is NOT trimmed (Boolean(" ") is truthy)', () => {
+ // Observable divergence from currentUrl/suggestedUrl: those are run
+ // through normalizeWebInterfaceUrl (which trims) before the truthiness
+ // check, but the diagnostic is fed straight to Boolean(). A whitespace
+ // diagnostic therefore still shows. Pinned here so a future refactor
+ // that "normalizes" the diagnostic is forced to reconsider the UX.
+ expect(
+ shouldShowWebInterfaceSuggestedDiagnostic({
+ discoveryLoading: false,
+ currentUrl: '',
+ suggestedUrl: '',
+ suggestedUrlDiagnostic: ' ',
+ }),
+ ).toBe(true);
+ });
+ });
+
+ describe('shouldShowWebInterfaceSuggestedUrl', () => {
+ // Source:
+ // const suggested = normalizeWebInterfaceUrl(options.suggestedUrl);
+ // if (classifyWebInterfaceUrl(suggested).status !== 'valid') return false;
+ // return suggested !== normalizeWebInterfaceUrl(options.currentUrl);
+
+ it('returns false when there is no suggestion (classify "missing" — early-return arm)', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: '',
+ suggestedUrl: '',
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false when the suggestion does not parse as a URL (classify "invalid" — catch arm feeds the early return)', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: '',
+ suggestedUrl: 'not-a-url',
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false when the suggestion uses a non-http(s) scheme (classify "invalid" via protocol guard)', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: '',
+ suggestedUrl: 'ftp://example.com',
+ }),
+ ).toBe(false);
+ });
+
+ it('returns true when the suggestion is valid and the user has entered nothing', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: '',
+ suggestedUrl: 'https://198.51.100.100:8006',
+ }),
+ ).toBe(true);
+ });
+
+ it('returns true when the suggestion is valid and differs from the user-entered URL', () => {
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: 'https://10.0.0.5:8006',
+ suggestedUrl: 'https://198.51.100.100:8006',
+ }),
+ ).toBe(true);
+ });
+
+ it('returns false when the user has already typed exactly the suggested URL (the !== tie arm)', () => {
+ // The suggestion card would be redundant noise here, so it is hidden.
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: 'https://198.51.100.100:8006',
+ suggestedUrl: 'https://198.51.100.100:8006',
+ }),
+ ).toBe(false);
+ });
+
+ it('returns false when the current URL matches the suggestion after trimming (normalization boundary on the tie)', () => {
+ // Both sides are normalized before the comparison, so leading/trailing
+ // whitespace cannot fool the tie detector.
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: ' https://198.51.100.100:8006 ',
+ suggestedUrl: 'https://198.51.100.100:8006',
+ }),
+ ).toBe(false);
+ });
+
+ it('normalizes the suggestion before classifying, so a padded valid suggestion still counts as valid', () => {
+ // ' https://... ' → 'https://...' which is valid; then differs from
+ // the empty current URL, so the card shows.
+ expect(
+ shouldShowWebInterfaceSuggestedUrl({
+ currentUrl: '',
+ suggestedUrl: ' https://198.51.100.100:8006 ',
+ }),
+ ).toBe(true);
+ });
+ });
+
+ describe('getWebInterfaceSuggestedUrlFallback', () => {
+ // Source is a thin delegate to getDiscoverySuggestedURLFallback, which
+ // returns `{ title: 'No suggested URL available', description: diagnostic || '' }`.
+ // We assert the concrete returned object (literal title + echoed/fallback
+ // description) — never that the delegate equals its delegate.
+
+ it('returns the fixed title with the diagnostic echoed into description when a diagnostic is provided', () => {
+ expect(getWebInterfaceSuggestedUrlFallback('No web port detected')).toStrictEqual({
+ title: 'No suggested URL available',
+ description: 'No web port detected',
+ });
+ });
+
+ it('falls back to an empty description when the diagnostic is undefined (`diagnostic || ""` falsy arm)', () => {
+ expect(getWebInterfaceSuggestedUrlFallback()).toStrictEqual({
+ title: 'No suggested URL available',
+ description: '',
+ });
+ });
+
+ it('echoes a diagnostic that contains only whitespace rather than treating it as missing', () => {
+ // `diagnostic || ''` does not trim, so a whitespace diagnostic survives
+ // into description. Pinned to surface the asymmetry with the truthiness
+ // handling used by the sibling helpers.
+ expect(getWebInterfaceSuggestedUrlFallback(' ').description).toBe(' ');
+ });
+ });
+});
diff --git a/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupRecoveryModel.branchcov0724pm.test.ts b/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupRecoveryModel.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..75959b6b37
--- /dev/null
+++ b/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupRecoveryModel.branchcov0724pm.test.ts
@@ -0,0 +1,371 @@
+import { describe, expect, it } from 'vitest';
+
+import type { BackupTask, GuestSnapshot, PBSBackup, StorageBackup } from '@/types/api';
+import type { Resource } from '@/types/resource';
+
+import {
+ buildProxmoxBackupRecoveryModel,
+ coverageRowMatchesSearch,
+ recoverableArtifactMatchesSearch,
+} from '../proxmoxBackupRecoveryModel';
+
+// ---------------------------------------------------------------------------
+// Constants & helpers
+// ---------------------------------------------------------------------------
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const NOW = Date.parse('2026-07-10T00:00:00Z');
+const isoDaysAgo = (days: number): string => new Date(NOW - days * DAY_MS).toISOString();
+
+// ---------------------------------------------------------------------------
+// Fixture builders (same shapes as the sibling recovery-model test files)
+// ---------------------------------------------------------------------------
+
+const workload = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: 'vm-100',
+ type: 'vm',
+ name: 'web-01',
+ displayName: 'web-01',
+ platformId: 'pve-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'running',
+ lastSeen: NOW,
+ proxmox: { vmid: 100, node: 'node-a' },
+ ...overrides,
+ }) as Resource;
+
+const pbsBackup = (overrides: Partial<PBSBackup> = {}): PBSBackup => ({
+ id: 'pbs/main/ns1/vm/100/2026-07-09T00:00:00Z',
+ instance: 'pbs',
+ datastore: 'main',
+ namespace: 'ns1',
+ backupType: 'vm',
+ vmid: '100',
+ backupTime: '2026-07-09T00:00:00Z',
+ size: 1_000_000,
+ protected: false,
+ verified: true,
+ files: ['index.json.blob'],
+ owner: 'backup@pbs',
+ ...overrides,
+});
+
+const archive = (overrides: Partial<StorageBackup> = {}): StorageBackup => ({
+ id: 'archive-100',
+ storage: 'local',
+ node: 'node-a',
+ instance: 'inst-a',
+ type: 'ct',
+ vmid: 100,
+ time: isoDaysAgo(2),
+ ctime: 0,
+ size: 4096,
+ format: 'zst',
+ protected: false,
+ volid: 'local:backup/vzdump-lxc-100.tar.zst',
+ isPBS: false,
+ verified: false,
+ ...overrides,
+});
+
+const snapshot = (overrides: Partial<GuestSnapshot> = {}): GuestSnapshot => ({
+ id: 'snap-100',
+ name: 'pre-upgrade',
+ node: 'node-a',
+ instance: 'inst-a',
+ type: 'ct',
+ vmid: 100,
+ time: isoDaysAgo(3),
+ vmstate: false,
+ ...overrides,
+});
+
+const task = (overrides: Partial<BackupTask> = {}): BackupTask => ({
+ id: 'task-100',
+ node: 'node-a',
+ instance: 'inst-a',
+ type: 'vm',
+ vmid: 100,
+ status: 'OK',
+ startTime: isoDaysAgo(5),
+ ...overrides,
+});
+
+type ModelInput = Parameters<typeof buildProxmoxBackupRecoveryModel>[0];
+
+const buildModel = (
+ input: Partial<ModelInput>,
+): ReturnType<typeof buildProxmoxBackupRecoveryModel> =>
+ buildProxmoxBackupRecoveryModel({
+ workloads: [],
+ pbsBackups: [],
+ archives: [],
+ snapshots: [],
+ tasks: [],
+ nowMs: NOW,
+ ...input,
+ });
+
+// ---------------------------------------------------------------------------
+// archive artifact fallback chains — location / detail / verified
+// (proxmoxBackupRecoveryModel.ts lines 505, 506, 508). Existing specs always
+// supply storage, node, volid and format, and use isPBS:false, so every
+// fall-through arm of these `||` / ternary chains is uncovered.
+// ---------------------------------------------------------------------------
+
+describe('archive artifact location fallback chain (||)', () => {
+ it('falls through to archive.node when storage is blank', () => {
+ const model = buildModel({
+ archives: [archive({ id: 'a-no-storage', storage: '', node: 'arch-node' })],
+ });
+ expect(model.recoverableArtifacts[0].location).toBe('arch-node');
+ });
+
+ it('falls through to the em-dash sentinel when both storage and node are blank', () => {
+ const model = buildModel({
+ archives: [archive({ id: 'a-blank-loc', storage: '', node: '' })],
+ });
+ expect(model.recoverableArtifacts[0].location).toBe('—');
+ });
+});
+
+describe('archive artifact detail fallback chain (||)', () => {
+ it('falls through to archive.format when volid is blank', () => {
+ const model = buildModel({
+ archives: [archive({ id: 'a-no-volid', volid: '', format: 'tgz' })],
+ });
+ expect(model.recoverableArtifacts[0].detail).toBe('tgz');
+ });
+
+ it('falls through to the source fallback label when volid and format are both blank', () => {
+ const model = buildModel({
+ archives: [archive({ id: 'a-blank-detail', volid: '', format: '' })],
+ });
+ expect(model.recoverableArtifacts[0].detail).toBe('PVE backup file');
+ });
+});
+
+describe('archive artifact verified ternary (isPBS ? archive.verified : undefined)', () => {
+ it('carries the verified flag through only for PBS-backed archives', () => {
+ const model = buildModel({
+ archives: [
+ archive({ id: 'a-pbs-verified', isPBS: true, verified: true }),
+ archive({ id: 'a-pve-only', isPBS: false, verified: true }),
+ ],
+ });
+ const byId = new Map(model.recoverableArtifacts.map((a) => [a.nativeId, a]));
+ expect(byId.get('a-pbs-verified')?.verified).toBe(true);
+ // isPBS:false forces verified to undefined regardless of the raw flag.
+ expect(byId.get('a-pve-only')?.verified).toBeUndefined();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// snapshot artifact fallback chains — location / detail
+// (lines 529, 530). Existing specs always supply node and a snapshot name.
+// ---------------------------------------------------------------------------
+
+describe('snapshot artifact location fallback chain (||)', () => {
+ it('falls through to snapshot.instance when node is blank', () => {
+ const model = buildModel({
+ snapshots: [snapshot({ id: 's-no-node', node: '', instance: 'snap-inst' })],
+ });
+ expect(model.recoverableArtifacts[0].location).toBe('snap-inst');
+ });
+
+ it('falls through to the em-dash sentinel when node and instance are blank', () => {
+ const model = buildModel({
+ snapshots: [snapshot({ id: 's-blank-loc', node: '', instance: '' })],
+ });
+ expect(model.recoverableArtifacts[0].location).toBe('—');
+ });
+});
+
+describe('snapshot artifact detail fallback chain (||)', () => {
+ it('falls back to the source label when description and name are both blank', () => {
+ const model = buildModel({
+ snapshots: [snapshot({ id: 's-blank-detail', name: '', description: undefined })],
+ });
+ expect(model.recoverableArtifacts[0].detail).toBe('Guest snapshot');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// latestTask replacement comparison (line 548). Existing specs add at most one
+// task per workload, so `!row.latestTask` always short-circuits and the
+// `(candidateTask.startedMs ?? 0) > (row.latestTask.startedMs ?? 0)` comparison
+// is never evaluated. We add multiple tasks for one workload.
+// ---------------------------------------------------------------------------
+
+describe('latestTask replacement comparison', () => {
+ it('replaces the stored task when a newer one arrives for the same workload', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ tasks: [
+ task({ id: 't-old', startTime: isoDaysAgo(5) }),
+ task({ id: 't-new', startTime: isoDaysAgo(1) }),
+ ],
+ });
+ expect(model.coverageRows[0].latestTask?.id).toBe('t-new');
+ });
+
+ it('keeps the newer task when an older one arrives afterwards', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ tasks: [
+ task({ id: 't-new', startTime: isoDaysAgo(1) }),
+ task({ id: 't-old', startTime: isoDaysAgo(5) }),
+ ],
+ });
+ expect(model.coverageRows[0].latestTask?.id).toBe('t-new');
+ });
+
+ it('treats a task with an unparseable start time as epoch (0) when comparing', () => {
+ // startedMs is undefined for the garbage timestamp -> ?? 0 -> always older.
+ const model = buildModel({
+ workloads: [workload({})],
+ tasks: [
+ task({ id: 't-valid', startTime: isoDaysAgo(2) }),
+ task({ id: 't-garbage', startTime: 'not-a-date' }),
+ ],
+ });
+ expect(model.coverageRows[0].latestTask?.id).toBe('t-valid');
+ expect(model.coverageRows[0].latestTask?.startedMs).toBe(Date.parse(isoDaysAgo(2)));
+ });
+
+ it('treats the stored task as epoch (0) when its start time is unparseable', () => {
+ // The first task wins the slot with an undefined startedMs; the second
+ // task's comparison then evaluates `(row.latestTask.startedMs ?? 0)`.
+ const later = isoDaysAgo(1);
+ const model = buildModel({
+ workloads: [workload({})],
+ tasks: [
+ task({ id: 't-garbage-first', startTime: 'not-a-date' }),
+ task({ id: 't-valid-later', startTime: later }),
+ ],
+ });
+ expect(model.coverageRows[0].latestTask?.id).toBe('t-valid-later');
+ expect(model.coverageRows[0].latestTask?.startedMs).toBe(Date.parse(later));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// recoverableArtifacts sort with undefined createdMs (line 589). Existing specs
+// only ever produce artifacts with parseable timestamps, so neither `?? 0`
+// default in the sort comparator is reached.
+// ---------------------------------------------------------------------------
+
+describe('recoverableArtifacts sort with undefined createdMs', () => {
+ it('sorts a defined-createdMs artifact ahead of undefined-createdMs ones (?? 0)', () => {
+ const model = buildModel({
+ pbsBackups: [
+ pbsBackup({ id: 'pbs-real', vmid: '100', backupTime: isoDaysAgo(1) }),
+ pbsBackup({ id: 'pbs-bad-a', vmid: '100', backupTime: 'not-a-date' }),
+ pbsBackup({ id: 'pbs-bad-b', vmid: '100', backupTime: '' }),
+ ],
+ });
+ // Defined timestamp sorts first; the two undefined-createdMs artifacts
+ // compare equal (0 - 0) and retain their stable insertion order.
+ expect(model.recoverableArtifacts.map((a) => a.nativeId)).toEqual([
+ 'pbs-real',
+ 'pbs-bad-a',
+ 'pbs-bad-b',
+ ]);
+ expect(model.recoverableArtifacts[1].createdMs).toBeUndefined();
+ expect(model.recoverableArtifacts[2].createdMs).toBeUndefined();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// coverageRowMatchesSearch / recoverableArtifactMatchesSearch — uncovered arms
+// in the haystack builders: empty search term short-circuit (610, 638),
+// `nativeNodeAliases ?? []` default for fallback/orphan workloads (618, 646),
+// and the verified/protected ternary arms (653, 657).
+// ---------------------------------------------------------------------------
+
+describe('search short-circuit for an empty term', () => {
+ it('coverageRowMatchesSearch returns true for an empty or whitespace term', () => {
+ const model = buildModel({
+ workloads: [workload({})],
+ pbsBackups: [pbsBackup({ vmid: '100' })],
+ });
+ const row = model.coverageRows[0];
+ expect(coverageRowMatchesSearch(row, '')).toBe(true);
+ expect(coverageRowMatchesSearch(row, ' ')).toBe(true);
+ });
+
+ it('recoverableArtifactMatchesSearch returns true for an empty term', () => {
+ const model = buildModel({
+ pbsBackups: [pbsBackup({ vmid: '100' })],
+ });
+ expect(recoverableArtifactMatchesSearch(model.recoverableArtifacts[0], '')).toBe(true);
+ });
+});
+
+describe('search haystack handles orphan workloads whose nativeNodeAliases are undefined', () => {
+ it('matches an orphan coverage row by vmid (nativeNodeAliases ?? [])', () => {
+ // vmid 777 has no inventory guest -> fallback workload with no
+ // nativeNodeAliases field, exercising the `?? []` default.
+ const model = buildModel({
+ pbsBackups: [pbsBackup({ id: 'pbs-777', vmid: '777', backupType: 'ct' })],
+ });
+ const orphanRow = model.coverageRows[0];
+ expect(orphanRow.workload.nativeNodeAliases).toBeUndefined();
+ expect(coverageRowMatchesSearch(orphanRow, '777')).toBe(true);
+ expect(coverageRowMatchesSearch(orphanRow, 'absent-token-xyz')).toBe(false);
+ });
+
+ it('matches an orphan recoverable artifact by vmid (nativeNodeAliases ?? [])', () => {
+ const model = buildModel({
+ pbsBackups: [pbsBackup({ id: 'pbs-888', vmid: '888', backupType: 'ct' })],
+ });
+ const orphanArtifact = model.recoverableArtifacts[0];
+ expect(orphanArtifact.workload.nativeNodeAliases).toBeUndefined();
+ expect(recoverableArtifactMatchesSearch(orphanArtifact, '888')).toBe(true);
+ });
+});
+
+describe('recoverableArtifactMatchesSearch verified/protected ternary arms', () => {
+ it('exposes the "verified" token only for a verified artifact', () => {
+ const model = buildModel({
+ pbsBackups: [
+ pbsBackup({ id: 'pbs-verified', vmid: '100', verified: true }),
+ pbsBackup({ id: 'pbs-unverified', vmid: '100', verified: false }),
+ ],
+ });
+ const byId = new Map(model.recoverableArtifacts.map((a) => [a.nativeId, a]));
+ expect(recoverableArtifactMatchesSearch(byId.get('pbs-verified')!, 'verified')).toBe(true);
+ expect(recoverableArtifactMatchesSearch(byId.get('pbs-verified')!, 'unverified')).toBe(false);
+ expect(recoverableArtifactMatchesSearch(byId.get('pbs-unverified')!, 'unverified')).toBe(true);
+ });
+
+ it('matches neither verified token when the artifact verification state is unknown', () => {
+ // A snapshot artifact always has verified === undefined (neither true nor
+ // false), so the nested ternary collapses to the `undefined` arm and no
+ // verification token is added to the haystack.
+ const model = buildModel({
+ snapshots: [snapshot({ id: 'snap-unknown', vmid: 100, name: 'pre-upgrade' })],
+ });
+ const artifact = model.recoverableArtifacts[0];
+ expect(artifact.verified).toBeUndefined();
+ expect(recoverableArtifactMatchesSearch(artifact, 'verified')).toBe(false);
+ expect(recoverableArtifactMatchesSearch(artifact, 'unverified')).toBe(false);
+ // The artifact is still discoverable through other haystack fields.
+ expect(recoverableArtifactMatchesSearch(artifact, 'pre-upgrade')).toBe(true);
+ });
+
+ it('exposes the "protected" token for a protected artifact and "unprotected" otherwise', () => {
+ const model = buildModel({
+ pbsBackups: [
+ pbsBackup({ id: 'pbs-protected', vmid: '100', protected: true }),
+ pbsBackup({ id: 'pbs-open', vmid: '100', protected: false }),
+ ],
+ });
+ const byId = new Map(model.recoverableArtifacts.map((a) => [a.nativeId, a]));
+ expect(recoverableArtifactMatchesSearch(byId.get('pbs-protected')!, 'protected')).toBe(true);
+ expect(recoverableArtifactMatchesSearch(byId.get('pbs-protected')!, 'unprotected')).toBe(false);
+ expect(recoverableArtifactMatchesSearch(byId.get('pbs-open')!, 'unprotected')).toBe(true);
+ });
+});
diff --git a/frontend-modern/src/features/standalone/__tests__/agentMachineTableModel.branchcov0724pm.test.ts b/frontend-modern/src/features/standalone/__tests__/agentMachineTableModel.branchcov0724pm.test.ts
new file mode 100644
index 0000000000..97485a9bf1
--- /dev/null
+++ b/frontend-modern/src/features/standalone/__tests__/agentMachineTableModel.branchcov0724pm.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it } from 'vitest';
+import type { HostRAIDArray } from '@/types/api';
+import type { Resource } from '@/types/resource';
+import {
+ getAgentMachineRaidArrayDetails,
+ matchesAgentMachineSearch,
+ sortAgentMachines,
+} from '../agentMachineTableModel';
+
+const resource = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: overrides.id ?? 'machine-1',
+ name: overrides.name ?? overrides.id ?? 'machine-1',
+ displayName: overrides.displayName ?? overrides.name ?? overrides.id ?? 'machine-1',
+ type: 'agent',
+ platformId: 'agent',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+ }) as Resource;
+
+const noopLabel = () => '';
+
+describe('agentMachineTableModel branch coverage 0724pm', () => {
+ describe('matchesAgentMachineSearch — canonicalIdentity optional-chain defined arm', () => {
+ it('indexes canonical hostname, primaryId, and aliases when canonicalIdentity is present', () => {
+ // Note: displayName and platformId are seeded in the fixture below but
+ // are never searched for, so only hostname, primaryId, and aliases are
+ // actually asserted — not "every" canonical identity field.
+ const machine = resource({
+ canonicalIdentity: {
+ displayName: 'Canonical Display',
+ hostname: 'canonical-host',
+ platformId: 'canonical-platform',
+ primaryId: 'canonical-primary',
+ aliases: ['alias-one'],
+ },
+ });
+
+ expect(matchesAgentMachineSearch(machine, 'canonical-host', noopLabel, noopLabel)).toBe(true);
+ expect(matchesAgentMachineSearch(machine, 'canonical-primary', noopLabel, noopLabel)).toBe(
+ true,
+ );
+ expect(matchesAgentMachineSearch(machine, 'alias-one', noopLabel, noopLabel)).toBe(true);
+ expect(matchesAgentMachineSearch(machine, 'never-present', noopLabel, noopLabel)).toBe(false);
+ });
+ });
+
+ describe('matchesAgentMachineSearch — sensorSearchValues non-standby arm', () => {
+ it('emits no standby token for SMART disks that are actively reporting', () => {
+ const machine = resource({
+ agent: {
+ sensors: {
+ smart: [{ device: '/dev/nvme0', temperature: 41 }],
+ },
+ },
+ });
+
+ // The active disk identifier is searchable...
+ expect(matchesAgentMachineSearch(machine, '/dev/nvme0', noopLabel, noopLabel)).toBe(true);
+ // ...but the "standby" sentinel is not emitted for an active disk.
+ expect(matchesAgentMachineSearch(machine, 'standby', noopLabel, noopLabel)).toBe(false);
+ });
+ });
+
+ describe('getAgentMachineRaidArrayDetails — device fallback arms', () => {
+ it('falls back to an empty device list when an array omits the devices field', () => {
+ // Note: raw object deliberately lacks `devices` to exercise `devices ?? []`.
+ const details = getAgentMachineRaidArrayDetails(
+ resource({
+ agent: {
+ raid: [{ device: '/dev/md0', state: 'clean' } as unknown as HostRAIDArray],
+ },
+ }),
+ );
+
+ expect(details).toHaveLength(1);
+ expect(details[0]?.device).toBe('/dev/md0');
+ expect(details[0]?.devices).toEqual([]);
+ });
+
+ it('falls back the device slot to its index when slot is absent but the device is named', () => {
+ const details = getAgentMachineRaidArrayDetails(
+ resource({
+ agent: {
+ raid: [
+ {
+ device: '/dev/md0',
+ state: 'clean',
+ devices: [{ device: '/dev/sda', state: 'active' }],
+ } as unknown as HostRAIDArray,
+ ],
+ },
+ }),
+ );
+
+ // slot is undefined but the device is retained (named), so the index (0) is used.
+ expect(details[0]?.devices).toEqual([{ device: '/dev/sda', state: 'active', slot: 0 }]);
+ });
+ });
+
+ describe('sortAgentMachines — compareNullableNumber tie (both missing)', () => {
+ it('treats two metric-less machines as equal and falls back to the name tiebreaker', () => {
+ const sorted = sortAgentMachines(
+ [resource({ id: 'beta', name: 'Beta' }), resource({ id: 'alpha', name: 'Alpha' })],
+ 'cpu',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ // Neither machine has a CPU metric; compareNullableNumber returns 0 (both
+ // undefined), so the ascending name tiebreaker decides the order.
+ expect(sorted.map((m) => m.id)).toEqual(['alpha', 'beta']);
+ });
+ });
+
+ describe('sortAgentMachines — compareText nullable operands', () => {
+ it('pushes machines missing architecture below the defined one using the empty-string fallback', () => {
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'noarch-b', name: 'NoArchB' }),
+ resource({ id: 'x86', agent: { architecture: 'x86_64' } }),
+ resource({ id: 'noarch-a', name: 'NoArchA' }),
+ ],
+ 'arch',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ // The defined architecture sorts first; the two undefined ones fall back to
+ // '' and are pushed to the bottom, tie-broken by name ascending.
+ expect(sorted.map((m) => m.id)).toEqual(['x86', 'noarch-a', 'noarch-b']);
+ });
+
+ it('pushes a machine missing kernelVersion below one that defines it (direction-independent: the empty-value guard short-circuits before desc applies)', () => {
+ // compareText returns 1 / -1 from the `!leftValue` / `!rightValue` guards
+ // before the `direction` flag is ever consulted, so the 'desc' branch
+ // (`-result`) is unreachable for this fixture. The assertion pins the
+ // empty-value push-down only; it does NOT exercise descending order.
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'nokernel-a' }),
+ resource({ id: 'kernel', agent: { kernelVersion: '6.6' } }),
+ ],
+ 'kernel',
+ 'desc',
+ noopLabel,
+ noopLabel,
+ );
+
+ expect(sorted.map((m) => m.id)).toEqual(['kernel', 'nokernel-a']);
+ });
+ });
+
+ describe('sortAgentMachines — uptime optional-chain arms on both operands', () => {
+ it('resolves agent-reported uptime and pushes fully-missing machines below it', () => {
+ // A mix forces the comparator to evaluate `uptime ?? agent?.uptimeSeconds` on
+ // both the left and right operands, in both the agent-defined and
+ // agent-absent arms of the optional chain.
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'none-1' }),
+ resource({ id: 'reported-1', agent: { uptimeSeconds: 1_000 } }),
+ resource({ id: 'direct', uptime: 100_000 }),
+ resource({ id: 'none-2' }),
+ resource({ id: 'reported-2', agent: { uptimeSeconds: 5_000 } }),
+ ],
+ 'uptime',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ // reported-1 (1000) < reported-2 (5000) < direct (100000); the two fully-missing
+ // machines fall to the bottom, tie-broken by id ascending.
+ expect(sorted.map((m) => m.id)).toEqual([
+ 'reported-1',
+ 'reported-2',
+ 'direct',
+ 'none-1',
+ 'none-2',
+ ]);
+ });
+ });
+
+ describe('sortAgentMachines — name fallback || chains', () => {
+ it('resolves labels through the name fallback in the primary name sort', () => {
+ // Empty displayName but set name → inner `displayName || name` falls to name.
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'id-1', name: 'gamma', displayName: '' }),
+ resource({ id: 'id-2', name: 'alpha', displayName: '' }),
+ resource({ id: 'id-3', name: 'echo', displayName: '' }),
+ ],
+ 'name',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ expect(sorted.map((m) => m.id)).toEqual(['id-2', 'id-3', 'id-1']);
+ });
+
+ it('resolves labels through the id fallback when both displayName and name are empty', () => {
+ // Empty displayName AND empty name → outer `(... || name) || id` falls to id,
+ // exercised on both comparator operands across the multi-element sort.
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'charlie', name: '', displayName: '' }),
+ resource({ id: 'alpha', name: '', displayName: '' }),
+ resource({ id: 'bravo', name: '', displayName: '' }),
+ ],
+ 'name',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ expect(sorted.map((m) => m.id)).toEqual(['alpha', 'bravo', 'charlie']);
+ });
+
+ it('uses the name fallback in the ascending tiebreaker when primary sort values tie', () => {
+ // Equal CPU forces the tiebreaker; empty displayName routes through `name`.
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'tie-1', name: 'zulu', displayName: '', cpu: { current: 50 } }),
+ resource({ id: 'tie-2', name: 'mike', displayName: '', cpu: { current: 50 } }),
+ resource({ id: 'tie-3', name: 'alfa', displayName: '', cpu: { current: 50 } }),
+ ],
+ 'cpu',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ expect(sorted.map((m) => m.id)).toEqual(['tie-3', 'tie-2', 'tie-1']);
+ });
+
+ it('uses the id fallback in the tiebreaker when both displayName and name are empty', () => {
+ // Equal CPU forces the tiebreaker; empty displayName AND name route through `id`.
+ const sorted = sortAgentMachines(
+ [
+ resource({ id: 'tie-charlie', name: '', displayName: '', cpu: { current: 50 } }),
+ resource({ id: 'tie-alpha', name: '', displayName: '', cpu: { current: 50 } }),
+ resource({ id: 'tie-bravo', name: '', displayName: '', cpu: { current: 50 } }),
+ ],
+ 'cpu',
+ 'asc',
+ noopLabel,
+ noopLabel,
+ );
+
+ expect(sorted.map((m) => m.id)).toEqual(['tie-alpha', 'tie-bravo', 'tie-charlie']);
+ });
+ });
+});