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): pulse PURE branch-cov (15 presentation/model modules)
rcourtman06a6028b2936
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/markdownMorph.branchcov0713.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/markdownMorph.branchcov0713.test.tsnew file mode 100644index 0000000000..54d21bc782--- /dev/null+++ b/frontend-modern/src/components/AI/Chat/__tests__/markdownMorph.branchcov0713.test.ts@@ -0,0 +1,230 @@+import { describe, expect, it } from 'vitest';+import { morphMarkdownInto } from '../markdownMorph';++// Branch-coverage companion to markdownMorph.test.ts. morphMarkdownInto is the+// only exported symbol; morphChildren / canMorphInPlace / morphNode /+// syncAttributes are all module-private, so every branch below is driven+// through morphMarkdownInto and observed via concrete DOM identity / innerHTML+// / attributes / nodeValue assertions.+//+// The existing sibling test covers: plain render, append-only growth (the+// `!oldNode` arm), in-place text growth inside a kept <p>/<li>, in-place list+// growth, full empty, in-place <ol> recursion, attribute add/update, and+// tag-change replacement (canMorphInPlace false via differing tagNames).+//+// This file targets the branches that sibling does NOT hit:+// - canMorphInPlace `nodeType !== nodeType` arm (text<->element swap)+// - canMorphInPlace COMMENT_NODE arm of the trailing return+// - morphNode non-element (comment) update arm+// - syncAttributes attribute-removal arm+// - syncAttributes equal-value skip arm+// - morphChildren trailing-drop while-loop with a kept prefix+// - top-level bare-text morph (canMorphInPlace TEXT arm at top level)++const make = (html: string): HTMLDivElement => {+ const el = document.createElement('div');+ morphMarkdownInto(el, html);+ return el;+};++// ---------------------------------------------------------------------------+// canMorphInPlace — `oldNode.nodeType !== newNode.nodeType` arm (returns false)+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: nodeType mismatch forces replacement', () => {+ it('replaces a bare text node when the new render is an element (text -> element)', () => {+ const el = make('draft');+ expect(el.childNodes).toHaveLength(1);+ expect(el.childNodes[0].nodeType).toBe(Node.TEXT_NODE);+ const textBefore = el.childNodes[0];++ // The streaming tick turns the loose text into a wrapped <p>.+ morphMarkdownInto(el, '<p>draft</p>');++ // canMorphInPlace(text, p): TEXT !== ELEMENT -> false -> replaceChild.+ expect(el.childNodes[0]).not.toBe(textBefore);+ expect(el.childNodes[0].nodeType).toBe(Node.ELEMENT_NODE);+ expect((el.childNodes[0] as Element).tagName).toBe('P');+ expect(el.innerHTML).toBe('<p>draft</p>');+ });++ it('replaces an element when the new render is bare text (element -> text)', () => {+ const el = make('<p>x</p>');+ const elBefore = el.childNodes[0];++ morphMarkdownInto(el, 'x');++ // canMorphInPlace(p, text): ELEMENT !== TEXT -> false -> replaceChild.+ expect(el.childNodes[0]).not.toBe(elBefore);+ expect(el.childNodes[0].nodeType).toBe(Node.TEXT_NODE);+ expect(el.textContent).toBe('x');+ });+});++// ---------------------------------------------------------------------------+// canMorphInPlace — COMMENT_NODE arm of `TEXT_NODE || COMMENT_NODE` + morphNode+// non-element update arm for comments.+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: comment nodes', () => {+ it('morphs a changed comment in place (COMMENT arm + comment nodeValue update)', () => {+ const el = make('<!-- note -->');+ expect(el.childNodes).toHaveLength(1);+ expect(el.childNodes[0].nodeType).toBe(Node.COMMENT_NODE);+ const commentBefore = el.childNodes[0] as Comment;++ morphMarkdownInto(el, '<!-- note2 -->');++ // isEqualNode false (nodeValue differs) -> canMorphInPlace true (both+ // COMMENT) -> morphNode non-element arm updates nodeValue, identity kept.+ // A comment's data is the literal text between `<!--` and `-->`, so the+ // surrounding spaces are part of nodeValue.+ expect(el.childNodes[0]).toBe(commentBefore);+ expect(commentBefore.nodeValue).toBe(' note2 ');+ expect(el.innerHTML).toBe('<!-- note2 -->');+ });++ it('keeps an identical comment untouched (isEqualNode true for comments)', () => {+ const el = make('<!-- keep -->');+ const commentBefore = el.childNodes[0];++ morphMarkdownInto(el, '<!-- keep -->');++ expect(el.childNodes[0]).toBe(commentBefore);+ });+});++// ---------------------------------------------------------------------------+// syncAttributes — attribute-removal arm (old has an attr new lacks).+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: attribute removal', () => {+ it('removes an attribute that disappears from the new render, keeping node identity', () => {+ const el = make('<a href="http://a.example" title="t">l</a>');+ const anchorBefore = el.children[0];++ morphMarkdownInto(el, '<a href="http://a.example">l</a>');++ // syncAttributes: old has `title`, new lacks it -> removeAttribute arm.+ expect(el.children[0]).toBe(anchorBefore);+ expect(anchorBefore.getAttribute('href')).toBe('http://a.example');+ expect(anchorBefore.getAttribute('title')).toBeNull();+ expect(anchorBefore.textContent).toBe('l');+ });+});++// ---------------------------------------------------------------------------+// syncAttributes — equal-value skip arm (getAttribute === attr.value).+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: attribute value unchanged', () => {+ it('skips setAttribute when the value is already correct, while still adding/removing others', () => {+ const el = make('<a href="http://keep.example" class="c">l</a>');+ const anchorBefore = el.children[0];++ morphMarkdownInto(el, '<a href="http://keep.example" rel="noopener">l</a>');++ // href value is unchanged -> inner guard skips setAttribute (equal arm).+ // `class` is removed (removal arm) and `rel` is added (add arm).+ expect(el.children[0]).toBe(anchorBefore);+ expect(anchorBefore.getAttribute('href')).toBe('http://keep.example');+ expect(anchorBefore.getAttribute('class')).toBeNull();+ expect(anchorBefore.getAttribute('rel')).toBe('noopener');+ });+});++// ---------------------------------------------------------------------------+// morphChildren — trailing-drop while-loop with a kept prefix (drops run after+// the for-loop's continue path).+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: partial trailing drop', () => {+ it('drops one trailing block while keeping an equal leading block', () => {+ const el = make('<p>a</p><p>b</p>');+ const aBefore = el.children[0];+ const bBefore = el.children[1];++ morphMarkdownInto(el, '<p>a</p>');++ // for-loop: i=0, <p>a</p> === <p>a</p> -> isEqualNode continue. Then the+ // while-loop drops the trailing <p>b</p> (length 2 > 1 -> remove).+ expect(el.children).toHaveLength(1);+ expect(el.children[0]).toBe(aBefore);+ expect(bBefore.parentNode).toBeNull();+ });++ it('drops several trailing blocks at once while keeping the equal prefix', () => {+ const el = make('<p>1</p><p>2</p><p>3</p>');+ const firstBefore = el.children[0];++ morphMarkdownInto(el, '<p>1</p>');++ // The while-loop iterates twice: 3>1 remove, 2>1 remove, 1>1 exit.+ expect(el.children).toHaveLength(1);+ expect(el.children[0]).toBe(firstBefore);+ expect(el.children[0].textContent).toBe('1');+ });+});++// ---------------------------------------------------------------------------+// Top-level bare text: canMorphInPlace TEXT arm + morphNode non-element update+// at the container top level (existing sibling only exercises text inside+// kept elements like <p>/<li>).+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: top-level bare text', () => {+ it('morphs a growing bare text node in place at the container top level', () => {+ const el = make('abc');+ const textBefore = el.childNodes[0];+ expect(textBefore.nodeType).toBe(Node.TEXT_NODE);++ morphMarkdownInto(el, 'abcd');++ // isEqualNode false -> canMorphInPlace(text, text) true (TEXT arm) ->+ // morphNode non-element arm updates nodeValue, identity kept.+ expect(el.childNodes[0]).toBe(textBefore);+ expect(el.textContent).toBe('abcd');+ });++ it('keeps an identical bare text node untouched', () => {+ const el = make('same');+ const textBefore = el.childNodes[0];++ morphMarkdownInto(el, 'same');++ expect(el.childNodes[0]).toBe(textBefore);+ expect(el.textContent).toBe('same');+ });++ it('appends a second top-level text node when one is already present', () => {+ const el = make('one');+ const firstBefore = el.childNodes[0];++ morphMarkdownInto(el, 'onetwo');++ expect(el.childNodes).toHaveLength(1);+ expect(el.childNodes[0]).toBe(firstBefore);+ expect(el.textContent).toBe('onetwo');+ });+});++// ---------------------------------------------------------------------------+// Multi-node initial render: the `!oldNode` arm fires repeatedly into an empty+// container, covering repeated appendChild across mixed element/text children.+// ---------------------------------------------------------------------------++describe('morphMarkdownInto branch coverage: multi-node append into empty container', () => {+ it('appends several top-level nodes (elements + trailing text) in one tick', () => {+ const el = document.createElement('div');++ morphMarkdownInto(el, '<p>first</p><p>second</p>tail');++ expect(el.childNodes).toHaveLength(3);+ expect((el.childNodes[0] as Element).tagName).toBe('P');+ expect((el.childNodes[0] as Element).textContent).toBe('first');+ expect((el.childNodes[1] as Element).tagName).toBe('P');+ expect((el.childNodes[1] as Element).textContent).toBe('second');+ expect(el.childNodes[2].nodeType).toBe(Node.TEXT_NODE);+ expect(el.childNodes[2].nodeValue).toBe('tail');+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/settingsHeaderMeta.branchcov0713.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsHeaderMeta.branchcov0713.test.tsnew file mode 100644index 0000000000..899e134619--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/settingsHeaderMeta.branchcov0713.test.ts@@ -0,0 +1,832 @@+/**+ * Branch-coverage tests for settingsHeaderMeta.+ *+ * Target functions:+ * - getSettingsHeaderMeta(locale?) (exported)+ * - getInfrastructureReadOnlyHeaderDescription(locale?) (exported)+ *+ * The sibling `settingsLocalization.test.ts` suite already exercises:+ * - getSettingsHeaderMeta('es') for: system-network, system-ai,+ * system-ai-assistant, system-billing+ * - getSettingsHeaderMeta('de') for: system-ai, system-ai-discovery,+ * system-ai-assistant, system-billing+ * - getSettingsHeaderMeta() (no-arg via active 'es') for security-auth.title+ * - getInfrastructureReadOnlyHeaderDescription('es') via .toContain('solo lectura')+ * - static SETTINGS_HEADER_META spot checks (system-billing, system-ai-discovery)+ *+ * This file pins the UNCOVERED branches of the two target functions:+ * - English baseline (the getLocaleFallbackChain single-element [en] arm and+ * the getLocaleMessage `!deferredLocale` EN_MESSAGES arm) for every SettingsTab+ * the sibling suite leaves untouched.+ * - locale argument variants: undefined (translateMessage default-parameter arm),+ * explicit 'en', null, and an unsupported locale string (both normalized to+ * DEFAULT_LOCALE via resolveSupportedLocale -> normalizeLocale).+ * - Map parity: every SettingsTab key present with non-empty title+description,+ * dynamic English output matches the static SETTINGS_HEADER_META (drift guard),+ * and Object.fromEntries yields a fresh object per call.+ * - getInfrastructureReadOnlyHeaderDescription across 'en' / 'de' / 'es' and the+ * no-arg (active-locale) arm plus null / unsupported-string normalization.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { DEFAULT_LOCALE, setActiveLocale, type SupportedLocale } from '@/i18n';+import type { SettingsHeaderMetaMap } from '../settingsNavigationModel';+import {+ getInfrastructureReadOnlyHeaderDescription,+ getSettingsHeaderMeta,+ SETTINGS_HEADER_META,+} from '../settingsHeaderMeta';+import type { SettingsTab } from '../settingsNavigationModel';++// Every SettingsTab from settingsNavigationModel.ts. Used for key-parity checks.+const ALL_TABS: readonly SettingsTab[] = [+ 'infrastructure-systems',+ 'monitoring-availability',+ 'system-general',+ 'system-network',+ 'system-updates',+ 'system-recovery',+ 'system-ai',+ 'system-ai-patrol',+ 'system-ai-assistant',+ 'system-ai-discovery',+ 'system-relay',+ 'system-billing',+ 'support-diagnostics',+ 'support-reporting',+ 'support-logs',+ 'organization-overview',+ 'organization-access',+ 'organization-sharing',+ 'organization-billing',+ 'organization-billing-admin',+ 'api',+ 'security-overview',+ 'security-data-handling',+ 'security-auth',+ 'security-sso',+ 'security-roles',+ 'security-users',+ 'security-audit',+ 'security-webhooks',+];++describe('getSettingsHeaderMeta', () => {+ afterEach(() => {+ setActiveLocale(DEFAULT_LOCALE);+ });++ // ---- English baseline -------------------------------------------------+ // getLocaleFallbackChain('en') returns [en] (the locale === fallbackLocale+ // single-element arm) and getLocaleMessage returns EN_MESSAGES[key] via the+ // `!deferredLocale` arm. The sibling suite only pins these tabs in es/de, so+ // every tab here is a newly-covered English entry.+ describe('English baseline (single-element [en] fallback chain)', () => {+ // Computed inside beforeAll so the i18n runtime (catalogVersion signal,+ // active-locale default) is fully initialized at evaluation time.+ let en: SettingsHeaderMetaMap;+ beforeAll(() => {+ en = getSettingsHeaderMeta('en');+ });++ it('localizes infrastructure-systems to the English baseline', () => {+ expect(en['infrastructure-systems']).toEqual({+ title: 'Infrastructure',+ description: 'Add, discover, and verify the infrastructure Pulse monitors.',+ });+ });++ it('localizes monitoring-availability to the English baseline', () => {+ expect(en['monitoring-availability']).toEqual({+ title: 'Availability checks',+ description:+ 'Monitor endpoint-only devices and services with ping, TCP, and HTTP probes.',+ });+ });++ it('localizes system-general to the English baseline', () => {+ expect(en['system-general']).toEqual({+ title: 'General',+ description: 'Manage appearance, layout, and default monitoring cadence.',+ });+ });++ it('localizes system-network to the English baseline (sibling only pinned es/de)', () => {+ expect(en['system-network']).toEqual({+ title: 'Network',+ description:+ 'Configure the public URL, CORS, embedding, and webhook network boundaries.',+ });+ });++ it('localizes system-updates to the English baseline', () => {+ expect(en['system-updates']).toEqual({+ title: 'Updates',+ description: 'Manage version checks, update channels, and automatic update behavior.',+ });+ });++ it('localizes system-recovery to the English baseline', () => {+ expect(en['system-recovery']).toEqual({+ title: 'Recovery',+ description:+ 'Manage backup/snapshot polling plus configuration export and import workflows.',+ });+ });++ it('localizes system-ai to the English baseline (sibling only pinned es/de)', () => {+ expect(en['system-ai']).toEqual({+ title: 'Provider & Models',+ description:+ 'Configure providers, default models, provider health, budget, and usage for Pulse Intelligence.',+ });+ });++ it('localizes system-ai-patrol to the English baseline', () => {+ expect(en['system-ai-patrol']).toEqual({+ title: 'Patrol',+ description: 'Set when Patrol runs, what starts it, and which model it uses.',+ });+ });++ it('localizes system-ai-assistant to the English baseline (sibling only pinned es/de)', () => {+ expect(en['system-ai-assistant']).toEqual({+ title: 'Assistant',+ description: 'Configure Assistant chat behavior, chat action permissions, and sessions.',+ });+ });++ it('localizes system-ai-discovery to the English baseline (sibling only pinned de)', () => {+ expect(en['system-ai-discovery']).toEqual({+ title: 'Service Context',+ description:+ 'Configure the model-backed service context Assistant and Patrol use. Infrastructure discovery and onboarding stay under Infrastructure.',+ });+ });++ it('localizes system-relay to the English baseline', () => {+ expect(en['system-relay']).toEqual({+ title: 'Remote Access',+ description:+ 'Configure Pulse relay connectivity for secure remote access and Pulse Mobile pairing.',+ });+ });++ it('localizes system-billing to the English baseline (sibling only pinned es/de)', () => {+ expect(en['system-billing']).toEqual({+ title: 'Plans & Billing',+ description: 'Plan, license, and Patrol mode for this instance.',+ });+ });++ it('localizes support-diagnostics to the English baseline', () => {+ expect(en['support-diagnostics']).toEqual({+ title: 'Diagnostics & Health',+ description:+ 'Run health checks, validate connectivity, and export troubleshooting snapshots.',+ });+ });++ it('localizes support-reporting to the English baseline', () => {+ expect(en['support-reporting']).toEqual({+ title: 'Data & Reports',+ description:+ 'Export inventory data and generate performance reports from the canonical settings shell.',+ });+ });++ it('localizes support-logs to the English baseline', () => {+ expect(en['support-logs']).toEqual({+ title: 'System Logs',+ description:+ 'Inspect the live Pulse log stream and download the captured buffer for support work.',+ });+ });++ it('localizes organization-overview to the English baseline', () => {+ expect(en['organization-overview']).toEqual({+ title: 'Organization Overview',+ description: 'Review organization metadata, membership footprint, and ownership.',+ });+ });++ it('localizes organization-access to the English baseline', () => {+ expect(en['organization-access']).toEqual({+ title: 'Organization Access',+ description: 'Manage organization invitations, member roles, and ownership transfers.',+ });+ });++ it('localizes organization-sharing to the English baseline', () => {+ expect(en['organization-sharing']).toEqual({+ title: 'Organization Sharing',+ description: 'Share resources between organizations with scoped access.',+ });+ });++ it('localizes organization-billing to the English baseline', () => {+ expect(en['organization-billing']).toEqual({+ title: 'Billing & Usage',+ description:+ 'Review your organization plan, applicable usage policies, and subscription status for paid access.',+ });+ });++ it('localizes organization-billing-admin to the English baseline', () => {+ expect(en['organization-billing-admin']).toEqual({+ title: 'Billing Admin',+ description:+ 'Review and manage tenant billing state across all organizations (hosted mode only).',+ });+ });++ it('localizes api to the English baseline', () => {+ expect(en['api']).toEqual({+ title: 'API Access',+ description:+ 'Generate and manage scoped Pulse tokens for agents, automation, and external integrations.',+ });+ });++ it('localizes security-overview to the English baseline', () => {+ expect(en['security-overview']).toEqual({+ title: 'Security Overview',+ description: 'View your security posture at a glance and monitor authentication status.',+ });+ });++ it('localizes security-data-handling to the English baseline', () => {+ expect(en['security-data-handling']).toEqual({+ title: 'Resource Privacy',+ description:+ 'See which monitored resource details can be summarized, must stay local, or are redacted.',+ });+ });++ it('localizes security-auth to the English baseline (sibling only pinned .title via es)', () => {+ expect(en['security-auth']).toEqual({+ title: 'Authentication',+ description: 'Manage password-based authentication and credential rotation.',+ });+ });++ it('localizes security-sso to the English baseline', () => {+ expect(en['security-sso']).toEqual({+ title: 'Single Sign-On Providers',+ description: 'Configure OIDC and SAML identity providers.',+ });+ });++ it('localizes security-roles to the English baseline', () => {+ expect(en['security-roles']).toEqual({+ title: 'Roles',+ description: 'Define custom roles and manage granular permissions for users and tokens.',+ });+ });++ it('localizes security-users to the English baseline', () => {+ expect(en['security-users']).toEqual({+ title: 'User Access',+ description:+ 'Assign roles to users and view effective permissions across your infrastructure.',+ });+ });++ it('localizes security-audit to the English baseline', () => {+ expect(en['security-audit']).toEqual({+ title: 'Audit Log',+ description: 'View security events, login attempts, and configuration changes.',+ });+ });++ it('localizes security-webhooks to the English baseline', () => {+ expect(en['security-webhooks']).toEqual({+ title: 'Audit Webhooks',+ description: 'Configure real-time delivery of audit events to external systems.',+ });+ });+ });++ // ---- locale argument handling ----------------------------------------+ describe('locale argument handling', () => {+ it('uses the active locale when called with no argument (translateMessage default-parameter arm)', () => {+ // Default active locale here is DEFAULT_LOCALE ('en'); the no-arg call+ // must match an explicit 'en' call.+ expect(getSettingsHeaderMeta()).toEqual(getSettingsHeaderMeta('en'));+ });++ it('honors an active non-default locale when no argument is passed', () => {+ setActiveLocale('de');+ const noArg = getSettingsHeaderMeta();+ // Concrete value pin proves the active-locale path really localized.+ expect(noArg['security-auth'].title).toBe('Authentifizierung');+ expect(noArg).toEqual(getSettingsHeaderMeta('de'));+ });++ it('normalizes an explicit null locale to DEFAULT_LOCALE (resolveSupportedLocale ?? DEFAULT_LOCALE arm)', () => {+ const nullMeta = getSettingsHeaderMeta(null as unknown as SupportedLocale);+ expect(nullMeta).toEqual(getSettingsHeaderMeta('en'));+ });++ it('normalizes an unsupported locale string to DEFAULT_LOCALE (base-locale lookup misses -> DEFAULT_LOCALE arm)', () => {+ // 'fr' is listed in NEXT_LOCALIZATION_LOCALES but is not a SupportedLocale,+ // so resolveSupportedLocale returns null and normalizeLocale falls back.+ const unsupported = getSettingsHeaderMeta('fr' as unknown as SupportedLocale);+ expect(unsupported).toEqual(getSettingsHeaderMeta('en'));+ });+ });++ // ---- map shape and key parity ----------------------------------------+ describe('map shape and key parity', () => {+ it('returns exactly one entry per SettingsTab', () => {+ const meta = getSettingsHeaderMeta('en');+ expect(Object.keys(meta).sort()).toEqual([...ALL_TABS].sort());+ });++ it('every entry has a non-empty string title and description', () => {+ const meta = getSettingsHeaderMeta('en');+ for (const tab of ALL_TABS) {+ const entry = meta[tab];+ expect(typeof entry.title).toBe('string');+ expect(entry.title.length).toBeGreaterThan(0);+ expect(typeof entry.description).toBe('string');+ expect(entry.description.length).toBeGreaterThan(0);+ }+ });++ it('keeps the dynamic English output in sync with the static SETTINGS_HEADER_META (drift guard)', () => {+ // SETTINGS_HEADER_META is the hand-maintained static baseline; the dynamic+ // getter reads the English i18n catalog. The two MUST agree for every tab+ // or copy edits silently bypass localization. (See GLM_REPORT.md.)+ const dynamic = getSettingsHeaderMeta('en');+ for (const tab of ALL_TABS) {+ expect(dynamic[tab]).toEqual(SETTINGS_HEADER_META[tab]);+ }+ });++ it('returns a fresh object on each call (Object.fromEntries yields a new map)', () => {+ const a = getSettingsHeaderMeta('en');+ const b = getSettingsHeaderMeta('en');+ expect(a).not.toBe(b);+ expect(a).toEqual(b);+ });+ });++ // ---- localized catalogs: uncovered tabs ------------------------------+ describe('German catalog — tabs not pinned by the sibling suite', () => {+ // Sibling already covers system-ai, system-ai-discovery, system-ai-assistant,+ // and system-billing in 'de'. Every other tab is pinned here so the German+ // fallback chain ([de, en]) resolves to the de override for each key.+ // Computed in beforeAll so the deferred 'de' catalog (loaded asynchronously+ // by setup.ts) is present at evaluation time.+ let de: SettingsHeaderMetaMap;+ beforeAll(() => {+ de = getSettingsHeaderMeta('de');+ });++ it('localizes infrastructure-systems', () => {+ expect(de['infrastructure-systems']).toEqual({+ title: 'Infrastruktur',+ description:+ 'Fuegen Sie Infrastruktur hinzu, finden Sie sie automatisch, und pruefen Sie, was Pulse ueberwacht.',+ });+ });++ it('localizes monitoring-availability', () => {+ expect(de['monitoring-availability']).toEqual({+ title: 'Verfuegbarkeitspruefungen',+ description:+ 'Ueberwachen Sie Endgeraete und Dienste nur ueber Ping-, TCP- und HTTP-Pruefungen.',+ });+ });++ it('localizes system-general', () => {+ expect(de['system-general']).toEqual({+ title: 'Allgemein',+ description: 'Verwalten Sie Darstellung, Layout und Standard-Monitoring-Takt.',+ });+ });++ it('localizes system-network', () => {+ expect(de['system-network']).toEqual({+ title: 'Netzwerk',+ description:+ 'Konfigurieren Sie oeffentliche URL, CORS, Einbettung und Netzwerkgrenzen fuer Webhooks.',+ });+ });++ it('localizes system-updates', () => {+ expect(de['system-updates']).toEqual({+ title: 'Updates',+ description:+ 'Verwalten Sie Versionspruefungen, Update-Kanaele und automatisches Update-Verhalten.',+ });+ });++ it('localizes system-recovery', () => {+ expect(de['system-recovery']).toEqual({+ title: 'Wiederherstellung',+ description:+ 'Verwalten Sie Backup-/Snapshot-Abfragen sowie Export- und Importablaeufe der Konfiguration.',+ });+ });++ it('localizes system-ai-patrol', () => {+ expect(de['system-ai-patrol']).toEqual({+ title: 'Patrol',+ description:+ 'Legen Sie fest, wann Patrol laeuft, was Patrol startet und welches Modell verwendet wird.',+ });+ });++ it('localizes system-relay', () => {+ expect(de['system-relay']).toEqual({+ title: 'Remote-Zugriff',+ description:+ 'Konfigurieren Sie Pulse-Relay-Konnektivitaet fuer sicheren Remote-Zugriff und Pulse-Mobile-Kopplung.',+ });+ });++ it('localizes support-diagnostics', () => {+ expect(de['support-diagnostics']).toEqual({+ title: 'Diagnose & Zustand',+ description:+ 'Fuehren Sie Zustandspruefungen aus, validieren Sie Verbindungen und exportieren Sie Troubleshooting-Snapshots.',+ });+ });++ it('localizes support-reporting', () => {+ expect(de['support-reporting']).toEqual({+ title: 'Daten & Berichte',+ description:+ 'Exportieren Sie Inventardaten und erstellen Sie Leistungsberichte aus der kanonischen Einstellungsoberflaeche.',+ });+ });++ it('localizes support-logs', () => {+ expect(de['support-logs']).toEqual({+ title: 'Systemprotokolle',+ description:+ 'Pruefen Sie den Live-Pulse-Logstream und laden Sie den erfassten Puffer fuer Supportarbeit herunter.',+ });+ });++ it('localizes organization-overview', () => {+ expect(de['organization-overview']).toEqual({+ title: 'Organisationsuebersicht',+ description: 'Pruefen Sie Organisationsdaten, Mitgliederumfang und Eigentum.',+ });+ });++ it('localizes organization-access', () => {+ expect(de['organization-access']).toEqual({+ title: 'Organisationszugriff',+ description:+ 'Verwalten Sie Einladungen, Mitgliederrollen und Eigentumsuebertragungen der Organisation.',+ });+ });++ it('localizes organization-sharing', () => {+ expect(de['organization-sharing']).toEqual({+ title: 'Organisationsfreigabe',+ description: 'Teilen Sie Ressourcen zwischen Organisationen mit begrenztem Zugriff.',+ });+ });++ it('localizes organization-billing', () => {+ expect(de['organization-billing']).toEqual({+ title: 'Abrechnung & Nutzung',+ description:+ 'Pruefen Sie Organisationsplan, geltende Nutzungsrichtlinien und Abonnementstatus fuer bezahlten Zugriff.',+ });+ });++ it('localizes organization-billing-admin', () => {+ expect(de['organization-billing-admin']).toEqual({+ title: 'Abrechnungsadmin',+ description:+ 'Pruefen und verwalten Sie den Abrechnungsstatus aller Mandanten (nur Hosted-Modus).',+ });+ });++ it('localizes api', () => {+ expect(de['api']).toEqual({+ title: 'API-Zugriff',+ description:+ 'Erstellen und verwalten Sie begrenzte Pulse-Tokens fuer Agents, Automatisierung und externe Integrationen.',+ });+ });++ it('localizes security-overview', () => {+ expect(de['security-overview']).toEqual({+ title: 'Sicherheitsuebersicht',+ description:+ 'Sehen Sie Ihre Sicherheitslage auf einen Blick und ueberwachen Sie den Authentifizierungsstatus.',+ });+ });++ it('localizes security-data-handling', () => {+ expect(de['security-data-handling']).toEqual({+ title: 'Ressourcenschutz',+ description:+ 'Sehen Sie, welche ueberwachten Ressourcendetails zusammengefasst werden duerfen, lokal bleiben muessen oder redigiert sind.',+ });+ });++ it('localizes security-auth', () => {+ expect(de['security-auth']).toEqual({+ title: 'Authentifizierung',+ description:+ 'Verwalten Sie passwortbasierte Authentifizierung und Zugangsdatenrotation.',+ });+ });++ it('localizes security-sso', () => {+ expect(de['security-sso']).toEqual({+ title: 'Single-Sign-On-Anbieter',+ description: 'Konfigurieren Sie OIDC- und SAML-Identity-Provider.',+ });+ });++ it('localizes security-roles', () => {+ expect(de['security-roles']).toEqual({+ title: 'Rollen',+ description:+ 'Definieren Sie eigene Rollen und verwalten Sie granulare Berechtigungen fuer Benutzer und Tokens.',+ });+ });++ it('localizes security-users', () => {+ expect(de['security-users']).toEqual({+ title: 'Benutzerzugriff',+ description:+ 'Weisen Sie Benutzern Rollen zu und sehen Sie effektive Berechtigungen in Ihrer Infrastruktur.',+ });+ });++ it('localizes security-audit', () => {+ expect(de['security-audit']).toEqual({+ title: 'Audit-Protokoll',+ description:+ 'Sehen Sie Sicherheitsereignisse, Anmeldeversuche und Konfigurationsaenderungen.',+ });+ });++ it('localizes security-webhooks', () => {+ expect(de['security-webhooks']).toEqual({+ title: 'Audit-Webhooks',+ description:+ 'Konfigurieren Sie die Echtzeit-Zustellung von Audit-Ereignissen an externe Systeme.',+ });+ });+ });++ describe('Spanish catalog — tabs not pinned by the sibling suite', () => {+ // Sibling already covers system-network, system-ai, system-ai-assistant,+ // and system-billing in 'es'. Every other tab is pinned here.+ // Computed in beforeAll so the deferred 'es' catalog is present.+ let es: SettingsHeaderMetaMap;+ beforeAll(() => {+ es = getSettingsHeaderMeta('es');+ });++ it('localizes infrastructure-systems', () => {+ expect(es['infrastructure-systems']).toEqual({+ title: 'Infraestructura',+ description: 'Agrega, descubre y verifica la infraestructura que Pulse supervisa.',+ });+ });++ it('localizes monitoring-availability', () => {+ expect(es['monitoring-availability']).toEqual({+ title: 'Comprobaciones de disponibilidad',+ description:+ 'Supervisa dispositivos y servicios solo por endpoint con pruebas ping, TCP y HTTP.',+ });+ });++ it('localizes system-general', () => {+ expect(es['system-general']).toEqual({+ title: 'General',+ description: 'Administra apariencia, diseño y cadencia predeterminada de supervisión.',+ });+ });++ it('localizes system-updates', () => {+ expect(es['system-updates']).toEqual({+ title: 'Actualizaciones',+ description:+ 'Administra comprobaciones de versión, canales de actualización y comportamiento de actualización automática.',+ });+ });++ it('localizes system-recovery', () => {+ expect(es['system-recovery']).toEqual({+ title: 'Recuperación',+ description:+ 'Administra sondeos de copias/snapshots y flujos de exportación e importación de configuración.',+ });+ });++ it('localizes system-ai-patrol', () => {+ expect(es['system-ai-patrol']).toEqual({+ title: 'Patrol',+ description: 'Configura cuando se ejecuta Patrol, que lo inicia y que modelo usa.',+ });+ });++ it('localizes system-ai-discovery title (sibling only pinned de for this tab)', () => {+ expect(es['system-ai-discovery'].title).toBe('Contexto de servicio');+ });++ it('localizes system-relay', () => {+ expect(es['system-relay']).toEqual({+ title: 'Acceso remoto',+ description:+ 'Configura la conectividad de relay de Pulse para acceso remoto seguro y vinculación con Pulse Mobile.',+ });+ });++ it('localizes support-diagnostics', () => {+ expect(es['support-diagnostics']).toEqual({+ title: 'Diagnóstico y salud',+ description:+ 'Ejecuta comprobaciones de salud, valida conectividad y exporta snapshots de resolución de problemas.',+ });+ });++ it('localizes support-reporting', () => {+ expect(es['support-reporting']).toEqual({+ title: 'Datos e informes',+ description:+ 'Exporta datos de inventario y genera informes de rendimiento desde la consola canónica de ajustes.',+ });+ });++ it('localizes support-logs', () => {+ expect(es['support-logs']).toEqual({+ title: 'Logs del sistema',+ description:+ 'Inspecciona el flujo de logs de Pulse en vivo y descarga el búfer capturado para soporte.',+ });+ });++ it('localizes organization-overview', () => {+ expect(es['organization-overview']).toEqual({+ title: 'Resumen de organización',+ description: 'Revisa metadatos, alcance de miembros y propiedad de la organización.',+ });+ });++ it('localizes organization-access', () => {+ expect(es['organization-access']).toEqual({+ title: 'Acceso de organización',+ description:+ 'Administra invitaciones, roles de miembros y transferencias de propiedad de la organización.',+ });+ });++ it('localizes organization-sharing', () => {+ expect(es['organization-sharing']).toEqual({+ title: 'Uso compartido de organización',+ description: 'Comparte recursos entre organizaciones con acceso delimitado.',+ });+ });++ it('localizes organization-billing', () => {+ expect(es['organization-billing']).toEqual({+ title: 'Facturación y uso',+ description:+ 'Revisa el plan de la organización, las políticas de uso aplicables y el estado de suscripción para acceso de pago.',+ });+ });++ it('localizes organization-billing-admin', () => {+ expect(es['organization-billing-admin']).toEqual({+ title: 'Admin de facturación',+ description:+ 'Revisa y administra el estado de facturación de todos los tenants (solo modo alojado).',+ });+ });++ it('localizes api', () => {+ expect(es['api']).toEqual({+ title: 'Acceso API',+ description:+ 'Genera y administra tokens de Pulse con alcance limitado para agentes, automatización e integraciones externas.',+ });+ });++ it('localizes security-overview', () => {+ expect(es['security-overview']).toEqual({+ title: 'Resumen de seguridad',+ description:+ 'Consulta tu postura de seguridad de un vistazo y supervisa el estado de autenticación.',+ });+ });++ it('localizes security-data-handling', () => {+ expect(es['security-data-handling']).toEqual({+ title: 'Privacidad de recursos',+ description:+ 'Consulta qué detalles de recursos supervisados se pueden resumir, deben quedarse locales o están redactados.',+ });+ });++ it('localizes security-auth (full entry, sibling only checked .title via active locale)', () => {+ expect(es['security-auth']).toEqual({+ title: 'Autenticación',+ description: 'Administra autenticación con contraseña y rotación de credenciales.',+ });+ });++ it('localizes security-sso', () => {+ expect(es['security-sso']).toEqual({+ title: 'Proveedores de inicio de sesión único',+ description: 'Configura proveedores de identidad OIDC y SAML.',+ });+ });++ it('localizes security-roles', () => {+ expect(es['security-roles']).toEqual({+ title: 'Roles',+ description:+ 'Define roles personalizados y administra permisos granulares para usuarios y tokens.',+ });+ });++ it('localizes security-users', () => {+ expect(es['security-users']).toEqual({+ title: 'Acceso de usuarios',+ description:+ 'Asigna roles a usuarios y consulta permisos efectivos en tu infraestructura.',+ });+ });++ it('localizes security-audit', () => {+ expect(es['security-audit']).toEqual({+ title: 'Registro de auditoría',+ description:+ 'Consulta eventos de seguridad, intentos de inicio de sesión y cambios de configuración.',+ });+ });++ it('localizes security-webhooks', () => {+ expect(es['security-webhooks']).toEqual({+ title: 'Webhooks de auditoría',+ description:+ 'Configura la entrega en tiempo real de eventos de auditoría a sistemas externos.',+ });+ });+ });+});++describe('getInfrastructureReadOnlyHeaderDescription', () => {+ afterEach(() => {+ setActiveLocale(DEFAULT_LOCALE);+ });++ it('returns the English baseline when locale is "en" (single-element fallback arm)', () => {+ expect(getInfrastructureReadOnlyHeaderDescription('en')).toBe(+ 'Review the current top-level monitored systems and reporting posture. Setup changes stay unavailable in this read-only session.',+ );+ });++ it('returns the German translation when locale is "de"', () => {+ expect(getInfrastructureReadOnlyHeaderDescription('de')).toBe(+ 'Pruefen Sie die aktuell ueberwachten Hauptsysteme und den Reporting-Status. Einrichtungsänderungen bleiben in dieser schreibgeschuetzten Sitzung nicht verfuegbar.',+ );+ });++ it('returns the full Spanish translation (sibling only asserted .toContain)', () => {+ expect(getInfrastructureReadOnlyHeaderDescription('es')).toBe(+ 'Revisa los sistemas principales supervisados y el estado de informes. Los cambios de configuración no están disponibles en esta sesión de solo lectura.',+ );+ });++ it('uses the active locale when called with no argument (translateMessage default-parameter arm)', () => {+ // Default active locale is DEFAULT_LOCALE ('en').+ expect(getInfrastructureReadOnlyHeaderDescription()).toBe(+ getInfrastructureReadOnlyHeaderDescription('en'),+ );+ });++ it('honors an active non-default locale when no argument is passed', () => {+ setActiveLocale('de');+ expect(getInfrastructureReadOnlyHeaderDescription()).toBe(+ getInfrastructureReadOnlyHeaderDescription('de'),+ );+ });++ it('normalizes an explicit null locale to DEFAULT_LOCALE', () => {+ expect(+ getInfrastructureReadOnlyHeaderDescription(null as unknown as SupportedLocale),+ ).toBe(getInfrastructureReadOnlyHeaderDescription('en'));+ });++ it('normalizes an unsupported locale string to DEFAULT_LOCALE', () => {+ // 'fr' is not yet a SupportedLocale, so normalizeLocale falls back to en.+ expect(+ getInfrastructureReadOnlyHeaderDescription('fr' as unknown as SupportedLocale),+ ).toBe(getInfrastructureReadOnlyHeaderDescription('en'));+ });+});diff --git a/frontend-modern/src/components/Workloads/__tests__/diskListModel.branchcov0713.test.ts b/frontend-modern/src/components/Workloads/__tests__/diskListModel.branchcov0713.test.tsnew file mode 100644index 0000000000..cb2900da53--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/diskListModel.branchcov0713.test.ts@@ -0,0 +1,288 @@+import { describe, expect, it } from 'vitest';++import type { Disk } from '@/types/api';+import type { MetricDisplayThresholds } from '@/utils/metricThresholds';++import {+ buildWorkloadsDiskPresentation,+ getWorkloadsDiskLabel,+ getWorkloadsDiskLabelTitle,+ getWorkloadsDiskProgressClass,+ getWorkloadsDiskProgressWidth,+ getWorkloadsDiskTypeLabel,+ getWorkloadsDiskUsagePercent,+ getWorkloadsDiskUsagePercentLabel,+ hasWorkloadsDiskCapacity,+} from '../diskListModel';++// getWorkloadsDiskUsageText is intentionally NOT re-tested here: every one of+// its branches is already pinned by diskListModel.branchcov0712c.test.ts. It is+// still exercised indirectly below through buildWorkloadsDiskPresentation+// (which composes it), which covers both arms without duplicating unit tests.++// Tailwind background classes mirrored from metricThresholds.BG_CLASSES. The+// default disk display thresholds are warning 80 / critical 90+// (METRIC_THRESHOLDS.disk), used whenever thresholds is undefined or null.+const NORMAL_CLASS = 'bg-metric-normal-bg dark:bg-metric-normal-bg';+const WARNING_CLASS = 'bg-metric-warning-bg dark:bg-metric-warning-bg';+const CRITICAL_CLASS = 'bg-metric-critical-bg dark:bg-metric-critical-bg';++const makeDisk = (overrides: Partial<Disk> = {}): Disk => ({+ total: 100,+ used: 25,+ free: 75,+ usage: 25,+ mountpoint: '/',+ type: 'ext4',+ device: '/dev/sda1',+ ...overrides,+});++describe('diskListModel (branch coverage 0713)', () => {+ describe('hasWorkloadsDiskCapacity', () => {+ it('returns true when total is a positive number (both typeof and > 0 true)', () => {+ expect(hasWorkloadsDiskCapacity(makeDisk({ total: 100 }))).toBe(true);+ });++ it('returns false when total === 0 (typeof number true, total > 0 false)', () => {+ expect(hasWorkloadsDiskCapacity(makeDisk({ total: 0 }))).toBe(false);+ });++ it('returns false when total is a negative number (typeof number true, total > 0 false)', () => {+ expect(hasWorkloadsDiskCapacity(makeDisk({ total: -10 }))).toBe(false);+ });++ it('returns false when total is not a number (typeof guard short-circuits before the > 0 compare)', () => {+ const disk = { total: undefined, used: 0 } as unknown as Disk;+ expect(hasWorkloadsDiskCapacity(disk)).toBe(false);+ });+ });++ describe('getWorkloadsDiskUsagePercent', () => {+ it('returns 0 when the disk has no capacity (false arm of the guard)', () => {+ expect(getWorkloadsDiskUsagePercent(makeDisk({ total: 0 }))).toBe(0);+ });++ it('returns (used / total) * 100 for a normal ratio (true arm of the guard)', () => {+ expect(getWorkloadsDiskUsagePercent(makeDisk({ used: 25, total: 100 }))).toBe(25);+ });++ it('does not clamp the upper bound, so used > total yields a value over 100', () => {+ expect(getWorkloadsDiskUsagePercent(makeDisk({ used: 150, total: 100 }))).toBe(150);+ });+ });++ describe('getWorkloadsDiskLabel', () => {+ it('returns the mountpoint when it is truthy (first || arm)', () => {+ expect(getWorkloadsDiskLabel(makeDisk({ mountpoint: '/data', device: '/dev/sda1' }))).toBe(+ '/data',+ );+ });++ it('falls back to the device when the mountpoint is an empty string (second || arm)', () => {+ expect(getWorkloadsDiskLabel(makeDisk({ mountpoint: '', device: '/dev/sda1' }))).toBe(+ '/dev/sda1',+ );+ });++ it('falls back to the device when the mountpoint is undefined (second || arm)', () => {+ expect(getWorkloadsDiskLabel(makeDisk({ mountpoint: undefined, device: '/dev/nvme0' }))).toBe(+ '/dev/nvme0',+ );+ });++ it('returns "Unknown" when both mountpoint and device are falsy (final || arm)', () => {+ expect(getWorkloadsDiskLabel(makeDisk({ mountpoint: undefined, device: undefined }))).toBe(+ 'Unknown',+ );+ });+ });++ describe('getWorkloadsDiskLabelTitle', () => {+ it('returns the label unchanged when it is not "Unknown" (true arm of the ternary)', () => {+ expect(getWorkloadsDiskLabelTitle('/data')).toBe('/data');+ });++ it('returns undefined when the label is "Unknown" (false arm of the ternary)', () => {+ expect(getWorkloadsDiskLabelTitle('Unknown')).toBeUndefined();+ });+ });++ describe('getWorkloadsDiskUsagePercentLabel', () => {+ it('formats a whole-number percent with toFixed(0) when the disk has capacity (true arm)', () => {+ expect(getWorkloadsDiskUsagePercentLabel(makeDisk({ used: 25, total: 100 }))).toBe('25%');+ });++ it('rounds a fractional percent to the nearest integer via toFixed(0)', () => {+ // (2 / 3) * 100 = 66.666...; toFixed(0) rounds to "67".+ expect(getWorkloadsDiskUsagePercentLabel(makeDisk({ used: 2, total: 3 }))).toBe('67%');+ });++ it('returns the em dash glyph when the disk has no capacity (false arm)', () => {+ expect(getWorkloadsDiskUsagePercentLabel(makeDisk({ total: 0 }))).toBe('—');+ });+ });++ describe('getWorkloadsDiskProgressClass', () => {+ it('maps a sub-warning percent to the normal class with default thresholds', () => {+ // Default disk thresholds: warning 80 / critical 90. 60 < 80 -> normal.+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 60, total: 100 }))).toBe(NORMAL_CLASS);+ });++ it('maps a percent in the warning band to the warning class with default thresholds', () => {+ // 85 >= 80 and < 90 -> warning.+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 85, total: 100 }))).toBe(WARNING_CLASS);+ });++ it('maps a percent at or above critical to the critical class with default thresholds', () => {+ // 90 >= 90 -> critical.+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 90, total: 100 }))).toBe(CRITICAL_CLASS);+ });++ it('maps a no-capacity disk (percent 0) to the normal class', () => {+ expect(getWorkloadsDiskProgressClass(makeDisk({ total: 0 }))).toBe(NORMAL_CLASS);+ });++ it('falls back to the default disk thresholds when thresholds is null (nullish arm)', () => {+ // thresholds null -> getMetricSeverity uses getFallbackSeverityThresholds('disk')+ // -> METRIC_THRESHOLDS.disk {80, 90}. 90 >= 90 -> critical.+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 90, total: 100 }), null)).toBe(+ CRITICAL_CLASS,+ );+ });++ it('honors custom thresholds that move the band boundaries', () => {+ // { warning: 50, critical: 75 }: 60 >= 50 and < 75 -> warning (would be+ // normal under the default 80/90 thresholds).+ const thresholds: MetricDisplayThresholds = { warning: 50, critical: 75 };+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 60, total: 100 }), thresholds)).toBe(+ WARNING_CLASS,+ );+ // 80 >= 75 -> critical under custom thresholds.+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 80, total: 100 }), thresholds)).toBe(+ CRITICAL_CLASS,+ );+ // 40 < 50 -> normal under custom thresholds.+ expect(getWorkloadsDiskProgressClass(makeDisk({ used: 40, total: 100 }), thresholds)).toBe(+ NORMAL_CLASS,+ );+ });+ });++ describe('getWorkloadsDiskProgressWidth', () => {+ it('renders the raw percent when it is <= 100', () => {+ expect(getWorkloadsDiskProgressWidth(makeDisk({ used: 25, total: 100 }))).toBe('25%');+ });++ it('clamps a percent over 100 down to 100 via Math.min', () => {+ // getWorkloadsDiskUsagePercent yields 150; Math.min(150, 100) -> 100.+ expect(getWorkloadsDiskProgressWidth(makeDisk({ used: 150, total: 100 }))).toBe('100%');+ });++ it('renders 0% for a no-capacity disk (percent 0)', () => {+ expect(getWorkloadsDiskProgressWidth(makeDisk({ total: 0 }))).toBe('0%');+ });+ });++ describe('getWorkloadsDiskTypeLabel', () => {+ it('uppercases a lowercase type string', () => {+ expect(getWorkloadsDiskTypeLabel(makeDisk({ type: 'ext4' }))).toBe('EXT4');+ });++ it('returns an empty string when type is undefined (?. short-circuits, ?? arm)', () => {+ expect(getWorkloadsDiskTypeLabel(makeDisk({ type: undefined }))).toBe('');+ });++ it('returns an empty string for an empty-string type without triggering the ?? arm', () => {+ // ''.toUpperCase() === '' which is not nullish, so ?? '' does not run, but+ // the observable result is still ''.+ expect(getWorkloadsDiskTypeLabel(makeDisk({ type: '' }))).toBe('');+ });+ });++ describe('buildWorkloadsDiskPresentation', () => {+ it('composes a full presentation for a populated disk with capacity', () => {+ // Every helper's true/happy arm: capacity present, mountpoint truthy,+ // type present. formatBytes(25) = '25.0 B', formatBytes(100) = '100 B'.+ const disk = makeDisk({+ mountpoint: '/data',+ device: '/dev/sda1',+ type: 'ext4',+ total: 100,+ used: 25,+ free: 75,+ });+ expect(buildWorkloadsDiskPresentation(disk, 2)).toStrictEqual({+ key: '/data:/dev/sda1:2',+ label: '/data',+ labelTitle: '/data',+ progressClass: NORMAL_CLASS,+ progressWidth: '25%',+ typeLabel: 'EXT4',+ usageText: '25.0 B/100 B',+ usagePercentLabel: '25%',+ });+ });++ it('uses the ?? "" arms in the key and forces the Unknown label when mountpoint and device are undefined', () => {+ // mountpoint ?? '' and device ?? '' both take their right arms -> "::0".+ // label = 'Unknown' (both falsy) -> labelTitle undefined.+ const disk = makeDisk({+ mountpoint: undefined,+ device: undefined,+ type: 'xfs',+ total: 200,+ used: 50,+ free: 150,+ });+ expect(buildWorkloadsDiskPresentation(disk, 0)).toStrictEqual({+ key: '::0',+ label: 'Unknown',+ labelTitle: undefined,+ progressClass: NORMAL_CLASS,+ progressWidth: '25%',+ typeLabel: 'XFS',+ // formatBytes(50) = '50.0 B', formatBytes(200) = '200 B'.+ usageText: '50.0 B/200 B',+ usagePercentLabel: '25%',+ });+ });++ it('renders the unavailable/zero/em-dash fields for a no-capacity disk (getWorkloadsDiskUsageText false arm)', () => {+ const disk = makeDisk({+ mountpoint: '/foo',+ device: '/dev/sdb',+ type: 'ext4',+ total: 0,+ used: 0,+ free: 0,+ });+ expect(buildWorkloadsDiskPresentation(disk, 5)).toStrictEqual({+ key: '/foo:/dev/sdb:5',+ label: '/foo',+ labelTitle: '/foo',+ progressClass: NORMAL_CLASS,+ progressWidth: '0%',+ typeLabel: 'EXT4',+ usageText: 'Usage unavailable',+ usagePercentLabel: '—',+ });+ });++ it('threads the thresholds argument through to the progress class', () => {+ // 60% is normal under default thresholds but warning under {50, 75}.+ const thresholds: MetricDisplayThresholds = { warning: 50, critical: 75 };+ const presentation = buildWorkloadsDiskPresentation(+ makeDisk({ used: 60, total: 100 }),+ 0,+ thresholds,+ );+ expect(presentation.progressClass).toBe(WARNING_CLASS);+ });++ it('reflects the index argument in the key segment', () => {+ const presentation = buildWorkloadsDiskPresentation(makeDisk(), 9);+ expect(presentation.key).toBe('/:/dev/sda1:9');+ });+ });+});diff --git a/frontend-modern/src/components/shared/FilterBar/__tests__/filterCatalog.branchcov0713.test.ts b/frontend-modern/src/components/shared/FilterBar/__tests__/filterCatalog.branchcov0713.test.tsnew file mode 100644index 0000000000..8d8eb5cef9--- /dev/null+++ b/frontend-modern/src/components/shared/FilterBar/__tests__/filterCatalog.branchcov0713.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it, vi } from 'vitest';+import { formatFilterChipValue } from '@/components/shared/FilterBar/filterCatalog';+import type { FilterDef, FilterSelectOption } from '@/components/shared/FilterBar/filterCatalog';++// Branch-coverage companion to FilterBar.test.tsx. The sibling suite renders+// FilterBar with fixtures that never set FilterDef.formatChipValue, so the+// custom-formatter true-arm of formatFilterChipValue is never exercised. These+// cases call the exported helper directly and drive each guard/ternary arm:+// the custom-formatter delegation, the matched-label lookup, the no-match+// `?? value` fallback, the empty-options fallback, the runtime-null-label+// fallback, and the empty-string-label `??` semantics.++// Builder that satisfies the full FilterDef shape while exposing only the+// fields formatFilterChipValue reads (value()/options()/formatChipValue).+// setValue is stubbed with vi.fn() to keep the fixture inert.+const makeFilter = (overrides: {+ value?: string;+ options?: FilterSelectOption[];+ formatChipValue?: (value: string, options: FilterSelectOption[]) => string;+}): FilterDef => ({+ id: 'under-test',+ label: 'UnderTest',+ value: () => overrides.value ?? '',+ setValue: vi.fn(),+ defaultValue: '',+ options: () => overrides.options ?? [],+ ...(overrides.formatChipValue !== undefined ? { formatChipValue: overrides.formatChipValue } : {}),+});++describe('formatFilterChipValue branch coverage', () => {+ describe('custom formatChipValue arm (truthy guard)', () => {+ it('delegates to filter.formatChipValue and returns its result (guard true-arm)', () => {+ const formatChipValue = vi.fn((v: string) => `custom:${v}`);+ const filter = makeFilter({+ value: 'vm',+ options: [{ value: 'vm', label: 'VMs' }],+ formatChipValue,+ });++ expect(formatFilterChipValue(filter)).toBe('custom:vm');+ expect(formatChipValue).toHaveBeenCalledOnce();+ });++ it('passes the current value and the resolved options array as arguments', () => {+ const seen: Array<{ value: string; opts: FilterSelectOption[] }> = [];+ const options: FilterSelectOption[] = [+ { value: 'all', label: 'All' },+ { value: 'pve1', label: 'pve1' },+ ];+ const filter = makeFilter({+ value: 'pve1',+ options,+ formatChipValue: (value, opts) => {+ seen.push({ value, opts });+ return 'formatted';+ },+ });++ expect(formatFilterChipValue(filter)).toBe('formatted');+ expect(seen).toHaveLength(1);+ expect(seen[0]).toEqual({ value: 'pve1', opts: options });+ });++ it('returns the custom result even when it differs from any option label', () => {+ const filter = makeFilter({+ value: 'all',+ options: [{ value: 'all', label: 'All' }],+ formatChipValue: () => 'Custom label',+ });++ expect(formatFilterChipValue(filter)).toBe('Custom label');+ });++ it('returns an empty string produced by the custom formatter', () => {+ const filter = makeFilter({+ value: 'all',+ options: [{ value: 'all', label: 'All' }],+ formatChipValue: () => '',+ });++ expect(formatFilterChipValue(filter)).toBe('');+ });++ it('skips the default lookup entirely when the custom formatter is present', () => {+ const formatChipValue = vi.fn(() => 'override');+ const filter = makeFilter({+ value: 'no-such-option',+ options: [{ value: 'all', label: 'All' }],+ formatChipValue,+ });++ expect(formatFilterChipValue(filter)).toBe('override');+ expect(formatChipValue).toHaveBeenCalledWith('no-such-option', [{ value: 'all', label: 'All' }]);+ });+ });++ describe('default lookup arm (formatChipValue absent)', () => {+ it('returns the matching option label (match?.label truthy)', () => {+ const filter = makeFilter({+ value: 'vm',+ options: [+ { value: 'all', label: 'All' },+ { value: 'vm', label: 'VMs' },+ ],+ });++ expect(formatFilterChipValue(filter)).toBe('VMs');+ });++ it('selects the first option whose value matches when duplicates exist', () => {+ const filter = makeFilter({+ value: 'dup',+ options: [+ { value: 'dup', label: 'First' },+ { value: 'dup', label: 'Second' },+ ],+ });++ expect(formatFilterChipValue(filter)).toBe('First');+ });++ it('falls back to the raw value when no option matches (?? value)', () => {+ const filter = makeFilter({+ value: 'orphan',+ options: [{ value: 'all', label: 'All' }],+ });++ expect(formatFilterChipValue(filter)).toBe('orphan');+ });++ it('falls back to the raw value when options is an empty array', () => {+ const filter = makeFilter({ value: 'lonely', options: [] });++ expect(formatFilterChipValue(filter)).toBe('lonely');+ });++ it('falls back to the raw value when the matched label is null at runtime', () => {+ // FilterSelectOption.label is declared `string`, so a null label violates+ // the type; cast through unknown to exercise the `?? value` fallback+ // without silencing a real type error.+ const malformedOptions = [{ value: 'ghost', label: null }] as unknown as FilterSelectOption[];+ const filter = makeFilter({ value: 'ghost', options: malformedOptions });++ expect(formatFilterChipValue(filter)).toBe('ghost');+ });++ it('falls back to the raw value when the matched label is undefined at runtime', () => {+ const malformedOptions = [+ { value: 'ghost', label: undefined },+ ] as unknown as FilterSelectOption[];+ const filter = makeFilter({ value: 'ghost', options: malformedOptions });++ expect(formatFilterChipValue(filter)).toBe('ghost');+ });++ it('returns an empty-string label verbatim because ?? only catches null/undefined', () => {+ // `match?.label ?? value` does not coerce '' to value; an explicit+ // empty label is a distinct, observable outcome.+ const filter = makeFilter({+ value: 'blank',+ options: [{ value: 'blank', label: '' }],+ });++ expect(formatFilterChipValue(filter)).toBe('');+ });++ it('returns the raw value when the value is the empty string with no empty-value option', () => {+ const filter = makeFilter({+ value: '',+ options: [{ value: 'all', label: 'All' }],+ });++ expect(formatFilterChipValue(filter)).toBe('');+ });++ it('returns the matching option label for an option whose value is the empty string', () => {+ const filter = makeFilter({+ value: '',+ options: [+ { value: '', label: 'All nodes' },+ { value: 'pve1', label: 'pve1' },+ ],+ });++ expect(formatFilterChipValue(filter)).toBe('All nodes');+ });+ });+});diff --git a/frontend-modern/src/components/shared/__tests__/statusBadgeModel.branchcov0713.test.ts b/frontend-modern/src/components/shared/__tests__/statusBadgeModel.branchcov0713.test.tsnew file mode 100644index 0000000000..6aefa5d2fe--- /dev/null+++ b/frontend-modern/src/components/shared/__tests__/statusBadgeModel.branchcov0713.test.ts@@ -0,0 +1,333 @@+import { describe, expect, it } from 'vitest';+import type { StatusBadgeProps, StatusBadgeSize } from '@/components/shared/statusBadgeModel';+import {+ getStatusBadgeClass,+ getStatusBadgeLabel,+ resolveStatusBadgeSize,+} from '@/components/shared/statusBadgeModel';++// NOTE: getStatusBadgeTitle is intentionally NOT exercised here — the sibling+// file `statusBadgeModel.branchcov0712.test.ts` already covers every branch of+// its `disabled` if/else, the three-level ?? cascade, and the isEnabled+// ternary. Re-testing those branches would be pure duplication; this file+// targets the other three exported functions whose branches are still+// uncovered.++// Mirror of the module-private class-string constants so assertions are+// exact-string equality rather than substring/truthiness checks. Keeping them+// in sync with the source is the same pattern used by+// containerUpdateBadgeModel.branchcov2.test.ts.+const STATUS_BADGE_BASE_CLASS =+ 'inline-flex items-center justify-center text-xs font-medium rounded-md transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-blue-400';+const STATUS_BADGE_PADDING_BY_SIZE: Record<StatusBadgeSize, string> = {+ sm: 'px-2 py-0.5',+ md: 'px-2.5 py-1',+};+const STATUS_BADGE_ENABLED_CLASS =+ 'bg-blue-50 text-blue-700 hover:bg-blue-100 dark:bg-blue-500 dark:text-blue-300 dark:hover:bg-blue-500';+const STATUS_BADGE_DISABLED_STATE_CLASS = 'text-muted hover:bg-surface-hover';+const STATUS_BADGE_INTERACTION_DISABLED_CLASS =+ 'opacity-60 cursor-not-allowed hover:bg-transparent dark:hover:bg-transparent';++// Minimal valid props; every optional label field defaults to undefined so+// each test can populate only the ones it needs to drive a specific branch.+function makeProps(overrides: Partial<StatusBadgeProps> = {}): StatusBadgeProps {+ return {+ isEnabled: false,+ ...overrides,+ };+}++describe('statusBadgeModel.branchcov0713', () => {+ describe('resolveStatusBadgeSize', () => {+ it('falls back to "sm" when size is undefined (?? right arm)', () => {+ expect(resolveStatusBadgeSize(undefined)).toBe('sm');+ });++ it('returns "sm" unchanged when explicitly passed (?? left arm)', () => {+ expect(resolveStatusBadgeSize('sm')).toBe('sm');+ });++ it('returns "md" unchanged when explicitly passed (?? left arm)', () => {+ expect(resolveStatusBadgeSize('md')).toBe('md');+ });++ it('distinguishes between the default "sm" and an explicit "sm" (both ?? arms are reachable)', () => {+ // Two tests above exercise each arm in isolation; this one asserts the+ // function never confuses the two distinct "sm" inputs.+ expect(resolveStatusBadgeSize(undefined)).toBe(resolveStatusBadgeSize('sm'));+ expect(resolveStatusBadgeSize('md')).not.toBe(resolveStatusBadgeSize('sm'));+ });++ it('treats a malformed size that happens to be falsy-string as the ?? right arm', () => {+ // The declared type is `StatusBadgeSize | undefined`; the only falsy+ // value that type permits is `undefined`. We still verify the ?? operator+ // is what's driving the default by passing the empty string through the+ // declared `undefined` slot — the function does not validate further.+ const malformed = '' as unknown as undefined;+ expect(resolveStatusBadgeSize(malformed)).toBe('');+ });+ });++ describe('getStatusBadgeClass', () => {+ describe('size lookup (Record<StatusBadgeSize, string>)', () => {+ it.each<StatusBadgeSize>(['sm', 'md'])(+ 'embeds the %s padding token between base and state class',+ (size) => {+ expect(getStatusBadgeClass(size, true, false)).toBe(+ [+ STATUS_BADGE_BASE_CLASS,+ STATUS_BADGE_PADDING_BY_SIZE[size],+ STATUS_BADGE_ENABLED_CLASS,+ ].join(' '),+ );+ },+ );+ });++ describe('isEnabled ternary', () => {+ it('selects the ENABLED class when isEnabled is true', () => {+ expect(getStatusBadgeClass('sm', true, false)).toBe(+ [+ STATUS_BADGE_BASE_CLASS,+ STATUS_BADGE_PADDING_BY_SIZE.sm,+ STATUS_BADGE_ENABLED_CLASS,+ ].join(' '),+ );+ });++ it('selects the DISABLED-STATE class when isEnabled is false', () => {+ expect(getStatusBadgeClass('sm', false, false)).toBe(+ [+ STATUS_BADGE_BASE_CLASS,+ STATUS_BADGE_PADDING_BY_SIZE.sm,+ STATUS_BADGE_DISABLED_STATE_CLASS,+ ].join(' '),+ );+ });+ });++ describe('disabled ternary', () => {+ it('appends the INTERACTION-DISABLED class when disabled is true', () => {+ expect(getStatusBadgeClass('sm', true, true)).toBe(+ [+ STATUS_BADGE_BASE_CLASS,+ STATUS_BADGE_PADDING_BY_SIZE.sm,+ STATUS_BADGE_ENABLED_CLASS,+ STATUS_BADGE_INTERACTION_DISABLED_CLASS,+ ].join(' '),+ );+ });++ it('emits an empty string token when disabled is false, then trims the trailing space', () => {+ // Defensive .trim() branch: the literal `''` fourth element produces a+ // trailing space after join(' '); .trim() must remove it so the+ // resulting class string has no trailing whitespace.+ const result = getStatusBadgeClass('sm', true, false);+ expect(result.endsWith(' ')).toBe(false);+ expect(result).toBe(+ [+ STATUS_BADGE_BASE_CLASS,+ STATUS_BADGE_PADDING_BY_SIZE.sm,+ STATUS_BADGE_ENABLED_CLASS,+ ].join(' '),+ );+ });+ });++ describe('full 2x2x2 matrix (size × isEnabled × disabled)', () => {+ // Every combination of the three boolean-ish inputs is enumerated so+ // every ternary arm of every input is reached alongside every other.+ const cases: ReadonlyArray<{+ name: string;+ size: StatusBadgeSize;+ isEnabled: boolean;+ disabled: boolean;+ stateClass: string;+ }> = [+ {+ name: 'sm + enabled + not-disabled',+ size: 'sm',+ isEnabled: true,+ disabled: false,+ stateClass: STATUS_BADGE_ENABLED_CLASS,+ },+ {+ name: 'sm + enabled + disabled',+ size: 'sm',+ isEnabled: true,+ disabled: true,+ stateClass: STATUS_BADGE_ENABLED_CLASS,+ },+ {+ name: 'sm + disabled-state + not-disabled',+ size: 'sm',+ isEnabled: false,+ disabled: false,+ stateClass: STATUS_BADGE_DISABLED_STATE_CLASS,+ },+ {+ name: 'sm + disabled-state + disabled',+ size: 'sm',+ isEnabled: false,+ disabled: true,+ stateClass: STATUS_BADGE_DISABLED_STATE_CLASS,+ },+ {+ name: 'md + enabled + not-disabled',+ size: 'md',+ isEnabled: true,+ disabled: false,+ stateClass: STATUS_BADGE_ENABLED_CLASS,+ },+ {+ name: 'md + enabled + disabled',+ size: 'md',+ isEnabled: true,+ disabled: true,+ stateClass: STATUS_BADGE_ENABLED_CLASS,+ },+ {+ name: 'md + disabled-state + not-disabled',+ size: 'md',+ isEnabled: false,+ disabled: false,+ stateClass: STATUS_BADGE_DISABLED_STATE_CLASS,+ },+ {+ name: 'md + disabled-state + disabled',+ size: 'md',+ isEnabled: false,+ disabled: true,+ stateClass: STATUS_BADGE_DISABLED_STATE_CLASS,+ },+ ];++ it.each(cases)('$name produces the exact class string', ({ size, isEnabled, disabled, stateClass }) => {+ const expected = [+ STATUS_BADGE_BASE_CLASS,+ STATUS_BADGE_PADDING_BY_SIZE[size],+ stateClass,+ disabled ? STATUS_BADGE_INTERACTION_DISABLED_CLASS : '',+ ]+ .join(' ')+ .trim();+ expect(getStatusBadgeClass(size, isEnabled, disabled)).toBe(expected);+ });++ it.each(cases)(+ '$name has no double spaces and no leading/trailing whitespace',+ ({ size, isEnabled, disabled }) => {+ const result = getStatusBadgeClass(size, isEnabled, disabled);+ expect(result).not.toMatch(/\s{2,}/);+ expect(result).toBe(result.trim());+ },+ );+ });++ describe('malformed size lookup (Record miss at runtime)', () => {+ // The declared type forbids anything outside 'sm' | 'md', but at runtime+ // `STATUS_BADGE_PADDING_BY_SIZE[size]` returns `undefined` for any other+ // key. `Array.prototype.join` stringifies `undefined` slots to the empty+ // string (per ECMA-262 §22.1.3.15), so the result contains a stray+ // internal double space where the padding token was supposed to sit.+ // `.trim()` only strips leading/trailing whitespace and does not collapse+ // the internal double space — see GLM_REPORT.md for the corresponding+ // suspected source bug. These tests lock in the current (defective)+ // runtime behavior so any future fix is forced to update them+ // deliberately.++ it('collapses the missing padding slot to an empty string, leaving a double space (out-of-union size, enabled, not-disabled)', () => {+ const bogus = 'xl' as unknown as StatusBadgeSize;+ const result = getStatusBadgeClass(bogus, true, false);+ // The undefined lookup contributes an empty string; the surrounding+ // separators collapse into a literal double space between the base+ // class and the enabled-state class.+ expect(result).toBe(+ `${STATUS_BADGE_BASE_CLASS} ${STATUS_BADGE_ENABLED_CLASS}`,+ );+ expect(result).toMatch(/\s{2,}/);+ });++ it('still appends the interaction-disabled class for a malformed size when disabled is true (double space preserved)', () => {+ const bogus = 'lg' as unknown as StatusBadgeSize;+ const result = getStatusBadgeClass(bogus, false, true);+ expect(result).toBe(+ `${STATUS_BADGE_BASE_CLASS} ${STATUS_BADGE_DISABLED_STATE_CLASS} ${STATUS_BADGE_INTERACTION_DISABLED_CLASS}`,+ );+ expect(result).toMatch(/\s{2,}/);+ });+ });+ });++ describe('getStatusBadgeLabel', () => {+ describe('isEnabled === true', () => {+ it('returns labelEnabled when it is a non-empty string (?? left arm)', () => {+ const props = makeProps({ isEnabled: true, labelEnabled: 'Active' });+ expect(getStatusBadgeLabel(props)).toBe('Active');+ });++ it('falls back to "Enabled" when labelEnabled is absent (?? right arm)', () => {+ const props = makeProps({ isEnabled: true });+ expect(getStatusBadgeLabel(props)).toBe('Enabled');+ });++ it('returns labelEnabled verbatim when it is an empty string (?? does NOT treat "" as nullish)', () => {+ // Subtle branch: `??` only falls through on null/undefined, so an+ // empty-string label is preserved as-is rather than replaced by the+ // "Enabled" default. This is the documented ?? semantics and is+ // asserted to lock in current behavior.+ const props = makeProps({ isEnabled: true, labelEnabled: '' });+ expect(getStatusBadgeLabel(props)).toBe('');+ });++ it('ignores labelDisabled entirely when isEnabled is true', () => {+ const props = makeProps({+ isEnabled: true,+ labelEnabled: 'On',+ labelDisabled: 'Should not appear',+ });+ expect(getStatusBadgeLabel(props)).toBe('On');+ });+ });++ describe('isEnabled === false', () => {+ it('returns labelDisabled when it is a non-empty string (?? left arm)', () => {+ const props = makeProps({ isEnabled: false, labelDisabled: 'Paused' });+ expect(getStatusBadgeLabel(props)).toBe('Paused');+ });++ it('falls back to "Disabled" when labelDisabled is absent (?? right arm)', () => {+ const props = makeProps({ isEnabled: false });+ expect(getStatusBadgeLabel(props)).toBe('Disabled');+ });++ it('returns labelDisabled verbatim when it is an empty string (?? does NOT treat "" as nullish)', () => {+ // Same ?? semantics as the enabled branch: empty string is preserved.+ const props = makeProps({ isEnabled: false, labelDisabled: '' });+ expect(getStatusBadgeLabel(props)).toBe('');+ });++ it('ignores labelEnabled entirely when isEnabled is false', () => {+ const props = makeProps({+ isEnabled: false,+ labelEnabled: 'Should not appear',+ labelDisabled: 'Off',+ });+ expect(getStatusBadgeLabel(props)).toBe('Off');+ });+ });++ describe('default values are the canonical English words', () => {+ // Lock in the exact default strings so a future refactor that changes+ // "Enabled" / "Disabled" to e.g. "On" / "Off" trips a test.+ it('uses exactly "Enabled" as the default for the enabled state', () => {+ expect(getStatusBadgeLabel(makeProps({ isEnabled: true }))).toBe('Enabled');+ });++ it('uses exactly "Disabled" as the default for the disabled state', () => {+ expect(getStatusBadgeLabel(makeProps({ isEnabled: false }))).toBe('Disabled');+ });+ });+ });+});diff --git a/frontend-modern/src/components/shared/__tests__/tooltipModel.branchcov0713.test.ts b/frontend-modern/src/components/shared/__tests__/tooltipModel.branchcov0713.test.tsnew file mode 100644index 0000000000..b83645989d--- /dev/null+++ b/frontend-modern/src/components/shared/__tests__/tooltipModel.branchcov0713.test.ts@@ -0,0 +1,338 @@+import { describe, expect, it } from 'vitest';+import {+ resolveTooltipPosition,+ sanitizeTooltipContent,+} from '@/components/shared/tooltipModel';+import type {+ TooltipAlignment,+ TooltipDirection,+ TooltipPosition,+} from '@/components/shared/tooltipModel';++// Module-internal constants mirrored here so each assertion is a concrete,+// hand-computed expected value rather than a re-derivation of the source.+// padding (gap between anchor and tooltip) = 8+// viewportPadding (min inset from the viewport edge) = 4+const PADDING = 8;+const VIEWPORT_PADDING = 4;++describe('tooltipModel.branchcov0713', () => {+ describe('sanitizeTooltipContent', () => {+ it('returns an empty string for empty-string input (Array.from produces no chars)', () => {+ expect(sanitizeTooltipContent('')).toBe('');+ });++ it('passes plain ASCII printable text through unchanged', () => {+ const text = 'Hello, World!';+ expect(sanitizeTooltipContent(text)).toBe(text);+ });++ it("keeps '\\n' (newline) via the first char === '\\n' arm", () => {+ expect(sanitizeTooltipContent('a\nb')).toBe('a\nb');+ });++ it("keeps '\\t' (tab) via the char === '\\t' arm", () => {+ expect(sanitizeTooltipContent('a\tb')).toBe('a\tb');+ });++ it("keeps both '\\n' and '\\t' together", () => {+ expect(sanitizeTooltipContent('\ta\tb\nc\td')).toBe('\ta\tb\nc\td');+ });++ it('returns a string that is only a newline unchanged', () => {+ expect(sanitizeTooltipContent('\n')).toBe('\n');+ });++ it("strips NUL ('\\x00') because codePoint 0 < 0x20 and it is not '\\n' or '\\t'", () => {+ expect(sanitizeTooltipContent('a\x00b')).toBe('ab');+ });++ it("strips BEL ('\\x07') and other C0 controls below 0x20", () => {+ expect(sanitizeTooltipContent('a\x07b\x01c')).toBe('abc');+ });++ it("strips CR ('\\r', 0x0d): below 0x20 and explicitly not '\\n'", () => {+ // Guards the subtlety that only '\n' (not '\r') is whitelisted among+ // line-break characters.+ expect(sanitizeTooltipContent('a\rb')).toBe('ab');+ });++ it("strips DEL ('\\x7f') via the codePoint !== 0x7f arm even though 0x7f >= 0x20", () => {+ expect(sanitizeTooltipContent('a\x7fb')).toBe('ab');+ });++ it('strips a string composed entirely of control characters to the empty string', () => {+ expect(sanitizeTooltipContent('\x00\x01\x07\x7f')).toBe('');+ });++ it("keeps '~' (0x7e), the printable char immediately below DEL", () => {+ // Boundary: 0x7e passes both `>= 0x20` and `!== 0x7f`.+ expect(sanitizeTooltipContent('a~b')).toBe('a~b');+ });++ it("keeps space (0x20), the lowest printable char (>= 0x20 boundary)", () => {+ expect(sanitizeTooltipContent('a b')).toBe('a b');+ });++ it('keeps an astral-plane emoji (codePoint well above 0x20, != 0x7f)', () => {+ expect(sanitizeTooltipContent('a😀b')).toBe('a😀b');+ });++ it('keeps a surrogate-pair code point as a single retained character', () => {+ // U+1D547 MATHEMATICAL DOUBLE-STRUCK CAPITAL Q -> codePoint 120135.+ // Array.from splits by code point, so the pair is one element and is kept.+ expect(sanitizeTooltipContent('x𝕏y')).toBe('x𝕏y');+ });++ it('filters a mixed string down to exactly its whitelisted characters', () => {+ expect(sanitizeTooltipContent('\thello\n\x00world\x7fend')).toBe(+ '\thello\nworldend',+ );+ });++ it('does not mutate or reorder retained characters when nothing is stripped', () => {+ const text = ' plainly visible ';+ expect(sanitizeTooltipContent(text)).toBe(text);+ });+ });++ describe('resolveTooltipPosition', () => {+ it("centers horizontally and opens above when align='center' and direction='up' (no clamping)", () => {+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 500,+ y: 600,+ align: 'center',+ direction: 'up',+ });+ // left = x - width/2 = 500 - 50 = 450+ // top = y - height - padding = 600 - 50 - 8 = 542+ // Neither value exceeds [viewportPadding, maxLeft]/[viewportPadding, maxTop].+ expect(result).toEqual({ left: 450, top: 542 } satisfies TooltipPosition);+ });++ it("keeps x and opens below when align='left' and direction='down' (no clamping)", () => {+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 500,+ y: 600,+ align: 'left',+ direction: 'down',+ });+ // left stays x = 500; top = y + padding = 600 + 8 = 608.+ expect(result).toEqual({ left: 500, top: 608 } satisfies TooltipPosition);+ });++ it("defaults align to 'center' and direction to 'up' when both are omitted (?? right arms)", () => {+ const withDefaults = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 500,+ y: 600,+ });+ // Same computation as the explicit center/up case.+ expect(withDefaults).toEqual({ left: 450, top: 542 });+ });++ it('clamps an above-viewport / left-of-viewport position back down to viewportPadding on both axes', () => {+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: -100,+ y: 10,+ align: 'left',+ direction: 'up',+ });+ // align left: left = x = -100 -> max(-100, 4) = 4 -> min(4, 896) = 4.+ // dir up: top = 10 - 50 - 8 = -48 -> max(-48, 4) = 4 -> min(4, 746) = 4.+ expect(result).toEqual({+ left: VIEWPORT_PADDING,+ top: VIEWPORT_PADDING,+ } satisfies TooltipPosition);+ });++ it('clamps a past-the-right / past-the-bottom position back to maxLeft / maxTop', () => {+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 2000,+ y: 2000,+ align: 'left',+ direction: 'down',+ });+ // maxLeft = 1000 - 100 - 4 = 896; maxTop = 800 - 50 - 4 = 746.+ // left = 2000 -> min(max(2000, 4), 896) = 896.+ // dir down: top = 2000 + 8 = 2008 -> min(max(2008, 4), 746) = 746.+ expect(result).toEqual({+ left: 1000 - 100 - VIEWPORT_PADDING,+ top: 800 - 50 - VIEWPORT_PADDING,+ } satisfies TooltipPosition);+ });++ it('forces both axes to viewportPadding when the rect is larger than the viewport (maxLeft/maxTop < viewportPadding branch)', () => {+ // The defensive `Math.max(maxLeft, viewportPadding)` term collapses to+ // viewportPadding when the tooltip does not fit at all.+ const result = resolveTooltipPosition({+ rect: { width: 1000, height: 1000 },+ viewportWidth: 100,+ viewportHeight: 100,+ x: 500,+ y: 500,+ align: 'left',+ direction: 'up',+ });+ // maxLeft = 100 - 1000 - 4 = -904 -> max(-904, 4) = 4.+ // left = min(max(500, 4), 4) = 4. Same for top.+ expect(result).toEqual({+ left: VIEWPORT_PADDING,+ top: VIEWPORT_PADDING,+ } satisfies TooltipPosition);+ });++ it("handles a zero-size rect: align='center' subtracts 0 and direction='up' subtracts only padding", () => {+ const result = resolveTooltipPosition({+ rect: { width: 0, height: 0 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 500,+ y: 600,+ align: 'center',+ direction: 'up',+ });+ // left = 500 - 0/2 = 500; top = 600 - 0 - 8 = 592.+ // maxLeft = 996, maxTop = 796 -> no clamping.+ expect(result).toEqual({ left: 500, top: 600 - PADDING } satisfies TooltipPosition);+ });++ it("clamps each axis independently when only one overflows (left axis overflows, top is in range)", () => {+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 5000,+ y: 100,+ align: 'center',+ direction: 'down',+ });+ // align center: left = 5000 - 50 = 4950 -> min(max(4950, 4), 896) = 896.+ // dir down: top = 100 + 8 = 108 -> in range, stays 108.+ expect(result).toEqual({+ left: 1000 - 100 - VIEWPORT_PADDING,+ top: 100 + PADDING,+ } satisfies TooltipPosition);+ });++ it("treats an out-of-union align as NOT 'center' (falls to the align='left' behavior)", () => {+ // Defensive: strict equality means any foreign value skips the centering+ // branch, leaving left === x.+ const bogusAlign =+ 'right' as unknown as Parameters<typeof resolveTooltipPosition>[0]['align'];+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 300,+ y: 400,+ align: bogusAlign,+ direction: 'up',+ });+ // left stays 300 (no centering); top = 400 - 50 - 8 = 342.+ expect(result).toEqual({ left: 300, top: 342 } satisfies TooltipPosition);+ });++ it("treats an out-of-union direction as NOT 'up' (falls to the direction='down' behavior)", () => {+ const bogusDirection =+ 'sideways' as unknown as TooltipDirection;+ const result = resolveTooltipPosition({+ rect: { width: 100, height: 50 },+ viewportWidth: 1000,+ viewportHeight: 800,+ x: 300,+ y: 400,+ align: 'center',+ direction: bogusDirection,+ });+ // align center: left = 300 - 50 = 250.+ // bogus direction -> else arm: top = 400 + 8 = 408.+ expect(result).toEqual({ left: 250, top: 408 } satisfies TooltipPosition);+ });++ it("computes maxLeft and maxTop from the supplied viewport dims even with an unusual align/direction pairing", () => {+ // align='left', direction='up' with a tight viewport to exercise both+ // clamps at once using only declared-union values.+ const result = resolveTooltipPosition({+ rect: { width: 40, height: 40 },+ viewportWidth: 200,+ viewportHeight: 150,+ x: 190,+ y: 5,+ align: 'left',+ direction: 'up',+ });+ // align left: left = 190.+ // maxLeft = 200 - 40 - 4 = 156 -> min(max(190, 4), 156) = 156.+ // dir up: top = 5 - 40 - 8 = -43 -> min(max(-43, 4), 106) = 4.+ // maxTop = 150 - 40 - 4 = 106.+ expect(result).toEqual({+ left: 200 - 40 - VIEWPORT_PADDING,+ top: VIEWPORT_PADDING,+ } satisfies TooltipPosition);+ });++ it('returns a plain { left, top } object with no extra enumerable keys', () => {+ const result = resolveTooltipPosition({+ rect: { width: 10, height: 10 },+ viewportWidth: 100,+ viewportHeight: 100,+ x: 50,+ y: 50,+ align: 'center',+ direction: 'down',+ });+ expect(Object.keys(result).sort()).toEqual(['left', 'top']);+ expect(typeof result.left).toBe('number');+ expect(typeof result.top).toBe('number');+ });++ it('matches the documented alignment/direction union members exhaustively', () => {+ // One assertion per declared align x direction combination, computed+ // against a viewport generous enough that no clamping occurs.+ const rect = { width: 20, height: 10 };+ const viewportWidth = 1000;+ const viewportHeight = 1000;+ const x = 200;+ const y = 300;++ const aligns: TooltipAlignment[] = ['left', 'center'];+ const directions: TooltipDirection[] = ['up', 'down'];++ for (const align of aligns) {+ for (const direction of directions) {+ const result = resolveTooltipPosition({+ rect,+ viewportWidth,+ viewportHeight,+ x,+ y,+ align,+ direction,+ });+ const expectedLeft = align === 'center' ? x - rect.width / 2 : x;+ const expectedTop =+ direction === 'up' ? y - rect.height - PADDING : y + PADDING;+ expect(result).toEqual({+ left: expectedLeft,+ top: expectedTop,+ } satisfies TooltipPosition);+ }+ }+ });+ });+});diff --git a/frontend-modern/src/features/actions/__tests__/actionPresentation.branchcov0713.test.ts b/frontend-modern/src/features/actions/__tests__/actionPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..7126dd6572--- /dev/null+++ b/frontend-modern/src/features/actions/__tests__/actionPresentation.branchcov0713.test.ts@@ -0,0 +1,147 @@+import { describe, expect, it } from 'vitest';+import type {+ ActionEvidenceClass,+ ActionPolicyAuthorityFactor,+ ActionPolicyAuthorityKind,+ ActionVerificationTruthStatus,+} from '@/types/actionAudit';+import {+ formatActionName,+ formatPolicyAuthority,+ verificationTruthLabel,+} from '../actionPresentation';++const makeAuthority = (+ kind: ActionPolicyAuthorityKind,+ overrides: Partial<ActionPolicyAuthorityFactor> = {},+): ActionPolicyAuthorityFactor => ({+ kind,+ sourceId: `authority:${kind}`,+ status: 'consulted',+ scope: { orgId: 'org-1', resourceId: 'proxmox:node:pve-1', capabilityName: 'install_os_updates' },+ reasonCodes: ['capability_auto_elevated'],+ ...overrides,+});++describe('formatActionName', () => {+ it('returns the curated human title for the install_os_updates capability', () => {+ expect(formatActionName('install_os_updates')).toBe('Install operating system updates');+ });++ it('returns the curated human title for the clean_package_cache capability', () => {+ expect(formatActionName('clean_package_cache')).toBe('Clear downloaded package data');+ });++ it.each([+ ['snake_case capability is humanized', 'restart_service', 'Restart Service'],+ ['dotted capability is humanized', 'restart.service', 'Restart Service'],+ ['dashed capability is humanized', 'restart-service', 'Restart Service'],+ ['mixed separators collapse to single spaces', 'restart._-service', 'Restart Service'],+ ['repeated separators collapse to a single space', 'restart___service', 'Restart Service'],+ ['multi-word capability title-cases each word', 'restart_long_running_service', 'Restart Long Running Service'],+ ['already-spaced phrase is still title-cased', 'restart service', 'Restart Service'],+ ['camelCase token has no separator and only first letter uppercased', 'restartService', 'RestartService'],+ ['leading and trailing separators are trimmed before title-casing', '_restart_service_', 'Restart Service'],+ ['single word is title-cased', 'reboot', 'Reboot'],+ ['single character is uppercased', 'x', 'X'],+ ] as const)('regex path: %s', (_name, input, expected) => {+ expect(formatActionName(input)).toBe(expected);+ });++ it('treats capability names that merely start with the curated key as generic regex input', () => {+ expect(formatActionName('install_os_updates_v2')).toBe('Install Os Updates V2');+ expect(formatActionName('clean_package_cache_extra')).toBe('Clean Package Cache Extra');+ });++ it('returns an empty string for empty input', () => {+ expect(formatActionName('')).toBe('');+ });++ it.each(['_', '.', '-', '_._', '-_.', '___'])('returns an empty string for an all-separator input %j', (input) => {+ expect(formatActionName(input)).toBe('');+ });++ it('throws a TypeError when called with null despite the declared string type', () => {+ expect(() => formatActionName(null as unknown as string)).toThrow(TypeError);+ });++ it('throws a TypeError when called with undefined despite the declared string type', () => {+ expect(() => formatActionName(undefined as unknown as string)).toThrow(TypeError);+ });+});++describe('formatPolicyAuthority', () => {+ it.each([+ ['capability_registry', 'Capability safety policy'],+ ['tenant_patrol_policy', 'Patrol policy for this organization'],+ ['resource_operator_policy', 'Policy for this resource'],+ ] as const)('returns the curated label for kind %s', (kind, expected) => {+ expect(formatPolicyAuthority(makeAuthority(kind))).toBe(expected);+ });++ it('ignores non-kind fields when selecting the label', () => {+ const consulted = makeAuthority('capability_registry', { status: 'consulted', reasonCodes: [] });+ const unavailable = makeAuthority('capability_registry', {+ status: 'unavailable',+ sourceId: 'other-source',+ approvalFloor: 'admin',+ });+ expect(formatPolicyAuthority(consulted)).toBe('Capability safety policy');+ expect(formatPolicyAuthority(unavailable)).toBe('Capability safety policy');+ });++ it('returns undefined when factor.kind is an unrecognized value, because the switch has no default arm', () => {+ const malformed = {+ ...makeAuthority('capability_registry'),+ kind: 'not_a_real_authority_kind',+ } as unknown as ActionPolicyAuthorityFactor;+ expect(formatPolicyAuthority(malformed)).toBeUndefined();+ });++ it('returns undefined when factor is an empty object, because kind is undefined and the switch has no default', () => {+ expect(formatPolicyAuthority({} as unknown as ActionPolicyAuthorityFactor)).toBeUndefined();+ });+});++describe('verificationTruthLabel', () => {+ it.each([+ ['confirmed', undefined, 'Confirmation lacks an evidence source'],+ ['confirmed', 'none' as ActionEvidenceClass, 'Confirmation lacks an evidence source'],+ ] as const)('reports a confirmed status without independent/agent evidence (%s, %s)', (status, evidenceClass, expected) => {+ expect(verificationTruthLabel(status, evidenceClass)).toBe(expected);+ });++ it('credits an independent observer for a confirmed outcome', () => {+ expect(verificationTruthLabel('confirmed', 'independent')).toBe('Confirmed by independent observer');+ });++ it('credits the executing agent for a confirmed outcome', () => {+ expect(verificationTruthLabel('confirmed', 'agent_attested')).toBe('Confirmed by executing agent');+ });++ it('routes an unrecognized evidence class to the "lacks an evidence source" arm without throwing', () => {+ expect(+ verificationTruthLabel('confirmed', 'bogus' as unknown as ActionEvidenceClass),+ ).toBe('Confirmation lacks an evidence source');+ });++ it.each([+ ['contradicted', 'Outcome contradicted'],+ ['inconclusive', 'Outcome inconclusive'],+ ['not_attempted', 'Outcome not verified'],+ ] as const)('returns the curated label for status %s', (status, expected) => {+ expect(verificationTruthLabel(status)).toBe(expected);+ });++ it('ignores evidenceClass for non-confirmed statuses', () => {+ expect(verificationTruthLabel('contradicted', 'independent')).toBe('Outcome contradicted');+ expect(verificationTruthLabel('inconclusive', 'agent_attested')).toBe('Outcome inconclusive');+ expect(verificationTruthLabel('not_attempted', 'none')).toBe('Outcome not verified');+ });++ it('returns undefined when status is unrecognized, because the switch has no default arm', () => {+ expect(+ verificationTruthLabel('bogus' as unknown as ActionVerificationTruthStatus, 'independent'),+ ).toBeUndefined();+ });+});diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageRowAlertPresentation.branchcov0713.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageRowAlertPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..e8174719b1--- /dev/null+++ b/frontend-modern/src/features/storageBackups/__tests__/storageRowAlertPresentation.branchcov0713.test.ts@@ -0,0 +1,373 @@+import { describe, expect, it } from 'vitest';+import type { StorageAlertRowState } from '@/features/storageBackups/storageAlertState';+import {+ getStorageRowAlertPresentation,+ type StorageRowAlertPresentation,+} from '@/features/storageBackups/storageRowAlertPresentation';++// ---------------------------------------------------------------------------+// Fixture builders — mirror the alert-state shape used by the sibling+// storageRowAlertPresentation.test.ts so casts and import paths match. The+// default describes a healthy row (no alerts, null severity); each case+// overrides the relevant flags to drive a single branch of+// getStorageRowAlertPresentation.+// ---------------------------------------------------------------------------++const makeAlertState = (+ overrides: Partial<StorageAlertRowState> = {},+): StorageAlertRowState => ({+ hasAlert: false,+ alertCount: 0,+ severity: null,+ hasUnacknowledgedAlert: false,+ unacknowledgedCount: 0,+ acknowledgedCount: 0,+ hasAcknowledgedOnlyAlert: false,+ ...overrides,+});++type RowOptions = Parameters<typeof getStorageRowAlertPresentation>[0];++const makeOptions = (overrides: Partial<RowOptions> = {}): RowOptions => ({+ alertState: makeAlertState(),+ parentNodeOnline: true,+ isExpanded: false,+ isResourceHighlighted: false,+ ...overrides,+});++// The two BASE_ROW_CLASSES the module always seeds, joined exactly as the+// module joins them (with a single space). Used to assert the "no extra+// classes" arm returns ONLY the base styling.+const BASE_ROW_CLASS = 'transition-all duration-200 hover:bg-surface-hover';++// ===========================================================================+// getStorageRowAlertPresentation — uncovered branches+// ===========================================================================+//+// The sibling storageRowAlertPresentation.test.ts already covers:+// - showAlertHighlight true + severity 'critical' (red bg + critical accent)+// - the acknowledged-only arm (severity 'warning', acknowledged classes)+// This file targets the remaining branch arms enumerated below.++describe('getStorageRowAlertPresentation branch coverage', () => {+ // ---- L30/L35 severity !== 'critical' (false arm) under showAlertHighlight -+ it('applies warning bg + warning accent for an unacknowledged warning alert', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'warning',+ hasUnacknowledgedAlert: true,+ unacknowledgedCount: 1,+ }),+ }),+ );++ expect(result.rowClass).toContain('bg-yellow-50');+ expect(result.rowClass).toContain('dark:bg-yellow-950');+ expect(result.rowClass).toContain('shadow-[inset_4px_0_0_0_#eab308]');+ // The critical classes must NOT appear on the warning arm.+ expect(result.rowClass).not.toContain('bg-red-50');+ expect(result.rowClass).not.toContain('shadow-[inset_4px_0_0_0_#ef4444]');+ expect(result.dataAlertState).toBe('unacknowledged');+ expect(result.dataAlertSeverity).toBe('warning');+ });++ // ---- L30/L35 severity !== 'critical' when severity is null but+ // hasUnacknowledgedAlert is true (malformed alert state): the ternary+ // falls to the warning-shaped else arm while dataAlertSeverity uses the+ // `|| 'none'` fallback. -----------------------------------------------+ it('falls to the warning-shaped classes when severity is null but unacknowledged is true', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: null,+ hasUnacknowledgedAlert: true,+ unacknowledgedCount: 1,+ }),+ }),+ );++ // severity !== 'critical' (null is not 'critical') -> warning else arm.+ expect(result.rowClass).toContain('bg-yellow-50');+ expect(result.rowClass).toContain('shadow-[inset_4px_0_0_0_#eab308]');+ // dataAlertSeverity fallback: null || 'none' -> 'none'.+ expect(result.dataAlertSeverity).toBe('none');+ expect(result.dataAlertState).toBe('unacknowledged');+ });++ // ---- L28 showAlertHighlight precedence over L39 isResourceHighlighted ----+ // When both are true, the critical/warning classes win and the blue+ // highlight classes must NOT be appended.+ it('prefers the unacknowledged-alert classes over resource highlighting', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'critical',+ hasUnacknowledgedAlert: true,+ unacknowledgedCount: 1,+ }),+ isResourceHighlighted: true,+ }),+ );++ expect(result.rowClass).toContain('bg-red-50');+ expect(result.rowClass).toContain('shadow-[inset_4px_0_0_0_#ef4444]');+ expect(result.rowClass).not.toContain('bg-blue-50');+ expect(result.rowClass).not.toContain('ring-blue-300');+ // dataResourceHighlighted still reflects the input verbatim.+ expect(result.dataResourceHighlighted).toBe('true');+ expect(result.dataAlertState).toBe('unacknowledged');+ });++ // ---- L39 else-if isResourceHighlighted true arm (blue highlight) ---------+ it('applies the blue resource-highlight classes when only isResourceHighlighted is true', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ isResourceHighlighted: true,+ }),+ );++ expect(result.rowClass).toContain('bg-blue-50');+ expect(result.rowClass).toContain('dark:bg-blue-900');+ expect(result.rowClass).toContain('ring-1');+ expect(result.rowClass).toContain('ring-blue-300');+ expect(result.rowClass).toContain('dark:ring-blue-600');+ // No alert styling should leak in.+ expect(result.rowClass).not.toContain('bg-red-50');+ expect(result.rowClass).not.toContain('bg-yellow-50');+ expect(result.rowClass).not.toContain('shadow-[inset_4px_0_0_0_rgba(156,163,175,0.8)]');+ expect(result.dataResourceHighlighted).toBe('true');+ // No alerts -> dataAlertState 'none' (the L51-55 ternary final arm).+ expect(result.dataAlertState).toBe('none');+ });++ // ---- L39 isResourceHighlighted precedence over L41 hasAcknowledgedOnly ---+ // The else-if chain means resource highlighting wins over acknowledged.+ // dataAlertState is computed independently and still reports+ // 'acknowledged'.+ it('prefers resource-highlight classes over acknowledged-only styling, but still reports acknowledged state', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'warning',+ acknowledgedCount: 1,+ hasAcknowledgedOnlyAlert: true,+ }),+ isResourceHighlighted: true,+ }),+ );++ // Blue classes from the resource-highlight arm.+ expect(result.rowClass).toContain('bg-blue-50');+ expect(result.rowClass).toContain('ring-blue-300');+ // Acknowledged accent must NOT be present (else-if did not reach it).+ expect(result.rowClass).not.toContain('shadow-[inset_4px_0_0_0_rgba(156,163,175,0.8)]');+ // dataAlertState is independent of the class if-chain.+ expect(result.dataAlertState).toBe('acknowledged');+ expect(result.dataResourceHighlighted).toBe('true');+ });++ // ---- No arm of the if/else-if chain (all flags false) --------------------+ // Only BASE_ROW_CLASSES remain; every data attr is the neutral default.+ it('returns only the base classes when no alert, highlight or expand flags are set', () => {+ const result: StorageRowAlertPresentation = getStorageRowAlertPresentation(+ makeOptions(),+ );++ expect(result.rowClass).toBe(BASE_ROW_CLASS);+ expect(result.dataAlertState).toBe('none');+ // severity null -> null || 'none' -> 'none' (L56 right arm).+ expect(result.dataAlertSeverity).toBe('none');+ expect(result.dataResourceHighlighted).toBe('false');+ });++ // ---- L45 isExpanded true arm ---------------------------------------------+ it('appends the expanded bg-surface-alt class when isExpanded is true', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({ isExpanded: true }),+ );++ // Base classes are still present and the expanded class is appended.+ expect(result.rowClass).toContain('transition-all duration-200');+ expect(result.rowClass).toContain('hover:bg-surface-hover');+ expect(result.rowClass).toContain('bg-surface-alt');+ // The expanded class appears exactly once (no alert/acknowledged arm ran).+ const surfaceAltCount = (result.rowClass.match(/bg-surface-alt/g) ?? []).length;+ expect(surfaceAltCount).toBe(1);+ });++ // ---- L45 isExpanded stacks on top of an unacknowledged critical alert ----+ it('stacks the expanded class on top of the critical unacknowledged classes', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'critical',+ hasUnacknowledgedAlert: true,+ unacknowledgedCount: 1,+ }),+ isExpanded: true,+ }),+ );++ expect(result.rowClass).toContain('bg-red-50');+ expect(result.rowClass).toContain('shadow-[inset_4px_0_0_0_#ef4444]');+ expect(result.rowClass).toContain('bg-surface-alt');+ });++ // ---- L45 isExpanded stacks on top of the acknowledged-only arm -----------+ it('stacks the expanded class on top of the acknowledged-only classes', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'warning',+ acknowledgedCount: 1,+ hasAcknowledgedOnlyAlert: true,+ }),+ isExpanded: true,+ }),+ );++ // Acknowledged accent + TWO bg-surface-alt (acknowledged arm + expanded).+ expect(result.rowClass).toContain('shadow-[inset_4px_0_0_0_rgba(156,163,175,0.8)]');+ const surfaceAltCount = (result.rowClass.match(/bg-surface-alt/g) ?? []).length;+ expect(surfaceAltCount).toBe(2);+ });++ // ---- L22-23 && short-circuit: hasUnacknowledgedAlert true but+ // parentNodeOnline false -> showAlertHighlight false -----------------+ it('suppresses the unacknowledged highlight when the parent node is offline', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'critical',+ hasUnacknowledgedAlert: true,+ unacknowledgedCount: 1,+ }),+ parentNodeOnline: false,+ }),+ );++ // No alert classes — the highlight was gated by parentNodeOnline.+ expect(result.rowClass).not.toContain('bg-red-50');+ expect(result.rowClass).not.toContain('bg-yellow-50');+ expect(result.rowClass).not.toContain('shadow-[inset_4px_0_0_0_#ef4444]');+ // showAlertHighlight is false, so dataAlertState is NOT 'unacknowledged'.+ expect(result.dataAlertState).toBe('none');+ // severity is still surfaced verbatim via the || fallback left operand.+ expect(result.dataAlertSeverity).toBe('critical');+ });++ // ---- L24-25 && short-circuit: hasAcknowledgedOnlyAlert true but+ // parentNodeOnline false -> local hasAcknowledgedOnlyAlert false -----+ it('suppresses the acknowledged-only styling when the parent node is offline', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 1,+ severity: 'warning',+ acknowledgedCount: 1,+ hasAcknowledgedOnlyAlert: true,+ }),+ parentNodeOnline: false,+ }),+ );++ expect(result.rowClass).not.toContain('shadow-[inset_4px_0_0_0_rgba(156,163,175,0.8)]');+ expect(result.rowClass).not.toContain('bg-surface-alt');+ // Local hasAcknowledgedOnlyAlert is false -> dataAlertState 'none'.+ expect(result.dataAlertState).toBe('none');+ });++ // ---- L51-55 dataAlertState 'none' arm (showAlertHighlight false AND+ // hasAcknowledgedOnlyAlert false) with a non-null severity to confirm+ // dataAlertSeverity uses the truthy left operand of `||` -------------+ it('reports dataAlertSeverity verbatim for a truthy warning severity with no row-level alert', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({ severity: 'warning' }),+ }),+ );++ expect(result.dataAlertState).toBe('none');+ // 'warning' is truthy -> left operand of `||` is used (NOT 'none').+ expect(result.dataAlertSeverity).toBe('warning');+ });++ // ---- L56 `severity || 'none'` left operand with critical severity --------+ it('reports dataAlertSeverity as critical when severity is critical', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({ severity: 'critical' }),+ }),+ );++ expect(result.dataAlertSeverity).toBe('critical');+ });++ // ---- L57 isResourceHighlighted false -> 'false' (explicit boundary) ------+ it('reports dataResourceHighlighted as false when isResourceHighlighted is false', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({ isResourceHighlighted: false }),+ );++ expect(result.dataResourceHighlighted).toBe('false');+ });++ // ---- Deliberately-malformed empty-string severity: '' is falsy, so the+ // `|| 'none'` fallback fires even though it is technically a string. -+ it('falls back to dataAlertSeverity none when severity is an empty string', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ severity: '' as unknown as StorageAlertRowState['severity'],+ }),+ }),+ );++ // '' is falsy -> right operand of || -> 'none'.+ expect(result.dataAlertSeverity).toBe('none');+ });++ // ---- Full return shape contract on a representative unacknowledged case -+ it('returns the full StorageRowAlertPresentation shape for an unacknowledged warning with highlight and expand', () => {+ const result = getStorageRowAlertPresentation(+ makeOptions({+ alertState: makeAlertState({+ hasAlert: true,+ alertCount: 2,+ severity: 'warning',+ hasUnacknowledgedAlert: true,+ unacknowledgedCount: 2,+ }),+ isExpanded: true,+ isResourceHighlighted: true,+ }),+ );++ // showAlertHighlight wins over isResourceHighlighted in the class chain.+ expect(result.rowClass).toContain('bg-yellow-50');+ expect(result.rowClass).toContain('shadow-[inset_4px_0_0_0_#eab308]');+ expect(result.rowClass).toContain('bg-surface-alt');+ // The four return fields and their literal types.+ expect(result.dataAlertState).toBe('unacknowledged');+ expect(result.dataAlertSeverity).toBe('warning');+ expect(result.dataResourceHighlighted).toBe('true');+ expect(typeof result.rowClass).toBe('string');+ });+});diff --git a/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..a87e78a9c3--- /dev/null+++ b/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.branchcov0713.test.ts@@ -0,0 +1,186 @@+import { describe, expect, it } from 'vitest';+import {+ buildPatrolScheduleOptions,+ getPatrolScheduleLabel,+ PATROL_SCHEDULE_PRESETS,+} from '@/utils/aiPatrolSchedulePresentation';++// Branch-coverage additions for the two currently under-exercised functions in+// aiPatrolSchedulePresentation.ts. The sibling suites already cover every+// canonical preset value and several finite unmatched integers/floats for+// getPatrolScheduleLabel, plus the preset(360) and custom(17) arms of+// buildPatrolScheduleOptions. This file targets the remaining arms:+// - getPatrolScheduleLabel: non-finite numbers and coerced non-number inputs+// that still flow through the template-literal fallback.+// - buildPatrolScheduleOptions: the Number.isFinite short-circuit arm, the+// preset-match (B-false) arm beyond value 360, the comparator sort+// positions (front / middle / end), reference freshness, and source-array+// immutability.++describe('aiPatrolSchedulePresentation — branch coverage (batch 0713)', () => {+ describe('getPatrolScheduleLabel — non-finite / coerced fallback arm', () => {+ it('falls back to a templated label for NaN (no preset matches)', () => {+ // NaN is a valid `number` value; it matches no preset, so the+ // `${minutes} min` template literal arm fires and String-coerces NaN.+ expect(getPatrolScheduleLabel(NaN)).toBe('NaN min');+ });++ it('falls back to a templated label for +Infinity', () => {+ expect(getPatrolScheduleLabel(Infinity)).toBe('Infinity min');+ });++ it('falls back to a templated label (with leading minus) for -Infinity', () => {+ expect(getPatrolScheduleLabel(-Infinity)).toBe('-Infinity min');+ });++ it('String-coerces a null input to "null min" through the fallback arm', () => {+ // `null` violates the declared `number` type but is observable through+ // the exported API; it does not match any preset, so the template+ // literal interpolates `String(null)` === 'null'.+ const minutes = null as unknown as Parameters<typeof getPatrolScheduleLabel>[0];+ expect(getPatrolScheduleLabel(minutes)).toBe('null min');+ });++ it('String-coerces an undefined input to "undefined min" through the fallback arm', () => {+ const minutes = undefined as unknown as Parameters<typeof getPatrolScheduleLabel>[0];+ expect(getPatrolScheduleLabel(minutes)).toBe('undefined min');+ });++ it('String-coerces an empty-string input to " min" through the fallback arm', () => {+ // '' is non-nullish but matches no preset value, so the fallback runs.+ const minutes = '' as unknown as Parameters<typeof getPatrolScheduleLabel>[0];+ expect(getPatrolScheduleLabel(minutes)).toBe(' min');+ });+ });++ describe('buildPatrolScheduleOptions — Number.isFinite short-circuit (A-false) arm', () => {+ it('returns the canonical presets unchanged when current is NaN', () => {+ // `Number.isFinite(NaN)` is false → the && short-circuits and no custom+ // option is appended.+ const result = buildPatrolScheduleOptions(NaN);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ expect(result).toHaveLength(PATROL_SCHEDULE_PRESETS.length);+ });++ it('returns the canonical presets unchanged when current is +Infinity', () => {+ const result = buildPatrolScheduleOptions(Infinity);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ expect(result).toHaveLength(PATROL_SCHEDULE_PRESETS.length);+ });++ it('returns the canonical presets unchanged when current is -Infinity', () => {+ const result = buildPatrolScheduleOptions(-Infinity);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ expect(result).toHaveLength(PATROL_SCHEDULE_PRESETS.length);+ });++ it('short-circuits for null coerced to number, returning presets unchanged', () => {+ // `Number.isFinite(null)` is false → short-circuit arm fires; no push,+ // no sort. Verifies defensive behavior against a type-violating input.+ const current = null as unknown as Parameters<typeof buildPatrolScheduleOptions>[0];+ const result = buildPatrolScheduleOptions(current);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ });++ it('short-circuits for undefined coerced to number, returning presets unchanged', () => {+ const current = undefined as unknown as Parameters<typeof buildPatrolScheduleOptions>[0];+ const result = buildPatrolScheduleOptions(current);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ });+ });++ describe('buildPatrolScheduleOptions — preset-match (B-false) arm', () => {+ it('returns presets unchanged for the 0 preset (boundary value, also falsy)', () => {+ // Guards against a regression where the some() predicate is replaced+ // with a truthy check that would mishandle the value 0.+ const result = buildPatrolScheduleOptions(0);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ expect(result).toContainEqual({ value: 0, label: 'Off' });+ });++ it('returns presets unchanged for the max preset (1440)', () => {+ const result = buildPatrolScheduleOptions(1440);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ expect(result).toContainEqual({ value: 1440, label: '24 hours' });+ });++ it('returns presets unchanged for the smallest non-zero preset (10)', () => {+ const result = buildPatrolScheduleOptions(10);+ expect(result).toEqual([...PATROL_SCHEDULE_PRESETS]);+ });+ });++ describe('buildPatrolScheduleOptions — custom value push + sort positions', () => {+ it('inserts a negative custom value at the front (sorted ascending)', () => {+ // Exercises the comparator `(a, b) => a.value - b.value` returning a+ // positive value, moving the new entry to index 0.+ const result = buildPatrolScheduleOptions(-5);+ expect(result).toHaveLength(PATROL_SCHEDULE_PRESETS.length + 1);+ expect(result[0]).toStrictEqual({ value: -5, label: '-5 min' });+ expect(result[1]).toStrictEqual({ value: 0, label: 'Off' });+ // Whole array remains sorted ascending by value.+ const values = result.map((o) => o.value);+ const sorted = [...values].sort((a, b) => a - b);+ expect(values).toEqual(sorted);+ });++ it('inserts a custom value that falls between two presets at the right middle index', () => {+ // 45 sits between preset 30 and preset 60 → must land at index 4.+ const result = buildPatrolScheduleOptions(45);+ expect(result).toHaveLength(PATROL_SCHEDULE_PRESETS.length + 1);+ expect(result[4]).toStrictEqual({ value: 45, label: '45 min' });+ expect(result[3]).toStrictEqual({ value: 30, label: '30 min' });+ expect(result[5]).toStrictEqual({ value: 60, label: '1 hour' });+ });++ it('inserts a custom value larger than the max preset at the end', () => {+ // Exercises the comparator returning a negative value for every existing+ // entry, leaving the new entry at the last index.+ const result = buildPatrolScheduleOptions(2000);+ expect(result).toHaveLength(PATROL_SCHEDULE_PRESETS.length + 1);+ expect(result[result.length - 1]).toStrictEqual({ value: 2000, label: '2000 min' });+ expect(result[result.length - 2]).toStrictEqual({ value: 1440, label: '24 hours' });+ });++ it('derives the custom entry label from getPatrolScheduleLabel (not a preset label)', () => {+ // 90 is not a preset, so the label is the templated fallback rather than+ // a canonical preset string. Confirms the push reuses the label helper.+ const result = buildPatrolScheduleOptions(90);+ const inserted = result.find((o) => o.value === 90);+ expect(inserted).toBeDefined();+ expect(inserted?.label).toBe(getPatrolScheduleLabel(90));+ expect(inserted?.label).toBe('90 min');+ });+ });++ describe('buildPatrolScheduleOptions — reference + source immutability', () => {+ it('returns a fresh array reference on every call (no shared mutation)', () => {+ const a = buildPatrolScheduleOptions(45);+ const b = buildPatrolScheduleOptions(45);+ expect(a).not.toBe(b);+ expect(a).toEqual(b);+ });++ it('does not mutate PATROL_SCHEDULE_PRESETS after inserting custom values', () => {+ // PATROL_SCHEDULE_PRESETS is declared `readonly`; calling the builder+ // with several custom values must leave the source array untouched.+ const before = [...PATROL_SCHEDULE_PRESETS];+ buildPatrolScheduleOptions(-5);+ buildPatrolScheduleOptions(45);+ buildPatrolScheduleOptions(2000);+ buildPatrolScheduleOptions(NaN);+ expect(PATROL_SCHEDULE_PRESETS).toEqual(before);+ expect(PATROL_SCHEDULE_PRESETS).toHaveLength(before.length);+ });++ it('does not retain prior custom values between independent calls', () => {+ // Each call rebuilds from the presets; a previous custom value must not+ // leak into a subsequent call's result.+ const withCustom = buildPatrolScheduleOptions(45);+ expect(withCustom).toContainEqual({ value: 45, label: '45 min' });+ const after = buildPatrolScheduleOptions(60);+ expect(after).not.toContainEqual({ value: 45, label: '45 min' });+ expect(after).toEqual([...PATROL_SCHEDULE_PRESETS]);+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/alertFormatters.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/alertFormatters.branchcov0713.test.tsnew file mode 100644index 0000000000..39a045058c--- /dev/null+++ b/frontend-modern/src/utils/__tests__/alertFormatters.branchcov0713.test.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from 'vitest';+import { getAlertUnit, formatAlertValue, formatAlertThreshold } from '@/utils/alertFormatters';++// Branch-coverage companion to alertFormatters.test.ts. The sibling suite+// already exercises the temperature/temp arms, the undefined/''/cpu/memory/disk+// default-% arms, and the NaN/Infinity -> N/A guard. This file targets arms and+// boundary values it leaves open.+//+// Two SUSPECTED SOURCE BUGS are exercised here by asserting their CURRENT+// behaviour (NOT fixed; new test file only — see GLM_REPORT.md):+//+// BUG #1 (critical): the throughput branch in getAlertUnit is DEAD CODE.+// alertFormatters.ts lowercases the metricType before lookup:+// const typeLower = metricType.toLowerCase();+// but THROUGHPUT_METRIC_TYPES holds camelCase keys+// ('diskRead','diskWrite','networkIn','networkOut'). After lowercasing,+// 'diskread' / 'networkin' etc. are NOT in the set, so the+// `return ' MB/s'` line is unreachable from any input and every throughput+// metric falls through to the default '%'. (TEMPERATURE works only because+// its set keys are already lowercase.)+//+// BUG #2 (minor): formatAlertThreshold only rejects NaN, not all non-finite+// values. Unlike formatAlertValue (which guards with !Number.isFinite),+// threshold guards with Number.isNaN, so +Infinity passes both guards and is+// interpolated verbatim as 'Infinity%'.++describe('alertFormatters — branch coverage (batch 0713)', () => {+ describe('getAlertUnit — null falsy arm, dead throughput branch, default arm', () => {+ it('treats null metricType as falsy and returns % via the !metricType guard', () => {+ // Declared type is `string | undefined`; null violates it, so cast through+ // unknown to keep strict TS clean. `!null` is true -> early '%'.+ const mt = null as unknown as Parameters<typeof getAlertUnit>[0];+ expect(getAlertUnit(mt)).toBe('%');+ });++ it('exact throughput set keys fall through to % — BUG #1 (dead branch)', () => {+ // Each value IS a member of THROUGHPUT_METRIC_TYPES, but because the source+ // lowercases the input and the set keys are camelCase, the lookup misses+ // and execution reaches the final `return '%'` instead of `return ' MB/s'`.+ expect(getAlertUnit('diskRead')).toBe('%');+ expect(getAlertUnit('diskWrite')).toBe('%');+ expect(getAlertUnit('networkIn')).toBe('%');+ expect(getAlertUnit('networkOut')).toBe('%');+ });++ it('upper / mixed / lower variants of throughput types also miss the set', () => {+ // Exercises the THROUGHPUT_METRIC_TYPES.has(typeLower) check returning+ // false for every case variant (the case-folding cannot reconstruct the+ // camelCase keys), then the final default '%'.+ expect(getAlertUnit('DISKREAD')).toBe('%');+ expect(getAlertUnit('NetworkIn')).toBe('%');+ expect(getAlertUnit('networkout')).toBe('%');+ });++ it('falls through to % for unknown and whitespace-only metric types', () => {+ // 'latency' is unknown to both sets; ' ' is a truthy non-empty string so+ // it skips the !metricType guard, lowercases to itself, misses both sets,+ // and hits the final `return '%'`.+ expect(getAlertUnit('latency')).toBe('%');+ expect(getAlertUnit(' ')).toBe('%');+ });+ });++ describe('formatAlertValue — finite boundaries, negatives, throughput propagation', () => {+ it('formats a finite 0 value (not N/A) — boundary for the isFinite guard', () => {+ // 0 is finite, so it must NOT take the 'N/A' arm; it formats normally.+ expect(formatAlertValue(0)).toBe('0.0%');+ expect(formatAlertValue(0, 'temperature')).toMatch(/^0\.0°[CF]$/);+ });++ it('formats a negative finite value rather than returning N/A', () => {+ // Only non-finite (NaN/+/-Infinity) hit N/A; a real negative formats.+ expect(formatAlertValue(-3.25)).toBe('-3.3%');+ });++ it('propagates the dead throughput branch to % through formatAlertValue — BUG #1', () => {+ // getAlertUnit('diskRead') returns '%' (see BUG #1), so the formatted+ // value carries '%' rather than ' MB/s'.+ expect(formatAlertValue(100, 'diskRead')).toBe('100.0%');+ expect(formatAlertValue(42.5, 'networkOut')).toBe('42.5%');+ });++ it('still returns N/A when the value is non-finite even with a throughput unit', () => {+ // The isFinite guard short-circuits before getAlertUnit is consulted, so+ // the (dead) throughput branch is never reached for non-finite values.+ expect(formatAlertValue(NaN, 'diskRead')).toBe('N/A');+ expect(formatAlertValue(Infinity, 'networkIn')).toBe('N/A');+ expect(formatAlertValue(-Infinity, 'diskWrite')).toBe('N/A');+ });+ });++ describe('formatAlertThreshold — non-finite arms, boundary, throughput propagation', () => {+ it('classifies -Infinity as Disabled via the value <= 0 arm', () => {+ // -Infinity passes the undefined/NaN guard (it is not NaN), then satisfies+ // `value <= 0`, so it is 'Disabled'. This contrasts with formatAlertValue,+ // which would return 'N/A' via !Number.isFinite — see BUG #2.+ expect(formatAlertThreshold(-Infinity, 'diskWrite')).toBe('Disabled');+ });++ it('formats a tiny positive threshold (boundary just above the <= 0 arm)', () => {+ // 0.001 > 0, so it escapes both guards and reaches the raw interpolation.+ expect(formatAlertThreshold(0.001)).toBe('0.001%');+ });++ it('propagates the dead throughput branch to % through formatAlertThreshold — BUG #1', () => {+ // formatAlertThreshold does not call toFixed; it interpolates the raw+ // number, so an integer renders without a trailing decimal. The unit is+ // '%' (not ' MB/s') because of BUG #1.+ expect(formatAlertThreshold(100, 'diskRead')).toBe('100%');+ expect(formatAlertThreshold(250.5, 'networkOut')).toBe('250.5%');+ });++ it('renders a positive Infinity threshold literally — BUG #2 (isFinite NOT guarded)', () => {+ // Unlike formatAlertValue, threshold only rejects NaN, so +Infinity is+ // not NaN, is not <= 0, and is interpolated verbatim. Asserting CURRENT+ // (buggy) behaviour so the suite stays green; GLM_REPORT.md documents it.+ expect(formatAlertThreshold(Infinity, 'diskRead')).toBe('Infinity%');+ expect(formatAlertThreshold(Infinity)).toBe('Infinity%');+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/clipboard.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/clipboard.branchcov0713.test.tsnew file mode 100644index 0000000000..15e3dd29d2--- /dev/null+++ b/frontend-modern/src/utils/__tests__/clipboard.branchcov0713.test.ts@@ -0,0 +1,178 @@+/**+ * Branch-coverage tests for clipboard.ts — second pass.+ *+ * Scope: ONLY `copyToClipboard`. The sibling clipboard.test.ts already drives:+ * - clipboard API happy path (writeText resolves → true),+ * - writeText rejects + execCommand returns true (fallback succeeds),+ * - writeText rejects + execCommand returns false (both fail),+ * - navigator.clipboard === undefined + document undefined → false.+ *+ * This file drives every remaining branch:+ *+ * - `typeof navigator !== 'undefined'` FALSE arm — navigator entirely absent+ * (SSR-like) — reaching the DOM fallback rather than the document-undefined+ * early return.+ * - `navigator.clipboard?.writeText` falsy arm reached two ways the sibling+ * test does not exercise: `clipboard` itself undefined while document IS+ * defined, and `writeText` undefined while `clipboard` exists. Both must+ * fall through to the execCommand fallback (the sibling only reaches this+ * point with `document` also undefined, hitting the early return).+ * - The fallback DOM setup: textarea.value, the three off-screen style+ * assignments, focus(), and select() — none of which the sibling asserts+ * because it stubs document wholesale.+ * - The execCommand THROWS arm (inner catch at the fallback try/catch) — the+ * sibling only drives the true/false return-value arms.+ * - The `finally` block: removeChild runs even on the success path.+ * - The OUTER try/catch: a throw inside the fallback setup (appendChild) is+ * swallowed and returns false.+ * - Empty-string input forwarded verbatim to the clipboard API.+ *+ * jsdom does not implement `document.execCommand`, so each fallback-path test+ * installs it via `Object.defineProperty` (configurable) and removes the stub+ * in `afterEach`. All other DOM interactions use the real jsdom document so+ * textarea side-effects (value, styles, focus, select) can be asserted+ * directly rather than against a wholesale mock.+ */+import { afterEach, describe, expect, it, vi } from 'vitest';++import { copyToClipboard } from '@/utils/clipboard';++/** Installs a configurable `execCommand` stub on document (jsdom omits it). */+const stubExecCommand = (impl: (commandId: string, value?: string) => boolean) => {+ const mock = vi.fn(impl);+ Object.defineProperty(document, 'execCommand', {+ value: mock,+ configurable: true,+ writable: true,+ });+ return mock;+};++describe('copyToClipboard (branch coverage)', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ // Remove our execCommand stub if it is still installed on the instance.+ const desc = Object.getOwnPropertyDescriptor(document, 'execCommand');+ if (desc?.configurable) {+ delete (document as unknown as { execCommand?: unknown }).execCommand;+ }+ document.body.innerHTML = '';+ });++ it('falls through to the DOM fallback when navigator is entirely undefined (typeof navigator arm)', async () => {+ vi.stubGlobal('navigator', undefined);+ const execSpy = stubExecCommand(() => true);++ const result = await copyToClipboard('payload-without-navigator');++ expect(result).toBe(true);+ expect(execSpy).toHaveBeenCalledWith('copy');+ });++ it('falls through to the DOM fallback when navigator exists but navigator.clipboard is undefined', async () => {+ // The sibling test only reaches this guard with document ALSO undefined;+ // here document is defined, so the execCommand fallback must run.+ vi.stubGlobal('navigator', { clipboard: undefined });+ const execSpy = stubExecCommand(() => true);++ const result = await copyToClipboard('payload-no-clipboard');++ expect(result).toBe(true);+ expect(execSpy).toHaveBeenCalledWith('copy');+ });++ it('falls through to the DOM fallback when navigator.clipboard exists but writeText is missing', async () => {+ vi.stubGlobal('navigator', { clipboard: {} });+ const execSpy = stubExecCommand(() => true);++ const result = await copyToClipboard('payload-no-writeText');++ expect(result).toBe(true);+ expect(execSpy).toHaveBeenCalledWith('copy');+ });++ it('configures the textarea (value, off-screen styles, focus, select) and cleans up via finally before returning true', async () => {+ // Force the fallback by removing the clipboard API entirely.+ vi.stubGlobal('navigator', undefined);++ // Pre-build the textarea and instrument it so we can assert the module's+ // DOM side-effects directly. createElement returns our instrumented node.+ const textArea = document.createElement('textarea');+ const focusSpy = vi.spyOn(textArea, 'focus');+ const selectSpy = vi.spyOn(textArea, 'select');+ const createSpy = vi.spyOn(document, 'createElement').mockReturnValue(textArea);+ const appendSpy = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node);+ const removeSpy = vi.spyOn(document.body, 'removeChild').mockImplementation((node) => node);+ const execSpy = stubExecCommand(() => true);++ const payload = 'configure-the-textarea';+ const result = await copyToClipboard(payload);++ expect(result).toBe(true);+ expect(createSpy).toHaveBeenCalledWith('textarea');+ // value + off-screen positioning:+ expect(textArea.value).toBe(payload);+ expect(textArea.style.position).toBe('fixed');+ expect(textArea.style.left).toBe('-999999px');+ expect(textArea.style.top).toBe('-999999px');+ // focus + select invoked exactly once each:+ expect(focusSpy).toHaveBeenCalledTimes(1);+ expect(selectSpy).toHaveBeenCalledTimes(1);+ // appendChild then removeChild (finally) on the SAME node:+ expect(appendSpy).toHaveBeenCalledWith(textArea);+ expect(removeSpy).toHaveBeenCalledWith(textArea);+ expect(removeSpy).toHaveBeenCalledTimes(1);+ expect(execSpy).toHaveBeenCalledWith('copy');+ });++ it('returns false and still runs the finally cleanup when document.execCommand throws (inner catch arm)', async () => {+ vi.stubGlobal('navigator', undefined);+ const textArea = document.createElement('textarea');+ vi.spyOn(document, 'createElement').mockReturnValue(textArea);+ const appendSpy = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node);+ const removeSpy = vi.spyOn(document.body, 'removeChild').mockImplementation((node) => node);+ const execErr = new Error('execCommand unavailable');+ stubExecCommand(() => {+ throw execErr;+ });++ const result = await copyToClipboard('exec-throws');++ expect(result).toBe(false);+ // finally block still runs cleanup even after the throw:+ expect(appendSpy).toHaveBeenCalledWith(textArea);+ expect(removeSpy).toHaveBeenCalledWith(textArea);+ });++ it('returns false from the outer catch when the fallback setup itself throws before execCommand', async () => {+ // The inner try wraps only execCommand; a throw in appendChild (part of+ // the setup) propagates to the OUTER try/catch and must be swallowed.+ vi.stubGlobal('navigator', undefined);+ const textArea = document.createElement('textarea');+ vi.spyOn(document, 'createElement').mockReturnValue(textArea);+ const setupErr = new Error('appendChild denied');+ const appendSpy = vi.spyOn(document.body, 'appendChild').mockImplementation(() => {+ throw setupErr;+ });+ // execCommand must NOT be reached, proving we never entered the inner try:+ const execSpy = stubExecCommand(() => true);++ const result = await copyToClipboard('setup-throws');++ expect(result).toBe(false);+ expect(appendSpy).toHaveBeenCalledWith(textArea);+ expect(execSpy).not.toHaveBeenCalled();+ });++ it('forwards an empty string verbatim to the clipboard API on the happy path', async () => {+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal('navigator', { clipboard: { writeText } });++ const result = await copyToClipboard('');++ expect(result).toBe(true);+ expect(writeText).toHaveBeenCalledWith('');+ expect(writeText).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend-modern/src/utils/__tests__/confidencePresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/confidencePresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..801fd1371a--- /dev/null+++ b/frontend-modern/src/utils/__tests__/confidencePresentation.branchcov0713.test.ts@@ -0,0 +1,137 @@+import { describe, expect, it } from 'vitest';++import {+ formatConfidenceLabel,+ formatConfidencePercentage,+} from '@/utils/confidencePresentation';++describe('confidencePresentation — branch coverage (branchcov0713)', () => {+ describe('formatConfidencePercentage — Number.isFinite guard arm', () => {+ it('returns empty string for NaN (non-finite)', () => {+ expect(formatConfidencePercentage(NaN)).toBe('');+ });++ it('returns empty string for positive Infinity (non-finite)', () => {+ expect(formatConfidencePercentage(Infinity)).toBe('');+ });++ it('returns empty string for negative Infinity (non-finite)', () => {+ expect(formatConfidencePercentage(-Infinity)).toBe('');+ });+ });++ describe('formatConfidencePercentage — rounding happy path & boundaries', () => {+ it('rounds a value whose product crosses .5 upward to the next integer', () => {+ expect(formatConfidencePercentage(0.875)).toBe('88%');+ });++ it('rounds 0.999 up to 100% (boundary that saturates the percent)', () => {+ expect(formatConfidencePercentage(0.999)).toBe('100%');+ });++ it('returns 100% for exactly 1', () => {+ expect(formatConfidencePercentage(1)).toBe('100%');+ });++ it('returns 0% for exactly 0', () => {+ expect(formatConfidencePercentage(0)).toBe('0%');+ });++ it('rounds a small positive value down to 0%', () => {+ expect(formatConfidencePercentage(0.001)).toBe('0%');+ });++ it('formats a negative ratio with a leading minus sign', () => {+ expect(formatConfidencePercentage(-0.5)).toBe('-50%');+ });++ it('formats a large value greater than 1 as an unscaled integer percent', () => {+ expect(formatConfidencePercentage(12.3456)).toBe('1235%');+ });+ });++ describe('formatConfidenceLabel — number arm', () => {+ it('delegates a finite number to formatConfidencePercentage', () => {+ expect(formatConfidenceLabel(0.999)).toBe('100%');+ });++ it('returns empty string for NaN via the number arm (non-finite propagation)', () => {+ expect(formatConfidenceLabel(NaN)).toBe('');+ });++ it('returns empty string for Infinity via the number arm (non-finite propagation)', () => {+ expect(formatConfidenceLabel(Infinity)).toBe('');+ });+ });++ describe('formatConfidenceLabel — string arm, trim-then-empty guard', () => {+ it('returns empty string for an empty string (falsy after trim)', () => {+ expect(formatConfidenceLabel('')).toBe('');+ });++ it('returns empty string for a whitespace-only string (falsy after trim)', () => {+ expect(formatConfidenceLabel(' ')).toBe('');+ });++ it('returns empty string for a tab/newline-only string (falsy after trim)', () => {+ expect(formatConfidenceLabel('\t\n ')).toBe('');+ });+ });++ describe('formatConfidenceLabel — string arm, humanizeToken variants', () => {+ it('title-cases a single lowercase token', () => {+ expect(formatConfidenceLabel('low')).toBe('Low');+ });++ it('trims surrounding whitespace then title-cases the token', () => {+ expect(formatConfidenceLabel(' medium ')).toBe('Medium');+ });++ it('replaces underscores with spaces and title-cases each token', () => {+ expect(formatConfidenceLabel('very_high')).toBe('Very High');+ });++ it('title-cases a multi-token underscore string preserving inner casing', () => {+ expect(formatConfidenceLabel('abc_def_ghi')).toBe('Abc Def Ghi');+ });++ it('title-cases each word of an all-caps multi-word token via the underscore path', () => {+ expect(formatConfidenceLabel('UPPER_CASE_TOKEN')).toBe('UPPER CASE TOKEN');+ });++ it('leaves a 4-char all-caps token untouched because preserveShortAllCaps is not passed', () => {+ expect(formatConfidenceLabel('HIGH')).toBe('HIGH');+ });++ it('title-cases a numeric string (digit is an inert word char)', () => {+ expect(formatConfidenceLabel('42')).toBe('42');+ });+ });++ describe('formatConfidenceLabel — nullish / non-string-non-number fallback arm', () => {+ it('returns empty string for undefined', () => {+ expect(formatConfidenceLabel(undefined)).toBe('');+ });++ it('returns empty string for null', () => {+ expect(formatConfidenceLabel(null)).toBe('');+ });++ it('returns empty string for a boolean (typeof !== string|number, cast to satisfy declared type)', () => {+ const malformed = true as unknown as Parameters<typeof formatConfidenceLabel>[0];+ expect(formatConfidenceLabel(malformed)).toBe('');+ });++ it('returns empty string for a plain object (typeof object, cast to satisfy declared type)', () => {+ const malformed = { confidence: 0.9 } as unknown as Parameters<+ typeof formatConfidenceLabel+ >[0];+ expect(formatConfidenceLabel(malformed)).toBe('');+ });++ it('returns empty string for an array (typeof object, cast to satisfy declared type)', () => {+ const malformed = [0.5] as unknown as Parameters<typeof formatConfidenceLabel>[0];+ expect(formatConfidenceLabel(malformed)).toBe('');+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/searchHistory.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/searchHistory.branchcov0713.test.tsnew file mode 100644index 0000000000..5cb47d7839--- /dev/null+++ b/frontend-modern/src/utils/__tests__/searchHistory.branchcov0713.test.ts@@ -0,0 +1,201 @@+/**+ * Branch-coverage tests for searchHistory.ts — supplemental pass.+ *+ * Scope: ONLY the uncovered branches of the exported functions+ * getSearchHistory, addSearchHistory, removeSearchHistory,+ * clearSearchHistory, and createSearchHistoryManager. The sibling+ * searchHistory.test.ts already drives the happy paths (add/remove/clear on+ * a working jsdom localStorage, malformed/non-array JSON, non-string array+ * filtering, case-insensitive dedup, and the default + custom maxEntries cap).+ *+ * This file drives the arms it leaves open:+ *+ * - isBrowser() false (SSR / no-window) early-return arm inside readHistory+ * AND writeHistory, reached through every exported function and through the+ * manager methods. Existing tests always run under jsdom where window and+ * localStorage are both defined, so the `!isBrowser()` guard is never hit.+ * - writeHistory catch arm (localStorage.setItem throwing) — the existing+ * mock never throws on setItem.+ * - readHistory catch arm entered via a throwing getItem (the sibling only+ * enters catch via JSON.parse on malformed JSON).+ * - readHistory `!raw` guard fed an empty string from getItem (the sibling+ * only feeds null).+ * - addSearchHistory Math.max(1, maxEntries) clamp behaviour for maxEntries+ * <= 0 (the constant 1 wins over the supplied bound).+ * - removeSearchHistory strict (===) case-sensitive semantics, which differ+ * from addSearchHistory's case-insensitive toLowerCase dedup.+ * - createSearchHistoryManager with an empty options object and with the+ * manager operating in a non-browser context.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ addSearchHistory,+ clearSearchHistory,+ createSearchHistoryManager,+ getSearchHistory,+ removeSearchHistory,+} from '../searchHistory';++const KEY = 'branchcov_history';++describe('searchHistory branch coverage (supplemental)', () => {+ beforeEach(() => {+ window.localStorage.clear();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ describe('getSearchHistory', () => {+ it('returns [] when localStorage holds an empty string (!raw falsy edge)', () => {+ // The InMemoryStorage from test setup returns '' (not null) for a key+ // explicitly set to ''. '' is falsy, so the `!raw` guard fires before+ // JSON.parse is ever attempted.+ window.localStorage.setItem(KEY, '');+ expect(getSearchHistory(KEY)).toEqual([]);+ });++ it('returns [] when localStorage.getItem throws (readHistory catch arm via getItem)', () => {+ // The sibling test only enters the catch through JSON.parse on bad JSON;+ // this drives the same catch via a throwing getItem.+ const spy = vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {+ throw new Error('SecurityError');+ });+ expect(getSearchHistory(KEY)).toEqual([]);+ expect(spy).toHaveBeenCalledWith(KEY);+ });++ it('returns [] in a non-browser context (isBrowser false -> readHistory early return)', () => {+ // Pre-seed while window exists so the assertion proves the data was NOT+ // read (rather than merely absent).+ window.localStorage.setItem(KEY, JSON.stringify(['seeded']));+ vi.stubGlobal('window', undefined);+ expect(getSearchHistory(KEY)).toEqual([]);+ });+ });++ describe('addSearchHistory', () => {+ it('clamps maxEntries = 0 to 1 via Math.max(1, maxEntries)', () => {+ window.localStorage.setItem(KEY, JSON.stringify(['old1', 'old2']));+ // Math.max(1, 0) === 1, so only the single newest entry survives.+ const result = addSearchHistory(KEY, 'newest', 0);+ expect(result).toEqual(['newest']);+ expect(getSearchHistory(KEY)).toEqual(['newest']);+ });++ it('clamps a negative maxEntries to 1 as well (boundary value)', () => {+ window.localStorage.setItem(KEY, JSON.stringify(['a', 'b', 'c']));+ expect(addSearchHistory(KEY, 'd', -5)).toEqual(['d']);+ });++ it('returns the computed history without persisting when setItem throws (writeHistory catch)', () => {+ window.localStorage.setItem(KEY, JSON.stringify(['existing']));+ const setSpy = vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {+ throw new Error('QuotaExceeded');+ });+ // readHistory still works (getItem is not mocked); only persistence fails.+ const result = addSearchHistory(KEY, 'fresh');+ expect(result).toEqual(['fresh', 'existing']);+ expect(setSpy).toHaveBeenCalled();+ // The throw was swallowed, so the underlying store is untouched.+ expect(window.localStorage.getItem(KEY)).toBe(JSON.stringify(['existing']));+ });++ it('returns [term] without reading or persisting in a non-browser context', () => {+ // Seeded data exists, but readHistory returns [] under SSR; writeHistory+ // is a no-op. The returned array contains only the new term, proving+ // neither the seeded history nor persistence participated.+ window.localStorage.setItem(KEY, JSON.stringify(['seeded']));+ vi.stubGlobal('window', undefined);+ expect(addSearchHistory(KEY, 'term')).toEqual(['term']);+ });++ it('returns [] for a whitespace-only term in a non-browser context', () => {+ // `!trimmed` early-return feeds straight into readHistory which is itself+ // an early [] under SSR.+ vi.stubGlobal('window', undefined);+ expect(addSearchHistory(KEY, ' ')).toEqual([]);+ });+ });++ describe('removeSearchHistory', () => {+ it('is case-sensitive: a differently-cased term is NOT removed (=== keeps the entry)', () => {+ // addSearchHistory dedups case-insensitively (toLowerCase comparison),+ // but removeSearchHistory uses strict ===, so 'foo' does not match 'Foo'.+ window.localStorage.setItem(KEY, JSON.stringify(['Foo', 'bar']));+ const result = removeSearchHistory(KEY, 'foo');+ expect(result).toEqual(['Foo', 'bar']);+ expect(getSearchHistory(KEY)).toEqual(['Foo', 'bar']);+ });++ it('returns the filtered history without persisting when setItem throws', () => {+ window.localStorage.setItem(KEY, JSON.stringify(['x', 'y']));+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {+ throw new Error('SecurityError');+ });+ expect(removeSearchHistory(KEY, 'x')).toEqual(['y']);+ });++ it('returns [] in a non-browser context (readHistory early return, writeHistory no-op)', () => {+ // Seeded data exists; under SSR readHistory returns [] so nothing is+ // filtered out and nothing is written.+ window.localStorage.setItem(KEY, JSON.stringify(['keep']));+ vi.stubGlobal('window', undefined);+ expect(removeSearchHistory(KEY, 'keep')).toEqual([]);+ });+ });++ describe('clearSearchHistory', () => {+ it('returns [] even when setItem throws (writeHistory catch arm)', () => {+ const setSpy = vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {+ throw new Error('QuotaExceeded');+ });+ expect(clearSearchHistory(KEY)).toEqual([]);+ expect(setSpy).toHaveBeenCalled();+ });++ it('returns [] in a non-browser context without touching storage', () => {+ vi.stubGlobal('window', undefined);+ expect(clearSearchHistory(KEY)).toEqual([]);+ });+ });++ describe('createSearchHistoryManager', () => {+ it('falls back to the default cap (10) for an empty options object', () => {+ // options?.maxEntries evaluates to undefined (no short-circuit since the+ // object is present), then ?? DEFAULT_MAX_HISTORY yields 10.+ const manager = createSearchHistoryManager(KEY, {});+ for (let i = 0; i < 15; i++) {+ manager.add(`term${i}`);+ }+ expect(manager.read().length).toBe(10);+ expect(manager.read()[0]).toBe('term14');+ });++ it('honours an explicit maxEntries through manager.add (clamp at the bound)', () => {+ const manager = createSearchHistoryManager(KEY, { maxEntries: 2 });+ manager.add('first');+ manager.add('second');+ manager.add('third');+ expect(manager.read()).toEqual(['third', 'second']);+ });++ it('degrades gracefully in a non-browser context across all four methods', () => {+ // Pre-seed while window exists to prove the SSR path ignores storage.+ window.localStorage.setItem(KEY, JSON.stringify(['seeded']));+ vi.stubGlobal('window', undefined);+ const manager = createSearchHistoryManager(KEY);+ // read -> readHistory early-return -> []+ expect(manager.read()).toEqual([]);+ // add -> readHistory [], writeHistory no-op -> [term]+ expect(manager.add('x')).toEqual(['x']);+ // remove -> readHistory [], writeHistory no-op -> []+ expect(manager.remove('x')).toEqual([]);+ // clear -> writeHistory no-op -> []+ expect(manager.clear()).toEqual([]);+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/securityAuthPresentation.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/securityAuthPresentation.branchcov0713.test.tsnew file mode 100644index 0000000000..f42cdc1e9f--- /dev/null+++ b/frontend-modern/src/utils/__tests__/securityAuthPresentation.branchcov0713.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';+import { getSecurityAuthRestartInstruction } from '@/utils/securityAuthPresentation';++// The sibling `securityAuthPresentation.test.ts` already exercises the+// `docker`, `proxmoxve`, `development`, and no-arg (undefined) arms of+// `getSecurityAuthRestartInstruction`. This file raises branch coverage by+// exercising the remaining arms of the `deploymentType` switch:+// - the shared `systemd` / `manual` case group+// - unrecognized non-empty strings that fall through to `default`+// - case-sensitivity of the switch (e.g. "DOCKER" != "docker")+// - boundary / malformed inputs (empty string, null, non-string runtime values)+//+// `deploymentType` is typed as `string | undefined`, so deliberately-wrong+// inputs are cast via `as unknown as DeploymentTypeParam` to keep strict+// type-check clean without `any` / `@ts-ignore` / `@ts-expect-error`.++type DeploymentTypeParam = Parameters<typeof getSecurityAuthRestartInstruction>[0];++describe('getSecurityAuthRestartInstruction — branch coverage (batch 0713)', () => {+ describe('shared `systemd` / `manual` case group', () => {+ it('returns the sudo systemctl restart instruction for systemd', () => {+ expect(getSecurityAuthRestartInstruction('systemd')).toEqual({+ label: 'Restart the service:',+ command: 'sudo systemctl restart pulse',+ });+ });++ it('returns the same sudo systemctl instruction for manual', () => {+ const manual = getSecurityAuthRestartInstruction('manual');+ const systemd = getSecurityAuthRestartInstruction('systemd');++ // Source declares `case 'systemd': case 'manual':` as a shared+ // fallthrough, so both inputs must produce identical output.+ expect(manual).toEqual(systemd);+ expect(manual).toEqual({+ label: 'Restart the service:',+ command: 'sudo systemctl restart pulse',+ });+ // The shared arm never exposes a secondaryLabel.+ expect(manual.secondaryLabel).toBeUndefined();+ });++ it('routes systemd/manual to the sudo-prefixed command, not the dev command', () => {+ // Confirms the systemd/manual branch is distinct from the+ // `development` arm which uses `npm run dev:restart`.+ expect(getSecurityAuthRestartInstruction('systemd').command).toBe(+ 'sudo systemctl restart pulse',+ );+ expect(getSecurityAuthRestartInstruction('manual').command).not.toBe(+ 'npm run dev:restart',+ );+ });+ });++ describe('default arm — unrecognized deployment types', () => {+ it('returns the generic fallback for an unknown non-empty deployment type', () => {+ const result = getSecurityAuthRestartInstruction('kubernetes');+ expect(result).toEqual({+ label: 'Restart Pulse using your deployment method',+ });+ expect(result.command).toBeUndefined();+ expect(result.secondaryLabel).toBeUndefined();+ });++ it('returns the generic fallback for another unknown deployment type', () => {+ expect(getSecurityAuthRestartInstruction('podman')).toEqual({+ label: 'Restart Pulse using your deployment method',+ });+ });++ it('is case-sensitive: "DOCKER" does not match the docker case', () => {+ // The switch uses strict string equality, so any case variant of a+ // known deployment type must fall through to default.+ const upper = getSecurityAuthRestartInstruction('DOCKER');+ expect(upper).toEqual({+ label: 'Restart Pulse using your deployment method',+ });+ expect(upper.command).toBeUndefined();++ // Same expectation for mixed-case / Systemd variants.+ expect(getSecurityAuthRestartInstruction('Systemd')).toEqual({+ label: 'Restart Pulse using your deployment method',+ });+ });++ it('falls through to default for an empty string', () => {+ // The empty string matches no `case` clause, so it hits default.+ const result = getSecurityAuthRestartInstruction('');+ expect(result.label).toBe('Restart Pulse using your deployment method');+ expect(result.command).toBeUndefined();+ });++ it('falls through to default for null (deliberately malformed input)', () => {+ const result = getSecurityAuthRestartInstruction(+ null as unknown as DeploymentTypeParam,+ );+ expect(result).toEqual({+ label: 'Restart Pulse using your deployment method',+ });+ expect(result.command).toBeUndefined();+ expect(result.secondaryLabel).toBeUndefined();+ });++ it('falls through to default for a non-string runtime value (deliberately malformed)', () => {+ const result = getSecurityAuthRestartInstruction(+ 42 as unknown as DeploymentTypeParam,+ );+ expect(result).toEqual({+ label: 'Restart Pulse using your deployment method',+ });+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/sourcePlatformOptions.branchcov0713.test.ts b/frontend-modern/src/utils/__tests__/sourcePlatformOptions.branchcov0713.test.tsnew file mode 100644index 0000000000..39a67e9f2f--- /dev/null+++ b/frontend-modern/src/utils/__tests__/sourcePlatformOptions.branchcov0713.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest';+import { orderSourcePlatformKeys } from '@/utils/sourcePlatformOptions';++// `orderSourcePlatformKeys` is the only exported function with uncovered branches+// after the sibling `sourcePlatformOptions.test.ts` suite (which exercises only the+// happy path of canonical keys present in DEFAULT_SOURCE_PLATFORM_ORDER). This file+// targets the gaps: empty/degenerate inputs, the .filter(Boolean) falsy outcome,+// Set-based deduplication, non-Array iterables, the explicit-preferredOrder arm,+// the indexA === -1 / indexB === -1 sort arms, and the localeCompare fallback that+// fires when NEITHER compared key appears in preferredOrder.++describe('orderSourcePlatformKeys — branch coverage (batch 0713)', () => {+ describe('empty / falsy inputs', () => {+ it('returns [] for an empty array', () => {+ expect(orderSourcePlatformKeys([])).toEqual([]);+ });++ it('returns [] for an empty Set (Iterable protocol, not Array)', () => {+ expect(orderSourcePlatformKeys(new Set<string>())).toEqual([]);+ });++ it('returns [] when every entry normalizes to empty string (.filter(Boolean) all-falsy arm)', () => {+ // normalizeSourcePlatformQueryValue trims+lowercases; whitespace-only inputs+ // collapse to '' and are stripped by .filter(Boolean).+ expect(orderSourcePlatformKeys(['', ' ', '\t', '\n'])).toEqual([]);+ });++ it('strips entries that normalize to "" while keeping valid ones (.filter(Boolean) truthy + falsy arms)', () => {+ expect(orderSourcePlatformKeys(['agent', '', ' ', 'docker'])).toEqual([+ 'agent',+ 'docker',+ ]);+ });++ it('tolerates null/undefined entries that violate the declared Iterable<string>', () => {+ // The implementation funnels every entry through normalizeSourcePlatformQueryValue,+ // which accepts `string | null | undefined` and maps nullish to "". Those empty+ // results are then dropped by .filter(Boolean), so the canonical keys survive.+ const malformed = ['agent', null, undefined, 'docker'] as unknown as Parameters<+ typeof orderSourcePlatformKeys+ >[0];+ expect(orderSourcePlatformKeys(malformed)).toEqual(['agent', 'docker']);+ });+ });++ describe('Iterable protocol support', () => {+ it('deduplicates alias and case variants through the inner new Set(...) construction', () => {+ // 'PBS' and 'pbs' both alias to 'proxmox-pbs'; 'AGENT' and 'agent' both+ // canonicalize to 'agent'. The surrounding new Set collapses each pair to a+ // single canonical entry, so the output has one of each.+ expect(orderSourcePlatformKeys(['PBS', 'pbs', 'AGENT', 'agent'])).toEqual([+ 'agent',+ 'proxmox-pbs',+ ]);+ });++ it('accepts a generator as input (Iterable, not Array)', () => {+ const generate = function* (): Generator<string> {+ yield 'docker';+ yield 'agent';+ };+ expect(orderSourcePlatformKeys(generate())).toEqual(['agent', 'docker']);+ });+ });++ describe('sort comparator: localeCompare fallback for two unknown keys', () => {+ it('orders two unknown keys alphabetically by presentation label when neither is in preferredOrder', () => {+ // Both 'zzz-custom' and 'aaa-custom' miss DEFAULT_SOURCE_PLATFORM_ORDER, so the+ // outer `if (indexA !== -1 || indexB !== -1)` is false and the comparator+ // falls through to getSourcePlatformLabel(a).localeCompare(getSourcePlatformLabel(b)).+ // Labels: 'Aaa Custom' < 'Zzz Custom' -> aaa-custom sorts first.+ expect(orderSourcePlatformKeys(['zzz-custom', 'aaa-custom'])).toEqual([+ 'aaa-custom',+ 'zzz-custom',+ ]);+ });++ it('keeps the "all" sentinel (truthy after normalize) and routes it through the label fallback', () => {+ // normalizeSourcePlatformQueryValue('all') returns 'all', which is truthy and+ // survives .filter(Boolean). 'all' is NOT in DEFAULT_SOURCE_PLATFORM_ORDER, so+ // it falls through to localeCompare alongside other unknowns.+ expect(orderSourcePlatformKeys(['all', 'agent'])).toEqual(['agent', 'all']);+ });+ });++ describe('sort comparator: known-vs-unknown arms', () => {+ it('places a known key before an unknown key (indexB === -1 -> return -1 arm)', () => {+ // Input order [known, unknown]: insertion sort calls compare('agent', 'custom-x').+ // indexA = 0 (agent in DEFAULT order), indexB = -1 (custom-x absent) -> return -1+ // -> agent stays before custom-x.+ expect(orderSourcePlatformKeys(['agent', 'custom-x'])).toEqual(['agent', 'custom-x']);+ });++ it('places an unknown key after a known key (indexA === -1 -> return 1 arm)', () => {+ // Input order [unknown, known]: insertion sort calls compare('custom-x', 'agent').+ // indexA = -1 (custom-x absent), indexB = 0 (agent in DEFAULT order) -> return 1+ // -> custom-x is pushed after agent.+ expect(orderSourcePlatformKeys(['custom-x', 'agent'])).toEqual(['agent', 'custom-x']);+ });++ it('exercises all four comparator outcomes across a single mixed input', () => {+ // agent (index 0) vs docker (index 6) -> return indexA - indexB arm.+ // agent/docker vs aaa-custom/zzz-custom -> indexA === -1 and indexB === -1 arms.+ // aaa-custom vs zzz-custom -> localeCompare fallback.+ expect(+ orderSourcePlatformKeys(['zzz-custom', 'agent', 'docker', 'aaa-custom']),+ ).toEqual(['agent', 'docker', 'aaa-custom', 'zzz-custom']);+ });+ });++ describe('explicit preferredOrder parameter (default-parameter branch)', () => {+ it('honors a caller-supplied preferredOrder instead of the default', () => {+ // With preferredOrder = ['docker', 'agent'], docker precedes agent even though+ // DEFAULT_SOURCE_PLATFORM_ORDER ranks agent first. This exercises the+ // "argument provided" arm of the default parameter.+ expect(orderSourcePlatformKeys(['agent', 'docker'], ['docker', 'agent'])).toEqual([+ 'docker',+ 'agent',+ ]);+ });++ it('still falls back to localeCompare for keys absent from the custom preferredOrder', () => {+ // preferredOrder = ['agent'] excludes both custom keys, forcing the comparator+ // into its localeCompare fallback branch.+ expect(orderSourcePlatformKeys(['zzz-custom', 'aaa-custom'], ['agent'])).toEqual([+ 'aaa-custom',+ 'zzz-custom',+ ]);+ });++ it('ranks preferred keys ahead of non-preferred keys, then orders unknowns by label', () => {+ // 'agent' is the only entry in the supplied preferredOrder, so it sorts first;+ // 'aaa-custom' and 'bbb-custom' fall through to label-based ordering.+ expect(+ orderSourcePlatformKeys(['bbb-custom', 'agent', 'aaa-custom'], ['agent']),+ ).toEqual(['agent', 'aaa-custom', 'bbb-custom']);+ });+ });+});