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
test(coverage): harvest 20 stranded branch-coverage tests from 13:30 wave
rcourtmanabcf7ec6ba28
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsFeatureGates.branchcov0712c.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsFeatureGates.branchcov0712c.test.tsnew file mode 100644index 0000000000..c314643c42--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/settingsFeatureGates.branchcov0712c.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it } from 'vitest';+import type { SettingsTab } from '../settingsNavigationModel';+import { isTabLocked, tabFeatureRequirements } from '../settingsFeatureGates';++// ---- Helpers ---------------------------------------------------------------+// Mirrors the `hasFeatures` factory used by the sibling+// `settingsNavigation.integration.test.tsx` and `settingsRouting.test.ts` so the+// invocation pattern and predicate semantics stay consistent across the suite.++const hasFeatures =+ (features: string[]) =>+ (feature: string): boolean =>+ features.includes(feature);++// The complete set of tabs that carry feature requirements in+// `tabFeatureRequirements`. Driving every entry guarantees the+// `tabFeatureRequirements[tab]` lookup -> defined-array arm is exercised for+// each key, not just a representative sample.+const allGatedTabs = Object.entries(tabFeatureRequirements) as Array<+ [SettingsTab, string[]]+>;++// A spread of real catalog tabs that are intentionally ABSENT from+// `tabFeatureRequirements`; each must resolve to `undefined` on lookup and+// therefore never lock, regardless of feature/runtime state.+const nonGatedTabs: SettingsTab[] = [+ 'infrastructure-systems',+ 'system-general',+ 'system-network',+ 'api',+ 'support-diagnostics',+ 'security-overview',+];++// ---- isTabLocked: tab NOT present in tabFeatureRequirements ---------------+// `tabFeatureRequirements[tab]` yields `undefined`, which is forwarded to+// `isFeatureLocked` and trips the `!features` arm of its first guard+// (`if (!features || features.length === 0) return false;`).++describe('isTabLocked - tab absent from tabFeatureRequirements (lookup -> undefined)', () => {+ it.each(nonGatedTabs)(+ 'never locks %s even when runtime is loaded and no features are held',+ (tab) => {+ expect(isTabLocked(tab, hasFeatures([]), () => true)).toBe(false);+ },+ );++ it('never locks a non-gated tab while runtime capabilities are unloaded', () => {+ expect(isTabLocked('system-general', hasFeatures([]), () => false)).toBe(false);+ });++ it('never locks a non-gated tab even when every feature flag is held', () => {+ // Ensures the `undefined` short-circuit wins over a permissive hasFeature.+ expect(+ isTabLocked(+ 'api',+ () => true,+ () => true,+ ),+ ).toBe(false);+ });+});++// ---- isTabLocked: tab present, runtime NOT loaded -------------------------+// `isFeatureLocked` second guard: `if (!runtimeCapabilitiesLoaded()) return false;`+// A tab with real requirements stays unlocked while license state is unresolved+// so the UI does not flash lock UI before capabilities are known.++describe('isTabLocked - gated tab while runtime capabilities are unloaded', () => {+ it.each(allGatedTabs)(+ 'does not lock %s (requires %s) before runtime capabilities load, even with no features',+ (tab, _required) => {+ expect(isTabLocked(tab, hasFeatures([]), () => false)).toBe(false);+ },+ );++ it('does not lock a gated tab when the required feature is held but runtime is unloaded', () => {+ // runtime-not-loaded guard must fire BEFORE the feature check, so holding the+ // feature must not change the outcome here.+ expect(isTabLocked('system-relay', hasFeatures(['relay']), () => false)).toBe(false);+ });+});++// ---- isTabLocked: tab present, runtime loaded, features all present -------+// `isFeatureLocked` reaches `return !features.every(hasFeature)` with every() -> true,+// yielding `!true === false` (unlocked).++describe('isTabLocked - gated tab unlocked by holding every required feature', () => {+ it.each(allGatedTabs)(+ 'does not lock %s when all required features (%s) are present and runtime is loaded',+ (tab, required) => {+ expect(isTabLocked(tab, hasFeatures(required), () => true)).toBe(false);+ },+ );++ it('stays unlocked when the hasFeature predicate grants features broadly', () => {+ // A permissive predicate still satisfies every() -> true -> unlocked.+ expect(+ isTabLocked(+ 'organization-overview',+ () => true,+ () => true,+ ),+ ).toBe(false);+ });+});++// ---- isTabLocked: tab present, runtime loaded, a required feature missing --+// `isFeatureLocked` reaches `return !features.every(hasFeature)` with every() -> false,+// yielding `!false === true` (LOCKED). This is the only branch that returns true.++describe('isTabLocked - gated tab locks when a required feature is missing', () => {+ it.each(allGatedTabs)(+ 'locks %s when none of the required features (%s) are held and runtime is loaded',+ (tab, _required) => {+ expect(isTabLocked(tab, hasFeatures([]), () => true)).toBe(true);+ },+ );++ it('locks even when an unrelated feature is held (every() -> false on partial match)', () => {+ // system-relay requires ['relay']; granting a different feature must NOT+ // satisfy the every() predicate -> locked.+ expect(isTabLocked('system-relay', hasFeatures(['multi_tenant']), () => true)).toBe(true);+ });++ it('locks when the held feature is a proper superset that omits the required key', () => {+ // security-webhooks requires ['audit_logging']; holding only 'relay' leaves+ // every() -> false -> locked. Pins the single-element every() false arm.+ expect(isTabLocked('security-webhooks', hasFeatures(['relay']), () => true)).toBe(true);+ });++ it('locks an organization tab when multi_tenant is missing despite other org features', () => {+ // organization-billing requires ['multi_tenant']; the presence of unrelated+ // features must not unlock it.+ expect(+ isTabLocked('organization-billing', hasFeatures(['audit_logging', 'relay']), () => true),+ ).toBe(true);+ });+});++// ---- isTabLocked: explicit per-key contract over the whole requirements map+// Pins the exact (tab -> required feature -> lock outcome) mapping so a future+// edit to `tabFeatureRequirements` cannot silently change lock behavior.++describe('isTabLocked - full tabFeatureRequirements contract', () => {+ // Source-of-truth snapshot of the requirements map; if this drifts the test+ // fails loudly, which is the point.+ const expectedMap: Partial<Record<SettingsTab, string[]>> = {+ 'system-relay': ['relay'],+ 'security-webhooks': ['audit_logging'],+ 'organization-overview': ['multi_tenant'],+ 'organization-access': ['multi_tenant'],+ 'organization-sharing': ['multi_tenant'],+ 'organization-billing': ['multi_tenant'],+ 'organization-billing-admin': ['multi_tenant'],+ };++ it('tabFeatureRequirements matches the expected snapshot', () => {+ expect(tabFeatureRequirements).toStrictEqual(expectedMap);+ });++ it.each(allGatedTabs)(+ '%s is locked iff its single required feature is absent (runtime loaded)',+ (tab, required) => {+ // LOCKED arm: every() -> false.+ expect(isTabLocked(tab, hasFeatures([]), () => true)).toBe(true);+ // UNLOCKED arm: every() -> true.+ expect(isTabLocked(tab, hasFeatures(required), () => true)).toBe(false);+ // UNLOADED arm: runtime guard returns false regardless of features.+ expect(isTabLocked(tab, hasFeatures(required), () => false)).toBe(false);+ },+ );+});++// ---- isTabLocked: defensive input shape -----------------------------------+// `isTabLocked` accepts any SettingsTab; a deliberately-cast tab that is not in+// the map exercises the `undefined` lookup path through a non-literal input,+// confirming no throw and a concrete `false` result.++describe('isTabLocked - defensive behavior for out-of-map tabs', () => {+ it('returns false for a cast tab id absent from tabFeatureRequirements', () => {+ const unknownTab = 'totally-not-a-real-tab' as unknown as SettingsTab;+ expect(isTabLocked(unknownTab, hasFeatures([]), () => true)).toBe(false);+ // Also confirm the runtime-unloaded path is equally safe.+ expect(isTabLocked(unknownTab, () => true, () => false)).toBe(false);+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/updatesSettingsModel.branchcov0712c.test.ts b/frontend-modern/src/components/Settings/__tests__/updatesSettingsModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..a5f198a3be--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/updatesSettingsModel.branchcov0712c.test.ts@@ -0,0 +1,323 @@+/**+ * Additional branch-coverage tests for buildUpdateInstallGuide in+ * updatesSettingsModel. This file is deliberately complementary to the sibling+ * updatesSettingsModel.branchcov0712.test.ts: it targets semantic branches that+ * the sibling does not exercise (optional-chain short-circuits on nullish+ * `updateInfo`, isProRuntime/dockerUpdate precedence, the docker OR's first+ * operand alone, the `(!deploymentType && isDocker)` fallback routed through the+ * community and pro-unavailable sub-arms, template-literal interpolation edges,+ * and a malformed-plan cast). v8's branch counter is coarse and reports these as+ * covered via neighbouring cases; the tests below pin the distinct runtime paths+ * and their concrete outputs.+ */+import { describe, expect, it } from 'vitest';+import { buildUpdateInstallGuide } from '../updatesSettingsModel';+import type {+ DockerUpdateCommands,+ UpdateInfo,+ UpdatePlan,+ VersionInfo,+} from '@/api/updates';++// ---- Fixtures ---------------------------------------------------------------+// Mirror the shapes used by the sibling branchcov0712 file so the two stay+// consistent. The model only consumes narrow Picks of these types.++type VersionInfoPick = Pick<VersionInfo, 'deploymentType' | 'isDocker'>;+type UpdateInfoPick = Pick<UpdateInfo, 'latestVersion' | 'dockerUpdate'>;+type UpdatePlanPick = Pick<UpdatePlan, 'canAutoUpdate'>;++const makeVersionInfo = (overrides: Partial<VersionInfoPick> = {}): VersionInfoPick => ({+ deploymentType: 'systemd',+ isDocker: false,+ ...overrides,+});++const makeUpdateInfo = (overrides: Partial<UpdateInfoPick> = {}): UpdateInfoPick => ({+ latestVersion: 'v6.0.5',+ ...overrides,+});++const makeUpdatePlan = (overrides: Partial<UpdatePlanPick> = {}): UpdatePlanPick => ({+ canAutoUpdate: false,+ ...overrides,+});++const digest = 'sha256:' + 'ab'.repeat(32);+const pinnedRef = `registry.pulserelay.pro/pulse/pulse-pro@${digest}`;+const makeDockerUpdate = (+ overrides: Partial<DockerUpdateCommands> = {},+): DockerUpdateCommands => ({+ version: 'v6.0.5',+ image: 'registry.pulserelay.pro/pulse/pulse-pro',+ imageDigest: digest,+ loginCommand:+ "printf '%s' '<activation-key>' | docker login registry.pulserelay.pro -u 'lic_test' --password-stdin",+ composePullCommand: `PULSE_IMAGE='${pinnedRef}' docker compose pull`,+ composeUpCommand: `PULSE_IMAGE='${pinnedRef}' docker compose up -d`,+ ...overrides,+});++const PRO_STEP_CODE_CLASS =+ 'block rounded-md border border-border bg-base p-3 font-mono text-sm text-green-400 whitespace-pre-wrap break-all';++// ---- buildUpdateInstallGuide (complementary branch-coverage) ----------------++describe('buildUpdateInstallGuide — optional-chain short-circuit on nullish updateInfo', () => {+ // The sibling tests always pass a *present* updateInfo object (setting+ // dockerUpdate: undefined). These two tests drive the `updateInfo?.dockerUpdate`+ // optional-chain short-circuit by passing nullish updateInfo itself, which+ // routes the docker arm to the community and pro-unavailable sub-branches+ // respectively and also short-circuits `updateInfo?.latestVersion`.++ it('short-circuits updateInfo?.dockerUpdate to falsy when updateInfo is null, routing to community guidance (not pro) and interpolating "undefined" into headerSummary', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),+ null,+ makeUpdatePlan({ canAutoUpdate: false }),+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide?.headerSummary).toBe('Version undefined is ready to install');+ expect(guide?.introText).toBe('Follow these steps to update manually:');+ expect(guide?.steps).toHaveLength(2);+ expect(guide?.steps[0]).toStrictEqual({+ id: 'docker-compose-update',+ title: 'Pull the new image and recreate the container',+ command: 'docker compose pull && docker compose up -d',+ });+ expect(guide?.steps[1]?.id).toBe('docker-manual-note');+ });++ it('short-circuits updateInfo?.dockerUpdate to falsy when updateInfo is undefined, routing to the pro-unavailable notice when isProRuntime is true', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),+ undefined,+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ true,+ );+ expect(guide?.headerSummary).toBe('Version undefined is ready to install');+ expect(guide?.introText).toBe('Follow these steps to update:');+ expect(guide?.steps).toHaveLength(1);+ expect(guide?.steps[0]?.id).toBe('docker-pro-unavailable');+ expect(guide?.steps[0]?.note).toContain('license server did not provide Docker update commands');+ });+});++describe('buildUpdateInstallGuide — isProRuntime / dockerUpdate precedence', () => {+ // The sibling dockerUpdate-present tests all pass isProRuntime: false. This+ // pins that dockerUpdate takes precedence over isProRuntime: when both are+ // truthy, the digest-pinned pro steps win and the pro-unavailable notice is+ // never reached.++ it('prefers digest-pinned pro docker steps over the isProRuntime notice when both dockerUpdate and isProRuntime are truthy', () => {+ const dockerUpdate = makeDockerUpdate();+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),+ makeUpdateInfo({ dockerUpdate }),+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ true,+ );+ expect(guide?.introText).toBe('Run these two commands on the Docker host to update:');+ expect(guide?.steps[0]).toStrictEqual({+ id: 'docker-pro-pull',+ title: 'Pull the new Pulse Pro image (pinned to this release\u2019s digest)',+ command: dockerUpdate.composePullCommand,+ commandCodeClass: PRO_STEP_CODE_CLASS,+ });+ expect(guide?.steps[1]?.id).toBe('docker-pro-up');+ expect(guide?.steps.some((s) => s.id === 'docker-pro-unavailable')).toBe(false);+ });+});++describe('buildUpdateInstallGuide — docker OR operand coverage', () => {+ // The sibling docker-arm tests always set isDocker: true alongside+ // deploymentType: 'docker'. This exercises the first OR operand being true on+ // its own (the second operand is not evaluated), confirming the arm is entered+ // regardless of isDocker when deploymentType is explicitly 'docker'.++ it('enters the docker arm via deploymentType==="docker" even when isDocker is false (first OR operand true, second not evaluated)', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: false }),+ makeUpdateInfo({ dockerUpdate: undefined }),+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide).not.toBeNull();+ expect(guide?.steps[0]?.id).toBe('docker-compose-update');+ });++ // The sibling fallback test (deploymentType undefined + isDocker true) only+ // routes through the dockerUpdate-present sub-arm. These two tests route the+ // fallback through the community and pro-unavailable sub-arms respectively.++ it('routes the (!deploymentType && isDocker) fallback to community guidance when not pro and no dockerUpdate', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: undefined, isDocker: true }),+ makeUpdateInfo({ dockerUpdate: undefined }),+ makeUpdatePlan(),+ 'v9.9.9',+ 'curl',+ false,+ );+ // headerSummary comes from updateInfo.latestVersion, not dockerImageTag.+ expect(guide?.headerSummary).toBe('Version v6.0.5 is ready to install');+ expect(guide?.steps[0]?.id).toBe('docker-compose-update');+ // dockerImageTag 'v9.9.9' is interpolated into the non-compose note.+ expect(guide?.steps[1]?.note).toContain('docker pull rcourtman/pulse:v9.9.9');+ });++ it('routes the (!deploymentType && isDocker) fallback to the pro-unavailable notice when isProRuntime and no dockerUpdate', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: undefined, isDocker: true }),+ makeUpdateInfo({ dockerUpdate: undefined }),+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ true,+ );+ expect(guide?.introText).toBe('Follow these steps to update:');+ expect(guide?.steps[0]?.id).toBe('docker-pro-unavailable');+ });+});++describe('buildUpdateInstallGuide — headerSummary interpolation for nullish updateInfo across arms', () => {+ // The sibling "Version undefined" test only covers the proxmox arm with null+ // updateInfo. These pin the same short-circuit behaviour (updateInfo?.latestVersion+ // -> undefined) for undefined updateInfo in the systemd and development arms,+ // and for null updateInfo in the docker community arm.++ it('interpolates "undefined" into headerSummary for the systemd arm when updateInfo is undefined', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'systemd' }),+ undefined,+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl -fsSL https://example.invalid/pulse.tar.gz',+ false,+ );+ expect(guide?.headerSummary).toBe('Version undefined is ready to install');+ // The systemd steps are still produced in full.+ expect(guide?.steps.map((s) => s.id)).toStrictEqual([+ 'systemd-stop',+ 'systemd-download',+ 'systemd-start',+ ]);+ });++ it('interpolates "undefined" into headerSummary for the development arm when updateInfo is null', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'development' }),+ null,+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide?.headerSummary).toBe('Version undefined is ready to install');+ expect(guide?.steps.map((s) => s.id)).toStrictEqual([+ 'development-pull',+ 'development-build',+ ]);+ });+});++describe('buildUpdateInstallGuide — template-literal and malformed-input edges', () => {+ // dockerImageTag is interpolated verbatim into the community note. An empty+ // tag still renders a well-formed (if odd) command string; this pins the+ // template-literal interpolation branch.+ it('interpolates an empty dockerImageTag into the community note (template-literal edge)', () => {+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),+ makeUpdateInfo({ dockerUpdate: undefined }),+ makeUpdatePlan(),+ '',+ 'curl',+ false,+ );+ expect(guide?.steps[1]?.note).toContain('docker pull rcourtman/pulse:');+ // No trailing version text after the colon.+ expect(guide?.steps[1]?.note).toMatch(/docker pull rcourtman\/pulse:,/);+ });++ // A present updateInfo whose latestVersion is absent cannot be expressed+ // through the typed UpdateInfoPick (latestVersion is required), so cast a+ // malformed object to exercise the same interpolation path via a distinct+ // runtime shape.+ it('interpolates "undefined" into headerSummary when updateInfo is present but latestVersion is missing (cast malformed updateInfo)', () => {+ const malformedUpdateInfo = {+ dockerUpdate: undefined,+ } as unknown as Parameters<typeof buildUpdateInstallGuide>[1];+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'systemd' }),+ malformedUpdateInfo,+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide?.headerSummary).toBe('Version undefined is ready to install');+ });++ // updatePlan.canAutoUpdate is a required boolean on the Pick; an undefined+ // value (malformed via cast) must still take the ternary falsy arm.+ it('uses the manual-only intro when updatePlan.canAutoUpdate is undefined (cast malformed plan -> ternary falsy arm)', () => {+ const malformedPlan = {+ canAutoUpdate: undefined,+ } as unknown as UpdatePlanPick;+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'systemd' }),+ makeUpdateInfo(),+ malformedPlan,+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide?.introText).toBe('Follow these steps to update manually:');+ });+});++describe('buildUpdateInstallGuide — buildProDockerUpdateSteps loginCommand falsy variants', () => {+ // The sibling test covers loginCommand undefined (falsy). An empty-string+ // loginCommand is also falsy but a distinct runtime value, and a non-empty+ // loginCommand is truthy. These pin both falsy variants' concrete outputs.++ it('omits the login note when loginCommand is an empty string (falsy empty-string arm)', () => {+ const dockerUpdate = makeDockerUpdate({ loginCommand: '' });+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),+ makeUpdateInfo({ dockerUpdate }),+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide?.steps).toHaveLength(2);+ expect(guide?.steps.map((s) => s.id)).toStrictEqual(['docker-pro-pull', 'docker-pro-up']);+ });++ it('includes the login note with the exact interpolated command when loginCommand is a non-empty custom string', () => {+ const customLogin = 'echo hunter2 | docker login registry.example.invalid -u ops --password-stdin';+ const dockerUpdate = makeDockerUpdate({ loginCommand: customLogin });+ const guide = buildUpdateInstallGuide(+ makeVersionInfo({ deploymentType: 'docker', isDocker: true }),+ makeUpdateInfo({ dockerUpdate }),+ makeUpdatePlan(),+ 'v6.0.5',+ 'curl',+ false,+ );+ expect(guide?.steps).toHaveLength(3);+ expect(guide?.steps[2]?.id).toBe('docker-pro-login-note');+ expect(guide?.steps[2]?.note).toBe(+ `If the pull is denied, sign in to the registry first (replace <activation-key> with the key from Settings \u2192 License): ${customLogin}`,+ );+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/diskListModel.branchcov0712c.test.ts b/frontend-modern/src/components/Workloads/__tests__/diskListModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..dceedefe2c--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/diskListModel.branchcov0712c.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import type { Disk } from '@/types/api';++import { getWorkloadsDiskUsageText } from '../diskListModel';++// getWorkloadsDiskUsageText is a single ternary delegating to+// hasWorkloadsDiskCapacity, which itself branches on+// `typeof disk.total === 'number' && disk.total > 0`. Each test below pins a+// concrete branch outcome (true arm formats used/total bytes; false arm returns+// the fixed 'Usage unavailable' copy) with exact string assertions.++const makeDisk = (overrides: Partial<Disk> = {}): Disk => ({+ total: 100,+ used: 25,+ free: 75,+ usage: 25,+ mountpoint: '/',+ type: 'ext4',+ device: '/dev/sda1',+ ...overrides,+});++describe('diskListModel.getWorkloadsDiskUsageText (branch coverage 0712c)', () => {+ describe('true arm: hasWorkloadsDiskCapacity(disk) is true (total is a positive number)', () => {+ it('formats "used/total" bytes with auto precision for both operands', () => {+ // hasWorkloadsDiskCapacity true (total 100 > 0) -> true arm.+ // formatBytes(25) = '25.0 B' (value 25 -> 1 decimal)+ // formatBytes(100) = '100 B' (value 100 -> 0 decimals)+ expect(getWorkloadsDiskUsageText(makeDisk({ used: 25, total: 100 }))).toBe('25.0 B/100 B');+ });++ it('renders 0 used bytes via the formatBytes(!bytes) early return, keeping the true arm', () => {+ // total 200 > 0 -> true arm; used 0 -> formatBytes(0) early-returns '0 B'.+ // formatBytes(200) = '200 B' (value >= 100 -> 0 decimals).+ expect(getWorkloadsDiskUsageText(makeDisk({ used: 0, total: 200 }))).toBe('0 B/200 B');+ });++ it('formats fractional sub-10 values with 2 decimals on the true arm', () => {+ // total 1024 > 0 -> true arm.+ // formatBytes(5) = '5.00 B' (value < 10 -> 2 decimals).+ // formatBytes(1024): i = floor(log(1024)/log(1024)) = 1, value = 1 (<10) -> '1.00 KB'.+ expect(getWorkloadsDiskUsageText(makeDisk({ used: 5, total: 1024 }))).toBe('5.00 B/1.00 KB');+ });+ });++ describe('false arm: hasWorkloadsDiskCapacity(disk) is false -> "Usage unavailable"', () => {+ it('returns the unavailable copy when total === 0 (total not > 0)', () => {+ // typeof total === 'number' true, but total > 0 false -> hasWorkloadsDiskCapacity false.+ expect(getWorkloadsDiskUsageText(makeDisk({ total: 0, used: 0, free: 0 }))).toBe(+ 'Usage unavailable',+ );+ });++ it('returns the unavailable copy when total is a negative number', () => {+ // typeof total === 'number' true, total > 0 false (-5) -> false arm.+ expect(getWorkloadsDiskUsageText(makeDisk({ total: -5, used: 0, free: 0 }))).toBe(+ 'Usage unavailable',+ );+ });++ it('returns the unavailable copy when total is not a number (typeof guard fails)', () => {+ // Defensive branch: a Disk whose total is undefined at runtime. The+ // typeof check inside hasWorkloadsDiskCapacity short-circuits before the+ // total > 0 comparison, so formatBytes is never called (no NaN output).+ // Disk.total is typed `number`, so the undefined value needs a cast.+ const disk = { total: undefined, used: 25, free: 75, usage: 25 } as unknown as Disk;+ expect(getWorkloadsDiskUsageText(disk)).toBe('Usage unavailable');+ });+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/guestDrawerModel.branchcov0712c.test.ts b/frontend-modern/src/components/Workloads/__tests__/guestDrawerModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..508308c9a4--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/guestDrawerModel.branchcov0712c.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest';++import { normalizeGuestDrawerTags } from '../guestDrawerModel';++// `normalizeGuestDrawerTags` narrows `Guest['tags']` (`string[] | string | null`).+// These tests deliberately drive both arms of every conditional in the body:+// 1. the `Array.isArray(tags)` branch (map -> trim, filter -> length > 0)+// 2. the `typeof tags === 'string'` branch (split -> trim, filter -> length > 0)+// 3. the terminal `return []` fallback (neither array nor string)+// A few inputs are deliberately outside the declared union (undefined / number)+// to exercise the defensive fallback; they are cast through `unknown` to satisfy+// strict null checks under the real tsconfig.+type TagsArg = Parameters<typeof normalizeGuestDrawerTags>[0];++describe('normalizeGuestDrawerTags', () => {+ describe('array input (Array.isArray branch)', () => {+ it('trims leading/trailing whitespace from each tag', () => {+ expect(normalizeGuestDrawerTags([' hello ', '\tworld\n'])).toStrictEqual([+ 'hello',+ 'world',+ ]);+ });++ it('preserves internal spacing because only the ends are trimmed', () => {+ expect(normalizeGuestDrawerTags(['web server', ' db primary '])).toStrictEqual([+ 'web server',+ 'db primary',+ ]);+ });++ it('keeps tags that are non-empty after trimming (filter length > 0 true arm)', () => {+ expect(normalizeGuestDrawerTags(['a', 'b', 'c'])).toStrictEqual(['a', 'b', 'c']);+ });++ it('drops empty-string tags (filter length > 0 false arm)', () => {+ expect(normalizeGuestDrawerTags(['a', '', 'b'])).toStrictEqual(['a', 'b']);+ });++ it('drops whitespace-only tags because trim yields an empty string', () => {+ expect(normalizeGuestDrawerTags(['a', ' ', '\t', 'b'])).toStrictEqual(['a', 'b']);+ });++ it('preserves the original order of the surviving tags', () => {+ expect(normalizeGuestDrawerTags([' c ', '', ' a ', ' b '])).toStrictEqual([+ 'c',+ 'a',+ 'b',+ ]);+ });++ it('returns an empty array for an empty input array', () => {+ expect(normalizeGuestDrawerTags([])).toStrictEqual([]);+ });++ it('returns an empty array when every element is empty or whitespace', () => {+ expect(normalizeGuestDrawerTags(['', ' ', '\t'])).toStrictEqual([]);+ });++ it('returns a new array instance rather than the same reference', () => {+ const input: TagsArg = ['a', 'b'];+ const result = normalizeGuestDrawerTags(input);+ expect(result).not.toBe(input);+ expect(result).toStrictEqual(['a', 'b']);+ });+ });++ describe('string input (typeof === "string" branch)', () => {+ it('returns a single tag untouched when there is no comma', () => {+ expect(normalizeGuestDrawerTags('solo')).toStrictEqual(['solo']);+ });++ it('splits on commas and trims each segment', () => {+ expect(normalizeGuestDrawerTags(' a , b ,c')).toStrictEqual(['a', 'b', 'c']);+ });++ it('preserves internal spacing within a segment while trimming its ends', () => {+ expect(normalizeGuestDrawerTags('web server, db primary ')).toStrictEqual([+ 'web server',+ 'db primary',+ ]);+ });++ it('drops empty segments produced by consecutive commas (filter false arm)', () => {+ expect(normalizeGuestDrawerTags('a,,b')).toStrictEqual(['a', 'b']);+ });++ it('drops whitespace-only segments because trim yields an empty string', () => {+ expect(normalizeGuestDrawerTags('a, ,\t,b')).toStrictEqual(['a', 'b']);+ });++ it('returns an empty array for the empty string', () => {+ expect(normalizeGuestDrawerTags('')).toStrictEqual([]);+ });++ it('returns an empty array for a string of only commas', () => {+ expect(normalizeGuestDrawerTags(',,,')).toStrictEqual([]);+ });++ it('returns an empty array for a string of only whitespace and commas', () => {+ expect(normalizeGuestDrawerTags(' , \t , ')).toStrictEqual([]);+ });+ });++ describe('fallback (neither array nor string)', () => {+ it('returns an empty array for null', () => {+ expect(normalizeGuestDrawerTags(null)).toStrictEqual([]);+ });++ it('returns an empty array for undefined', () => {+ expect(normalizeGuestDrawerTags(undefined as unknown as TagsArg)).toStrictEqual([]);+ });++ it('returns an empty array for an unexpected numeric value', () => {+ expect(normalizeGuestDrawerTags(123 as unknown as TagsArg)).toStrictEqual([]);+ });+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0712c.test.ts b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..04f77f17de--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0712c.test.ts@@ -0,0 +1,202 @@+import { describe, expect, it } from 'vitest';++import type { CoreTemp, Node, Temperature } from '@/types/api';++import { getNodeDrawerHistoryFallbackMetrics } from '../nodeDrawerModel';++const makeNode = (overrides: Partial<Node> = {}): Node => ({+ id: 'agent:pve-node-1',+ name: 'pve-node-1',+ instance: 'homelab',+ host: 'pve-node-1',+ status: 'online',+ type: 'agent',+ cpu: 0.42,+ memory: { total: 8000, used: 3200, free: 4800, usage: 40 },+ disk: { total: 10000, used: 4500, free: 5500, usage: 45 },+ networkIn: 1200,+ networkOut: 800,+ diskRead: 400,+ diskWrite: 300,+ uptime: 3600,+ loadAverage: [0.5],+ kernelVersion: '6.8.0',+ pveVersion: 'pve-manager/9.1.9',+ cpuInfo: { model: 'Ryzen', cores: 8, sockets: 1, mhz: '3200' },+ temperature: {+ cpuPackage: 62.5,+ cpuMax: 65,+ available: true,+ hasCPU: true,+ lastUpdate: new Date().toISOString(),+ },+ temperatureMonitoringEnabled: true,+ lastSeen: new Date().toISOString(),+ connectionHealth: 'online',+ isClusterMember: true,+ clusterName: 'homelab',+ linkedAgentId: '',+ ...overrides,+});++const makeTemp = (overrides: Partial<Temperature> = {}): Temperature => ({+ available: true,+ lastUpdate: new Date().toISOString(),+ ...overrides,+});++describe('getNodeDrawerHistoryFallbackMetrics (branch coverage 0712c)', () => {+ it('returns temperature: undefined when the temperature object is present but available is missing', () => {+ // Optional chain `?.available` with a truthy object whose `available` key is absent:+ // !undefined === true -> early null -> ?? undefined (right arm).+ const node = makeNode({+ temperature: makeTemp({ available: undefined as unknown as boolean }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: undefined,+ });+ });++ it('returns temperature: 0 when cpuPackage is 0 (zero is a valid finite candidate)', () => {+ // isValidTemperature(0): typeof === 'number' && Number.isFinite(0) -> true (left arm of ??).+ // Asserts the boundary that 0 is NOT clobbered by the nullish coalescing operator.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: 0, cpuMax: undefined }),+ });+ const result = getNodeDrawerHistoryFallbackMetrics(node);+ expect(result.temperature).toBe(0);+ expect(result).toStrictEqual({ temperature: 0 });+ });++ it('preserves a fractional cpuPackage exactly through the ?? left arm', () => {+ // Float candidate survives Math.max single-element spread unchanged.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: 62.5, cpuMax: undefined }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 62.5,+ });+ });++ it('skips an Infinity cpuPackage (non-finite) and falls back to cpuMax', () => {+ // isValidTemperature(Infinity): Number.isFinite(Infinity) === false -> cpuPackage skipped.+ // Distinct from the NaN case: Infinity is a typeof 'number' that is not finite.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: Number.POSITIVE_INFINITY, cpuMax: 71 }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 71,+ });+ });++ it('still returns cpuPackage when cores is an empty array (forEach with zero iterations)', () => {+ // Array.isArray([]) === true (cores branch taken) but forEach never executes,+ // so no core candidates are appended; cpuPackage is the sole candidate.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: 55, cpuMax: undefined, cores: [] }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 55,+ });+ });++ it('builds candidates solely from cores when cpuPackage and cpuMax are absent', () => {+ // cpuPackage/cpuMax undefined -> both isValidTemperature false arms; the entire+ // candidates list is populated by the cores forEach, then Math.max returns 92.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: undefined,+ cpuMax: undefined,+ cores: [+ { core: 0, temp: 88 },+ { core: 1, temp: 92 },+ { core: 2, temp: 90 },+ ],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 92,+ });+ });++ it('skips a core whose temp is missing and keeps the valid sibling core', () => {+ // A CoreTemp with `temp` absent (required field omitted via cast): core.temp is+ // undefined -> isValidTemperature false -> skipped; the valid sibling is kept.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: undefined,+ cpuMax: undefined,+ cores: [+ { core: 0 } as unknown as CoreTemp,+ { core: 1, temp: 75 },+ ],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 75,+ });+ });++ it('ignores a malformed non-array cores value and yields undefined when no candidates remain', () => {+ // Array.isArray(<object>) === false (distinct from undefined): cores branch skipped.+ // cpuPackage/cpuMax absent -> candidates empty -> length === 0 -> null -> ?? undefined.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: undefined,+ cpuMax: undefined,+ cores: { '0': { temp: 99 } } as unknown as CoreTemp[],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: undefined,+ });+ });++ it('returns the maximum (least-negative) value across all-negative finite candidates', () => {+ // All candidates are finite negatives; Math.max picks the least-negative (-3),+ // proving the max aggregation works below zero rather than defaulting to null.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: -40,+ cpuMax: -20,+ cores: [+ { core: 0, temp: -10 },+ { core: 1, temp: -3 },+ ],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: -3,+ });+ });++ it('returns temperature: undefined when available is true but every candidate field is invalid', () => {+ // available === true (guard passes), yet cpuPackage/cpuMax are NaN and cores absent:+ // isValidTemperature false for both -> candidates empty -> length === 0 -> null.+ const node = makeNode({+ temperature: makeTemp({ cpuPackage: Number.NaN, cpuMax: Number.NaN }),+ });+ const result = getNodeDrawerHistoryFallbackMetrics(node);+ expect(result).toStrictEqual({ temperature: undefined });+ expect('temperature' in result).toBe(true);+ });++ it('prefers the largest valid core temp over higher-indexed invalid ones', () => {+ // Mixed valid/invalid cores: index 0 valid (95), index 1 NaN (skipped),+ // index 2 valid (60); cpuPackage/cpuMax absent -> Math.max(95, 60) === 95.+ const node = makeNode({+ temperature: makeTemp({+ cpuPackage: undefined,+ cpuMax: undefined,+ cores: [+ { core: 0, temp: 95 },+ { core: 1, temp: Number.NaN },+ { core: 2, temp: 60 },+ ],+ }),+ });+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({+ temperature: 95,+ });+ });+});diff --git a/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0712c.test.ts b/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..1c5e2920ec--- /dev/null+++ b/frontend-modern/src/components/shared/__tests__/commandPaletteModel.branchcov0712c.test.ts@@ -0,0 +1,313 @@+import { describe, expect, it } from 'vitest';+import {+ filterCommandPaletteCommands,+ type CommandPaletteModalCommand,+} from '@/components/shared/commandPaletteModel';++// Complementary branch-coverage suite for `filterCommandPaletteCommands`.+// Each assertion is a concrete equality/strict-equality check against the real+// return shape (no truthiness-only checks). This file deliberately targets+// branches/angles that the sibling `branchcov0712` suite does not exercise:+//+// A. Empty input array — drives BOTH the early-return arm (empty query ->+// same [] reference) AND the `.filter` arm with zero elements (non-empty+// query -> fresh empty array, NOT the same reference).+// B. Present-but-EMPTY optional fields (`description: ''`, `shortcut: ''`,+// `keywords: []`). The `??` operator returns its LEFT operand for every+// non-null/undefined value, so an empty-string / empty-array value hits+// the LEFT (present) arm of `??` with a falsy payload — a distinct branch+// state from "present with content" and from "absent (undefined)".+// C. All optionals absent at once (label-only command) — combines every+// RIGHT (absent) arm of `??` in a single pass.+// D. Cross-field join-boundary matching — substring spans the `join(' ')`+// seam between two fields once whitespace is stripped.+// E. Realistic multi-command subset selection + order preservation across a+// mix of present/absent fields and case/whitespace variance.++function makeCommand(+ overrides: Partial<CommandPaletteModalCommand> = {},+): CommandPaletteModalCommand {+ return {+ id: 'cmd-1',+ label: 'Go to Proxmox',+ description: '/proxmox',+ shortcut: 'g p',+ keywords: ['proxmox', 'pve', 'backups'],+ action: () => {},+ ...overrides,+ };+}++describe('commandPaletteModel.branchcov0712c', () => {+ describe('filterCommandPaletteCommands', () => {+ describe('A. empty input array (early-return arm vs filter arm with 0 elements)', () => {+ it('returns the SAME empty array reference for an empty query (early-return arm)', () => {+ const commands: CommandPaletteModalCommand[] = [];+ // `!normalizedQuery` is true -> `return commands` (same reference).+ expect(filterCommandPaletteCommands(commands, '')).toBe(commands);+ });++ it('returns the SAME empty array reference for a whitespace-only query', () => {+ const commands: CommandPaletteModalCommand[] = [];+ // ' \t ' normalizes to '' -> falsy -> early return (same reference).+ expect(filterCommandPaletteCommands(commands, ' \t ')).toBe(commands);+ });++ it('returns a NEW empty array (different reference) for a non-empty query on [] (filter arm)', () => {+ const commands: CommandPaletteModalCommand[] = [];+ // `commands.filter(...)` always allocates a fresh array, even when it+ // stays empty, so the reference must differ from the input.+ const result = filterCommandPaletteCommands(commands, 'anything');+ expect(result).toStrictEqual([]);+ expect(result).not.toBe(commands);+ });+ });++ describe('B. present-but-empty optional fields (LEFT arm of ?? with falsy payload)', () => {+ it('treats `description: ""` as the LEFT arm of ?? and still matches on other fields', () => {+ // description is present but empty -> `description ?? ''` yields ''+ // (the LEFT operand), not via the RIGHT arm. Match must come from label.+ const command = makeCommand({+ id: 'empty-desc',+ label: 'Go to Docker',+ description: '',+ shortcut: 'g d',+ keywords: ['docker'],+ });+ const result = filterCommandPaletteCommands([command], 'docker');+ expect(result).toStrictEqual([command]);+ });++ it('does NOT match the literal "undefined" string when description is "" (LEFT arm intact)', () => {+ // A present empty string must never inject 'undefined' into the haystack.+ const command = makeCommand({+ id: 'empty-desc-2',+ label: 'Go to Docker',+ description: '',+ action: () => {},+ });+ const result = filterCommandPaletteCommands([command], 'undefined');+ expect(result).toStrictEqual([]);+ });++ it('treats `shortcut: ""` as the LEFT arm of ?? and matches on other fields', () => {+ const command = makeCommand({+ id: 'empty-shortcut',+ label: 'Go to Kubernetes',+ description: '/k8s',+ shortcut: '',+ keywords: ['k8s'],+ });+ const result = filterCommandPaletteCommands([command], 'kubernetes');+ expect(result).toStrictEqual([command]);+ });++ it('treats `keywords: []` as the LEFT arm of ?? (empty spread, no elements added)', () => {+ // keywords present but empty -> `keywords ?? []` yields [] (LEFT arm),+ // and the spread contributes nothing. Matching still works via label.+ const command = makeCommand({+ id: 'empty-keywords',+ label: 'Go to TrueNAS',+ description: '/truenas',+ shortcut: 'g n',+ keywords: [],+ });+ const result = filterCommandPaletteCommands([command], 'truenas');+ expect(result).toStrictEqual([command]);+ });++ it('matches nothing when ALL fields are present-but-empty except an unrelated label', () => {+ // description:'', shortcut:'', keywords:[] — every ?? takes its LEFT arm+ // with an empty payload, so only the label feeds the haystack.+ const command = makeCommand({+ id: 'all-empty-opt',+ label: 'Go to Settings',+ description: '',+ shortcut: '',+ keywords: [],+ });+ // A query that is NOT in the label must yield no matches.+ expect(filterCommandPaletteCommands([command], 'proxmox')).toStrictEqual([]);+ // But a label substring still matches.+ expect(filterCommandPaletteCommands([command], 'settings')).toStrictEqual([command]);+ });+ });++ describe('C. all optionals absent at once (RIGHT arm of every ?? simultaneously)', () => {+ it('builds the haystack from the label only and matches a label substring', () => {+ const command: CommandPaletteModalCommand = {+ id: 'label-only',+ label: 'Go to Alerts',+ action: () => {},+ // description, shortcut, keywords ALL omitted -> every ?? hits RIGHT arm.+ };+ const result = filterCommandPaletteCommands([command], 'alerts');+ expect(result).toStrictEqual([command]);+ });++ it('returns no match when the (label-only) haystack lacks the query', () => {+ const command: CommandPaletteModalCommand = {+ id: 'label-only-2',+ label: 'Go to Patrol',+ action: () => {},+ };+ const result = filterCommandPaletteCommands([command], 'docker');+ expect(result).toStrictEqual([]);+ });+ });++ describe('D. cross-field join-boundary matching', () => {+ it('matches a substring that spans the label/description seam after whitespace stripping', () => {+ // label 'Go' + description '/to' -> join(' ') -> 'Go /to' -> strip ws+ // -> 'go/to'. Query 'go/to' spans the join boundary.+ const command = makeCommand({+ id: 'seam-1',+ label: 'Go',+ description: '/to',+ shortcut: 'g g',+ keywords: ['unrelated'],+ });+ const result = filterCommandPaletteCommands([command], 'go/to');+ expect(result).toStrictEqual([command]);+ });++ it('matches a substring spanning the shortcut/keyword seam', () => {+ // shortcut 'g p' (-> 'gp' after strip) + keyword 've' -> join -> strip+ // -> '...gpve...'. Query 'gpve' crosses the shortcut|keyword boundary.+ const command = makeCommand({+ id: 'seam-2',+ label: 'Proxmox',+ description: '/px',+ shortcut: 'g p',+ keywords: ['ve', 'extra'],+ });+ const result = filterCommandPaletteCommands([command], 'gpve');+ expect(result).toStrictEqual([command]);+ });++ it('does NOT falsely match across a seam when the stripped substring is absent', () => {+ // Confirm the seam logic is exact: a near-miss query yields nothing.+ const command = makeCommand({+ id: 'seam-3',+ label: 'Alpha',+ description: 'beta',+ shortcut: 'g g',+ keywords: ['gamma'],+ });+ const result = filterCommandPaletteCommands([command], 'alphabetaz');+ expect(result).toStrictEqual([]);+ });+ });++ describe('E. realistic multi-command subset selection + order preservation', () => {+ it('selects a shortcut-omitted command (RIGHT arm of ??) from a mixed set', () => {+ const a = makeCommand({+ id: 'nav-proxmox',+ label: 'Go to Proxmox',+ description: '/proxmox',+ shortcut: 'g p',+ keywords: ['proxmox', 'pve'],+ });+ const b: CommandPaletteModalCommand = {+ id: 'nav-docker',+ label: 'Go to Docker',+ description: '/docker',+ // shortcut omitted (RIGHT arm of ??)+ keywords: ['docker', 'containers'],+ action: () => {},+ };+ const c: CommandPaletteModalCommand = {+ id: 'nav-truenas',+ label: 'Go to TrueNAS',+ // description, shortcut, keywords all omitted (all RIGHT arms)+ action: () => {},+ };++ // Query 'docker' matches ONLY b, whose `shortcut ?? ''` took the RIGHT+ // (absent) arm — proving omitted-field commands still filter correctly.+ const result = filterCommandPaletteCommands([a, b, c], 'docker');+ expect(result).toStrictEqual([b]);+ });++ it('selects a 2-element subset in input order across mixed field shapes', () => {+ const a = makeCommand({+ id: 'nav-proxmox',+ label: 'Go to Proxmox',+ description: '/proxmox',+ shortcut: 'g p',+ keywords: ['proxmox', 'pve'],+ });+ const b: CommandPaletteModalCommand = {+ id: 'nav-docker',+ label: 'Go to Docker',+ description: '/docker',+ keywords: ['docker', 'containers'],+ action: () => {},+ };+ const c: CommandPaletteModalCommand = {+ id: 'nav-truenas',+ label: 'Go to TrueNAS',+ action: () => {},+ };+ const d = makeCommand({+ id: 'nav-vmware',+ label: 'Go to vSphere',+ description: '/vmware',+ shortcut: 'g v',+ keywords: ['vmware', 'vsphere'],+ });++ // Query 'v' normalizes to 'v': matches a (via 'pve') and d (via+ // 'vsphere'/'vmware'/'g v'), but not b (docker/containers) nor c.+ const result = filterCommandPaletteCommands([a, b, c, d], 'v');+ expect(result).toStrictEqual([a, d]);+ });++ it('preserves order when every command matches', () => {+ const commands = [+ makeCommand({ id: 'first', keywords: ['shared'] }),+ makeCommand({ id: 'second', keywords: ['shared'] }),+ makeCommand({ id: 'third', keywords: ['shared'] }),+ ];+ const result = filterCommandPaletteCommands(commands, 'shared');+ expect(result.map((c) => c.id)).toStrictEqual(['first', 'second', 'third']);+ // Returned elements are the same object references, in order.+ expect(result).toStrictEqual(commands);+ });++ it('returns a fresh array (not the input reference) on the filter arm even when all match', () => {+ const commands = [makeCommand({ id: 'a' }), makeCommand({ id: 'b' })];+ const result = filterCommandPaletteCommands(commands, 'proxmox');+ // Same contents, different array object — confirms `.filter` allocation.+ expect(result).toStrictEqual(commands);+ expect(result).not.toBe(commands);+ });++ it('matches a single command out of many via a case-mixed query', () => {+ const commands = [+ makeCommand({ id: 'a', label: 'Go to Settings' }),+ makeCommand({ id: 'b', label: 'Go to Patrol' }),+ makeCommand({ id: 'c', label: 'Go to Alerts' }),+ ];+ // Mixed-case query normalizes to lowercase and matches only 'c'.+ const result = filterCommandPaletteCommands(commands, 'aLeRtS');+ expect(result.map((c) => c.id)).toStrictEqual(['c']);+ });++ it('matches via an internal-whitespace query token against a multi-word keyword', () => {+ const command = makeCommand({+ id: 'patrol',+ label: 'Go to Patrol',+ description: '/patrol',+ shortcut: 'g r',+ keywords: ['needs attention', 'patrol'],+ });+ // 'needs attention' in the keyword -> haystack strips the space ->+ // 'needsattention'. Query ' Needs Attention ' normalizes (trim ++ // collapse) to 'needsattention' and matches.+ const result = filterCommandPaletteCommands([command], ' Needs Attention ');+ expect(result).toStrictEqual([command]);+ });+ });+ });+});diff --git a/frontend-modern/src/components/shared/__tests__/searchTipsPopoverModel.branchcov0712c.test.ts b/frontend-modern/src/components/shared/__tests__/searchTipsPopoverModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..a35eb93b86--- /dev/null+++ b/frontend-modern/src/components/shared/__tests__/searchTipsPopoverModel.branchcov0712c.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';+import {+ getSearchTipsPopoverPositionClass,+ getSearchTipsPopoverTriggerClass,+} from '@/components/shared/searchTipsPopoverModel';++// `triggerBaseClasses` is a module-private const that is not exported, so we+// mirror the literal here in order to assert the full, concrete composed string+// for every branch of getSearchTipsPopoverTriggerClass.+const TRIGGER_BASE_CLASSES =+ 'text-xs font-medium focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 focus:ring-offset-white dark:focus:ring-blue-400';++describe('searchTipsPopoverModel.branchcov0712c', () => {+ describe('getSearchTipsPopoverPositionClass', () => {+ it("returns 'left-0' when align === 'left' (truthy ternary arm)", () => {+ expect(getSearchTipsPopoverPositionClass('left')).toBe('left-0');+ });++ it("returns 'right-0' when align === 'right' (falsy ternary arm)", () => {+ expect(getSearchTipsPopoverPositionClass('right')).toBe('right-0');+ });++ it("returns 'right-0' when align is omitted (undefined -> falsy ternary arm)", () => {+ expect(getSearchTipsPopoverPositionClass()).toBe('right-0');+ });++ it('returns the else-arm value for an unexpected align value (defensive)', () => {+ // The ternary only special-cases 'left'; anything else (including a+ // wrong-typed value that slips past the union at runtime) must fall to+ // the 'right-0' arm.+ const bogus =+ 'center' as unknown as Parameters<typeof getSearchTipsPopoverPositionClass>[0];+ expect(getSearchTipsPopoverPositionClass(bogus)).toBe('right-0');+ });+ });++ describe('getSearchTipsPopoverTriggerClass', () => {+ it("returns the button variant classes when triggerVariant === 'button' (first if arm)", () => {+ expect(getSearchTipsPopoverTriggerClass('button')).toBe(+ `rounded-md border border-border px-2.5 py-1 text-muted transition-colors hover:bg-surface-hover ${TRIGGER_BASE_CLASSES}`,+ );+ });++ it("returns the link variant classes when triggerVariant === 'link' (first if false, second if arm)", () => {+ expect(getSearchTipsPopoverTriggerClass('link')).toBe(+ `rounded px-1 py-0.5 underline decoration-dotted underline-offset-4 transition-colors hover:text-base-content ${TRIGGER_BASE_CLASSES}`,+ );+ });++ it("returns the icon variant classes when triggerVariant === 'icon' (both ifs false -> default return)", () => {+ expect(getSearchTipsPopoverTriggerClass('icon')).toBe(+ `flex h-10 w-10 items-center justify-center rounded-full transition-colors hover:text-muted sm:h-5 sm:w-5 ${TRIGGER_BASE_CLASSES}`,+ );+ });++ it('falls through both ifs to the default return for an unknown variant (defensive)', () => {+ // An out-of-union value must not match either `if` guard and so lands in+ // the trailing default (the icon) return.+ const bogus =+ 'ghost' as unknown as Parameters<typeof getSearchTipsPopoverTriggerClass>[0];+ expect(getSearchTipsPopoverTriggerClass(bogus)).toBe(+ `flex h-10 w-10 items-center justify-center rounded-full transition-colors hover:text-muted sm:h-5 sm:w-5 ${TRIGGER_BASE_CLASSES}`,+ );+ });++ it('appends the shared trigger base classes to every named variant', () => {+ // Guards the invariant that all three branches keep the focus-ring tail;+ // also exercises each variant once more on a single, concrete assertion.+ expect(getSearchTipsPopoverTriggerClass('button')).toContain(TRIGGER_BASE_CLASSES);+ expect(getSearchTipsPopoverTriggerClass('link')).toContain(TRIGGER_BASE_CLASSES);+ expect(getSearchTipsPopoverTriggerClass('icon')).toContain(TRIGGER_BASE_CLASSES);+ });+ });+});diff --git a/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.ts b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.tsnew file mode 100644index 0000000000..77be9e6f0a--- /dev/null+++ b/frontend-modern/src/features/alerts/__tests__/alertDestinationsModel.branchcov0712c.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it } from 'vitest';++import type { UIEmailConfig } from '../types';++import { buildEmailConfigPayload } from '../alertDestinationsModel';++// ---------------------------------------------------------------------------+// Fixture — minimal valid UIEmailConfig. Tests override only the fields+// relevant to the branch under examination. Mirrors the helper used by the+// sibling `branchcov0712` suite so conventions stay identical.+// ---------------------------------------------------------------------------++function makeUIEmailConfig(overrides: Partial<UIEmailConfig> = {}): UIEmailConfig {+ return {+ enabled: true,+ provider: 'smtp',+ server: 'smtp.internal',+ port: 587,+ username: '[email protected]',+ password: 'secret',+ from: '[email protected]',+ to: ['[email protected]'],+ tls: true,+ startTLS: true,+ replyTo: '',+ maxRetries: 3,+ retryDelay: 60,+ rateLimit: 0,+ ...overrides,+ };+}++describe('buildEmailConfigPayload — branch coverage (batch 3 / 0712c)', () => {+ // -----------------------------------------------------------------------+ // to.map((entry) => entry.trim())+ // The trim arm is exercised for each distinct class of whitespace+ // `String.prototype.trim` removes. The sibling suite already covers+ // ' ', '\t', '\n'; here we drive the remaining whitespace code points+ // so the trim callback is hit with inputs that previously had no+ // dedicated test. Several of these also collapse to '' and thus feed+ // the filter false arm with exotic-whitespace-only entries.+ // -----------------------------------------------------------------------+ describe('trim arm — exotic whitespace', () => {+ it('strips carriage-return and CRLF sequences from both ends', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ to: ['\r\[email protected]\r\n'] }),+ );+ expect(result.to).toStrictEqual(['[email protected]']);+ });++ it('strips form-feed and vertical-tab characters', () => {+ // \f (form feed, U+000C) and \v (vertical tab, U+000B) are both+ // in the trim set; an entry made solely of them must collapse and+ // be dropped by the filter.+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ to: ['\f\v', '\[email protected]\v'] }),+ );+ expect(result.to).toStrictEqual(['[email protected]']);+ });++ it('strips Unicode whitespace: NBSP, em space, ideographic space', () => {+ // U+00A0 (no-break space), U+2003 (em space), U+3000 (ideographic+ // space) are all removed by trim(). A whitespace-only entry drops;+ // a padded entry is cleaned.+ const nbsp = '\u00A0';+ const em = '\u2003';+ const ideo = '\u3000';+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({+ to: [`${nbsp}${em}${ideo}`, `${nbsp}[email protected]${ideo}`],+ }),+ );+ expect(result.to).toStrictEqual(['[email protected]']);+ });++ it('drops entries composed of Unicode line/paragraph separators', () => {+ // U+2028 (line separator) and U+2029 (paragraph separator) are+ // whitespace from trim()'s perspective; a sole entry of them must+ // be filtered out, leaving an empty to list.+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ to: ['\u2028\u2029'] }),+ );+ expect(result.to).toStrictEqual([]);+ });+ });++ // -----------------------------------------------------------------------+ // to.filter((entry) => entry.length > 0)+ // The predicate is `entry.length > 0`, NOT Boolean coercion. The+ // sibling suite never feeds a recipient whose truthiness differs from+ // its non-emptiness, so these cases pin down the exact semantics of+ // the filter arm.+ // -----------------------------------------------------------------------+ describe('filter predicate — length-vs-truthiness', () => {+ it('keeps the string "0" because length > 0 (not truthiness)', () => {+ // "0" is falsy under Boolean() but has length 1; the contract is+ // to keep it.+ const result = buildEmailConfigPayload(makeUIEmailConfig({ to: ['0'] }));+ expect(result.to).toStrictEqual(['0']);+ });++ it('keeps the literal string "false" because length > 0', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ to: ['false'] }),+ );+ expect(result.to).toStrictEqual(['false']);+ });++ it('drops a single whitespace-only entry, invoking the filter predicate exactly once on the false arm', () => {+ // Existing suites drop whitespace with multi-element arrays or an+ // empty array. A single-element drop exercises the false arm with+ // the predicate called exactly once.+ const result = buildEmailConfigPayload(makeUIEmailConfig({ to: [' '] }));+ expect(result.to).toStrictEqual([]);+ });++ it('keeps every entry when none collapse to empty (filter true arm only)', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({+ }),+ );+ expect(result.to).toStrictEqual([+ '[email protected]',+ '[email protected]',+ '[email protected]',+ ]);+ });+ });++ // -----------------------------------------------------------------------+ // trim() only strips leading/trailing whitespace. Internal whitespace —+ // including characters trim recognises — must survive. This separates+ // "trim both ends" from a hypothetical "trim everywhere" implementation.+ // -----------------------------------------------------------------------+ describe('internal whitespace preservation', () => {+ it('preserves an internal newline while trimming ends', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ to: [' multi\[email protected] '] }),+ );+ expect(result.to).toStrictEqual(['multi\[email protected]']);+ });++ it('preserves an internal tab while trimming ends', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ to: ['\ta\[email protected]\t'] }),+ );+ expect(result.to).toStrictEqual(['a\[email protected]']);+ });+ });++ // -----------------------------------------------------------------------+ // Output contract — assert the EXACT key set so any future field added+ // to UIEmailConfig that fails to be forwarded (or any UI-only field+ // that leaks through) is caught. This is the structural complement to+ // the value-level toStrictEqual checks in the sibling suite.+ // -----------------------------------------------------------------------+ describe('payload contract — exact key set', () => {+ it('emits exactly the 11 EmailConfig keys in declaration order and omits replyTo/maxRetries/retryDelay/rateLimit', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({+ replyTo: '[email protected]',+ maxRetries: 9,+ retryDelay: 300,+ rateLimit: 50,+ }),+ );+ expect(Object.keys(result)).toStrictEqual([+ 'enabled',+ 'provider',+ 'server',+ 'port',+ 'username',+ 'password',+ 'from',+ 'to',+ 'tls',+ 'startTLS',+ ]);+ expect(result).not.toHaveProperty('replyTo');+ expect(result).not.toHaveProperty('maxRetries');+ expect(result).not.toHaveProperty('retryDelay');+ // rateLimit exists on EmailConfig (optional) yet is never+ // forwarded — see GLM_REPORT.md (suspected source bug).+ expect(result).not.toHaveProperty('rateLimit');+ });+ });++ // -----------------------------------------------------------------------+ // Scalar passthrough — provider is a free-form string; verify both an+ // empty and a custom value flow through untouched (distinct from the+ // hardcoded 'smtp'/'ses' values used elsewhere).+ // -----------------------------------------------------------------------+ describe('provider passthrough', () => {+ it('forwards an empty provider string unchanged', () => {+ const result = buildEmailConfigPayload(makeUIEmailConfig({ provider: '' }));+ expect(result.provider).toBe('');+ });++ it('forwards a custom provider string unchanged', () => {+ const result = buildEmailConfigPayload(+ makeUIEmailConfig({ provider: 'mailgun' }),+ );+ expect(result.provider).toBe('mailgun');+ });+ });++ // -----------------------------------------------------------------------+ // Defensive gap — the function performs no type guard on `to` entries+ // before calling .trim(). A non-string entry (impossible via the typed+ // surface but reachable through `as unknown as`) propagates a TypeError,+ // documenting that there is no graceful handling branch to hit.+ // -----------------------------------------------------------------------+ describe('defensive behaviour on malformed input', () => {+ it('throws a TypeError when a to entry is not a string (no guard branch)', () => {+ const malformed = makeUIEmailConfig({+ to: ['[email protected]', 12345] as unknown as string[],+ });+ expect(() => buildEmailConfigPayload(malformed)).toThrow(TypeError);+ });+ });+});diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageAlertState.branchcov0712c.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageAlertState.branchcov0712c.test.tsnew file mode 100644index 0000000000..d514b58aa4--- /dev/null+++ b/frontend-modern/src/features/storageBackups/__tests__/storageAlertState.branchcov0712c.test.ts@@ -0,0 +1,402 @@+import { describe, expect, it } from 'vitest';+import type { Alert } from '@/types/api';+import type { StorageRecord } from '@/features/storageBackups/models';+import {+ asStorageAlertRecord,+ getStorageRecordAlertResourceIds,+} from '@/features/storageBackups/storageAlertState';++// ---------------------------------------------------------------------------+// Fixture builder — mirrors storageAlertState.test.ts so casts, import paths+// and the default record shape match the sibling suite. The defaults describe+// a healthy truenas pool; cases override `refs` / `details` / `id` / `name`+// to drive individual branches of getStorageRecordAlertResourceIds.+// ---------------------------------------------------------------------------++const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({+ id: 'storage-1',+ name: 'tank',+ category: 'pool',+ health: 'healthy',+ location: { label: 'truenas01', scope: 'host' },+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },+ capabilities: ['capacity'],+ source: {+ platform: 'truenas',+ family: 'onprem',+ origin: 'resource',+ adapterId: 'resource-storage',+ },+ observedAt: Date.now(),+ ...overrides,+});++// A minimal well-formed Alert for the object/array pass-through assertions.+const makeAlert = (overrides: Partial<Alert> = {}): Alert => ({+ id: 'alert-1',+ type: 'disk.usage',+ level: 'critical',+ resourceId: 'storage-1',+ resourceName: 'tank',+ node: 'truenas01',+ instance: 'truenas01',+ message: 'pool almost full',+ value: 92,+ threshold: 90,+ startTime: '2024-01-01T00:00:00Z',+ acknowledged: false,+ ...overrides,+});++// ===========================================================================+// asStorageAlertRecord+// ===========================================================================++describe('asStorageAlertRecord branch coverage', () => {+ // ---- Branch L25 `if (!value) return {}` — every falsy arm ----------------+ it('returns {} for null (falsy arm)', () => {+ expect(asStorageAlertRecord(null)).toEqual({});+ });++ it('returns {} for undefined (falsy arm)', () => {+ expect(asStorageAlertRecord(undefined)).toEqual({});+ });++ it('returns {} for the empty string (falsy arm)', () => {+ expect(asStorageAlertRecord('')).toEqual({});+ });++ it('returns {} for 0 (falsy arm)', () => {+ expect(asStorageAlertRecord(0)).toEqual({});+ });++ it('returns {} for false (falsy arm)', () => {+ expect(asStorageAlertRecord(false)).toEqual({});+ });++ // ---- Branch L27 array path: L29 valid element (string id) is included ----+ it('indexes a valid array element by its string id', () => {+ const a = makeAlert({ id: 'a', level: 'warning' });+ const b = makeAlert({ id: 'b', level: 'critical' });+ expect(asStorageAlertRecord([a, b])).toStrictEqual({ a, b });+ });++ // ---- Branch L29 false arm: null element is skipped -----------------------+ it('skips null elements inside an array', () => {+ const a = makeAlert({ id: 'a' });+ expect(asStorageAlertRecord([a, null])).toStrictEqual({ a });+ });++ // ---- Branch L29 false arm: primitive element is skipped ------------------+ it('skips primitive (non-object) elements inside an array', () => {+ const a = makeAlert({ id: 'a' });+ // `alert && typeof alert === 'object'` is false for a string/number.+ expect(asStorageAlertRecord([a, 'not-an-alert', 42, true])).toStrictEqual({ a });+ });++ // ---- Branch L29 false arm: object with no `id` is skipped ----------------+ it('skips object elements that have no id field', () => {+ const a = makeAlert({ id: 'a' });+ expect(asStorageAlertRecord([a, { severity: 'warning' }])).toStrictEqual({ a });+ });++ // ---- Branch L29 false arm: object with a non-string id is skipped --------+ it('skips object elements whose id is not a string', () => {+ const a = makeAlert({ id: 'a' });+ // typeof id === 'string' is false for number 123 → dropped.+ expect(asStorageAlertRecord([a, { id: 123, level: 'warning' }])).toStrictEqual({ a });+ });++ // ---- Branch L29: later element overwrites earlier under the same id ------+ it('lets a later array element overwrite an earlier one sharing the same id', () => {+ const first = makeAlert({ id: 'a', level: 'warning', message: 'old' });+ const second = makeAlert({ id: 'a', level: 'critical', message: 'new' });+ expect(asStorageAlertRecord([first, second])).toStrictEqual({ a: second });+ });++ // ---- Branch L36 `typeof value !== 'object'` true → {} --------------------+ it('returns {} for a truthy non-object primitive (non-empty string)', () => {+ // passes the `!value` guard (truthy) and the Array.isArray guard, then+ // hits `typeof value !== 'object'` → {}.+ expect(asStorageAlertRecord('alerts')).toEqual({});+ });++ it('returns {} for a truthy non-object primitive (positive number)', () => {+ expect(asStorageAlertRecord(7)).toEqual({});+ });++ it('returns {} for the truthy boolean primitive `true`', () => {+ expect(asStorageAlertRecord(true)).toEqual({});+ });++ // ---- Branch L37 object path: returned by reference without validation ----+ it('returns a plain object by reference (no per-value validation on this arm)', () => {+ const input: Record<string, Alert> = { x: makeAlert({ id: 'x' }) };+ // L37 `return value as Record<string, Alert>` hands the same reference back.+ expect(asStorageAlertRecord(input)).toBe(input);+ });++ it('passes an empty object through as {} on the object arm', () => {+ expect(asStorageAlertRecord({})).toEqual({});+ });++ it('returns a multi-key alert object unchanged on the object arm', () => {+ const a = makeAlert({ id: 'a' });+ const b = makeAlert({ id: 'b' });+ const input = { a, b };+ expect(asStorageAlertRecord(input)).toStrictEqual(input);+ });+});++// ===========================================================================+// getStorageRecordAlertResourceIds+// ===========================================================================++describe('getStorageRecordAlertResourceIds branch coverage', () => {+ // ---- Branch L70 `record.refs || {}` right operand: refs undefined → {} ---+ it('does not throw and omits refs-derived ids when refs is undefined', () => {+ // refs undefined → `{}` → resourceId/platformEntityId undefined → filtered.+ // details undefined → `{}` → node undefined → detailNode '' → derived ''.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({ id: 'only-id', refs: undefined, details: undefined }),+ ),+ ).toStrictEqual(['only-id']);+ });++ // ---- Branch L71 `(record.details || {})` right operand: details null -----+ it('treats null details as {} and still returns the record id', () => {+ // `details: null` is an explicitly-malformed input to drive the+ // `(record.details || {})` right operand; cast through unknown for ts.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({ id: 'solo', details: null as unknown as Record<string, unknown> }),+ ),+ ).toStrictEqual(['solo']);+ });++ // ---- Branch L72 `typeof details.node === 'string'` false arm -------------+ it('yields an empty detailNode when details.node is a non-string', () => {+ // node is a number → typeof !== 'string' → detailNode ''. With no+ // detailNode the derivedLegacyId ternary falls to ''.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'solo',+ refs: { platformEntityId: 'cluster-a', resourceId: 'res-1' },+ details: { node: 999 } as Record<string, unknown>,+ }),+ ),+ ).toStrictEqual(['solo', 'res-1']);+ });++ // ---- Branch L72 true arm: details.node string is trimmed -----------------+ it('trims whitespace from details.node when building the derived legacy id', () => {+ // node ' pve1 ' → trim → 'pve1'; platformEntityId 'cluster-a' → 'cluster-a'.+ // derived = `cluster-a-pve1-tank`.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { platformEntityId: 'cluster-a' },+ details: { node: ' pve1 ' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'cluster-a-pve1-tank']);+ });++ // ---- Branch L74 `typeof refs.platformEntityId === 'string'` false arm ----+ it('yields an empty detailInstance when refs.platformEntityId is a non-string', () => {+ // platformEntityId is a number → detailInstance '' → derived ''.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'solo',+ refs: { platformEntityId: 418 as unknown as string, resourceId: 'res-1' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['solo', 'res-1']);+ });++ // ---- Branch L74 true arm: refs.platformEntityId string is trimmed --------+ it('trims whitespace from refs.platformEntityId when building the derived legacy id', () => {+ // platformEntityId ' cluster-a ' → 'cluster-a'; node 'pve1' → 'pve1'.+ // derived = `cluster-a-pve1-tank`.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { platformEntityId: ' cluster-a ' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'cluster-a-pve1-tank']);+ });++ // ---- Branch L76 ternary false arm: missing record.name → derived '' -----+ it('does not synthesize a legacy id when record.name is empty', () => {+ // detailInstance + detailNode truthy but record.name '' → falsy → derived ''.+ // name '' also is dropped by the post-trim length>0 filter downstream is N/A+ // here (name only feeds the template, not the candidate list directly).+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: '',+ refs: { platformEntityId: 'cluster-a', resourceId: 'res-1' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'res-1']);+ });++ // ---- Branch L76 ternary false arm: missing detailNode → derived '' -------+ it('does not synthesize a legacy id when details.node is absent', () => {+ // detailInstance truthy, detailNode '' (no node key) → derived ''.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { platformEntityId: 'cluster-a', resourceId: 'res-1' },+ details: { other: 'x' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'res-1']);+ });++ // ---- Branch L76 ternary false arm: missing detailInstance → derived '' ---+ it('does not synthesize a legacy id when refs.platformEntityId is absent', () => {+ // detailInstance '' (no platformEntityId) → derived ''.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { resourceId: 'res-1' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'res-1']);+ });++ // ---- Branch L76 ternary true arm: all three present → derived built ------+ it('synthesizes the legacy id when instance, node and name are all present', () => {+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { platformEntityId: 'cluster-a', resourceId: 'res-1' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'res-1', 'cluster-a-pve1-tank']);+ });++ // ---- Branch L83 `typeof value === 'string'` filter: non-string dropped ---+ it('drops a non-string refs.resourceId (e.g. number) from the candidate set', () => {+ // resourceId is a number → typeof !== 'string' → filtered out at L83.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { resourceId: 418 as unknown as string },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1']);+ });++ // ---- Branch L85 `value.length > 0` filter: whitespace-only id dropped ----+ it('drops an id that is only whitespace after trimming', () => {+ // id ' ' → trim '' → length 0 → dropped. resourceId 'res-1' survives.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: ' ',+ name: 'tank',+ refs: { resourceId: 'res-1' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['res-1']);+ });++ // ---- Branch L84 `.map(trim)`: surrounding whitespace is stripped ---------+ it('trims surrounding whitespace from each surviving candidate id', () => {+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: ' storage-1 ',+ name: 'tank',+ refs: { resourceId: ' res-1 ' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'res-1']);+ });++ // ---- Branch L81 `new Set(...)`: duplicate ids are de-duplicated ----------+ it('de-duplicates identical candidate ids via the Set', () => {+ // id, resourceId and the derived id all collapse to the same literal so+ // the Set yields exactly one entry.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'dup',+ name: 'ignored',+ refs: { resourceId: 'dup' },+ details: {},+ }),+ ),+ ).toStrictEqual(['dup']);+ });++ // ---- Branch L81 `new Set(...)`: dedup after trim collapses equivalents ---+ it('de-duplicates ids that only differ by surrounding whitespace', () => {+ // 'dup' and ' dup ' both trim to 'dup' → one Set entry.+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'dup',+ name: 'ignored',+ refs: { resourceId: ' dup ' },+ details: {},+ }),+ ),+ ).toStrictEqual(['dup']);+ });++ // ---- Combined: empty record id + no refs/details → empty result ----------+ it('returns an empty array when every candidate is empty or non-string', () => {+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: ' ',+ name: '',+ refs: { resourceId: 0 as unknown as string },+ details: undefined,+ }),+ ),+ ).toStrictEqual([]);+ });++ // ---- Ordering preserved: id, resourceId, derivedLegacyId insertion order -+ it('preserves insertion order [id, resourceId, derived] when all are unique', () => {+ expect(+ getStorageRecordAlertResourceIds(+ makeRecord({+ id: 'storage-1',+ name: 'tank',+ refs: { platformEntityId: 'cluster-a', resourceId: 'legacy-storage-id' },+ details: { node: 'pve1' },+ }),+ ),+ ).toStrictEqual(['storage-1', 'legacy-storage-id', 'cluster-a-pve1-tank']);+ });+});diff --git a/frontend-modern/src/routing/__tests__/navigation.branchcov0712c.test.ts b/frontend-modern/src/routing/__tests__/navigation.branchcov0712c.test.tsnew file mode 100644index 0000000000..f2e1cd92c2--- /dev/null+++ b/frontend-modern/src/routing/__tests__/navigation.branchcov0712c.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';+import { getActiveTabForPath } from '@/routing/navigation';+import {+ ACTIONS_PATH,+ DOCKER_PATH,+ KUBERNETES_PATH,+ PROXMOX_PATH,+ STANDALONE_PATH,+ TRUENAS_PATH,+ VMWARE_PATH,+} from '@/routing/resourceLinks';++// Branch-coverage companion to navigation.test.ts. The sibling suite drives the+// proxmox / standalone / alerts / actions / ai (patrol) / settings true-arms and+// the `return null` fallback, but never forces the docker, kubernetes, truenas,+// or vmware `if (path.startsWith(...))` checks to a truthy return. Each block+// below targets one of those four uncovered true-arms (plus the empty-path+// fallback and the no-boundary `startsWith` over-match documented in+// GLM_REPORT.md).++describe('getActiveTabForPath branch coverage', () => {+ it('returns "docker" for the DOCKER_PATH root and nested docker routes (docker true-arm)', () => {+ expect(getActiveTabForPath(DOCKER_PATH)).toBe('docker');+ expect(getActiveTabForPath(`${DOCKER_PATH}/containers`)).toBe('docker');+ expect(getActiveTabForPath(`${DOCKER_PATH}/host/pve-1`)).toBe('docker');+ });++ it('returns "kubernetes" for the KUBERNETES_PATH root and nested routes (kubernetes true-arm)', () => {+ expect(getActiveTabForPath(KUBERNETES_PATH)).toBe('kubernetes');+ expect(getActiveTabForPath(`${KUBERNETES_PATH}/workloads`)).toBe('kubernetes');+ expect(getActiveTabForPath(`${KUBERNETES_PATH}/config/networking`)).toBe('kubernetes');+ });++ it('returns "truenas" for the TRUENAS_PATH root and nested routes (truenas true-arm)', () => {+ expect(getActiveTabForPath(TRUENAS_PATH)).toBe('truenas');+ expect(getActiveTabForPath(`${TRUENAS_PATH}/datasets`)).toBe('truenas');+ expect(getActiveTabForPath(`${TRUENAS_PATH}/sharing/smb`)).toBe('truenas');+ });++ it('returns "vmware" for the VMWARE_PATH root and nested routes (vmware true-arm)', () => {+ expect(getActiveTabForPath(VMWARE_PATH)).toBe('vmware');+ expect(getActiveTabForPath(`${VMWARE_PATH}/hosts`)).toBe('vmware');+ expect(getActiveTabForPath(`${VMWARE_PATH}/hosts/clusters`)).toBe('vmware');+ });++ it('returns null for an empty path so every startsWith false-arm runs in sequence', () => {+ expect(getActiveTabForPath('')).toBeNull();+ });++ it('returns null for single-character slashes that share only the leading "/"', () => {+ expect(getActiveTabForPath('/d')).toBeNull();+ expect(getActiveTabForPath('/k')).toBeNull();+ expect(getActiveTabForPath('/t')).toBeNull();+ expect(getActiveTabForPath('/v')).toBeNull();+ });++ it('over-matches because startsWith enforces no "/" boundary after the prefix', () => {+ // Documents current semantics: a path that merely begins with the literal+ // prefix — with no path-segment boundary — still resolves to the tab.+ // Reported as a suspected over-match in GLM_REPORT.md (not fixed here).+ expect(getActiveTabForPath(`${DOCKER_PATH}x`)).toBe('docker');+ expect(getActiveTabForPath(`${KUBERNETES_PATH}x`)).toBe('kubernetes');+ expect(getActiveTabForPath(`${TRUENAS_PATH}x`)).toBe('truenas');+ expect(getActiveTabForPath(`${VMWARE_PATH}x`)).toBe('vmware');+ expect(getActiveTabForPath(`${PROXMOX_PATH}y`)).toBe('proxmox');+ expect(getActiveTabForPath(`${STANDALONE_PATH}y`)).toBe('standalone');+ expect(getActiveTabForPath(`${ACTIONS_PATH}y`)).toBe('actions');+ });++ it('resolves each platform root to its own tab rather than a later arm (precedence sanity)', () => {+ // The docker/kubernetes/truenas/vmware checks run before standalone and the+ // remaining arms; confirm a platform root is classified by its own check.+ expect(getActiveTabForPath(DOCKER_PATH)).toBe('docker');+ expect(getActiveTabForPath(KUBERNETES_PATH)).toBe('kubernetes');+ expect(getActiveTabForPath(TRUENAS_PATH)).toBe('truenas');+ expect(getActiveTabForPath(VMWARE_PATH)).toBe('vmware');+ });+});diff --git a/frontend-modern/src/utils/__tests__/actionAuditPresentation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/actionAuditPresentation.branchcov0712c.test.tsnew file mode 100644index 0000000000..e414569baf--- /dev/null+++ b/frontend-modern/src/utils/__tests__/actionAuditPresentation.branchcov0712c.test.ts@@ -0,0 +1,272 @@+import { describe, expect, it } from 'vitest';++import type {+ ActionExecutionTruth,+ ActionResultV2,+ ActionVerificationTruth,+} from '@/types/actionAudit';+import {+ getActionAuditResultPresentation,+ getActionAuditVerificationOutcomePresentation,+} from '@/utils/actionAuditPresentation';++// This suite is scoped to the two named presentation functions and targets the+// `actionResultV2` "truth-layer" branches that the sibling suites never reach:+// every existing test for these two functions exercises either the legacy+// `verificationOutcome` map or the pre-v2 `result` shape, so the v2 execution+// and verification truth branches below were entirely uncovered.++const auditWithExecutionTruth = (+ execution: ActionExecutionTruth,+): Parameters<typeof getActionAuditResultPresentation>[0] => ({+ // success:true forces getActionAuditRefusalPresentation's+ // `!audit.result || audit.result.success` guard to short-circuit, so the+ // refusal branch is skipped and the execution-truth branch is reached.+ result: {+ success: true,+ actionResultV2: {+ version: 2,+ execution,+ verification: { status: 'not_attempted', evidenceClass: 'none' },+ compensation: { support: 'unavailable', status: 'not_needed' },+ },+ },+});++const auditWithVerificationTruth = (+ verification: ActionVerificationTruth,+): Parameters<typeof getActionAuditVerificationOutcomePresentation>[0] => ({+ result: {+ success: true,+ actionResultV2: {+ version: 2,+ execution: { status: 'succeeded' },+ verification,+ compensation: { support: 'unavailable', status: 'not_needed' },+ },+ },+});++describe('getActionAuditResultPresentation — actionResultV2 execution truth path', () => {+ it('maps a succeeded execution to the success badge, trimming summary and formatting reasonCode (both truthy ternary arms)', () => {+ const presentation = getActionAuditResultPresentation(+ auditWithExecutionTruth({+ status: 'succeeded',+ summary: ' service restarted ',+ reasonCode: 'executor_timeout',+ }),+ );+ expect(presentation).toStrictEqual({+ kind: 'success',+ label: 'Execution succeeded',+ detail: 'service restarted',+ reasonLabel: 'Executor Timeout',+ className:+ 'border-blue-200 bg-blue-50 text-blue-800 dark:border-blue-800 dark:bg-blue-950/40 dark:text-blue-200',+ });+ });++ it('maps a failed execution with no summary/reasonCode to the failure badge (both falsy ternary arms)', () => {+ const presentation = getActionAuditResultPresentation(+ auditWithExecutionTruth({ status: 'failed' }),+ );+ expect(presentation).toStrictEqual({+ kind: 'failure',+ label: 'Execution failed',+ detail: undefined,+ reasonLabel: undefined,+ className:+ 'border-red-200 bg-red-50 text-red-800 dark:border-red-800 dark:bg-red-950/40 dark:text-red-300',+ });+ });++ it('maps a not_run execution to the neutral "did not run" badge and collapses whitespace summary to undefined', () => {+ // `truth.summary?.trim()` -> '' -> `|| undefined` (trim-to-empty falsy arm).+ const presentation = getActionAuditResultPresentation(+ auditWithExecutionTruth({ status: 'not_run', summary: ' ' }),+ );+ expect(presentation).toStrictEqual({+ kind: 'failure',+ label: 'Execution did not run',+ detail: undefined,+ reasonLabel: undefined,+ className: 'border-border bg-surface text-base-content',+ });+ });++ it('maps an inconclusive execution to the amber badge with a formatted reasonLabel', () => {+ const presentation = getActionAuditResultPresentation(+ auditWithExecutionTruth({+ status: 'inconclusive',+ summary: 'partial output captured',+ reasonCode: 'window_closed',+ }),+ );+ expect(presentation).toStrictEqual({+ kind: 'failure',+ label: 'Execution inconclusive',+ detail: 'partial output captured',+ reasonLabel: 'Window Closed',+ className:+ 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300',+ });+ });++ it('falls through to the success branch when actionResultV2 exists but execution is absent (optional-chain short-circuit)', () => {+ // `result.actionResultV2?.execution` -> undefined when the execution key is+ // missing, so `if (truth)` is false and control reaches the `result.success`+ // branch. Distinct from actionResultV2 being entirely absent (covered by+ // sibling suites): here actionResultV2 is present, exercising the `?.`+ // short-circuit on a real-but-incomplete v2 record.+ const presentation = getActionAuditResultPresentation({+ result: {+ success: true,+ actionResultV2: {+ version: 2,+ verification: { status: 'not_attempted', evidenceClass: 'none' },+ compensation: { support: 'unavailable', status: 'not_needed' },+ } as unknown as ActionResultV2,+ },+ });+ expect(presentation).toStrictEqual({+ kind: 'success',+ label: 'Result',+ detail: undefined,+ className: 'border-border bg-surface text-base-content',+ });+ });+});++describe('getActionAuditVerificationOutcomePresentation — actionResultV2 verification truth path', () => {+ it('renders confirmed+independent with the independent-observer copy, trimmed summary, and emerald badge', () => {+ const presentation = getActionAuditVerificationOutcomePresentation(+ auditWithVerificationTruth({+ status: 'confirmed',+ evidenceClass: 'independent',+ summary: ' readback matched ',+ }),+ );+ expect(presentation).toStrictEqual({+ label: 'Confirmed by independent observer',+ detail: 'An observer in a different trust domain confirmed the intended state.',+ evidenceSummary: 'readback matched Source: Independent observer.',+ className:+ 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300',+ });+ });++ it('renders confirmed+agent_attested with the agent-attested copy and the default summary fallback', () => {+ // Exercises the agent_attested arm of both the `source` ternary and the+ // nested `confirmed` statusCopy ternary, plus the `summary?.trim() ||`+ // fallback arm (no summary -> canned message).+ const presentation = getActionAuditVerificationOutcomePresentation(+ auditWithVerificationTruth({+ status: 'confirmed',+ evidenceClass: 'agent_attested',+ }),+ );+ expect(presentation).toStrictEqual({+ label: 'Confirmed by executing agent',+ detail: 'The same agent trust domain that executed the action reported the intended state.',+ evidenceSummary:+ 'No additional verification summary. Source: Executing agent (agent-attested).',+ className:+ 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300',+ });+ });++ it('renders confirmed+none with the "lacks an evidence source" copy (else arm of both evidenceClass ternaries)', () => {+ const presentation = getActionAuditVerificationOutcomePresentation(+ auditWithVerificationTruth({+ status: 'confirmed',+ evidenceClass: 'none',+ }),+ );+ expect(presentation).toStrictEqual({+ label: 'Confirmation lacks an evidence source',+ detail: 'The record says confirmed but provides no evidence source; do not treat it as independently verified.',+ evidenceSummary: 'No additional verification summary. Source: No evidence source.',+ className:+ 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300',+ });+ });++ it('renders contradicted with the rose badge (contradicted statusCopy arm + rose className arm)', () => {+ const presentation = getActionAuditVerificationOutcomePresentation(+ auditWithVerificationTruth({+ status: 'contradicted',+ evidenceClass: 'independent',+ summary: 'observed state differed',+ }),+ );+ expect(presentation).toStrictEqual({+ label: 'Outcome contradicted',+ detail: 'Observed evidence contradicted the intended state.',+ evidenceSummary: 'observed state differed Source: Independent observer.',+ className:+ 'border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-300',+ });+ });++ it('renders inconclusive with the amber badge (inconclusive statusCopy arm + amber className else arm)', () => {+ const presentation = getActionAuditVerificationOutcomePresentation(+ auditWithVerificationTruth({+ status: 'inconclusive',+ evidenceClass: 'agent_attested',+ }),+ );+ expect(presentation).toStrictEqual({+ label: 'Outcome inconclusive',+ detail: 'Available evidence could not establish the intended state.',+ evidenceSummary:+ 'No additional verification summary. Source: Executing agent (agent-attested).',+ className:+ 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300',+ });+ });++ it('renders not_attempted with the amber badge (not_attempted statusCopy arm + amber className else arm)', () => {+ const presentation = getActionAuditVerificationOutcomePresentation(+ auditWithVerificationTruth({+ status: 'not_attempted',+ evidenceClass: 'none',+ }),+ );+ expect(presentation).toStrictEqual({+ label: 'Outcome not verified',+ detail: 'No outcome verification was attempted.',+ evidenceSummary: 'No additional verification summary. Source: No evidence source.',+ className:+ 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300',+ });+ });++ it('falls through to the legacy verificationOutcome path when actionResultV2 exists but verification is absent', () => {+ // `audit.result?.actionResultV2?.verification` -> undefined when the+ // verification key is missing, so `if (truth)` is false and control reaches+ // the `verificationOutcome` legacy branch. Distinct from result/actionResultV2+ // being absent: here actionResultV2 is present, exercising the `?.verification`+ // short-circuit on a real-but-incomplete v2 record.+ const presentation = getActionAuditVerificationOutcomePresentation({+ result: {+ success: true,+ actionResultV2: {+ version: 2,+ execution: { status: 'succeeded' },+ compensation: { support: 'unavailable', status: 'not_needed' },+ } as unknown as ActionResultV2,+ },+ verificationOutcome: {+ status: 'verified',+ evidenceSummary: 'legacy readback',+ },+ });+ expect(presentation).toStrictEqual({+ label: 'Legacy check passed (source unclassified)',+ detail: 'This older record does not identify an evidence source. Do not treat it as independent confirmation.',+ evidenceSummary: 'legacy readback',+ className:+ 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300',+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.branchcov0712c.test.tsnew file mode 100644index 0000000000..d08a7d9140--- /dev/null+++ b/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.branchcov0712c.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';+import { getPatrolScheduleLabel } from '@/utils/aiPatrolSchedulePresentation';++describe('getPatrolScheduleLabel (branch coverage)', () => {+ describe('preset-found arm: if (preset) return preset.label', () => {+ it('returns the "Off" label when minutes is 0 even though 0 is a falsy value', () => {+ // Guards against a regression where the guard is refactored to+ // `if (minutes)` (which would wrongly fall through for the 0 preset).+ expect(getPatrolScheduleLabel(0)).toBe('Off');+ });++ it('returns the canonical label for every remaining preset value not covered by the sibling suite', () => {+ // Sibling suite already covers 60 -> '1 hour'; here we exercise the+ // find() predicate true-arm for the rest of PATROL_SCHEDULE_PRESETS.+ expect(getPatrolScheduleLabel(10)).toBe('10 min');+ expect(getPatrolScheduleLabel(15)).toBe('15 min');+ expect(getPatrolScheduleLabel(30)).toBe('30 min');+ expect(getPatrolScheduleLabel(180)).toBe('3 hours');+ expect(getPatrolScheduleLabel(360)).toBe('6 hours');+ expect(getPatrolScheduleLabel(720)).toBe('12 hours');+ expect(getPatrolScheduleLabel(1440)).toBe('24 hours');+ });+ });++ describe('preset-not-found arm: return `${minutes} min`', () => {+ it('falls back to a templated label for an unmatched positive integer', () => {+ // Sibling suite already covers 17; use a different value here.+ expect(getPatrolScheduleLabel(5)).toBe('5 min');+ });++ it('falls back to a templated label for a large unmatched value', () => {+ expect(getPatrolScheduleLabel(9999)).toBe('9999 min');+ });++ it('falls back to a templated label (including the minus sign) for a negative value', () => {+ expect(getPatrolScheduleLabel(-5)).toBe('-5 min');+ });++ it('falls back to a templated label that preserves fractional minutes', () => {+ // Exercises String interpolation of a non-integer through the template+ // literal in the fallback branch.+ expect(getPatrolScheduleLabel(1.5)).toBe('1.5 min');+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/alertHistoryPresentation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/alertHistoryPresentation.branchcov0712c.test.tsnew file mode 100644index 0000000000..e183685169--- /dev/null+++ b/frontend-modern/src/utils/__tests__/alertHistoryPresentation.branchcov0712c.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest';+import { getAlertHistoryResourceTypeBadgeClass } from '@/utils/alertHistoryPresentation';++// Branch-coverage companion to alertHistoryPresentation.test.ts. The sibling+// suite only asserts partial substrings (`.toContain('bg-blue-100')` etc.) and+// omits the `system-container` arm, the nullish/empty normalization branches,+// and the exact full-class composition (including the `dark:` variants). These+// tests pin the complete concrete output strings and drive every+// previously-uncovered branch: the 4th OR operand (`system-container`), the+// `??` right operand for null/undefined/omitted, the trim-to-empty default arm,+// surrounding-whitespace trimming, and case-insensitive matching on each arm.++// Full canonical class strings mirrored from the source module so the+// assertions describe the documented badge composition (including the `dark:`+// variants the sibling suite never checked) rather than echoing a partial+// substring.+const VM_NODE_BADGE =+ 'text-xs px-1 py-0.5 rounded bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300';+const CONTAINER_BADGE =+ 'text-xs px-1 py-0.5 rounded bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300';+const STORAGE_BADGE =+ 'text-xs px-1 py-0.5 rounded bg-orange-100 dark:bg-orange-900 text-orange-700 dark:text-orange-300';+const DEFAULT_BADGE = 'text-xs px-1 py-0.5 rounded bg-surface-hover text-base-content';++describe('getAlertHistoryResourceTypeBadgeClass — vm/node arm (first if)', () => {+ it('returns the exact blue badge for lowercase "vm" (full dark: variants)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('vm')).toBe(VM_NODE_BADGE);+ });++ it('returns the exact blue badge for lowercase "node"', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('node')).toBe(VM_NODE_BADGE);+ });++ it('matches "VM" case-insensitively (toLowerCase branch)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('VM')).toBe(VM_NODE_BADGE);+ });++ it('matches "NoDe" mixed-case case-insensitively (second OR operand of first if)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('NoDe')).toBe(VM_NODE_BADGE);+ });+});++describe('getAlertHistoryResourceTypeBadgeClass — container arm (second if, all four OR operands)', () => {+ it('returns the exact green badge for "container" (1st OR operand, full dark: variants)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('container')).toBe(CONTAINER_BADGE);+ });++ it('returns the exact green badge for "ct" (2nd OR operand)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('ct')).toBe(CONTAINER_BADGE);+ });++ it('returns the exact green badge for "lxc" (3rd OR operand)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('lxc')).toBe(CONTAINER_BADGE);+ });++ it('returns the exact green badge for "system-container" (4th OR operand, previously uncovered)', () => {+ // The sibling suite never passes 'system-container'; this newly exercises+ // the last disjunct in the container if-block — the unified-model name the+ // v6 alert engine stamps for LXC guests (guest_snapshot.go resourceType()).+ expect(getAlertHistoryResourceTypeBadgeClass('system-container')).toBe(CONTAINER_BADGE);+ });++ it('matches "System-Container" case-insensitively (4th OR operand via toLowerCase)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('System-Container')).toBe(CONTAINER_BADGE);+ });++ it('matches "LXC" case-insensitively (3rd OR operand via toLowerCase)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('LXC')).toBe(CONTAINER_BADGE);+ });+});++describe('getAlertHistoryResourceTypeBadgeClass — storage arm (third if)', () => {+ it('returns the exact orange badge for "storage" (full dark: variants)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('storage')).toBe(STORAGE_BADGE);+ });++ it('matches "STORAGE" case-insensitively', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('STORAGE')).toBe(STORAGE_BADGE);+ });+});++describe('getAlertHistoryResourceTypeBadgeClass — default arm and nullish normalization (?? + trim)', () => {+ it('returns the default badge for an unrecognized resource type that skips all ifs', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('network')).toBe(DEFAULT_BADGE);+ });++ it('returns the default badge when resourceType is null (?? right operand)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass(null)).toBe(DEFAULT_BADGE);+ });++ it('returns the default badge when resourceType is undefined (?? right operand)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass(undefined)).toBe(DEFAULT_BADGE);+ });++ it('returns the default badge when resourceType is omitted (?? via undefined argument)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass()).toBe(DEFAULT_BADGE);+ });++ it('returns the default badge for an empty string (normalized to "" -> default)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('')).toBe(DEFAULT_BADGE);+ });++ it('returns the default badge for a whitespace-only value (trim -> empty -> default)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass(' ')).toBe(DEFAULT_BADGE);+ });++ it('trims surrounding whitespace before matching (" vm " still hits the vm arm)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass(' vm ')).toBe(VM_NODE_BADGE);+ });++ it('trims and lowercases before matching (" StOrAgE " hits the storage arm)', () => {+ expect(getAlertHistoryResourceTypeBadgeClass(' StOrAgE ')).toBe(STORAGE_BADGE);+ });++ it('lowercases an unrecognized mixed-case value before reaching the default arm', () => {+ expect(getAlertHistoryResourceTypeBadgeClass('UNKNOWN')).toBe(DEFAULT_BADGE);+ });+});diff --git a/frontend-modern/src/utils/__tests__/alertsActivation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/alertsActivation.branchcov0712c.test.tsnew file mode 100644index 0000000000..c9ef5cf528--- /dev/null+++ b/frontend-modern/src/utils/__tests__/alertsActivation.branchcov0712c.test.ts@@ -0,0 +1,171 @@+/**+ * Branch-coverage tests for alertsActivation.ts.+ *+ * Scope: ONLY `setGlobalActivationState` and `isAlertsActivationEnabled`.+ * The sibling alertsActivation.test.ts exercises the browser happy-path for+ * both functions; this file drives every remaining branch:+ *+ * - `setGlobalActivationState`:+ * - The `if (!isBrowser) return` early-return arm (SSR), verified by+ * reloading the module while `window` is undefined and asserting that+ * `window.__pulseAlertsActivationState` is left untouched and no event+ * is dispatched.+ * - The browser dispatch arm for every value of `ActivationState | null`,+ * asserting each dispatched event is a genuine `CustomEvent` instance,+ * its `type` equals `ALERTS_ACTIVATION_EVENT`, and its `detail` equals+ * the exact value passed (including `null`), and that each call+ * dispatches a fresh event with no dedup.+ *+ * - `isAlertsActivationEnabled`:+ * - The `if (!isBrowser) return true` SSR arm.+ * - The `state === 'pending_review'` case flowing through the+ * `return state === 'active'` false arm (sibling test only covers+ * 'snoozed' for that arm).+ * - The `state === undefined || state === null` early-true arm via both+ * inputs independently.+ *+ * The SSR arms are reached with `vi.resetModules()` + a dynamic `import()`+ * while `window` is stubbed to `undefined`, so the module-level `isBrowser`+ * const is re-evaluated to `false`. The stub is always cleared via+ * `vi.unstubAllGlobals()` in `afterEach` (and inside `finally` blocks).+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { ActivationState } from '@/types/alerts';+import {+ ALERTS_ACTIVATION_EVENT,+ isAlertsActivationEnabled,+ setGlobalActivationState,+} from '@/utils/alertsActivation';++describe('setGlobalActivationState (branch coverage)', () => {+ beforeEach(() => {+ window.__pulseAlertsActivationState = null;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('writes the exact value to window.__pulseAlertsActivationState for every ActivationState and null', () => {+ const cases: Array<ActivationState | null> = [+ 'pending_review',+ 'active',+ 'snoozed',+ null,+ ];+ for (const c of cases) {+ setGlobalActivationState(c);+ expect(window.__pulseAlertsActivationState).toBe(c);+ }+ });++ it('dispatches a fresh genuine CustomEvent whose detail equals each value passed (all ActivationState and null)', () => {+ const dispatchSpy = vi.spyOn(window, 'dispatchEvent');+ const seen: Array<{+ type: string;+ detail: ActivationState | null;+ isCustomEvent: boolean;+ }> = [];+ dispatchSpy.mockImplementation((event: Event) => {+ seen.push({+ type: event.type,+ detail: (event as CustomEvent<ActivationState | null>).detail,+ isCustomEvent: event instanceof CustomEvent,+ });+ return true;+ });++ const cases: Array<ActivationState | null> = [+ 'pending_review',+ 'active',+ 'snoozed',+ null,+ ];+ for (const c of cases) {+ setGlobalActivationState(c);+ }++ expect(seen).toStrictEqual(+ cases.map((c) => ({+ type: ALERTS_ACTIVATION_EVENT,+ detail: c,+ isCustomEvent: true,+ })),+ );+ // No dedup: exactly one dispatch per call.+ expect(dispatchSpy).toHaveBeenCalledTimes(cases.length);+ });++ it('early-returns in an SSR context (window undefined at module load) without mutating state or dispatching', async () => {+ // Sentinel: the SSR call must NOT overwrite this.+ window.__pulseAlertsActivationState = 'active';+ const dispatchSpy = vi.spyOn(window, 'dispatchEvent');+ const callsBefore = dispatchSpy.mock.calls.length;++ vi.resetModules();+ vi.stubGlobal('window', undefined);+ try {+ // Fresh module instance: module-level `isBrowser` is re-evaluated to+ // `false` because `typeof window === 'undefined'` at load time.+ const mod = await import('@/utils/alertsActivation');+ mod.setGlobalActivationState(null);+ mod.setGlobalActivationState('snoozed');+ } finally {+ vi.unstubAllGlobals();+ }++ // window is restored: sentinel must be unchanged, and no new dispatch+ // may have occurred during the SSR calls.+ expect(window.__pulseAlertsActivationState).toBe('active');+ expect(dispatchSpy.mock.calls.length).toBe(callsBefore);+ });+});++describe('isAlertsActivationEnabled (branch coverage)', () => {+ beforeEach(() => {+ window.__pulseAlertsActivationState = null;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('returns false for pending_review (false arm of `state === "active"`, not exercised by sibling test)', () => {+ setGlobalActivationState('pending_review');+ expect(isAlertsActivationEnabled()).toBe(false);+ });++ it('returns false for snoozed (false arm of `state === "active"`)', () => {+ setGlobalActivationState('snoozed');+ expect(isAlertsActivationEnabled()).toBe(false);+ });++ it('returns true for active (true arm of `state === "active"`)', () => {+ setGlobalActivationState('active');+ expect(isAlertsActivationEnabled()).toBe(true);+ });++ it('returns true when window.__pulseAlertsActivationState is explicitly undefined (left || operand true)', () => {+ window.__pulseAlertsActivationState = undefined;+ expect(isAlertsActivationEnabled()).toBe(true);+ });++ it('returns true when window.__pulseAlertsActivationState is null (right || operand true)', () => {+ window.__pulseAlertsActivationState = null;+ expect(isAlertsActivationEnabled()).toBe(true);+ });++ it('returns true in an SSR context (window undefined at module load) via the !isBrowser early return', async () => {+ vi.resetModules();+ vi.stubGlobal('window', undefined);+ try {+ const mod = await import('@/utils/alertsActivation');+ expect(mod.isAlertsActivationEnabled()).toBe(true);+ } finally {+ vi.unstubAllGlobals();+ }+ });+});diff --git a/frontend-modern/src/utils/__tests__/appShellScrollRestoration.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/appShellScrollRestoration.branchcov0712c.test.tsnew file mode 100644index 0000000000..da89478a76--- /dev/null+++ b/frontend-modern/src/utils/__tests__/appShellScrollRestoration.branchcov0712c.test.ts@@ -0,0 +1,84 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ capturePendingAppShellRestoreTop,+ clearPendingAppShellRestoreTop,+ readPendingAppShellRestoreTop,+} from '@/utils/appShellScrollRestoration';++describe('capturePendingAppShellRestoreTop – branch coverage', () => {+ beforeEach(() => {+ clearPendingAppShellRestoreTop();+ document.body.innerHTML = '';+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = '';+ });++ it('returns early without capturing when document is undefined (SSR guard arm)', () => {+ vi.stubGlobal('document', undefined);++ capturePendingAppShellRestoreTop();++ expect(readPendingAppShellRestoreTop()).toBeNull();+ });++ it('does not capture when no .app-scroll-shell element exists (!shell short-circuit arm)', () => {+ capturePendingAppShellRestoreTop();++ expect(readPendingAppShellRestoreTop()).toBeNull();+ });++ it('does not capture when the shell is at the top (scrollTop === 0 hits the <= 0 boundary arm)', () => {+ const shell = document.createElement('div');+ shell.className = 'app-scroll-shell';+ shell.scrollTop = 0;+ document.body.appendChild(shell);++ capturePendingAppShellRestoreTop();++ expect(readPendingAppShellRestoreTop()).toBeNull();+ });++ it('does not capture when the shell reports a negative scrollTop (defensive <= 0 arm)', () => {+ // Real browsers never report a negative scrollTop, so inject a stub+ // element via querySelector to force the <= 0 guard's negative side and+ // confirm the exact selector contract.+ const stubShell = { scrollTop: -10 } as unknown as HTMLElement;+ const querySpy = vi.spyOn(document, 'querySelector').mockReturnValue(stubShell);++ capturePendingAppShellRestoreTop();++ expect(readPendingAppShellRestoreTop()).toBeNull();+ expect(querySpy).toHaveBeenCalledWith('.app-scroll-shell');+ querySpy.mockRestore();+ });++ it('captures the exact scrollTop when the shell is scrolled past the top (happy path)', () => {+ const shell = document.createElement('div');+ shell.className = 'app-scroll-shell';+ shell.scrollTop = 327;+ document.body.appendChild(shell);++ capturePendingAppShellRestoreTop();++ expect(readPendingAppShellRestoreTop()).toBe(327);+ });++ it('preserves a previously captured value when a later capture hits a guard arm (no-overwrite)', () => {+ const scrolled = document.createElement('div');+ scrolled.className = 'app-scroll-shell';+ scrolled.scrollTop = 150;+ document.body.appendChild(scrolled);++ capturePendingAppShellRestoreTop();+ expect(readPendingAppShellRestoreTop()).toBe(150);++ scrolled.remove();+ capturePendingAppShellRestoreTop();++ expect(readPendingAppShellRestoreTop()).toBe(150);+ });+});diff --git a/frontend-modern/src/utils/__tests__/resourceMetadataEvents.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/resourceMetadataEvents.branchcov0712c.test.tsnew file mode 100644index 0000000000..3361377ceb--- /dev/null+++ b/frontend-modern/src/utils/__tests__/resourceMetadataEvents.branchcov0712c.test.ts@@ -0,0 +1,207 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ RESOURCE_METADATA_CHANGED_EVENT,+ dispatchResourceMetadataChanged,+} from '@/utils/resourceMetadataEvents';+import type { ResourceMetadataChangedDetail } from '@/utils/resourceMetadataEvents';++// Branch-coverage companion for resourceMetadataEvents.ts. The module exposes a+// single side-effecting function `dispatchResourceMetadataChanged` plus the+// exported event-name constant; there is no sibling unit test for it, so this+// file drives every branch of the guard (`typeof window === 'undefined'` and+// `!detail.metadataId`), the happy-path `try` success arm across all three+// `metadataKind` values and the optional `customUrl`, and the defensive+// `catch` arm that swallows dispatch failures. Assertions are concrete event+// shapes / spy call counts rather than truthiness.++// Capture the real jsdom window once, at module load, so listeners stay wired+// to a stable object even when an individual test stubs the global `window`+// binding to undefined. The function under test reads the global `window`;+// when that binding is the real jsdom window it is the SAME object as `win`,+// so dispatches still reach listeners wired here. Spies are created locally in+// each test (matching the sibling convention) so their precise return types+// are inferred without a fragile field annotation.+const win: Window & typeof globalThis = window;++describe('dispatchResourceMetadataChanged', () => {+ let listener: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ listener = vi.fn();+ win.addEventListener(RESOURCE_METADATA_CHANGED_EVENT, listener);+ });++ afterEach(() => {+ // Restore globals FIRST so a stubbed-out `window`/`CustomEvent` is back in+ // place before we touch listeners; otherwise the next line could throw and+ // leak into the following test.+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ win.removeEventListener(RESOURCE_METADATA_CHANGED_EVENT, listener);+ });++ describe('guard early-return branches (no event is dispatched)', () => {+ it('returns without dispatching when `typeof window === "undefined"` (first guard arm)', () => {+ const dispatchSpy = vi.spyOn(win, 'dispatchEvent');+ // The guard's left operand short-circuits before `!detail.metadataId`+ // is even evaluated, so a perfectly valid detail still yields no dispatch.+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'agent',+ metadataId: 'agent-7',+ };+ vi.stubGlobal('window', undefined);++ dispatchResourceMetadataChanged(detail);++ expect(dispatchSpy).not.toHaveBeenCalled();+ expect(listener).not.toHaveBeenCalled();+ });++ it('returns without dispatching when metadataId is the empty string (`!detail.metadataId` arm)', () => {+ const dispatchSpy = vi.spyOn(win, 'dispatchEvent');+ // `typeof window` is defined, but the right guard operand is true for '',+ // so the function bails before constructing a CustomEvent.+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'guest',+ metadataId: '',+ };++ dispatchResourceMetadataChanged(detail);++ expect(dispatchSpy).not.toHaveBeenCalled();+ expect(listener).not.toHaveBeenCalled();+ });++ it('treats a whitespace-only metadataId as truthy and dispatches (documents that the guard is not a trim check)', () => {+ // The guard uses a raw truthiness check on metadataId, NOT a trim check,+ // so ' ' is a non-empty string and clears the guard. Pinning the actual+ // (arguably surprising) behaviour: the event is dispatched verbatim.+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'docker',+ metadataId: ' ',+ };++ dispatchResourceMetadataChanged(detail);++ expect(listener).toHaveBeenCalledTimes(1);+ const event = listener.mock.calls[0][0] as CustomEvent<ResourceMetadataChangedDetail>;+ expect(event.type).toBe(RESOURCE_METADATA_CHANGED_EVENT);+ expect(event.detail).toStrictEqual(detail);+ });+ });++ describe('happy-path try-success arm (event is dispatched with the exact detail)', () => {+ it.each([+ ['agent', { metadataKind: 'agent', metadataId: 'agent-1' } as const],+ ['guest', { metadataKind: 'guest', metadataId: 'vm-100' } as const],+ ['docker', { metadataKind: 'docker', metadataId: 'container-abc' } as const],+ ])('dispatches a CustomEvent for metadataKind=%s without customUrl', (_label, detail) => {+ const dispatchSpy = vi.spyOn(win, 'dispatchEvent');++ dispatchResourceMetadataChanged(detail);++ expect(dispatchSpy).toHaveBeenCalledTimes(1);+ expect(listener).toHaveBeenCalledTimes(1);+ const event = listener.mock.calls[0][0] as CustomEvent<ResourceMetadataChangedDetail>;+ // The exported constant is threaded through verbatim as the event type.+ expect(event.type).toBe(RESOURCE_METADATA_CHANGED_EVENT);+ // The detail object is forwarded by reference, including metadataKind.+ expect(event.detail).toStrictEqual(detail);+ // A fresh CustomEvent instance is constructed (not, e.g., a reused one).+ expect(event).toBeInstanceOf(CustomEvent);+ });++ it('forwards an optional customUrl when present on the detail', () => {+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'agent',+ metadataId: 'agent-2',+ customUrl: 'https://host:9090/agent/agent-2',+ };++ dispatchResourceMetadataChanged(detail);++ expect(listener).toHaveBeenCalledTimes(1);+ const event = listener.mock.calls[0][0] as CustomEvent<ResourceMetadataChangedDetail>;+ expect(event.detail).toStrictEqual(detail);+ expect(event.detail.customUrl).toBe('https://host:9090/agent/agent-2');+ });++ it('omits customUrl from the forwarded detail when it was not supplied', () => {+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'guest',+ metadataId: 'vm-101',+ };++ dispatchResourceMetadataChanged(detail);++ const event = listener.mock.calls[0][0] as CustomEvent<ResourceMetadataChangedDetail>;+ // toStrictEqual asserts the key is genuinely absent, not just undefined.+ expect(event.detail).toStrictEqual({ metadataKind: 'guest', metadataId: 'vm-101' });+ expect('customUrl' in event.detail).toBe(false);+ });++ it('passes the detail object by reference (no defensive clone)', () => {+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'docker',+ metadataId: 'container-ref',+ };++ dispatchResourceMetadataChanged(detail);++ const event = listener.mock.calls[0][0] as CustomEvent<ResourceMetadataChangedDetail>;+ // Pin the by-reference forwarding: the same object identity reaches the+ // listener. A future clone would break this test deliberately.+ expect(event.detail).toBe(detail);+ });+ });++ describe('catch arm (dispatch failures are swallowed, not re-thrown)', () => {+ it('swallows a throw from window.dispatchEvent and does not propagate', () => {+ const dispatchSpy = vi+ .spyOn(win, 'dispatchEvent')+ .mockImplementation(() => {+ throw new Error('dispatch boom');+ });+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'agent',+ metadataId: 'agent-3',+ };++ // The catch block is a no-op; the function must resolve to undefined.+ const result = dispatchResourceMetadataChanged(detail);++ expect(result).toBeUndefined();+ // The throw happens *inside* dispatchEvent, proving we reached the try+ // body — i.e. the guard did NOT short-circuit.+ expect(dispatchSpy).toHaveBeenCalledTimes(1);+ // No real listener receives the event because dispatchEvent threw before+ // any delivery could occur.+ expect(listener).not.toHaveBeenCalled();+ });++ it('swallows a throw from the CustomEvent constructor itself', () => {+ const dispatchSpy = vi.spyOn(win, 'dispatchEvent');+ // Drive the catch via the other throwable site: make `new CustomEvent`+ // reject. This confirms the whole try expression is guarded, not just+ // the dispatchEvent call.+ const original = globalThis.CustomEvent;+ vi.stubGlobal('CustomEvent', class {+ constructor() {+ throw new Error('ctor boom');+ }+ });+ const detail: ResourceMetadataChangedDetail = {+ metadataKind: 'guest',+ metadataId: 'vm-102',+ };++ expect(() => dispatchResourceMetadataChanged(detail)).not.toThrow();+ // dispatchEvent is never reached because the constructor threw first.+ expect(dispatchSpy).not.toHaveBeenCalled();+ expect(listener).not.toHaveBeenCalled();++ vi.stubGlobal('CustomEvent', original);+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/unifiedAgentStatusPresentation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/unifiedAgentStatusPresentation.branchcov0712c.test.tsnew file mode 100644index 0000000000..5b24c376ce--- /dev/null+++ b/frontend-modern/src/utils/__tests__/unifiedAgentStatusPresentation.branchcov0712c.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from 'vitest';+import {+ getUnifiedAgentStatusPresentation,+ MONITORING_STOPPED_STATUS_LABEL,+} from '@/utils/unifiedAgentStatusPresentation';++const REMOVED_BADGE = 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200';+const CONNECTED_BADGE = 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300';+const DISCONNECTED_BADGE = 'bg-surface-alt text-base-content';++describe('getUnifiedAgentStatusPresentation — branch coverage', () => {+ describe("state === 'removed' short-circuits before any health-status check", () => {+ it('takes precedence over a connected health status (online)', () => {+ expect(getUnifiedAgentStatusPresentation('removed', 'online')).toStrictEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });++ it('takes precedence over a disconnected health status (offline)', () => {+ expect(getUnifiedAgentStatusPresentation('removed', 'offline')).toStrictEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });++ it('applies when healthStatus is omitted', () => {+ expect(getUnifiedAgentStatusPresentation('removed')).toStrictEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });++ it('applies when healthStatus is null', () => {+ expect(getUnifiedAgentStatusPresentation('removed', null)).toStrictEqual({+ badgeClass: REMOVED_BADGE,+ label: MONITORING_STOPPED_STATUS_LABEL,+ });+ });+ });++ describe("state === 'active' with a connected health status (isConnectedHealthStatus === true)", () => {+ it("returns the green badge with the raw 'online' label", () => {+ expect(getUnifiedAgentStatusPresentation('active', 'online')).toStrictEqual({+ badgeClass: CONNECTED_BADGE,+ label: 'online',+ });+ });++ it("treats 'running' as connected", () => {+ expect(getUnifiedAgentStatusPresentation('active', 'running')).toStrictEqual({+ badgeClass: CONNECTED_BADGE,+ label: 'running',+ });+ });++ it("treats 'healthy' as connected", () => {+ expect(getUnifiedAgentStatusPresentation('active', 'healthy')).toStrictEqual({+ badgeClass: CONNECTED_BADGE,+ label: 'healthy',+ });+ });++ it('matches connectivity case-insensitively while preserving the raw label casing', () => {+ expect(getUnifiedAgentStatusPresentation('active', 'OnLiNe')).toStrictEqual({+ badgeClass: CONNECTED_BADGE,+ label: 'OnLiNe',+ });+ });++ it('trims surrounding whitespace for the connectivity check while keeping the raw label', () => {+ expect(getUnifiedAgentStatusPresentation('active', ' Running ')).toStrictEqual({+ badgeClass: CONNECTED_BADGE,+ label: ' Running ',+ });+ });+ });++ describe("state === 'active' with a non-connected health status (isConnectedHealthStatus === false)", () => {+ it("returns the muted badge and preserves a truthy non-connected status ('offline')", () => {+ expect(getUnifiedAgentStatusPresentation('active', 'offline')).toStrictEqual({+ badgeClass: DISCONNECTED_BADGE,+ label: 'offline',+ });+ });++ it("preserves a degraded status ('degraded') as the raw label", () => {+ expect(getUnifiedAgentStatusPresentation('active', 'degraded')).toStrictEqual({+ badgeClass: DISCONNECTED_BADGE,+ label: 'degraded',+ });+ });++ it("preserves the literal 'unknown' status as the label (truthy-fallback arm)", () => {+ expect(getUnifiedAgentStatusPresentation('active', 'unknown')).toStrictEqual({+ badgeClass: DISCONNECTED_BADGE,+ label: 'unknown',+ });+ });++ it('falls back to the "unknown" label when healthStatus is undefined', () => {+ expect(getUnifiedAgentStatusPresentation('active')).toStrictEqual({+ badgeClass: DISCONNECTED_BADGE,+ label: 'unknown',+ });+ });++ it('falls back to the "unknown" label when healthStatus is null', () => {+ expect(getUnifiedAgentStatusPresentation('active', null)).toStrictEqual({+ badgeClass: DISCONNECTED_BADGE,+ label: 'unknown',+ });+ });++ it('falls back to the "unknown" label when healthStatus is an empty string', () => {+ expect(getUnifiedAgentStatusPresentation('active', '')).toStrictEqual({+ badgeClass: DISCONNECTED_BADGE,+ label: 'unknown',+ });+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/upgradeNavigation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/upgradeNavigation.branchcov0712c.test.tsnew file mode 100644index 0000000000..e9543cd4e8--- /dev/null+++ b/frontend-modern/src/utils/__tests__/upgradeNavigation.branchcov0712c.test.ts@@ -0,0 +1,210 @@+import { describe, expect, it, vi } from 'vitest';+import {+ navigateToUpgradeDestination,+ openExternalUpgradeDestination,+} from '@/utils/upgradeNavigation';+import type { UpgradeDestination } from '@/utils/upgradeNavigation';++describe('upgradeNavigation (branch coverage)', () => {+ describe('openExternalUpgradeDestination', () => {+ it('skips window.open under SSR (typeof window === "undefined") and opens when window is present', () => {+ const openSpy = vi.fn();++ // SSR guard: typeof window === 'undefined' -> early return before window.open.+ // If the guard were absent, `undefined.open(...)` would throw.+ vi.stubGlobal('window', undefined);+ expect(() => openExternalUpgradeDestination('https://example.com/pricing', false)).not.toThrow();+ vi.unstubAllGlobals();+ // The held spy was never wired during the SSR call -> concrete proof the guard fired.+ expect(openSpy).toHaveBeenCalledTimes(0);++ // Contrast: with window present the same call reaches window.open with the+ // safe new-tab policy.+ vi.stubGlobal('window', { open: openSpy });+ openExternalUpgradeDestination('https://example.com/pricing', false);+ vi.unstubAllGlobals();+ expect(openSpy).toHaveBeenCalledTimes(1);+ expect(openSpy).toHaveBeenLastCalledWith(+ 'https://example.com/pricing',+ '_blank',+ 'noopener,noreferrer',+ );+ });++ it('omits the noopener,noreferrer feature string when preserveOpener=true (preserveOpener truthy arm)', () => {+ const openSpy = vi.fn();+ vi.stubGlobal('window', { open: openSpy });++ openExternalUpgradeDestination('/auth/license-purchase-start?feature=relay', true);++ vi.unstubAllGlobals();+ // preserveOpener truthy branch: window.open is called with exactly two+ // args — the third "noopener,noreferrer" arg must NOT be present, so the+ // opened page can post messages back to refresh the opener.+ expect(openSpy).toHaveBeenCalledTimes(1);+ expect(openSpy).toHaveBeenCalledWith('/auth/license-purchase-start?feature=relay', '_blank');+ expect(openSpy).toHaveBeenNthCalledWith(+ 1,+ '/auth/license-purchase-start?feature=relay',+ '_blank',+ );+ });+ });++ describe('navigateToUpgradeDestination', () => {+ it('honors an explicit newTab=true even when external is false (?? left arm for newTab)', () => {+ const navigate = vi.fn();+ const openExternal = vi.fn();+ const destination: UpgradeDestination = {+ href: '/cloud',+ external: false,+ newTab: true,+ };++ navigateToUpgradeDestination(destination, navigate, openExternal);++ // newTab=true overrides external=false -> opens externally; preserveOpener+ // omitted so the ?? falls back to false.+ expect(openExternal).toHaveBeenCalledWith('/cloud', false);+ expect(navigate).not.toHaveBeenCalled();+ });++ it('honors explicit newTab=false and hardNavigation=false even when external is true (?? left arms, navigate fall-through)', () => {+ const navigate = vi.fn();+ const openExternal = vi.fn();+ const hardNavigate = vi.fn();+ const destination: UpgradeDestination = {+ href: 'https://example.com/pricing',+ external: true,+ newTab: false,+ hardNavigation: false,+ };++ navigateToUpgradeDestination(destination, navigate, openExternal, hardNavigate);++ expect(openExternal).not.toHaveBeenCalled();+ expect(hardNavigate).not.toHaveBeenCalled();+ expect(navigate).toHaveBeenCalledWith('https://example.com/pricing');+ });++ it('routes through hardNavigate when hardNavigation=true and newTab=false (hardNavigation true arm)', () => {+ const navigate = vi.fn();+ const openExternal = vi.fn();+ const hardNavigate = vi.fn();+ const destination: UpgradeDestination = {+ href: '/reload-me',+ external: false,+ newTab: false,+ hardNavigation: true,+ };++ navigateToUpgradeDestination(destination, navigate, openExternal, hardNavigate);++ expect(hardNavigate).toHaveBeenCalledWith('/reload-me');+ expect(openExternal).not.toHaveBeenCalled();+ expect(navigate).not.toHaveBeenCalled();+ });++ it('falls back to external for hardNavigation when hardNavigation is omitted and newTab=false (?? right arm)', () => {+ const navigate = vi.fn();+ const openExternal = vi.fn();+ const hardNavigate = vi.fn();+ const destination: UpgradeDestination = {+ href: 'https://example.com/x',+ external: true,+ newTab: false,+ // hardNavigation omitted -> ?? falls back to external=true -> hard navigate.+ };++ navigateToUpgradeDestination(destination, navigate, openExternal, hardNavigate);++ expect(hardNavigate).toHaveBeenCalledWith('https://example.com/x');+ expect(openExternal).not.toHaveBeenCalled();+ expect(navigate).not.toHaveBeenCalled();+ });++ it('forwards preserveOpener=true to openExternal when opening in a new tab (?? left arm for preserveOpener)', () => {+ const navigate = vi.fn();+ const openExternal = vi.fn();+ const destination: UpgradeDestination = {+ href: '/auth/license-purchase-start',+ external: false,+ newTab: true,+ preserveOpener: true,+ };++ navigateToUpgradeDestination(destination, navigate, openExternal);++ expect(openExternal).toHaveBeenCalledWith('/auth/license-purchase-start', true);+ expect(navigate).not.toHaveBeenCalled();+ });++ it('uses the default openExternalUpgradeDestination when openExternal is omitted (default param)', () => {+ const openSpy = vi.fn();+ vi.stubGlobal('window', { open: openSpy });+ const navigate = vi.fn();+ const destination: UpgradeDestination = {+ href: 'https://example.com/pricing',+ external: true,+ // openExternal omitted -> default openExternalUpgradeDestination runs.+ };++ navigateToUpgradeDestination(destination, navigate);++ vi.unstubAllGlobals();+ expect(openSpy).toHaveBeenCalledWith(+ 'https://example.com/pricing',+ '_blank',+ 'noopener,noreferrer',+ );+ expect(navigate).not.toHaveBeenCalled();+ });++ it('uses the default hardNavigate (window.location.assign) and respects its SSR guard', () => {+ // jsdom's window.location is a non-configurable own property, so swap the+ // whole descriptor (same pattern as pricingHandoff tests) and restore it+ // afterwards.+ const originalDescriptor = Object.getOwnPropertyDescriptor(window, 'location');+ const assignSpy = vi.fn();+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: { assign: assignSpy },+ });+ try {+ const navigate = vi.fn();+ const openExternal = vi.fn();+ const destination: UpgradeDestination = {+ href: '/hard-reload',+ external: false,+ newTab: false,+ hardNavigation: true,+ // hardNavigate omitted -> default closure calls window.location.assign.+ };++ navigateToUpgradeDestination(destination, navigate, openExternal);++ // Default hardNavigate, window present -> assign reached.+ expect(assignSpy).toHaveBeenCalledWith('/hard-reload');+ expect(assignSpy).toHaveBeenCalledTimes(1);+ expect(openExternal).not.toHaveBeenCalled();+ expect(navigate).not.toHaveBeenCalled();++ // SSR guard inside the default hardNavigate: typeof window !== 'undefined'+ // is false, so assign is skipped and the count is unchanged.+ vi.stubGlobal('window', undefined);+ navigateToUpgradeDestination(+ { href: '/hard-reload-2', external: false, newTab: false, hardNavigation: true },+ navigate,+ openExternal,+ );+ vi.unstubAllGlobals();++ expect(assignSpy).toHaveBeenCalledTimes(1);+ } finally {+ if (originalDescriptor) {+ Object.defineProperty(window, 'location', originalDescriptor);+ }+ }+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/url.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/url.branchcov0712c.test.tsnew file mode 100644index 0000000000..44d3453a88--- /dev/null+++ b/frontend-modern/src/utils/__tests__/url.branchcov0712c.test.ts@@ -0,0 +1,276 @@+/**+ * Branch-coverage tests for `url.ts` — second pass (0712c).+ *+ * Scope: ONLY these still-uncovered named functions:+ * getPulseBaseUrl, getPulseWebSocketUrl, initKioskMode, isKioskMode,+ * getKioskModePreference, setKioskMode, getPulseHostname+ *+ * The sibling `url.test.ts` exercises the happy paths. This file drives every+ * remaining branch: SSR early-returns, storage try/catch arms, the+ * `origin === 'null'` rebuild path in getPulseBaseUrl, the unparseable-origin+ * fallback in getPulseHostname / getPulseWebSocketUrl, the >16KB auth-length+ * guard, non-object / malformed-JSON auth payloads, and the kiosk URL-param+ * `false`/absent/`true` arms.+ *+ * SSR arms are reached with `vi.stubGlobal('window', undefined)` (the module+ * guards on `typeof window === 'undefined'` before touching window), restored+ * via `vi.unstubAllGlobals()` in afterEach. window.location / sessionStorage+ * are replaced with plain mocks exactly as the sibling test does.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getPulseBaseUrl,+ getPulseHostname,+ getPulseWebSocketUrl,+ getKioskModePreference,+ initKioskMode,+ isKioskMode,+ setKioskMode,+ subscribeToKioskMode,+} from '../url';++const FALLBACK_BASE_URL = 'http://localhost:7655';++describe('url.ts branch coverage (0712c)', () => {+ const originalLocation = window.location;+ const originalSessionStorage = window.sessionStorage;++ beforeEach(() => {+ // Replace window.location with a plain writable object (same pattern as+ // the sibling url.test.ts). origin is a data prop here, so per-test code+ // can freely reassign it via `(window.location as any).origin = ...`.+ delete (window as any).location;+ window.location = {+ origin: 'http://localhost:3000',+ protocol: 'http:',+ hostname: 'localhost',+ port: '3000',+ host: 'localhost:3000',+ search: '',+ } as any;++ const storage: Record<string, string> = {};+ (window as any).sessionStorage = {+ getItem: vi.fn((key: string) => storage[key] ?? null),+ setItem: vi.fn((key: string, value: string) => {+ storage[key] = value;+ }),+ removeItem: vi.fn((key: string) => {+ delete storage[key];+ }),+ clear: vi.fn(() => {+ for (const key of Object.keys(storage)) delete storage[key];+ }),+ } as any;+ });++ afterEach(() => {+ // Restore the stubbed `window` first so reassigning location/sessionStorage+ // targets the real global, then restore originals + reset mocks.+ vi.unstubAllGlobals();+ (window as any).location = originalLocation;+ (window as any).sessionStorage = originalSessionStorage;+ vi.restoreAllMocks();+ });++ describe('getPulseBaseUrl', () => {+ it('returns the fallback when window is undefined (SSR arm of the guard)', () => {+ vi.stubGlobal('window', undefined);+ expect(getPulseBaseUrl()).toBe(FALLBACK_BASE_URL);+ });++ it('returns the fallback when window.location is missing (!window.location arm)', () => {+ (window as any).location = undefined;+ expect(getPulseBaseUrl()).toBe(FALLBACK_BASE_URL);+ });++ it('returns a non-default origin verbatim (truthy, !== "null" arm)', () => {+ (window.location as any).origin = 'https://ui.pulse.local:9000';+ expect(getPulseBaseUrl()).toBe('https://ui.pulse.local:9000');+ });++ it('rebuilds origin WITH port when location.origin is the string "null"', () => {+ (window.location as any).origin = 'null';+ (window.location as any).protocol = 'http:';+ (window.location as any).hostname = 'example.com';+ (window.location as any).port = '8080';+ expect(getPulseBaseUrl()).toBe('http://example.com:8080');+ });++ it('rebuilds origin WITHOUT port when location.origin is "null" and port is empty', () => {+ (window.location as any).origin = 'null';+ (window.location as any).protocol = 'https:';+ (window.location as any).hostname = 'host.io';+ (window.location as any).port = '';+ expect(getPulseBaseUrl()).toBe('https://host.io');+ });++ it('returns the fallback when origin is "null" and protocol/hostname are missing', () => {+ (window.location as any).origin = 'null';+ (window.location as any).protocol = '';+ (window.location as any).hostname = '';+ expect(getPulseBaseUrl()).toBe(FALLBACK_BASE_URL);+ });+ });++ describe('getPulseHostname', () => {+ it('returns the parsed hostname when origin is a valid URL', () => {+ (window.location as any).origin = 'https://nav.pulse.io:7000';+ expect(getPulseHostname()).toBe('nav.pulse.io');+ });++ it('returns "localhost" when the origin cannot be parsed (origin?.hostname || "localhost" fallback)', () => {+ // 'not-a-valid-origin' is truthy and !== 'null' so getPulseBaseUrl returns+ // it verbatim, but `new URL(...)` throws -> getPulseOriginUrl() === null.+ (window.location as any).origin = 'not-a-valid-origin';+ expect(getPulseHostname()).toBe('localhost');+ });+ });++ describe('getPulseWebSocketUrl', () => {+ it('returns ws://localhost<path> when the origin is unparseable (!origin arm)', () => {+ (window.location as any).origin = 'not-a-valid-origin';+ expect(getPulseWebSocketUrl('/events')).toBe('ws://localhost/events');+ });++ it('normalizes a path without a leading slash into a ws:// URL (http -> ws)', () => {+ // origin is the default http://localhost:3000; no auth stored.+ expect(getPulseWebSocketUrl('stream')).toBe('ws://localhost:3000/stream');+ });++ it('omits the token when the stored pulse_auth payload exceeds 16KB (>MAX guard)', () => {+ const huge = JSON.stringify({ type: 'token', value: 'x'.repeat(20 * 1024) });+ vi.mocked(window.sessionStorage.getItem).mockImplementation((key: string) =>+ key === 'pulse_auth' ? huge : null,+ );+ expect(getPulseWebSocketUrl('/ws')).toBe('ws://localhost:3000/ws');+ });++ it('omits the token for a non-object auth payload (parsed?.type optional-chain arm)', () => {+ vi.mocked(window.sessionStorage.getItem).mockImplementation((key: string) =>+ key === 'pulse_auth' ? JSON.stringify('just-a-string') : null,+ );+ expect(getPulseWebSocketUrl('/ws')).toBe('ws://localhost:3000/ws');+ });++ it('swallows malformed JSON in pulse_auth (JSON.parse -> catch arm)', () => {+ vi.mocked(window.sessionStorage.getItem).mockImplementation((key: string) =>+ key === 'pulse_auth' ? '{not-json' : null,+ );+ expect(getPulseWebSocketUrl('/ws')).toBe('ws://localhost:3000/ws');+ });++ it('swallows a throwing sessionStorage.getItem (storage catch arm)', () => {+ vi.mocked(window.sessionStorage.getItem).mockImplementation(() => {+ throw new Error('SecurityError');+ });+ expect(getPulseWebSocketUrl('/ws')).toBe('ws://localhost:3000/ws');+ });++ it('uses the fallback host and skips token lookup in SSR (storage === null arm)', () => {+ vi.stubGlobal('window', undefined);+ expect(getPulseWebSocketUrl('/ws')).toBe('ws://localhost:7655/ws');+ });+ });++ describe('initKioskMode', () => {+ it('is a no-op in SSR (typeof window === "undefined" early return)', () => {+ const storage = window.sessionStorage;+ vi.stubGlobal('window', undefined);+ initKioskMode();+ expect(vi.mocked(storage.setItem)).not.toHaveBeenCalled();+ expect(vi.mocked(storage.removeItem)).not.toHaveBeenCalled();+ });++ it('removes kiosk mode when the URL param is "false" (kioskParam === "false" arm)', () => {+ (window.location as any).search = '?kiosk=false';+ initKioskMode();+ expect(window.sessionStorage.removeItem).toHaveBeenCalledWith('pulse_kiosk_mode');+ expect(window.sessionStorage.setItem).not.toHaveBeenCalled();+ });++ it('does nothing when no kiosk param is present (neither if arm fires)', () => {+ (window.location as any).search = '?foo=bar';+ initKioskMode();+ expect(window.sessionStorage.setItem).not.toHaveBeenCalled();+ expect(window.sessionStorage.removeItem).not.toHaveBeenCalled();+ });++ it('swallows a throwing sessionStorage.setItem (storage catch arm)', () => {+ (window.location as any).search = '?kiosk=1';+ vi.mocked(window.sessionStorage.setItem).mockImplementation(() => {+ throw new Error('QuotaExceeded');+ });+ expect(() => initKioskMode()).not.toThrow();+ // The throw happens inside the setItem branch, so removeItem never runs.+ expect(window.sessionStorage.removeItem).not.toHaveBeenCalled();+ });+ });++ describe('isKioskMode', () => {+ it('returns false in SSR (typeof window === "undefined" early return)', () => {+ vi.stubGlobal('window', undefined);+ expect(isKioskMode()).toBe(false);+ });++ it('returns true via the URL "kiosk=true" arm when nothing is stored', () => {+ vi.mocked(window.sessionStorage.getItem).mockReturnValue(null);+ (window.location as any).search = '?kiosk=true';+ expect(isKioskMode()).toBe(true);+ });++ it('returns false when nothing is stored and no kiosk param is present (URL fallback -> false)', () => {+ vi.mocked(window.sessionStorage.getItem).mockReturnValue(null);+ (window.location as any).search = '';+ expect(isKioskMode()).toBe(false);+ });++ it('returns false when sessionStorage.getItem throws (catch arm)', () => {+ vi.mocked(window.sessionStorage.getItem).mockImplementation(() => {+ throw new Error('SecurityError');+ });+ expect(isKioskMode()).toBe(false);+ });+ });++ describe('getKioskModePreference', () => {+ it('returns null in SSR (typeof window === "undefined" early return)', () => {+ vi.stubGlobal('window', undefined);+ expect(getKioskModePreference()).toBeNull();+ });++ it('returns null when sessionStorage.getItem throws (catch arm)', () => {+ vi.mocked(window.sessionStorage.getItem).mockImplementation(() => {+ throw new Error('SecurityError');+ });+ expect(getKioskModePreference()).toBeNull();+ });+ });++ describe('setKioskMode', () => {+ it('is a no-op in SSR (no storage write; typeof window === "undefined" early return)', () => {+ const storage = window.sessionStorage;+ vi.stubGlobal('window', undefined);+ setKioskMode(true);+ expect(vi.mocked(storage.setItem)).not.toHaveBeenCalled();+ });++ it('swallows a throwing sessionStorage.setItem and skips listener notification (catch arm)', () => {+ const listener = vi.fn();+ const unsubscribe = subscribeToKioskMode(listener);++ vi.mocked(window.sessionStorage.setItem).mockImplementation(() => {+ throw new Error('QuotaExceeded');+ });++ expect(() => setKioskMode(true)).not.toThrow();+ // Confirms the enabled branch was entered, then the throw diverted to catch.+ expect(window.sessionStorage.setItem).toHaveBeenCalledWith('pulse_kiosk_mode', 'true');+ // notifyKioskListeners sits after setItem in the try block, so it must be skipped.+ expect(listener).not.toHaveBeenCalled();++ unsubscribe();+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/workloadTypePresentation.branchcov0712c.test.ts b/frontend-modern/src/utils/__tests__/workloadTypePresentation.branchcov0712c.test.tsnew file mode 100644index 0000000000..003bba2c0a--- /dev/null+++ b/frontend-modern/src/utils/__tests__/workloadTypePresentation.branchcov0712c.test.ts@@ -0,0 +1,203 @@+import { describe, expect, it } from 'vitest';+import {+ getWorkloadTypePresentation,+ normalizeWorkloadTypePresentationKey,+} from '@/utils/workloadTypePresentation';++describe('workloadTypePresentation (branch coverage 0712c)', () => {+ describe('normalizeWorkloadTypePresentationKey', () => {+ it('returns null when canonicalization yields nothing (null/undefined/blank)', () => {+ expect(normalizeWorkloadTypePresentationKey(null)).toBeNull();+ expect(normalizeWorkloadTypePresentationKey(undefined)).toBeNull();+ expect(normalizeWorkloadTypePresentationKey('')).toBeNull();+ expect(normalizeWorkloadTypePresentationKey(' ')).toBeNull();+ });++ it('maps the oci-container canonical to system-container', () => {+ expect(normalizeWorkloadTypePresentationKey('oci-container')).toBe('system-container');+ });++ it('passes the vm canonical through unchanged', () => {+ expect(normalizeWorkloadTypePresentationKey('vm')).toBe('vm');+ });++ it('passes the system-container canonical through unchanged', () => {+ expect(normalizeWorkloadTypePresentationKey('system-container')).toBe('system-container');+ });++ it('passes the app-container canonical through unchanged', () => {+ expect(normalizeWorkloadTypePresentationKey('app-container')).toBe('app-container');+ });++ it('passes the pod canonical through unchanged', () => {+ expect(normalizeWorkloadTypePresentationKey('pod')).toBe('pod');+ });++ it('passes the agent canonical through unchanged', () => {+ expect(normalizeWorkloadTypePresentationKey('agent')).toBe('agent');+ });++ it('returns null for canonical resource types that are not workload kinds', () => {+ expect(normalizeWorkloadTypePresentationKey('ceph')).toBeNull();+ expect(normalizeWorkloadTypePresentationKey('storage')).toBeNull();+ expect(normalizeWorkloadTypePresentationKey('network')).toBeNull();+ expect(normalizeWorkloadTypePresentationKey('pbs')).toBeNull();+ });+ });++ describe('getWorkloadTypePresentation', () => {+ it('returns the full vm presentation object including className and pluralLabel', () => {+ expect(getWorkloadTypePresentation('vm')).toStrictEqual({+ label: 'VM',+ pluralLabel: 'VMs',+ title: 'Virtual Machine',+ className: 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300',+ });+ });++ it('returns the full system-container presentation object', () => {+ expect(getWorkloadTypePresentation('system-container')).toStrictEqual({+ label: 'LXC',+ pluralLabel: 'LXC',+ title: 'System Container',+ className: 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300',+ });+ });++ it('returns the full app-container presentation object', () => {+ expect(getWorkloadTypePresentation('app-container')).toStrictEqual({+ label: 'Container',+ pluralLabel: 'Containers',+ title: 'Application Container',+ className: 'bg-sky-100 text-sky-700 dark:bg-sky-900 dark:text-sky-300',+ });+ });++ it('returns the full pod presentation object', () => {+ expect(getWorkloadTypePresentation('pod')).toStrictEqual({+ label: 'Pod',+ pluralLabel: 'Pods',+ title: 'Kubernetes Pod',+ className: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',+ });+ });++ it('returns the full agent presentation object', () => {+ expect(getWorkloadTypePresentation('agent')).toStrictEqual({+ label: 'Agent',+ pluralLabel: 'Agents',+ title: 'Agent',+ className: 'bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300',+ });+ });++ it('presents oci-container using the system-container base', () => {+ expect(getWorkloadTypePresentation('oci-container')).toStrictEqual({+ label: 'LXC',+ pluralLabel: 'LXC',+ title: 'System Container',+ className: 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300',+ });+ });++ it('applies label/pluralLabel/title overrides over a known base presentation', () => {+ expect(+ getWorkloadTypePresentation('vm', {+ label: 'My VM',+ pluralLabel: 'My VMs',+ title: 'My Machine',+ }),+ ).toStrictEqual({+ label: 'My VM',+ pluralLabel: 'My VMs',+ title: 'My Machine',+ className: 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300',+ });+ });++ it('keeps base values when override fields are empty strings (falsy)', () => {+ expect(+ getWorkloadTypePresentation('vm', { label: '', pluralLabel: '', title: '' }),+ ).toStrictEqual({+ label: 'VM',+ pluralLabel: 'VMs',+ title: 'Virtual Machine',+ className: 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300',+ });+ });++ it('applies a partial override and leaves the remaining fields at their base values', () => {+ expect(getWorkloadTypePresentation('pod', { title: 'My Pod Title' })).toStrictEqual({+ label: 'Pod',+ pluralLabel: 'Pods',+ title: 'My Pod Title',+ className: 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300',+ });+ });++ it('falls back to a titleized label for an unknown string type with no overrides', () => {+ expect(getWorkloadTypePresentation('custom-type')).toStrictEqual({+ label: 'Custom Type',+ pluralLabel: 'Custom Type',+ title: 'Custom Type',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('uses DEFAULT label when rawType is null/undefined (titleCase yields empty)', () => {+ expect(getWorkloadTypePresentation(null)).toStrictEqual({+ label: 'Unknown',+ pluralLabel: 'Unknown',+ title: 'Unknown',+ className: 'bg-surface-alt text-base-content',+ });+ expect(getWorkloadTypePresentation(undefined)).toStrictEqual({+ label: 'Unknown',+ pluralLabel: 'Unknown',+ title: 'Unknown',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('honors full overrides on the fallback path for unknown types', () => {+ expect(+ getWorkloadTypePresentation('custom-type', {+ label: 'CustomLabel',+ pluralLabel: 'CustomLabels',+ title: 'Custom Title',+ }),+ ).toStrictEqual({+ label: 'CustomLabel',+ pluralLabel: 'CustomLabels',+ title: 'Custom Title',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('derives fallback label from titleized rawType when only title/pluralLabel are overridden', () => {+ expect(+ getWorkloadTypePresentation('mystery-thing', {+ title: 'Mystery',+ pluralLabel: 'Mysteries',+ }),+ ).toStrictEqual({+ label: 'Mystery Thing',+ pluralLabel: 'Mysteries',+ title: 'Mystery',+ className: 'bg-surface-alt text-base-content',+ });+ });++ it('treats a non-string rawType as unknown and falls back to DEFAULT', () => {+ type RawTypeArg = Parameters<typeof getWorkloadTypePresentation>[0];+ expect(+ getWorkloadTypePresentation(0 as unknown as RawTypeArg),+ ).toStrictEqual({+ label: 'Unknown',+ pluralLabel: 'Unknown',+ title: 'Unknown',+ className: 'bg-surface-alt text-base-content',+ });+ });+ });+});