Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Cover patrol handoff, resource adapters and TrueNAS page branch arms

rcourtmane8740159cc92
diff --git a/frontend-modern/src/components/shared/__tests__/contextualFocus.branchcov0723pm.test.ts b/frontend-modern/src/components/shared/__tests__/contextualFocus.branchcov0723pm.test.ts
new file mode 100644
index 0000000000..5d51cadc3e
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/contextualFocus.branchcov0723pm.test.ts
@@ -0,0 +1,476 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ findInlineDetailElement,
+ revealInlineDetailInViewport,
+} from '@/components/shared/contextualFocus';
+
+// Branch-coverage tests for the DOM scroller helpers in contextualFocus.ts.
+// The four private helpers (isWindowScroller, resolveVerticalScroller,
+// getScrollerMetrics, scrollVerticalScroller) are only reachable through the
+// exported `revealInlineDetailInViewport` entry point, so every test here
+// drives them through real DOM elements (jsdom) with stubbed layout values.
+// Every asserted value below is hand-computed against the source in
+// src/components/shared/contextualFocus.ts — no snapshots, no source-string
+// reads, no constant-equals-itself tautologies.
+
+const buildRect = (top: number, height = 32): DOMRect =>
+ ({
+ x: 0,
+ y: top,
+ width: 240,
+ height,
+ top,
+ bottom: top + height,
+ left: 0,
+ right: 240,
+ toJSON: () => ({}),
+ }) as DOMRect;
+
+// Build a div whose scroll geometry is observable to resolveScrollableAncestor
+// (overflow-y computed style + scrollHeight > clientHeight).
+const buildScrollableAncestor = (
+ overrides: {
+ scrollHeight?: number;
+ clientHeight?: number;
+ scrollTop?: number;
+ rectTop?: number;
+ } = {},
+): HTMLDivElement => {
+ const scroller = document.createElement('div');
+ scroller.style.overflowY = 'auto';
+ Object.defineProperty(scroller, 'scrollHeight', {
+ configurable: true,
+ value: overrides.scrollHeight ?? 1000,
+ });
+ Object.defineProperty(scroller, 'clientHeight', {
+ configurable: true,
+ value: overrides.clientHeight ?? 400,
+ });
+ scroller.scrollTop = overrides.scrollTop ?? 0;
+ Object.defineProperty(scroller, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => buildRect(overrides.rectTop ?? 0, overrides.clientHeight ?? 400),
+ });
+ return scroller;
+};
+
+describe('contextualFocus.branchcov0723pm', () => {
+ let originalScrollTo: PropertyDescriptor | undefined;
+ let originalDocumentScrollTop: PropertyDescriptor | undefined;
+ let originalBodyScrollTop: PropertyDescriptor | undefined;
+
+ beforeEach(() => {
+ // innerHeight=800 → minTopMargin=96, preferredTop=224, detailPeek=192 for
+ // the window-scroller path. Keeps expected offsets stable per scenario.
+ vi.stubGlobal('innerHeight', 800);
+ vi.stubGlobal('scrollY', 0);
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
+ cb(0);
+ return 1;
+ });
+ originalScrollTo = Object.getOwnPropertyDescriptor(window, 'scrollTo');
+ originalDocumentScrollTop = Object.getOwnPropertyDescriptor(
+ document.documentElement,
+ 'scrollTop',
+ );
+ originalBodyScrollTop = Object.getOwnPropertyDescriptor(document.body, 'scrollTop');
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = '';
+ document.documentElement.scrollTop = 0;
+ document.body.scrollTop = 0;
+ if (originalScrollTo) {
+ Object.defineProperty(window, 'scrollTo', originalScrollTo);
+ }
+ if (originalDocumentScrollTop) {
+ Object.defineProperty(document.documentElement, 'scrollTop', originalDocumentScrollTop);
+ }
+ if (originalBodyScrollTop) {
+ Object.defineProperty(document.body, 'scrollTop', originalBodyScrollTop);
+ }
+ vi.unstubAllGlobals();
+ });
+
+ describe('findInlineDetailElement', () => {
+ // `if (!root || !normalizedId) return null;` — every falsy combination of
+ // the two guards collapses to null before the querySelector runs.
+
+ it('returns null when root is null (root guard, left operand)', () => {
+ expect(findInlineDetailElement(null, 'workload-a')).toBeNull();
+ });
+
+ it('returns null when seriesId is null (normalizedId guard, ?? right arm)', () => {
+ const root = document.createElement('div');
+ expect(findInlineDetailElement(root, null)).toBeNull();
+ });
+
+ it('returns null when seriesId is the empty string (normalized truthiness guard)', () => {
+ const root = document.createElement('div');
+ expect(findInlineDetailElement(root, '')).toBeNull();
+ });
+
+ it('returns null when seriesId is whitespace-only (trim() collapses to empty)', () => {
+ const root = document.createElement('div');
+ expect(findInlineDetailElement(root, ' ')).toBeNull();
+ });
+
+ it('returns null when no descendant matches the data attribute (querySelector miss)', () => {
+ const root = document.createElement('div');
+ const decoy = document.createElement('div');
+ decoy.setAttribute('data-inline-detail-for', 'other');
+ root.appendChild(decoy);
+ expect(findInlineDetailElement(root, 'workload-a')).toBeNull();
+ });
+
+ it('returns the matching element when one is present (querySelector hit)', () => {
+ const root = document.createElement('div');
+ const detail = document.createElement('div');
+ detail.setAttribute('data-inline-detail-for', 'workload-a');
+ root.appendChild(detail);
+ expect(findInlineDetailElement(root, 'workload-a')).toBe(detail);
+ });
+
+ it('trims surrounding whitespace from seriesId before querying (trim() before selector)', () => {
+ const root = document.createElement('div');
+ const detail = document.createElement('div');
+ detail.setAttribute('data-inline-detail-for', 'workload-a');
+ root.appendChild(detail);
+ expect(findInlineDetailElement(root, '\t workload-a \n')).toBe(detail);
+ });
+
+ it('matches against a Document root, not just Element roots (ParentNode overload)', () => {
+ const detail = document.createElement('div');
+ detail.setAttribute('data-inline-detail-for', 'workload-a');
+ document.body.appendChild(detail);
+ expect(findInlineDetailElement(document, 'workload-a')).toBe(detail);
+ });
+ });
+
+ describe('revealInlineDetailInViewport — window-scroller resolution', () => {
+ // resolveVerticalScroller falls back to `window` whenever the row has no
+ // scrollable ancestor (no element with overflow-y auto/scroll AND
+ // scrollHeight>clientHeight up the parent chain). isWindowScroller then
+ // steers metrics + scrollVerticalScroller down the window arms.
+
+ it('returns false without scrolling when the row already has breathing room and detail peeks (early-return false arm)', () => {
+ const row = document.createElement('div');
+ // rowRect.top=200 → currentRowOffset=200 >= minTopMargin(96) → breathing room true.
+ row.getBoundingClientRect = vi.fn(() => buildRect(200, 40));
+ // detail.top=300 → 300 <= height(800)-peek(192)=608 → detailHasPeek true.
+ const detail = document.createElement('div');
+ detail.getBoundingClientRect = vi.fn(() => buildRect(300, 220));
+ document.body.append(row, detail);
+
+ expect(revealInlineDetailInViewport({ row, detail, behavior: 'smooth' })).toBe(false);
+ });
+
+ it('returns false without scrolling when detail is omitted (?? null → detailHasPeek forced true)', () => {
+ const row = document.createElement('div');
+ row.getBoundingClientRect = vi.fn(() => buildRect(200, 40));
+ document.body.appendChild(row);
+ expect(revealInlineDetailInViewport({ row })).toBe(false);
+ });
+
+ it('scrolls the window via window.scrollTo when the row sits above minTopMargin (canUseScrollTo=true, window arm)', () => {
+ const scrollTo = vi.fn();
+ Object.defineProperty(window, 'scrollTo', { configurable: true, value: scrollTo });
+ vi.stubGlobal('scrollY', 50);
+
+ const row = document.createElement('div');
+ // rowRect.top=80 → currentRowOffset=80 < minTopMargin(96) → breathing room false.
+ row.getBoundingClientRect = vi.fn(() => buildRect(80, 40));
+ document.body.appendChild(row);
+
+ // desiredRowOffset = 80 > preferredTop(224)? no → max(96, 80)=96
+ // nextScrollTop = 50 + 80 - 96 = 34
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 34, behavior: 'smooth' });
+ });
+
+ it('uses the explicit behavior override when scrolling the window (behavior ?? right arm)', () => {
+ const scrollTo = vi.fn();
+ Object.defineProperty(window, 'scrollTo', { configurable: true, value: scrollTo });
+ vi.stubGlobal('scrollY', 50);
+
+ const row = document.createElement('div');
+ row.getBoundingClientRect = vi.fn(() => buildRect(80, 40));
+ document.body.appendChild(row);
+
+ expect(revealInlineDetailInViewport({ row, detail: null, behavior: 'auto' })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 34, behavior: 'auto' });
+ });
+
+ it('falls back to document.documentElement.scrollTop when window.scrollTo lacks a `.mock` marker (jsdom fallback arm)', () => {
+ // A plain function with no `.mock` property → canUseScrollTo=false for the
+ // window scroller → the code sets documentElement/body.scrollTop instead
+ // of calling window.scrollTo.
+ Object.defineProperty(window, 'scrollTo', {
+ configurable: true,
+ value: function notImplemented() {},
+ });
+ vi.stubGlobal('scrollY', 50);
+
+ const row = document.createElement('div');
+ row.getBoundingClientRect = vi.fn(() => buildRect(80, 40));
+ document.body.appendChild(row);
+
+ let observedDocumentTop = -1;
+ let observedBodyTop = -1;
+ Object.defineProperty(document.documentElement, 'scrollTop', {
+ configurable: true,
+ get: () => observedDocumentTop,
+ set: (v: number) => {
+ observedDocumentTop = v;
+ },
+ });
+ Object.defineProperty(document.body, 'scrollTop', {
+ configurable: true,
+ get: () => observedBodyTop,
+ set: (v: number) => {
+ observedBodyTop = v;
+ },
+ });
+
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ // nextScrollTop = 50 + 80 - 96 = 34; both documentElement and body receive it.
+ expect(observedDocumentTop).toBe(34);
+ expect(observedBodyTop).toBe(34);
+ });
+
+ it('reads window.scrollY through getScrollerMetrics when computing nextScrollTop (window metrics branch)', () => {
+ const scrollTo = vi.fn();
+ Object.defineProperty(window, 'scrollTo', { configurable: true, value: scrollTo });
+ vi.stubGlobal('scrollY', 150);
+
+ const row = document.createElement('div');
+ row.getBoundingClientRect = vi.fn(() => buildRect(20, 40));
+ document.body.appendChild(row);
+
+ // currentRowOffset = 20 (rowRect.top - metrics.top(=0))
+ // desiredRowOffset = max(96, 20) = 96
+ // nextScrollTop = 150 + 20 - 96 = 74
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 74, behavior: 'smooth' });
+ });
+ });
+
+ describe('revealInlineDetailInViewport — element-scroller resolution', () => {
+ // resolveScrollableAncestor returns a real HTMLElement when an ancestor
+ // has overflow-y auto/scroll AND scrollHeight>clientHeight. That drives
+ // getScrollerMetrics down the rect-based arm and scrollVerticalScroller
+ // down the HTMLElement arm.
+
+ it('scrolls the nearest scrollable ancestor via scrollTo with the rect-derived offset (HTMLElement canUseScrollTo=true)', () => {
+ // scroller: clientHeight=400 → minTopMargin=max(72,48)=72,
+ // preferredTop=max(72,112)=112, detailPeek=max(160,96)=160.
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 200,
+ rectTop: 0,
+ });
+ const scrollTo = vi.fn();
+ Object.defineProperty(scroller, 'scrollTo', { configurable: true, value: scrollTo });
+
+ const row = document.createElement('div');
+ // rowRect.top=40 → currentRowOffset = 40 - metrics.top(=0) = 40
+ // rowHasBreathingRoom = 40 >= 72? false → trigger scroll.
+ // desiredRowOffset = 40 > 112? no → max(72, 40) = 72
+ // nextScrollTop = 200 + 40 - 72 = 168
+ row.getBoundingClientRect = vi.fn(() => buildRect(40, 40));
+ scroller.appendChild(row);
+ document.body.appendChild(scroller);
+
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 168, behavior: 'smooth' });
+ });
+
+ it('takes the preferredTop arm of desiredRowOffset when the row sits below preferredTop (ternary left arm)', () => {
+ // Same scroller geometry (clientHeight=400 → preferredTop=112).
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 0,
+ rectTop: 0,
+ });
+ const scrollTo = vi.fn();
+ Object.defineProperty(scroller, 'scrollTo', { configurable: true, value: scrollTo });
+
+ const row = document.createElement('div');
+ row.getBoundingClientRect = vi.fn(() => buildRect(400, 40));
+ // rowRect.top=400 → currentRowOffset=400 > preferredTop(112) → left arm.
+ const detail = document.createElement('div');
+ // detail.top=700 → 700 > height(400)-peek(160)=240 → detailHasPeek false → trigger.
+ detail.getBoundingClientRect = vi.fn(() => buildRect(700, 220));
+ scroller.append(row, detail);
+ document.body.appendChild(scroller);
+
+ // desiredRowOffset = 400 > 112 ? 112 : ... → 112
+ // nextScrollTop = 0 + 400 - 112 = 288
+ expect(revealInlineDetailInViewport({ row, detail })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 288, behavior: 'smooth' });
+ });
+
+ it('takes the max(minTopMargin, currentRowOffset) arm when row sits between minTopMargin and preferredTop and detail is below the peek (ternary right arm)', () => {
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 20,
+ rectTop: 0,
+ });
+ const scrollTo = vi.fn();
+ Object.defineProperty(scroller, 'scrollTo', { configurable: true, value: scrollTo });
+
+ const row = document.createElement('div');
+ // currentRowOffset=100, between minTopMargin(72) and preferredTop(112).
+ row.getBoundingClientRect = vi.fn(() => buildRect(100, 40));
+ const detail = document.createElement('div');
+ // detail.top=700 → detailHasPeek false → trigger scroll.
+ detail.getBoundingClientRect = vi.fn(() => buildRect(700, 220));
+ scroller.append(row, detail);
+ document.body.appendChild(scroller);
+
+ // rowRect.top=100 → currentRowOffset=100; rowHasBreathingRoom = 100>=72 = true.
+ // detailHasPeek = 700<=240 = false → scroll path.
+ // desiredRowOffset = 100 > 112 ? 112 : max(72, 100) = 100 (right arm)
+ // nextScrollTop = 20 + 100 - 100 = 20
+ expect(revealInlineDetailInViewport({ row, detail })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 20, behavior: 'smooth' });
+ });
+
+ it('clamps a deeply negative nextScrollTop to 0 when the row is at the very top (Math.max(0, top))', () => {
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 0,
+ rectTop: 0,
+ });
+ const scrollTo = vi.fn();
+ Object.defineProperty(scroller, 'scrollTo', { configurable: true, value: scrollTo });
+
+ const row = document.createElement('div');
+ // rowRect.top=5 → currentRowOffset=5 → desiredRowOffset=max(72,5)=72
+ // nextScrollTop = 0 + 5 - 72 = -67 → clamped 0 (NOT -67).
+ row.getBoundingClientRect = vi.fn(() => buildRect(5, 40));
+ scroller.appendChild(row);
+ document.body.appendChild(scroller);
+
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'smooth' });
+ });
+
+ it('assigns scroller.scrollTop directly when the scroller has no callable scrollTo (HTMLElement canUseScrollTo=false arm)', () => {
+ // Deliberately malformed: a scroller whose scrollTo is undefined, cast
+ // back through `unknown` to satisfy TS while breaking the runtime guard
+ // `typeof scroller.scrollTo !== 'function'`.
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 50,
+ rectTop: 0,
+ });
+ Object.defineProperty(scroller, 'scrollTo', {
+ configurable: true,
+ value: undefined,
+ });
+ const malformedScroller = scroller as unknown as HTMLElement & {
+ scrollTo?: unknown;
+ };
+
+ const row = document.createElement('div');
+ // rowRect.top=60 → currentRowOffset=60 → rowHasBreathingRoom = 60>=72 = false.
+ // desiredRowOffset = max(72, 60) = 72 → nextScrollTop = 50 + 60 - 72 = 38.
+ row.getBoundingClientRect = vi.fn(() => buildRect(60, 40));
+ scroller.appendChild(row);
+ document.body.appendChild(scroller);
+
+ expect(
+ revealInlineDetailInViewport({
+ row: malformedScroller.firstElementChild as HTMLElement,
+ detail: null,
+ }),
+ ).toBe(true);
+ // scroller.scrollTop is the natural writable property (jsdom supports it)
+ // and gets reassigned by the `scroller.scrollTop = clampedTop` arm.
+ expect(scroller.scrollTop).toBe(38);
+ });
+
+ it('does not throw when scroller.scrollTo throws inside scrollVerticalScroller (outer try/catch swallow arm)', () => {
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 0,
+ rectTop: 0,
+ });
+ const throwingScrollTo = vi.fn(() => {
+ throw new Error('scroll boom');
+ });
+ Object.defineProperty(scroller, 'scrollTo', {
+ configurable: true,
+ value: throwingScrollTo,
+ });
+
+ const row = document.createElement('div');
+ row.getBoundingClientRect = vi.fn(() => buildRect(5, 40));
+ scroller.appendChild(row);
+ document.body.appendChild(scroller);
+
+ // revealInlineDetailInViewport must still return true; the thrown error
+ // is swallowed by the outer try/catch in scrollVerticalScroller.
+ expect(() => revealInlineDetailInViewport({ row, detail: null })).not.toThrow();
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ expect(throwingScrollTo).toHaveBeenCalled();
+ });
+
+ it('treats an HTMLElement scroller whose scrollTo source contains "notImplemented" as canUseScrollTo=false (toString.includes arm)', () => {
+ // For an HTMLElement scroller the jsdom-specific shortcut is skipped
+ // (isWindowScroller is false), so the code reaches the
+ // Function.prototype.toString.call(...).includes('notImplemented')
+ // check. A function whose own source contains that string makes
+ // canUseScrollTo return false → scroller.scrollTop is assigned directly.
+ const scroller = buildScrollableAncestor({
+ scrollHeight: 1000,
+ clientHeight: 400,
+ scrollTop: 50,
+ rectTop: 0,
+ });
+ Object.defineProperty(scroller, 'scrollTo', {
+ configurable: true,
+ // The literal name in the source is what the includes() check matches.
+ value: function notImplementedScrollTo() {},
+ });
+
+ const row = document.createElement('div');
+ // rowRect.top=60 → currentRowOffset=60 → rowHasBreathingRoom false.
+ // desiredRowOffset = max(72, 60) = 72 → nextScrollTop = 50 + 60 - 72 = 38.
+ row.getBoundingClientRect = vi.fn(() => buildRect(60, 40));
+ scroller.appendChild(row);
+ document.body.appendChild(scroller);
+
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ // The "notImplemented" arm routes through `scroller.scrollTop = clampedTop`.
+ expect(scroller.scrollTop).toBe(38);
+ });
+
+ it('falls back to the window scroller when no ancestor is scrollable', () => {
+ // resolveScrollableAncestor walks parentElement, so it never sees the
+ // Document. A row attached directly to body finds no overflow-y:auto
+ // oversized ancestor, so resolveVerticalScroller returns window.
+ const scrollTo = vi.fn();
+ Object.defineProperty(window, 'scrollTo', { configurable: true, value: scrollTo });
+ vi.stubGlobal('scrollY', 50);
+
+ const row = document.createElement('div');
+ // rowRect.top=80 → currentRowOffset=80 < minTopMargin(96) → trigger.
+ // desiredRowOffset = max(96, 80) = 96 → nextScrollTop = 50 + 80 - 96 = 34.
+ row.getBoundingClientRect = vi.fn(() => buildRect(80, 40));
+ document.body.appendChild(row);
+
+ expect(revealInlineDetailInViewport({ row, detail: null })).toBe(true);
+ // Window-scroller path: window.scrollTo receives the offset.
+ expect(scrollTo).toHaveBeenCalledWith({ top: 34, behavior: 'smooth' });
+ });
+ });
+});
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.branchcov0723pm.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.branchcov0723pm.test.ts
new file mode 100644
index 0000000000..b58bad4b8c
--- /dev/null
+++ b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.branchcov0723pm.test.ts
@@ -0,0 +1,1320 @@
+import { describe, expect, it } from 'vitest';
+import type { RemediationPlan } from '@/api/ai';
+import type { InvestigationRecord } from '@/api/ai';
+import type { ResourceCorrelation } from '@/types/aiIntelligence';
+import type { ResourceChange } from '@/types/resource';
+import type { PatrolRunRecord } from '@/api/patrol';
+
+import {
+ buildPatrolAssessmentAssistantHandoff,
+ buildPatrolAssistantFindingBriefing,
+ buildPatrolAssistantFindingHandoff,
+ buildPatrolAssistantFindingHandoffActions,
+ buildPatrolConfigurationFailureHandoff,
+ buildPatrolInvestigationContextSummary,
+ buildPatrolInvestigationRecordPresentation,
+ buildPatrolRemediationPlanAssistantBriefing,
+ buildPatrolRemediationPlanAssistantModelContext,
+ buildPatrolRunAssistantHandoff,
+ patrolAssistantFindingHandoffRequiresApprovalMode,
+ selectPatrolSupportingRecentChanges,
+} from '../patrolInvestigationContextModel';
+
+// Second branch-coverage companion to patrolInvestigationContextModel.test.ts.
+// Targets the residual uncovered arms (v8 branch coverage): null/empty
+// collections, absent timestamps, unknown resource kinds, null handoff
+// metadata, truncation/cap boundaries, and every fallback label. Does not
+// duplicate the happy paths already pinned by the dev test or the first
+// branchcov file.
+
+const minimalRecord = {
+ id: 'r',
+ finding_id: 'f',
+ subject: { resource_id: 'vm-1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+} as unknown as InvestigationRecord;
+
+describe('buildPatrolInvestigationContextSummary (residual branches)', () => {
+ it('returns zero correlations when the response is present but has no count and no array', () => {
+ // normalizeCorrelationCount final `return 0` arm: object that is neither a
+ // finite numeric count nor an Array `correlations` field.
+ const summary = buildPatrolInvestigationContextSummary({
+ correlations: { unexpected: 'shape' } as unknown as
+ import('@/types/aiIntelligence').CorrelationsResponse | null,
+ });
+
+ expect(summary).toMatchObject({
+ correlationCount: 0,
+ hasContext: false,
+ summaryText: '',
+ });
+ });
+});
+
+describe('selectPatrolSupportingRecentChanges (same-state transition branches)', () => {
+ it('uses a custom reason and skips non-array changedFields', () => {
+ // formatSameStateTransitionReason: changedFieldLabels empty (metadata
+ // present but changedFields not an array) -> falls through to the reason
+ // arm, and a reason that is not the default yields "${reason} while ${state}".
+ const [change] = selectPatrolSupportingRecentChanges([
+ {
+ id: 'c-reason',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'state_transition',
+ from: 'online',
+ to: 'online',
+ sourceType: 'pulse_diff',
+ confidence: 'high',
+ reason: 'operator-initiated restart',
+ metadata: { note: 'not an array' },
+ },
+ ]);
+
+ expect(change).toMatchObject({
+ from: undefined,
+ to: undefined,
+ reason: 'operator-initiated restart while online',
+ });
+ });
+
+ it('skips blank changed-field entries and falls back to the identifier label for unknown fields', () => {
+ const [change] = selectPatrolSupportingRecentChanges([
+ {
+ id: 'c-fields',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'restart',
+ from: 'on',
+ to: 'on',
+ sourceType: 'pulse_diff',
+ confidence: 'high',
+ metadata: { changedFields: ['', ' ', 'custom_field', 'tags'] },
+ },
+ ]);
+
+ // Blank entries are skipped; 'custom_field' uses formatIdentifierLabel
+ // fallback ("Custom Field"); 'tags' resolves to the known map label.
+ expect(change.reason).toBe('Custom Field and tags changed while on');
+ });
+
+ it('renders the single-field and three-or-more-field compact label lists', () => {
+ const [single] = selectPatrolSupportingRecentChanges([
+ {
+ id: 'c-one',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'state_transition',
+ from: 'online',
+ to: 'online',
+ sourceType: 'pulse_diff',
+ confidence: 'high',
+ metadata: { changedFields: ['tags'] },
+ },
+ ]);
+ expect(single.reason).toBe('tags changed while online');
+
+ const [many] = selectPatrolSupportingRecentChanges([
+ {
+ id: 'c-many',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'state_transition',
+ from: 'online',
+ to: 'online',
+ sourceType: 'pulse_diff',
+ confidence: 'high',
+ metadata: { changedFields: ['status', 'incidents', 'parentId'] },
+ },
+ ]);
+ expect(many.reason).toBe('status, incident state, and 1 more changed while online');
+ });
+
+ it('falls back to the default wording when the reason is exactly the no-op default', () => {
+ const [change] = selectPatrolSupportingRecentChanges([
+ {
+ id: 'c-default',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'state_transition',
+ from: 'online',
+ to: 'online',
+ sourceType: 'pulse_diff',
+ confidence: 'high',
+ reason: 'Resource state changed',
+ },
+ ]);
+
+ // Case-insensitive match against the default -> generic fallback wording.
+ expect(change.reason).toBe('state details changed while online');
+ });
+});
+
+describe('buildPatrolInvestigationRecordPresentation (residual branches)', () => {
+ it('labels an unknown tool via the identifier fallback', () => {
+ const presentation = buildPatrolInvestigationRecordPresentation({
+ ...minimalRecord,
+ tools_used: ['metrics.history', 'custom.diagnostic.tool'],
+ });
+
+ // Known tool resolves to its map label; unknown tool falls through to
+ // formatIdentifierLabel.
+ expect(presentation.toolsUsed).toEqual(['Metrics history', 'Custom Diagnostic Tool']);
+ });
+});
+
+describe('buildPatrolRunAssistantHandoff (residual branches)', () => {
+ it('falls back every identity field when the run carries no id, type, or status', () => {
+ const handoff = buildPatrolRunAssistantHandoff({
+ id: '',
+ type: '',
+ status: '',
+ } as unknown as PatrolRunRecord);
+
+ // runId || undefined, normalizeText(run.type) || undefined,
+ // normalizeText(run.status) || undefined -> all collapse to undefined.
+ expect(handoff.context.targetId).toBeUndefined();
+ expect(handoff.context.handoffMetadata?.runId).toBeUndefined();
+ expect(handoff.context.context?.runId).toBeUndefined();
+ expect(handoff.context.context?.runType).toBeUndefined();
+ expect(handoff.context.context?.status).toBeUndefined();
+ // run.status is absent, so the || 'unknown' arm is taken and surfaces on
+ // both the context and the handoff metadata.
+ expect(handoff.context.context?.effectiveStatus).toBe('unknown');
+ expect(handoff.context.handoffMetadata?.runStatus).toBe('unknown');
+ });
+
+ it('renders the coverage-facts fallback list from non-resource check counts', () => {
+ // resources_checked is 0 with no scope ids -> getPatrolRunCoverageSummary
+ // returns '' -> the fallback briefing-string list is used. Each non-zero
+ // *_checked count then contributes its fact string.
+ const handoff = buildPatrolRunAssistantHandoff({
+ id: 'run-cov',
+ type: 'full',
+ status: 'healthy',
+ resources_checked: 0,
+ nodes_checked: 1,
+ guests_checked: 1,
+ docker_checked: 1,
+ storage_checked: 1,
+ hosts_checked: 1,
+ truenas_checked: 1,
+ kubernetes_checked: 1,
+ } as unknown as PatrolRunRecord);
+
+ expect(handoff.context.briefing?.statusLabel).toContain('1 nodes');
+ expect(handoff.context.briefing?.statusLabel).toContain('1 VMs');
+ expect(handoff.context.briefing?.statusLabel).toContain('1 containers');
+ expect(handoff.context.briefing?.statusLabel).toContain('1 storage resources');
+ expect(handoff.context.briefing?.statusLabel).toContain('1 agents');
+ expect(handoff.context.briefing?.statusLabel).toContain('1 TrueNAS systems');
+ expect(handoff.context.briefing?.statusLabel).toContain('1 Kubernetes resources');
+ });
+
+ it('singularizes each outcome fact when exactly one of each was observed', () => {
+ const handoff = buildPatrolRunAssistantHandoff({
+ id: 'run-one',
+ type: 'full',
+ status: 'healthy',
+ new_findings: 1,
+ existing_findings: 1,
+ resolved_findings: 1,
+ rejected_findings: 1,
+ auto_fix_count: 1,
+ error_count: 1,
+ } as unknown as PatrolRunRecord);
+
+ expect(handoff.context.briefing?.evidence?.[0]).toBe(
+ '1 new finding; 1 existing finding; 1 resolved finding; 1 rejected finding; 1 auto-remediation; 1 error',
+ );
+ });
+
+ it('pluralizes each outcome fact when more than one was observed', () => {
+ const handoff = buildPatrolRunAssistantHandoff({
+ id: 'run-many',
+ type: 'full',
+ status: 'healthy',
+ new_findings: 2,
+ existing_findings: 2,
+ resolved_findings: 2,
+ rejected_findings: 2,
+ auto_fix_count: 2,
+ error_count: 2,
+ } as unknown as PatrolRunRecord);
+
+ expect(handoff.context.briefing?.evidence?.[0]).toBe(
+ '2 new findings; 2 existing findings; 2 resolved findings; 2 rejected findings; 2 auto-remediations; 2 errors',
+ );
+ });
+
+ it('singularizes and pluralizes the triage-flag effort fact', () => {
+ const one = buildPatrolRunAssistantHandoff({
+ id: 'run-eff1',
+ type: 'full',
+ status: 'healthy',
+ triage_flags: 1,
+ } as unknown as PatrolRunRecord);
+ expect(one.context.briefing?.detailLines).toContain('1 triage flag');
+
+ const two = buildPatrolRunAssistantHandoff({
+ id: 'run-eff2',
+ type: 'full',
+ status: 'healthy',
+ triage_flags: 2,
+ } as unknown as PatrolRunRecord);
+ expect(two.context.briefing?.detailLines).toContain('2 triage flags');
+ });
+
+ it('caps run handoff resources at eight and leaves the type unset for multi-type scopes', () => {
+ // scope_resource_types length != 1 -> resource type collapses to ''.
+ // Nine distinct ids -> the ninth is skipped once resources.size hits the cap.
+ const ids = Array.from({ length: 9 }, (_, i) => `res-${i + 1}`);
+ const handoff = buildPatrolRunAssistantHandoff({
+ id: 'run-cap',
+ type: 'scoped',
+ status: 'healthy',
+ scope_resource_ids: ids,
+ scope_resource_types: ['vm', 'host'],
+ } as unknown as PatrolRunRecord);
+
+ expect(handoff.context.context?.handoffResourceCount).toBe(8);
+ });
+});
+
+describe('buildPatrolConfigurationFailureHandoff (residual branches)', () => {
+ it('emits the Cause line using the identifier-formatted cause', () => {
+ // cause truthy arm of the Cause detail-line ternary.
+ const handoff = buildPatrolConfigurationFailureHandoff({
+ message: 'm',
+ readiness: { cause: 'model_unsupported_tools' },
+ });
+
+ expect(handoff.context.briefing?.detailLines).toContain('Cause: Model Unsupported Tools');
+ expect(handoff.context.context?.readinessCause).toBe('model_unsupported_tools');
+ });
+
+ it('omits the Cause line entirely when no cause is available', () => {
+ const handoff = buildPatrolConfigurationFailureHandoff({ message: 'm' });
+
+ expect(handoff.context.briefing?.detailLines).toEqual([]);
+ expect(handoff.context.briefing?.statusLabel).toBeUndefined();
+ });
+
+ it('withholds a detail whose key or value normalizes to empty', () => {
+ // formatSafeConfigurationFailureDetail early-return when key or value is empty.
+ const handoff = buildPatrolConfigurationFailureHandoff({
+ message: 'm',
+ details: {
+ ' ': 'visible',
+ empty_value: ' ',
+ good: 'kept',
+ },
+ });
+
+ expect(handoff.context.briefing?.evidence).toEqual(['Good: kept']);
+ });
+
+ it('passes a digits-only detail key through the identifier formatter unchanged', () => {
+ // formatIdentifierLabel('123') returns '123' - there is no [._-] to expand
+ // and no letter to title-case - so the label is the key verbatim WITHOUT
+ // the || fallback being taken. The genuine empty-formatter fallback arm is
+ // covered separately by the separator-only key case below.
+ const handoff = buildPatrolConfigurationFailureHandoff({
+ message: 'm',
+ details: { '123': 'value-here' },
+ });
+
+ expect(handoff.context.briefing?.evidence).toEqual(['123: value-here']);
+ });
+});
+
+describe('buildPatrolAssessmentAssistantHandoff (residual branches)', () => {
+ it('falls back to the default assessment title in both briefing and model context', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { description: 'only a description' },
+ activeFindings: [],
+ });
+
+ expect(handoff.context.briefing?.subject).toBe('Pulse Patrol assessment');
+ expect(handoff.context.handoffContext).toContain('Assessment: Pulse Patrol assessment');
+ });
+
+ it('drops findings that carry no id, title, resourceId, or record id, and tolerates a null list', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ activeFindings: [
+ { severity: 'critical' },
+ { title: 'kept-by-title' },
+ { resourceId: 'kept-by-resource' },
+ { investigationRecord: { id: 'rec-kept' } as unknown as InvestigationRecord },
+ ],
+ });
+
+ // activeFindingCount reflects the raw input length, but the severity-only
+ // finding (no id/title/resourceId/record id) is filtered out of the model
+ // context, so only three Finding lines render.
+ expect(handoff.context.context?.activeFindingCount).toBe(4);
+ expect(handoff.context.handoffContext).toContain('Finding 1: kept-by-title');
+ expect(handoff.context.handoffContext).toContain('Finding 3: Patrol finding');
+ expect(handoff.context.handoffContext).not.toContain('Finding 4:');
+ });
+
+ it('counts active findings as zero and omits actions when activeFindings is null', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({ activeFindings: null });
+
+ expect(handoff.context.context?.activeFindingCount).toBe(0);
+ expect(handoff.context.context?.pendingApprovalCount).toBe(0);
+ expect(handoff.context.handoffActions).toBeUndefined();
+ });
+
+ it('reports omitted findings and an omitted singular recent change in the model context', () => {
+ const findings = Array.from({ length: 6 }, (_, i) => ({
+ id: `f-${i + 1}`,
+ title: `Finding ${i + 1}`,
+ }));
+ const changes = Array.from({ length: 4 }, (_, i) => ({
+ id: `c-${i + 1}`,
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: `vm-${i + 1}`,
+ kind: 'metric_anomaly',
+ sourceType: 'heuristic',
+ confidence: 'high',
+ reason: `reason ${i + 1}`,
+ })) as unknown as ResourceChange[];
+
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: { recentChanges: changes },
+ activeFindings: findings,
+ });
+
+ // 6 findings, cap 5 -> 1 omitted (singular wording).
+ expect(handoff.context.handoffContext).toContain(
+ '1 additional Patrol finding omitted from this bounded handoff summary.',
+ );
+ // 4 recent changes, cap 3 -> 1 omitted (singular wording).
+ expect(handoff.context.handoffContext).toContain(
+ '1 additional recent change omitted from this bounded handoff summary.',
+ );
+ });
+
+ it('renders a finding context line with no resource, no id, and no status parts', () => {
+ // Bare finding: resource resolves to nothing, finding.id empty, no status
+ // fields -> each ternary takes its undefined arm.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: [{ title: 'Bare finding' }],
+ });
+
+ expect(handoff.context.handoffContext).toContain('Bare finding on affected resource');
+ // No "finding <id>" segment, no status segment -> the line is exactly the
+ // title-on-resource form with no trailing parts.
+ const ctx = handoff.context.handoffContext!;
+ const line = ctx.split('\n').find((l) => l.startsWith('Finding 1:'));
+ expect(line).toBe('Finding 1: Bare finding on affected resource');
+ });
+
+ it('surfaces record error, regression singular, and a divergent record approval id', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: [
+ {
+ id: 'f-1',
+ title: 'High CPU',
+ regressionCount: 1,
+ pendingApproval: { id: 'pa-1', status: 'approved', riskLevel: 'high' },
+ investigationRecord: {
+ id: 'rec-1',
+ finding_id: 'f-1',
+ subject: { resource_id: 'vm-1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ error: 'investigation aborted',
+ approval_id: 'rec-approval',
+ } as unknown as InvestigationRecord,
+ },
+ ],
+ });
+
+ const line = handoff.context
+ .handoffContext!.split('\n')
+ .find((l) => l.startsWith('Finding 1:'))!;
+ expect(line).toContain('regressed 1 time');
+ expect(line).toContain('investigation error investigation aborted');
+ expect(line).toContain('approval rec-approval');
+ // Non-pending approval posture is rendered as inline approval parts:
+ // "approved approval" (status) and "high risk" (risk label).
+ expect(line).toContain('approved approval');
+ expect(line).toContain('high risk');
+ });
+
+ it('renders metric fallback labels, singularized custom and non-plural labels, and the no-signal summary', () => {
+ // primaryLabel absent -> default 'Active findings' label; fixedLabel
+ // 'Categories' with value 1 -> singular 'category' (ies rule).
+ const primaryAndCategories = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ metricState: { primaryValue: 1, fixedValue: 1, fixedLabel: 'Categories' },
+ activeFindings: [],
+ });
+ expect(primaryAndCategories.context.briefing?.statusLabel).toContain('1 active finding');
+ expect(primaryAndCategories.context.briefing?.statusLabel).toContain('1 category');
+
+ // secondaryLabel absent (and distinct from the explicit primary label) ->
+ // default 'Warnings' label.
+ const secondaryFallback = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ metricState: { primaryLabel: 'Active findings', primaryValue: 1, secondaryValue: 1 },
+ activeFindings: [],
+ });
+ expect(secondaryFallback.context.briefing?.statusLabel).toContain('1 active finding');
+ expect(secondaryFallback.context.briefing?.statusLabel).toContain('1 warning');
+
+ // Non-plural label ('Fixed') with value 1 -> stays 'fixed'.
+ const fixedOne = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ metricState: { fixedValue: 1 },
+ activeFindings: [],
+ });
+ expect(fixedOne.context.briefing?.statusLabel).toContain('1 fixed');
+
+ // No metric values and no findings -> default attention summary.
+ const empty = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: [],
+ });
+ expect(empty.context.briefing?.statusLabel).toContain('No active Patrol findings');
+ });
+
+ it('always emits a Health line, defaulting the chip label to "Health" when no signal is present', () => {
+ // formatAssessmentHealth can never be empty because the chip label itself
+ // defaults to 'Health'; with no grade or score the line is just that label.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: [],
+ });
+
+ expect(handoff.context.handoffContext).toContain('\nHealth: Health');
+ });
+
+ it('includes verification sub-facts only when their timestamps are present', () => {
+ const withFacts = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ verification: {
+ title: 'Checked',
+ description: 'desc',
+ lastFullRunAt: '2026-01-01T00:00:00Z',
+ activityMixLabel: 'mix',
+ },
+ activeFindings: [],
+ });
+ expect(withFacts.context.handoffContext).toContain('last full run 2026-01-01T00:00:00Z');
+ expect(withFacts.context.handoffContext).toContain('recent activity mix mix');
+
+ const withoutFacts = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ verification: { title: 'Checked', description: 'desc' },
+ activeFindings: [],
+ });
+ expect(withoutFacts.context.handoffContext).not.toContain('last full run');
+ expect(withoutFacts.context.handoffContext).not.toContain('recent activity mix');
+ });
+
+ it('falls back to the Last Patrol label and returns undefined recency with no signal', () => {
+ const withTimestampOnly = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ recency: { timestamp: '2026-01-01T00:00:00Z' },
+ activeFindings: [],
+ });
+ expect(withTimestampOnly.context.handoffContext).toContain(
+ 'Last Patrol: Last Patrol 2026-01-01T00:00:00Z',
+ );
+
+ const withNothing = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ recency: null,
+ activeFindings: [],
+ });
+ expect(withNothing.context.handoffContext).not.toContain('\nLast Patrol:');
+ });
+
+ it('builds sparse correlation endpoints and their context/evidence lines', () => {
+ // Correlation with only a source_id (no names/types, no target id) ->
+ // endpoint name/type collapse to undefined; the empty target id means the
+ // target resource is never added.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ correlations: [
+ {
+ source_id: 'src-1',
+ event_pattern: 'p',
+ occurrences: 1,
+ avg_delay: 1,
+ } as unknown as ResourceCorrelation,
+ ],
+ },
+ activeFindings: [],
+ });
+
+ // Correlation context line renders the source id.
+ expect(handoff.context.handoffContext).toContain('Correlation 1: src-1');
+ // Only the source resource is added, with no name or type (empty target id
+ // is dropped by addAssessmentHandoffResource).
+ expect(handoff.context.handoffResources).toEqual([{ id: 'src-1' }]);
+ });
+
+ it('renders correlation context sub-facts (pattern, last seen, description) and full evidence join', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ correlations: [
+ {
+ source_id: 'src-1',
+ source_name: 'Source',
+ source_type: 'vm',
+ target_id: 'tgt-1',
+ target_name: 'Target',
+ target_type: 'host',
+ event_pattern: 'a -> b',
+ occurrences: 1,
+ avg_delay: 1,
+ confidence: 0.9,
+ last_seen: '2026-01-01T00:00:00Z',
+ description: 'correlated activity',
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+
+ const line = handoff.context
+ .handoffContext!.split('\n')
+ .find((l) => l.startsWith('Correlation 1:'))!;
+ // Both endpoints resolve -> the " to " join is used.
+ expect(line).toContain('Source');
+ expect(line).toContain(' to ');
+ expect(line).toContain('Target');
+ expect(line).toContain('last seen 2026-01-01T00:00:00Z');
+ expect(line).toContain('description correlated activity');
+ const evidence = handoff.context.briefing?.evidence ?? [];
+ expect(evidence.some((e) => e.includes('Source') && e.includes(' to '))).toBe(true);
+ expect(evidence.some((e) => e.includes('pattern'))).toBe(true);
+ });
+
+ it('renders sparse recent-change evidence and context sub-facts', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: 'c-1',
+ observedAt: '2026-01-01T00:00:00Z',
+ occurredAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'config_update',
+ sourceType: 'user_action',
+ sourceAdapter: 'proxmox_adapter',
+ confidence: 'medium',
+ actor: 'operator-one',
+ reason: 'manual edit',
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+
+ const line = handoff.context
+ .handoffContext!.split('\n')
+ .find((l) => l.startsWith('Recent Change 1:'))!;
+ expect(line).toContain('change c-1');
+ expect(line).toContain('resource vm-1');
+ expect(line).toContain('observed 2026-01-01T00:00:00Z');
+ expect(line).toContain('occurred 2026-01-01T00:00:00Z');
+ expect(line).toContain('source user action');
+ expect(line).toContain('adapter Proxmox Adapter');
+ expect(line).toContain('medium confidence');
+ expect(line).toContain('actor operator-one');
+ });
+
+ it('falls back to the change id then the bare resource token when no reason is present', () => {
+ const byId = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: 'c-id',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: '',
+ kind: 'activity',
+ sourceType: 'platform_event',
+ confidence: 'low',
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+ expect(byId.context.handoffContext).toContain('Recent Change 1: Activity: c-id');
+
+ const bare = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: '',
+ observedAt: '',
+ resourceId: '',
+ kind: 'metric_anomaly',
+ sourceType: 'heuristic',
+ confidence: 'low',
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+ expect(bare.context.handoffContext).toContain('Recent Change 1: Metric anomaly: resource');
+ });
+
+ it('renders a state-transition summary for differing states and keeps command-bearing wording', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: 'c-trans',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'state_transition',
+ from: 'offline',
+ to: 'online',
+ sourceType: 'pulse_diff',
+ confidence: 'high',
+ },
+ {
+ id: 'c-runbook',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'runbook_executed',
+ sourceType: 'agent_action',
+ confidence: 'high',
+ reason: 'ran the playbook',
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+
+ expect(handoff.context.handoffContext).toContain(
+ 'Recent Change 1: State transition: offline to online',
+ );
+ expect(handoff.context.handoffContext).toContain(
+ 'Recent Change 2: Runbook executed: execution event recorded',
+ );
+ });
+
+ it('formats the two-label related-resource list and a no-omission three-label list', () => {
+ const two = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: 'c-2',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'metric_anomaly',
+ sourceType: 'heuristic',
+ confidence: 'high',
+ reason: 'r',
+ relatedResources: ['alpha', 'beta'],
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+ expect(two.context.handoffContext).toContain('related resources alpha and beta');
+
+ const three = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: 'c-3',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'metric_anomaly',
+ sourceType: 'heuristic',
+ confidence: 'high',
+ reason: 'r',
+ relatedResources: ['alpha', 'beta', 'gamma'],
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+ expect(three.context.handoffContext).toContain('related resources alpha, beta, gamma');
+ });
+
+ it('caps assessment handoff resources at eight across many distinct resources', () => {
+ const findings = Array.from({ length: 5 }, (_, i) => ({
+ id: `f-${i + 1}`,
+ title: `F${i + 1}`,
+ resourceId: `finding-res-${i + 1}`,
+ }));
+ const changes = Array.from({ length: 3 }, (_, i) => ({
+ id: `c-${i + 1}`,
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: `change-res-${i + 1}`,
+ kind: 'metric_anomaly',
+ sourceType: 'heuristic',
+ confidence: 'high',
+ reason: 'r',
+ relatedResources: [`rel-${i + 1}-a`, `rel-${i + 1}-b`],
+ })) as unknown as ResourceChange[];
+
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: { recentChanges: changes },
+ activeFindings: findings,
+ });
+
+ // MAX_ASSESSMENT_RESOURCES = 8; the ninth distinct resource is dropped.
+ expect(handoff.context.handoffResources).toHaveLength(8);
+ });
+
+ it('caps assessment handoff actions at four when more action-bearing findings exist', () => {
+ const findings = Array.from({ length: 6 }, (_, i) => ({
+ id: `f-${i + 1}`,
+ title: `F${i + 1}`,
+ proposedFix: { description: `Restart ${i + 1}` },
+ }));
+
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: findings,
+ });
+
+ expect(handoff.context.handoffActions).toHaveLength(4);
+ });
+});
+
+describe('buildPatrolAssistantFindingHandoff (residual branches)', () => {
+ it('collapses findingId to undefined in both top-level and nested context when no id exists', () => {
+ const handoff = buildPatrolAssistantFindingHandoff({ title: 'T', subject: 'S' });
+
+ expect(handoff.context.findingId).toBeUndefined();
+ expect(handoff.context.context?.findingId).toBeUndefined();
+ expect(handoff.context.context?.investigationRecordId).toBeUndefined();
+ });
+
+ it('resolves the resource name from the record subject and from the subject string', () => {
+ // resourceName absent -> record subject.resource_name used.
+ const fromRecord = buildPatrolAssistantFindingHandoff({
+ title: 'T',
+ subject: 'S',
+ resourceId: 'r1',
+ investigationRecord: {
+ id: 'rec',
+ finding_id: 'f',
+ subject: { resource_id: 'r1', resource_name: 'From Record', resource_type: 'vm' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ } as unknown as InvestigationRecord,
+ });
+ expect(fromRecord.context.handoffResources?.[0]).toMatchObject({
+ id: 'r1',
+ name: 'From Record',
+ type: 'vm',
+ });
+
+ // resourceName and record absent -> falls back to the subject string; type
+ // and node collapse to undefined.
+ const fromSubject = buildPatrolAssistantFindingHandoff({
+ title: 'T',
+ subject: 'SubjectName',
+ resourceId: 'r2',
+ });
+ expect(fromSubject.context.handoffResources?.[0]).toMatchObject({
+ id: 'r2',
+ name: 'SubjectName',
+ type: undefined,
+ node: undefined,
+ });
+ });
+
+ it('uses the explicit resource name and type when provided', () => {
+ const handoff = buildPatrolAssistantFindingHandoff({
+ title: 'T',
+ subject: 'S',
+ resourceId: 'r1',
+ resourceName: 'Explicit',
+ resourceType: 'host',
+ });
+ expect(handoff.context.handoffResources?.[0]).toMatchObject({
+ id: 'r1',
+ name: 'Explicit',
+ type: 'host',
+ });
+ });
+
+ it('falls back to default finding/subject titles in the model context', () => {
+ const handoff = buildPatrolAssistantFindingHandoff({
+ title: '',
+ subject: '',
+ resourceId: 'r1',
+ });
+
+ expect(handoff.context.handoffContext).toContain('Finding: Patrol finding');
+ expect(handoff.context.handoffContext).toContain('Subject: affected resource');
+ });
+
+ it('renders rollback entries and an approved (non-pending) approval posture', () => {
+ const handoff = buildPatrolAssistantFindingHandoff({
+ id: 'f-1',
+ title: 'T',
+ subject: 'S',
+ resourceId: 'r1',
+ regressionCount: 1,
+ pendingApproval: { id: 'pa-1', status: 'approved', riskLevel: 'high' },
+ investigationRecord: {
+ id: 'rec',
+ finding_id: 'f-1',
+ subject: { resource_id: 'r1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ rollback: ['Restore prior config'],
+ } as unknown as InvestigationRecord,
+ });
+
+ // Rollback entries are mapped (the record has rollback summaries).
+ expect(handoff.context.handoffContext).toContain('Rollback 1: Restore prior config');
+ // The model context renders the approval via labelled context lines
+ // (Approval / Approval Status / Approval Risk), not the inline parts used
+ // by the assessment finding context line.
+ expect(handoff.context.handoffContext).toContain('Approval: pa-1');
+ expect(handoff.context.handoffContext).toContain('Approval Status: approved');
+ expect(handoff.context.handoffContext).toContain('Approval Risk: high');
+ // Regression singular wording.
+ expect(handoff.context.handoffContext).toContain('regressed 1 time');
+ });
+
+ it('includes destructive and rationale action-artifact facts when the fix carries them', () => {
+ const handoff = buildPatrolAssistantFindingHandoff({
+ id: 'f-1',
+ title: 'T',
+ subject: 'S',
+ resourceId: 'r1',
+ proposedFix: {
+ description: 'Restart',
+ rationale: 'wedged process',
+ destructive: true,
+ commandCount: 1,
+ },
+ });
+
+ expect(handoff.context.handoffContext).toContain('destructive action artifact');
+ expect(handoff.context.handoffContext).toContain('rationale wedged process');
+ });
+});
+
+describe('buildPatrolAssistantFindingHandoffActions (residual branches)', () => {
+ it('leaves finding/resource targeting undefined for an action with sparse finding fields', () => {
+ const [action] = buildPatrolAssistantFindingHandoffActions({
+ pendingApproval: { actionId: 'act-1' },
+ });
+
+ expect(action).toMatchObject({
+ actionId: 'act-1',
+ findingId: undefined,
+ targetResourceId: undefined,
+ targetResourceType: undefined,
+ fixId: undefined,
+ description: undefined,
+ });
+ });
+});
+
+describe('patrolAssistantFindingHandoffRequiresApprovalMode (residual branches)', () => {
+ it('requires approval when the record carries an approval id', () => {
+ expect(
+ patrolAssistantFindingHandoffRequiresApprovalMode({
+ investigationRecord: {
+ id: 'rec',
+ finding_id: 'f',
+ subject: { resource_id: 'r1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ approval_id: 'ap-1',
+ } as unknown as InvestigationRecord,
+ }),
+ ).toBe(true);
+ });
+
+ it('requires approval when only the record outcome is a governed action outcome', () => {
+ expect(
+ patrolAssistantFindingHandoffRequiresApprovalMode({
+ investigationRecord: {
+ id: 'rec',
+ finding_id: 'f',
+ subject: { resource_id: 'r1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ outcome: 'fix_executed',
+ } as unknown as InvestigationRecord,
+ }),
+ ).toBe(true);
+ });
+
+ it('does not require approval for a benign outcome', () => {
+ expect(
+ patrolAssistantFindingHandoffRequiresApprovalMode({
+ investigationRecord: {
+ id: 'rec',
+ finding_id: 'f',
+ subject: { resource_id: 'r1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ outcome: 'needs_attention',
+ } as unknown as InvestigationRecord,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('buildPatrolRemediationPlanAssistant (residual branches)', () => {
+ const planWithoutCommands: RemediationPlan = {
+ id: 'plan-1',
+ finding_id: 'f-1',
+ resource_id: 'r-1',
+ title: 'Restore service',
+ description: 'Restart and verify.',
+ risk_level: 'high',
+ status: 'pending',
+ created_at: '2026-01-01T00:00:00Z',
+ steps: [],
+ };
+
+ it('falls back to default titles and the no-command safety note for an empty plan', () => {
+ const modelContext = buildPatrolRemediationPlanAssistantModelContext({
+ title: '',
+ subject: '',
+ plan: planWithoutCommands,
+ });
+ const briefing = buildPatrolRemediationPlanAssistantBriefing({
+ title: '',
+ subject: '',
+ plan: planWithoutCommands,
+ });
+
+ expect(modelContext).toContain('Finding: Patrol finding on the affected resource');
+ expect(briefing.subject).toBe('Patrol finding on affected resource');
+ // No commands -> commandSummary undefined and the alternate safety note.
+ expect(briefing.commandSummary).toBeUndefined();
+ expect(briefing.safetyNote).toBe(
+ 'Assistant should decide remediation from evidence before any governed action.',
+ );
+ // No Governed Action Context line is emitted when commandSummary is absent.
+ expect(modelContext).not.toContain('Governed Action Context:');
+ });
+
+ it('renders the artifact line, risk status, and governed-action context for a plan with commands', () => {
+ const plan: RemediationPlan = {
+ ...planWithoutCommands,
+ steps: [{ order: 1, action: 'restart', command: 'systemctl restart x', risk_level: 'high' }],
+ };
+ const modelContext = buildPatrolRemediationPlanAssistantModelContext({
+ title: 'T',
+ subject: 'S',
+ plan,
+ });
+
+ expect(modelContext).toContain('Governed Action Context: 1 command recorded');
+ expect(modelContext).toContain('Treat this as approval state, not remediation guidance.');
+ });
+
+ it('omits the risk status segment and artifact line when the plan lacks them', () => {
+ const plan = {
+ id: 'plan-2',
+ finding_id: 'f-1',
+ resource_id: 'r-1',
+ title: '',
+ description: '',
+ risk_level: '',
+ status: '',
+ created_at: '2026-01-01T00:00:00Z',
+ steps: [],
+ } as unknown as RemediationPlan;
+ const briefing = buildPatrolRemediationPlanAssistantBriefing({
+ title: 'T',
+ subject: 'S',
+ plan,
+ });
+
+ expect(briefing.statusLabel).toBeUndefined();
+ expect(briefing.detailLines).toEqual([]);
+ });
+
+ it('counts rollback commands in the plan command summary', () => {
+ const plan: RemediationPlan = {
+ ...planWithoutCommands,
+ steps: [
+ { order: 1, action: 'a', rollback_command: 'systemctl stop x', risk_level: 'low' },
+ { order: 2, action: 'b', rollback_command: 'systemctl stop y', risk_level: 'low' },
+ ],
+ };
+ const briefing = buildPatrolRemediationPlanAssistantBriefing({
+ title: 'T',
+ subject: 'S',
+ plan,
+ });
+
+ expect(briefing.commandSummary).toBe('2 rollback commands recorded');
+ });
+});
+
+describe('buildPatrolAssistantFindingBriefing (residual branches)', () => {
+ it('falls back to default finding/subject titles', () => {
+ const briefing = buildPatrolAssistantFindingBriefing({
+ title: '',
+ subject: '',
+ findingStatus: 'active',
+ });
+
+ expect(briefing?.subject).toBe('Patrol finding on affected resource');
+ // severity/findingStatus are finding facts, not status parts in this
+ // briefing, so an empty status stays undefined.
+ expect(briefing?.statusLabel).toBeUndefined();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Residual v8 branch arms not reached by the cases above. Each test below
+// targets a specific uncovered conditional arm (the `||`/`??` fallback, the
+// falsy ternary alternate, or a singular/plural boundary) and asserts a real
+// observable value. Arms that are provably unreachable from any public entry
+// point are documented in GLM_REPORT_fe-patrolctx.md rather than faked here.
+// ---------------------------------------------------------------------------
+
+describe('buildPatrolConfigurationFailureHandoff (identifier fallback arms)', () => {
+ it('uses the raw cause verbatim when the identifier formatter collapses it to empty', () => {
+ // cause '...' is all separator chars: formatIdentifierLabel('...') returns
+ // '' (falsy) -> `formatIdentifierLabel(cause) || cause` falls back to the
+ // verbatim cause string.
+ const handoff = buildPatrolConfigurationFailureHandoff({
+ message: 'm',
+ readiness: { cause: '...' },
+ });
+
+ expect(handoff.context.briefing?.detailLines).toContain('Cause: ...');
+ expect(handoff.context.context?.readinessCause).toBe('...');
+ });
+
+ it('uses the raw detail key verbatim when the identifier formatter yields nothing', () => {
+ // formatSafeConfigurationFailureDetail: a key of all separators makes
+ // formatIdentifierLabel(normalizedKey) return '' -> `|| normalizedKey`.
+ const handoff = buildPatrolConfigurationFailureHandoff({
+ message: 'm',
+ details: { '...': 'plain-value' },
+ });
+
+ expect(handoff.context.briefing?.evidence).toEqual(['...: plain-value']);
+ });
+});
+
+describe('buildPatrolAssistantFindingHandoffActions (findingId source fallback)', () => {
+ it('derives the action findingId from the investigation record when the finding has no id', () => {
+ // finding.id absent -> normalizeText(finding.id) is '' (falsy) -> the
+ // record's finding_id arm of `finding.id || record.finding_id || undefined`.
+ const [action] = buildPatrolAssistantFindingHandoffActions({
+ investigationRecord: {
+ id: 'rec',
+ finding_id: 'rec-finding',
+ subject: { resource_id: 'r1' },
+ trigger: { detected_at: '2026-01-01T00:00:00Z' },
+ status: 'completed',
+ proposed_fix: { id: 'fix-1', description: 'Restart service' },
+ } as unknown as InvestigationRecord,
+ });
+
+ expect(action.findingId).toBe('rec-finding');
+ });
+});
+
+describe('buildPatrolInvestigationRecordPresentation (tool label fallback)', () => {
+ it('drops a tool name that the identifier formatter reduces to empty', () => {
+ // '___' is not a known tool and formatIdentifierLabel('___') returns '' ->
+ // `formatIdentifierLabel(normalized) || ''` -> '' -> filtered out by
+ // .filter(Boolean). A genuine unknown tool still resolves via the fallback.
+ const presentation = buildPatrolInvestigationRecordPresentation({
+ ...minimalRecord,
+ tools_used: ['___', 'custom.tool'],
+ });
+
+ expect(presentation.toolsUsed).toEqual(['Custom Tool']);
+ });
+});
+
+describe('buildPatrolRemediationPlanAssistantBriefing (non-array steps)', () => {
+ it('treats a non-array steps field as empty when computing the command summary', () => {
+ // Array.isArray(plan.steps) is false -> the `: []` arm -> no commands are
+ // counted -> commandSummary stays undefined.
+ const plan = {
+ id: 'plan-1',
+ finding_id: 'f-1',
+ resource_id: 'r-1',
+ title: 'Restore',
+ description: 'desc',
+ risk_level: 'low',
+ status: 'pending',
+ created_at: '2026-01-01T00:00:00Z',
+ steps: 'not-an-array',
+ } as unknown as RemediationPlan;
+
+ const briefing = buildPatrolRemediationPlanAssistantBriefing({
+ title: 'T',
+ subject: 'S',
+ plan,
+ });
+
+ expect(briefing.commandSummary).toBeUndefined();
+ expect(briefing.safetyNote).toBe(
+ 'Assistant should decide remediation from evidence before any governed action.',
+ );
+ });
+});
+
+describe('buildPatrolAssessmentAssistantHandoff (correlation filter + sparse endpoints)', () => {
+ it('keeps a correlation that carries only an event_pattern', () => {
+ // The correlation filter `||` chain falls through source_id, source_name,
+ // target_id and target_name (all empty) and is retained by event_pattern.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ correlations: [
+ {
+ event_pattern: 'cpu-spike',
+ occurrences: 1,
+ avg_delay: 1,
+ } as unknown as ResourceCorrelation,
+ ],
+ },
+ activeFindings: [],
+ });
+
+ // Both endpoints resolve to undefined (no source/target ids or names), so
+ // the context line is kept solely by its pattern/summary facts.
+ expect(handoff.context.handoffContext).toContain('Correlation 1:');
+ expect(handoff.context.handoffContext).toContain('pattern');
+ });
+
+ it('renders a target-only correlation and omits the pattern fact when event_pattern is absent', () => {
+ // source endpoint undefined, target endpoint present -> `source && target`
+ // is falsy -> alternate `source || target` evaluates target. With no
+ // event_pattern the pattern fact takes its `: undefined` arm.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ correlations: [
+ {
+ target_id: 'tgt-1',
+ target_name: 'Target',
+ target_type: 'host',
+ occurrences: 1,
+ avg_delay: 1,
+ } as unknown as ResourceCorrelation,
+ ],
+ },
+ activeFindings: [],
+ });
+
+ const line = handoff.context
+ .handoffContext!.split('\n')
+ .find((l) => l.startsWith('Correlation 1:'))!;
+ expect(line).toContain('Target');
+ expect(line).not.toContain('pattern');
+ });
+
+ it('falls back to the "Items" metric label when the provided label is whitespace-only', () => {
+ // primaryLabel ' ' is a truthy string so the caller's `|| 'Active
+ // findings'` keeps it, but normalizeText trims it to '' inside
+ // formatAssessmentMetricCount -> `normalizeText(label) || 'Items'`. With a
+ // singular value the 'Items' label is singularized to 'item'.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ metricState: { primaryLabel: ' ', primaryValue: 1 },
+ activeFindings: [],
+ });
+
+ expect(handoff.context.briefing?.statusLabel).toContain('1 item');
+ });
+
+ it('renders a single related-resource label without an omitted-count suffix', () => {
+ // formatAssessmentRelatedResourceList: labels.length === 1 with omittedCount
+ // 0 -> the bare-label arm (the omittedCount > 0 arm is unreachable here
+ // because a single visible label always implies zero omitted).
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ supportingEvidence: {
+ recentChanges: [
+ {
+ id: 'c-1',
+ observedAt: '2026-01-01T00:00:00Z',
+ resourceId: 'vm-1',
+ kind: 'metric_anomaly',
+ sourceType: 'heuristic',
+ confidence: 'high',
+ reason: 'r',
+ relatedResources: ['solo'],
+ },
+ ],
+ },
+ activeFindings: [],
+ });
+
+ expect(handoff.context.handoffContext).toContain('related resources solo');
+ expect(handoff.context.handoffContext).not.toContain('and 0 more');
+ });
+
+ it('pluralizes the regression count in the assessment finding context line', () => {
+ // regressionCount > 1 -> the 's' arm of `regressionCount === 1 ? '' : 's'`.
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: [{ id: 'f-1', title: 'High CPU', regressionCount: 3 }],
+ });
+
+ const line = handoff.context
+ .handoffContext!.split('\n')
+ .find((l) => l.startsWith('Finding 1:'))!;
+ expect(line).toContain('regressed 3 times');
+ });
+
+ it('reports plural omitted findings when more than one is truncated', () => {
+ // 7 findings, cap 5 -> 2 omitted -> the 's' arm of the findings-omitted
+ // ternary.
+ const findings = Array.from({ length: 7 }, (_, i) => ({
+ id: `f-${i + 1}`,
+ title: `F${i + 1}`,
+ }));
+
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: { title: 'T' },
+ activeFindings: findings,
+ });
+
+ expect(handoff.context.handoffContext).toContain(
+ '2 additional Patrol findings omitted from this bounded handoff summary.',
+ );
+ });
+});
+
+describe('buildPatrolAssistantFindingHandoff (regression plural arm)', () => {
+ it('pluralizes the regression count in the finding model context', () => {
+ const handoff = buildPatrolAssistantFindingHandoff({
+ id: 'f-1',
+ title: 'T',
+ subject: 'S',
+ resourceId: 'r1',
+ regressionCount: 2,
+ });
+
+ expect(handoff.context.handoffContext).toContain('regressed 2 times');
+ });
+});
diff --git a/frontend-modern/src/features/truenas/__tests__/truenasPageModel.branchcov0723pm.test.ts b/frontend-modern/src/features/truenas/__tests__/truenasPageModel.branchcov0723pm.test.ts
new file mode 100644
index 0000000000..0a59857e5e
--- /dev/null
+++ b/frontend-modern/src/features/truenas/__tests__/truenasPageModel.branchcov0723pm.test.ts
@@ -0,0 +1,407 @@
+import { describe, expect, it } from 'vitest';
+import type { RecoveryPoint } from '@/types/recovery';
+import type { Resource } from '@/types/resource';
+import {
+ buildTrueNASIncidentRows,
+ buildTrueNASServiceRows,
+ buildTrueNASStorageTopologyRows,
+ filterTrueNASApps,
+ filterTrueNASIncidents,
+ filterTrueNASProtectionPoints,
+ filterTrueNASShares,
+ filterTrueNASStorageTopologyRows,
+ filterTrueNASVMs,
+ sortTrueNASProtectionPoints,
+} from '../truenasPageModel';
+
+// Branch-coverage completion: these specs target the residual fallback arms
+// left uncovered by the happy-path suites. Every assertion proves a specific
+// branch of the named function returns a concrete observable value.
+
+const makeResource = (resource: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({
+ name: resource.id,
+ displayName: resource.id,
+ platformId: 'lab',
+ platformType: 'truenas',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...resource,
+});
+
+const makeRecoveryPoint = (
+ point: Partial<RecoveryPoint> & Pick<RecoveryPoint, 'id' | 'kind' | 'mode'>,
+): RecoveryPoint => ({
+ outcome: 'success',
+ platform: 'truenas',
+ startedAt: '2026-05-20T00:00:00Z',
+ completedAt: '2026-05-20T00:00:00Z',
+ ...point,
+});
+
+describe('truenasPageModel branchcov0723pm', () => {
+ describe('compareStorageResources tiebreakers (via buildTrueNASStorageTopologyRows sort)', () => {
+ // compareStorageResources: rank -> displayName -> parentName -> id.
+ // The existing suite only sorted pools with distinct status ranks, so the
+ // name/parent/id tiebreak arms were never reached.
+
+ it('breaks a rank tie by display-name localeCompare (nameDelta !== 0 return)', () => {
+ const tank = makeResource({
+ id: 'pool-tank',
+ type: 'pool',
+ name: 'tank',
+ displayName: 'tank',
+ status: 'online',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const archive = makeResource({
+ id: 'pool-archive',
+ type: 'pool',
+ name: 'archive',
+ displayName: 'archive',
+ status: 'online',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const rows = buildTrueNASStorageTopologyRows([tank, archive]);
+ // Both healthy (rank 3); 'archive' < 'tank' so archive sorts first.
+ expect(rows.map((row) => row.id)).toEqual(['pool:pool-archive', 'pool:pool-tank']);
+ });
+
+ it('breaks a name tie by parentName localeCompare (parentDelta !== 0 return)', () => {
+ const onNasB = makeResource({
+ id: 'pool-on-b',
+ type: 'pool',
+ name: 'tank',
+ displayName: 'tank',
+ parentName: 'nas-b',
+ status: 'online',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const onNasA = makeResource({
+ id: 'pool-on-a',
+ type: 'pool',
+ name: 'tank',
+ displayName: 'tank',
+ parentName: 'nas-a',
+ status: 'online',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const rows = buildTrueNASStorageTopologyRows([onNasB, onNasA]);
+ // Same rank, same name; 'nas-a' < 'nas-b' so pool-on-a sorts first.
+ expect(rows.map((row) => row.id)).toEqual(['pool:pool-on-a', 'pool:pool-on-b']);
+ });
+
+ it('falls back to "" via ?? when parentName is blank, then breaks the tie by id', () => {
+ const e = makeResource({
+ id: 'pool-e',
+ type: 'pool',
+ name: 'tank',
+ displayName: 'tank',
+ status: 'online',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const f = makeResource({
+ id: 'pool-f',
+ type: 'pool',
+ name: 'tank',
+ displayName: 'tank',
+ status: 'online',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const rows = buildTrueNASStorageTopologyRows([f, e]);
+ // parentName absent -> asTrimmedString -> ?? '' -> parentDelta 0 -> id
+ // tiebreak: 'pool-e' < 'pool-f'.
+ expect(rows.map((row) => row.id)).toEqual(['pool:pool-e', 'pool:pool-f']);
+ });
+ });
+
+ describe('compareServiceRows tiebreakers + serviceStatusRank attention (via buildTrueNASServiceRows)', () => {
+ it('hits the attention case of serviceStatusRank and orders it before running', () => {
+ // webdav FAILED -> attention (rank 0); smb RUNNING -> running (rank 3).
+ const system = makeResource({
+ id: 'sys',
+ type: 'agent',
+ displayName: 'sys',
+ truenas: {
+ services: [
+ { id: '1', service: 'smb', enabled: true, state: 'RUNNING' },
+ { id: '2', service: 'webdav', enabled: true, state: 'FAILED' },
+ ],
+ },
+ });
+ const rows = buildTrueNASServiceRows([system]);
+ // attention (0) sorts before running (3).
+ expect(rows.map((row) => row.service.service)).toEqual(['webdav', 'smb']);
+ });
+
+ it('breaks a rank tie by systemName localeCompare (systemDelta !== 0 return)', () => {
+ const nasB = makeResource({
+ id: 'sys-b',
+ type: 'agent',
+ name: 'nas-b',
+ displayName: 'nas-b',
+ truenas: { services: [{ id: '1', service: 'smb', enabled: true, state: 'RUNNING' }] },
+ });
+ const nasA = makeResource({
+ id: 'sys-a',
+ type: 'agent',
+ name: 'nas-a',
+ displayName: 'nas-a',
+ truenas: { services: [{ id: '1', service: 'nfs', enabled: true, state: 'RUNNING' }] },
+ });
+ const rows = buildTrueNASServiceRows([nasB, nasA]);
+ // Both running (rank 3); 'nas-a' < 'nas-b' so nfs sorts first.
+ expect(rows.map((row) => row.service.service)).toEqual(['nfs', 'smb']);
+ });
+
+ it('breaks a systemName tie by serviceDisplayName localeCompare', () => {
+ const system = makeResource({
+ id: 'sys',
+ type: 'agent',
+ displayName: 'sys',
+ truenas: {
+ services: [
+ { id: '1', service: 'smb', enabled: true, state: 'RUNNING' },
+ { id: '2', service: 'nfs', enabled: true, state: 'RUNNING' },
+ ],
+ },
+ });
+ const rows = buildTrueNASServiceRows([system]);
+ // Same rank, same system; 'nfs' < 'smb'.
+ expect(rows.map((row) => row.service.service)).toEqual(['nfs', 'smb']);
+ });
+ });
+
+ describe('owningDatasetId parent-walk short-circuit (via buildTrueNASStorageTopologyRows)', () => {
+ it('short-circuits the parent && isTrueNASPoolResource check when parentId is not a storage row', () => {
+ // The dataset's parentId points at an agent, which is absent from the
+ // storage-only resourceById map, so resourceById.get(...) is undefined
+ // and both `parent && ...` guards short-circuit. The dataset lands at
+ // the root because no pool/dataset ancestor is resolvable.
+ const system = makeResource({ id: 'sys', type: 'agent' });
+ const dataset = makeResource({
+ id: 'ds-rootless',
+ type: 'dataset',
+ name: 'tank/media',
+ parentId: system.id,
+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },
+ });
+ const rows = buildTrueNASStorageTopologyRows([system, dataset]);
+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([
+ ['dataset:ds-rootless', 0, undefined],
+ ]);
+ });
+
+ it('continues the parent walk through a disk when the dataset parentId is a disk', () => {
+ // A disk is in the storage resourceById map but is neither pool nor
+ // dataset, so owningDatasetId must not short-circuit on it: it reads
+ // parent?.parentId (the defined arm) and walks on to the pool. The
+ // dataset ultimately nests under the pool that owns the disk.
+ const pool = makeResource({
+ id: 'pool-tank',
+ type: 'pool',
+ name: 'tank',
+ storage: { topology: 'pool', platform: 'truenas' },
+ });
+ const disk = makeResource({
+ id: 'disk-sda',
+ type: 'physical_disk',
+ name: 'sda',
+ parentId: pool.id,
+ physicalDisk: { devPath: '/dev/sda', serial: 'x' },
+ });
+ const dataset = makeResource({
+ id: 'ds-x',
+ type: 'dataset',
+ name: 'tank/x',
+ parentId: disk.id,
+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/x' },
+ });
+ const rows = buildTrueNASStorageTopologyRows([pool, disk, dataset]);
+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([
+ ['pool:pool-tank', 0, undefined],
+ ['dataset:ds-x', 1, 'pool:pool-tank'],
+ ['disk:disk-sda', 1, 'pool:pool-tank'],
+ ]);
+ });
+ });
+
+ describe('sortTrueNASProtectionPoints label-fallback chain arms', () => {
+ // Each operand of the `||` chain must be the resolving label for both
+ // sides at least once. Equal timestamps force the label tiebreak.
+
+ it('resolves both labels via display.subjectLabel (itemLabel absent)', () => {
+ const z = makeRecoveryPoint({
+ id: 'z-id',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ display: { subjectLabel: 'zzz' },
+ });
+ const a = makeRecoveryPoint({
+ id: 'a-id',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ display: { subjectLabel: 'aaa' },
+ });
+ expect(sortTrueNASProtectionPoints([z, a]).map((p) => p.id)).toEqual(['a-id', 'z-id']);
+ });
+
+ it('resolves both labels via itemRef.name (display absent)', () => {
+ const z = makeRecoveryPoint({
+ id: 'z-id',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ itemRef: { type: 'truenas-dataset', name: 'zzz' },
+ });
+ const a = makeRecoveryPoint({
+ id: 'a-id',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ itemRef: { type: 'truenas-dataset', name: 'aaa' },
+ });
+ expect(sortTrueNASProtectionPoints([z, a]).map((p) => p.id)).toEqual(['a-id', 'z-id']);
+ });
+
+ it('resolves both labels via subjectRef.name (display and itemRef absent)', () => {
+ const z = makeRecoveryPoint({
+ id: 'z-id',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ subjectRef: { type: 'truenas-dataset', name: 'zzz' },
+ });
+ const a = makeRecoveryPoint({
+ id: 'a-id',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ subjectRef: { type: 'truenas-dataset', name: 'aaa' },
+ });
+ expect(sortTrueNASProtectionPoints([z, a]).map((p) => p.id)).toEqual(['a-id', 'z-id']);
+ });
+ });
+
+ describe('trueNASProtectionSearchTokens subjectRef optional-chaining arms (via filterTrueNASProtectionPoints)', () => {
+ it('matches by subjectRef namespace, uid, id, and name when subjectRef is fully populated', () => {
+ const point = makeRecoveryPoint({
+ id: 'p',
+ kind: 'snapshot',
+ mode: 'snapshot',
+ subjectRef: {
+ type: 'truenas-dataset',
+ namespace: 'subj-ns-token',
+ name: 'subj-name-token',
+ uid: 'subj-uid-token',
+ id: 'subj-id-token',
+ },
+ });
+ expect(
+ filterTrueNASProtectionPoints([point], 'subj-ns-token', 'all').map((p) => p.id),
+ ).toEqual(['p']);
+ expect(
+ filterTrueNASProtectionPoints([point], 'subj-uid-token', 'all').map((p) => p.id),
+ ).toEqual(['p']);
+ expect(
+ filterTrueNASProtectionPoints([point], 'subj-id-token', 'all').map((p) => p.id),
+ ).toEqual(['p']);
+ expect(
+ filterTrueNASProtectionPoints([point], 'subj-name-token', 'all').map((p) => p.id),
+ ).toEqual(['p']);
+ });
+ });
+
+ describe('matchesTrueNASStorageSearch metricsTarget optional-chaining (via filterTrueNASStorageTopologyRows)', () => {
+ it('matches a storage row by metricsTarget.resourceId', () => {
+ const pool = makeResource({
+ id: 'tank',
+ type: 'pool',
+ storage: { topology: 'pool', platform: 'truenas' },
+ metricsTarget: { resourceType: 'storage', resourceId: 'metrics-target-token' },
+ });
+ const rows = buildTrueNASStorageTopologyRows([pool]);
+ expect(
+ filterTrueNASStorageTopologyRows(rows, 'metrics-target-token', 'all').map((r) => r.id),
+ ).toEqual(['pool:tank']);
+ });
+ });
+
+ describe('buildIncidentRow severity fallback to "info"', () => {
+ it('defaults severity to info when incident and resource severity are both blank', () => {
+ // Non-blank summary keeps the incident past hasIncidentSignal; both
+ // severity sources blank forces the final || 'info' arm.
+ const resource = makeResource({
+ id: 'r',
+ type: 'pool',
+ incidents: [{ code: 'truenas_x', severity: ' ', summary: 'something happened' }],
+ });
+ const row = buildTrueNASIncidentRows([resource])[0];
+ expect(row?.severity).toBe('info');
+ expect(row?.severityBucket).toBe('info');
+ });
+ });
+
+ describe('buildTrueNASIncidentRows sort priority tiebreak', () => {
+ it('breaks a severity-rank tie by priority descending (priorityDelta !== 0 return)', () => {
+ // Both critical (rank 3). Higher priority sorts first even though its
+ // resource name would sort later alphabetically, proving the priority
+ // comparator decides the order rather than the name fallback.
+ const highPriorityLateName = makeResource({
+ id: 'r-z',
+ type: 'pool',
+ incidentPriority: 100,
+ incidents: [{ code: 'cz', severity: 'critical', summary: 'sz' }],
+ });
+ const lowPriorityEarlyName = makeResource({
+ id: 'r-a',
+ type: 'pool',
+ incidentPriority: 50,
+ incidents: [{ code: 'ca', severity: 'critical', summary: 'sa' }],
+ });
+ const rows = buildTrueNASIncidentRows([highPriorityLateName, lowPriorityEarlyName]);
+ expect(rows.map((row) => row.resourceId)).toEqual(['r-z', 'r-a']);
+ });
+ });
+
+ describe('filter empty-needle early-return arms', () => {
+ it('filterTrueNASApps keeps every app when the needle is blank', () => {
+ const a = makeResource({ id: 'a', type: 'app-container' });
+ const b = makeResource({ id: 'b', type: 'app-container' });
+ expect(filterTrueNASApps([a, b], '', 'all').map((app) => app.id)).toEqual(['a', 'b']);
+ });
+
+ it('filterTrueNASVMs keeps every vm when the needle is blank', () => {
+ const a = makeResource({ id: 'a', type: 'vm' });
+ const b = makeResource({ id: 'b', type: 'vm' });
+ expect(filterTrueNASVMs([a, b], '', 'all').map((vm) => vm.id)).toEqual(['a', 'b']);
+ });
+
+ it('filterTrueNASShares keeps every share when the needle is blank', () => {
+ const a = makeResource({ id: 'a', type: 'network-share' });
+ const b = makeResource({ id: 'b', type: 'network-share' });
+ expect(filterTrueNASShares([a, b], '', 'all').map((share) => share.id)).toEqual(['a', 'b']);
+ });
+
+ it('filterTrueNASIncidents keeps every row when the needle is blank', () => {
+ const resource = makeResource({
+ id: 'r',
+ type: 'pool',
+ incidents: [{ code: 'truenas_x', severity: 'info', summary: 's' }],
+ });
+ const rows = buildTrueNASIncidentRows([resource]);
+ expect(filterTrueNASIncidents(rows, '', 'all')).toHaveLength(rows.length);
+ });
+ });
+
+ describe('incidentSearchHaystack truenas.hostname optional-chaining (via filterTrueNASIncidents)', () => {
+ it('matches an incident row by the resource truenas.hostname', () => {
+ const resource = makeResource({
+ id: 'r',
+ type: 'pool',
+ truenas: { hostname: 'incident-host-token' },
+ incidents: [{ code: 'truenas_x', severity: 'info', summary: 's' }],
+ });
+ const rows = buildTrueNASIncidentRows([resource]);
+ expect(
+ filterTrueNASIncidents(rows, 'incident-host-token', 'all').map((row) => row.resourceId),
+ ).toEqual(['r']);
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.ts
new file mode 100644
index 0000000000..05005a8ce5
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.ts
@@ -0,0 +1,614 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ canonicalizeRealtimeResource,
+ mergeCanonicalResource,
+ mergeCanonicalResourceSnapshot,
+ nodeFromResource,
+ pbsInstanceFromResource,
+ pmgInstanceFromResource,
+} from '../resourceStateAdapters';
+import type { Resource } from '@/types/resource';
+
+// Branch-coverage supplement for resourceStateAdapters.ts. These tests
+// exercise the fallback / default arms that the happy-path suites
+// (resourceStateAdapters.test.ts, .coverage.test.ts, .coverage2.test.ts)
+// leave untouched: absent/partial platform payloads, unknown status strings,
+// missing nested metric objects, and the zero-vs-undefined numeric
+// distinctions inside buildMemory / buildDisk and the PBS/PMG mappers.
+//
+// The module-private helpers (asNumber, asString, normalizeSourceToken,
+// sourceListHas, buildMemory, mapPBS*, mapPMG*, ...) are only reachable
+// through the exported entry points below, so every test drives a public
+// export and asserts an observable, specific value.
+
+// ---------------------------------------------------------------------------
+// Fixture builders (mirroring the conventions in coverage2.test.ts).
+// ---------------------------------------------------------------------------
+
+const agent = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'agent-1',
+ type: 'agent',
+ name: 'agent-name',
+ displayName: 'Agent',
+ platformId: 'agent-1',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+ }) as Resource;
+
+const pbsResource = (
+ pbsFacet: Record<string, unknown>,
+ overrides: Partial<Resource> = {},
+): Resource =>
+ ({
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'pbs-name',
+ displayName: 'PBS',
+ platformId: 'pbs-1',
+ platformType: 'proxmox-pbs',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ cpu: { current: 0 },
+ memory: { current: 0, total: 0, used: 0 },
+ disk: { current: 0, total: 0, used: 0 },
+ platformData: { pbs: pbsFacet },
+ ...overrides,
+ }) as Resource;
+
+const pmgResource = (
+ pmgFacet: Record<string, unknown>,
+ overrides: Partial<Resource> = {},
+): Resource =>
+ ({
+ id: 'pmg-1',
+ type: 'pmg',
+ name: 'pmg-name',
+ displayName: 'PMG',
+ platformId: 'pmg-1',
+ platformType: 'proxmox-pmg',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ cpu: { current: 0 },
+ memory: { current: 0, total: 0, used: 0 },
+ disk: { current: 0, total: 0, used: 0 },
+ platformData: { pmg: pmgFacet },
+ ...overrides,
+ }) as Resource;
+
+const pd = (r: Resource): Record<string, unknown> =>
+ (r.platformData ?? {}) as Record<string, unknown>;
+
+// ===========================================================================
+// normalizeSourceToken / sourceListHas — the `|| value.trim().toLowerCase()`
+// fallback arm is only evaluated when normalizeSourcePlatformKey() rejects the
+// token. Reach it by merging a resource whose authoritative sources contain a
+// token the platform-key map does not recognise.
+// ===========================================================================
+
+describe('normalizeSourceToken unknown-token fallback (via mergeCanonicalResource)', () => {
+ it('evaluates the trim/lowercase fallback for an unmapped source token and drops non-matching facets', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['custom-xyz'], agent: { hostname: 'incoming' } },
+ }),
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['custom-xyz'], agent: { hostname: 'existing' } },
+ }),
+ );
+ // 'agent' is not in the authoritative ['custom-xyz'] sources, so the
+ // merged agent facet is dropped — proving sourceListHas ran the unknown
+ // token through the fallback normaliser.
+ expect(pd(merged).agent).toBeUndefined();
+ expect(pd(merged).sources).toEqual(['custom-xyz']);
+ });
+});
+
+// ===========================================================================
+// mergePlatformData — `incomingSources ?? existingSources` fallback arm.
+// ===========================================================================
+
+describe('mergePlatformData sources fallback (via mergeCanonicalResource)', () => {
+ it('falls back to the existing sources when the incoming platformData has none', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { agent: { hostname: 'incoming' } },
+ }),
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'], agent: { hostname: 'existing' } },
+ }),
+ );
+ expect(pd(merged).sources).toEqual(['agent']);
+ expect((pd(merged).agent as Record<string, unknown>).hostname).toBe('incoming');
+ });
+});
+
+// ===========================================================================
+// deriveLegacySourceList — the per-facet `sources.push(...)` arms for pbs,
+// pmg, vmware and kubernetes (proxmox/docker/truenas/availability/agent are
+// already exercised by the happy-path suites).
+// ===========================================================================
+
+describe('deriveLegacySourceList facet detection (via canonicalizeRealtimeResource)', () => {
+ it('derives ["pbs"] from a lone pbs facet', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({ platformData: { pbs: { hostname: 'pbs.local' } } }),
+ );
+ expect(pd(result).sources).toEqual(['pbs']);
+ });
+
+ it('derives ["pmg"] from a lone pmg facet', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({ platformData: { pmg: { hostname: 'pmg.local' } } }),
+ );
+ expect(pd(result).sources).toEqual(['pmg']);
+ });
+
+ it('derives ["vmware"] from a lone vmware facet', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({ platformData: { vmware: { hostname: 'vc.local' } } }),
+ );
+ expect(pd(result).sources).toEqual(['vmware']);
+ });
+
+ it('derives ["kubernetes"] from a lone kubernetes facet', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({ platformData: { kubernetes: { nodeName: 'worker-1' } } }),
+ );
+ expect(pd(result).sources).toEqual(['kubernetes']);
+ });
+});
+
+// ===========================================================================
+// canonicalizeLegacyPlatformData — the `platformData.disks` carry-over arms
+// for the agent / docker / proxmox legacy-payload builders.
+// ===========================================================================
+
+describe('legacy payload disks carry-over (via canonicalizeRealtimeResource)', () => {
+ it('attaches disks to a synthesised agent payload', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { agentId: 'legacy-agent', disks: [{ device: 'sda', mountpoint: '/' }] },
+ }),
+ );
+ const agentFacet = pd(result).agent as Record<string, unknown> | undefined;
+ expect(agentFacet?.agentId).toBe('legacy-agent');
+ expect(agentFacet?.disks).toEqual([{ device: 'sda', mountpoint: '/' }]);
+ });
+
+ it('attaches disks to a synthesised docker payload', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({
+ platformType: 'docker',
+ sourceType: 'api',
+ platformData: { runtime: 'docker', disks: [{ device: 'sdb' }] },
+ }),
+ );
+ const dockerFacet = pd(result).docker as Record<string, unknown> | undefined;
+ expect(dockerFacet?.runtime).toBe('docker');
+ expect(dockerFacet?.disks).toEqual([{ device: 'sdb' }]);
+ });
+
+ it('attaches disks to a synthesised proxmox payload', () => {
+ const result = canonicalizeRealtimeResource(
+ agent({
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ platformData: { node: 'pve-1', disks: [{ device: 'sdc' }] },
+ }),
+ );
+ const proxmoxFacet = pd(result).proxmox as Record<string, unknown> | undefined;
+ expect(proxmoxFacet?.nodeName).toBe('pve-1');
+ expect(proxmoxFacet?.disks).toEqual([{ device: 'sdc' }]);
+ });
+});
+
+// ===========================================================================
+// canonicalizeRealtimeResource — the availability-consequent arm of the
+// platformType ternary (reached only when resolvePlatformTypeFromSources
+// cannot resolve the sources but an availability facet is still present).
+// ===========================================================================
+
+describe('platformType availability consequent (via canonicalizeRealtimeResource)', () => {
+ it('classifies as availability when sources are unmapped but an availability facet exists', () => {
+ const result = canonicalizeRealtimeResource({
+ id: 'a1',
+ type: 'agent',
+ name: 'a',
+ displayName: 'A',
+ platformId: 'a1',
+ platformType: 'generic',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ sources: ['custom-unknown'],
+ availability: { targetId: 'x' } as unknown as Resource['availability'],
+ } as Resource);
+ expect(result.platformType).toBe('availability');
+ });
+});
+
+// ===========================================================================
+// mergeCanonicalIdentity / mergeCanonicalResource — the no-existing and
+// platformType-?? fallback arms, plus the tags/labels truthy arms.
+// ===========================================================================
+
+describe('mergeCanonicalIdentity + merge fallbacks (via mergeCanonicalResource)', () => {
+ it('returns the incoming canonical identity unchanged when the existing resource has none', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ canonicalIdentity: { primaryId: 'inc-primary', hostname: 'h' },
+ }),
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ canonicalIdentity: undefined,
+ }),
+ );
+ expect(merged.canonicalIdentity?.primaryId).toBe('inc-primary');
+ });
+
+ it('falls back to the existing platformType when the incoming omits it', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: undefined as unknown as Resource['platformType'],
+ sourceType: 'hybrid',
+ platformData: { sources: ['proxmox', 'agent'] },
+ }),
+ agent({
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ platformData: { sources: ['proxmox', 'agent'] },
+ }),
+ );
+ // The incoming.platformType ?? existingCanonical.platformType arm feeds the
+ // scope normaliser, so platformScopes is derived from the existing
+ // proxmox-pve type even though the incoming platformType is absent.
+ expect(merged.platformScopes).toEqual(['proxmox-pve']);
+ });
+
+ it('keeps the incoming non-empty tags array', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ tags: ['new'],
+ }),
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ tags: ['old'],
+ }),
+ );
+ expect(merged.tags).toEqual(['new']);
+ });
+
+ it('keeps the incoming non-empty labels record', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ labels: { env: 'prod' },
+ }),
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'] },
+ labels: { env: 'dev' },
+ }),
+ );
+ expect(merged.labels).toEqual({ env: 'prod' });
+ });
+});
+
+// ===========================================================================
+// mergeCanonicalResourceSnapshot — empty-incoming early return, and the
+// getHostResourceMergeKey `undefined` arm (reached only when every identity
+// candidate — including the resource id — is blank).
+// ===========================================================================
+
+describe('mergeCanonicalResourceSnapshot edge arms', () => {
+ it('returns an empty array when the incoming snapshot is empty', () => {
+ const existing: Resource = agent({ platformData: { sources: ['agent'] } });
+ expect(mergeCanonicalResourceSnapshot([], [existing])).toEqual([]);
+ });
+
+ it('does not coalesce two agents whose every identity candidate is blank', () => {
+ const blank = (): Resource =>
+ ({
+ id: '',
+ type: 'agent',
+ name: '',
+ displayName: '',
+ platformId: '',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 100,
+ }) as unknown as Resource;
+ const out = mergeCanonicalResourceSnapshot([blank(), blank()], []);
+ // No host key derivable (getHostResourceMergeKey returns undefined) → both
+ // stay as separate entries instead of being coalesced.
+ expect(out).toHaveLength(2);
+ });
+});
+
+// ===========================================================================
+// nodeFromResource — non-agent guard, fully-blank identity host chain, missing
+// metrics, and the cpuInfo value-present arms.
+// ===========================================================================
+
+describe('nodeFromResource fallback arms', () => {
+ it('returns null for a non-agent resource', () => {
+ expect(nodeFromResource({ id: 'x', type: 'pbs' } as Resource)).toBeNull();
+ });
+
+ it('resolves host/status/cpu/connectionHealth/memory to defaults for a fully-blank agent', () => {
+ const node = nodeFromResource({
+ id: '',
+ type: 'agent',
+ name: '',
+ displayName: '',
+ platformId: '',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: '' as unknown as Resource['status'],
+ lastSeen: 1_700_000_000_000,
+ cpu: undefined,
+ memory: undefined,
+ } as unknown as Resource);
+ // preferredHostLabel chain falls through every resolver down to resource.id
+ expect(node?.host).toBe('');
+ expect(node?.status).toBe('unknown');
+ expect(node?.cpu).toBe(0);
+ expect(node?.connectionHealth).toBe('unknown');
+ // buildMemory with no metric and no fallback → every numeric ?? 0 arm.
+ expect(node?.memory.total).toBe(0);
+ expect(node?.memory.used).toBe(0);
+ expect(node?.memory.usage).toBe(0);
+ });
+
+ it('maps cpuInfo fields when proxmox.cpuInfo is fully populated', () => {
+ const node = nodeFromResource(
+ agent({
+ proxmox: {
+ nodeName: 'n1',
+ cpuInfo: { model: 'X86_64', cores: 8, sockets: 2, mhz: '3200' },
+ } as unknown as Resource['proxmox'],
+ }),
+ );
+ expect(node?.cpuInfo).toEqual({ model: 'X86_64', cores: 8, sockets: 2, mhz: '3200' });
+ });
+});
+
+// ===========================================================================
+// pbsInstanceFromResource — non-pbs guard, id-||'' arms for sync/verify/prune/
+// garbage jobs, hostName/status/connectionHealth fallbacks.
+// ===========================================================================
+
+describe('pbsInstanceFromResource fallback arms', () => {
+ it('returns null for a non-pbs resource', () => {
+ expect(pbsInstanceFromResource({ id: 'x', type: 'agent' } as Resource)).toBeNull();
+ });
+
+ it('defaults sync job id to empty string when absent', () => {
+ const instance = pbsInstanceFromResource(pbsResource({ syncJobs: [{ store: 's1' }] }));
+ expect(instance?.syncJobs[0]).toMatchObject({ id: '', store: 's1' });
+ });
+
+ it('defaults verify job id to empty string when absent', () => {
+ const instance = pbsInstanceFromResource(pbsResource({ verifyJobs: [{ store: 's1' }] }));
+ expect(instance?.verifyJobs[0]).toMatchObject({ id: '', store: 's1' });
+ });
+
+ it('defaults prune job id to empty string when absent', () => {
+ const instance = pbsInstanceFromResource(pbsResource({ pruneJobs: [{ store: 's1' }] }));
+ expect(instance?.pruneJobs[0]).toMatchObject({ id: '', store: 's1' });
+ });
+
+ it('defaults garbage job id to empty string when absent', () => {
+ const instance = pbsInstanceFromResource(pbsResource({ garbageJobs: [{ store: 's1' }] }));
+ expect(instance?.garbageJobs[0]).toMatchObject({ id: '', store: 's1', removedBytes: 0 });
+ });
+
+ it('falls back to resource.id for hostName when no hostname is resolvable', () => {
+ const instance = pbsInstanceFromResource(
+ pbsResource({}, { platformId: '', name: '', displayName: '' }),
+ );
+ // hostName === resource.id ('pbs-1'); platformId empty → synthesised URL.
+ expect(instance?.host).toBe('https://pbs-1:8007');
+ });
+
+ it('reports unknown status and connectionHealth when resource status is blank', () => {
+ const instance = pbsInstanceFromResource(
+ pbsResource({}, { status: '' as unknown as Resource['status'] }),
+ );
+ expect(instance?.status).toBe('unknown');
+ expect(instance?.connectionHealth).toBe('unknown');
+ });
+});
+
+// ===========================================================================
+// pmgInstanceFromResource — non-pmg guard, domain-||'' arm, hostName/status/
+// connectionHealth fallbacks.
+// ===========================================================================
+
+describe('pmgInstanceFromResource fallback arms', () => {
+ it('returns null for a non-pmg resource', () => {
+ expect(pmgInstanceFromResource({ id: 'x', type: 'agent' } as Resource)).toBeNull();
+ });
+
+ it('defaults domain stat domain to empty string when absent', () => {
+ const instance = pmgInstanceFromResource(pmgResource({ domainStats: [{ mailCount: 5 }] }));
+ expect(instance?.domainStats?.[0]).toMatchObject({ domain: '', mailCount: 5 });
+ });
+
+ it('falls back to resource.id for hostName when no hostname is resolvable', () => {
+ const instance = pmgInstanceFromResource(
+ pmgResource({}, { platformId: '', name: '', displayName: '' }),
+ );
+ expect(instance?.host).toBe('https://pmg-1:8006');
+ });
+
+ it('reports unknown status and connectionHealth when resource status is blank', () => {
+ const instance = pmgInstanceFromResource(
+ pmgResource({}, { status: '' as unknown as Resource['status'] }),
+ );
+ expect(instance?.status).toBe('unknown');
+ expect(instance?.connectionHealth).toBe('unknown');
+ });
+});
+
+// ===========================================================================
+// normalizeResourceIdentityToken — the `normalized.length > 0 ? normalized :
+// undefined` false arm. Only reachable via getHostResourceMergeKey, which runs
+// every identity candidate through the normaliser. A whitespace-only candidate
+// is truthy (so it skips the `!value` guard) but trims to ''.
+// ===========================================================================
+
+describe('normalizeResourceIdentityToken whitespace candidate (via mergeCanonicalResourceSnapshot)', () => {
+ it('drops a whitespace-only platformId candidate while still coalescing on a valid hostname', () => {
+ const mkAgent = (id: string, lastSeen: number): Resource =>
+ ({
+ id,
+ type: 'agent',
+ name: 'merge-host',
+ displayName: 'merge-host',
+ platformId: 'merge-host',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen,
+ canonicalIdentity: { platformId: ' ', hostname: 'merge-host' },
+ }) as unknown as Resource;
+
+ const out = mergeCanonicalResourceSnapshot([mkAgent('a', 100), mkAgent('b', 200)], []);
+ // The whitespace platformId candidate exercises the length===0 false arm
+ // (→ undefined) but 'merge-host' still forms hostKey 'agent:merge-host',
+ // so the two hybrid agents coalesce into one.
+ expect(out).toHaveLength(1);
+ });
+});
+
+// ===========================================================================
+// sourceListHas — the `!sources || sources.length === 0` early-return arm.
+// sourceListHas is only ever called with an empty/undefined list through
+// sourceListContainsRuntimePlatform when unionSources is undefined, which
+// happens when two coalescing agents each derive no canonical sources.
+// ===========================================================================
+
+describe('sourceListHas empty-sources arm (via mergeCanonicalResourceSnapshot)', () => {
+ it('does not merge two agents that share a host key but derive no canonical sources', () => {
+ const mkAgent = (id: string, lastSeen: number): Resource =>
+ ({
+ id,
+ type: 'agent',
+ name: 'gen-host',
+ displayName: 'gen-host',
+ platformId: 'gen-host',
+ platformType: 'generic',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen,
+ canonicalIdentity: { hostname: 'gen-host' },
+ }) as unknown as Resource;
+
+ const out = mergeCanonicalResourceSnapshot([mkAgent('a', 100), mkAgent('b', 200)], []);
+ // Both derive hostKey 'agent:gen-host', but getCanonicalSourceList returns
+ // undefined for each (generic + api, no facets) → unionSources undefined →
+ // sourceListHas(undefined, 'agent') takes its empty-sources arm → false.
+ expect(out).toHaveLength(2);
+ expect(out.map((r) => r.id).sort()).toEqual(['a', 'b']);
+ });
+});
+
+// ===========================================================================
+// readStringArray — the `normalized.length > 0 ? ... : undefined` false arm.
+// Reached when an array is supplied but every entry is blank after trim. The
+// only public path that feeds an already-arrayed platformData.sources through
+// readStringArray is mergePlatformData (mergeCanonicalResource).
+// ===========================================================================
+
+describe('readStringArray all-invalid arm (via mergeCanonicalResource)', () => {
+ it('treats a sources array of only blank entries as absent and falls back to existing sources', () => {
+ const merged = mergeCanonicalResource(
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: {
+ sources: ['', ' ', ' \t '],
+ agent: { hostname: 'incoming' },
+ },
+ }),
+ agent({
+ platformType: 'agent',
+ sourceType: 'agent',
+ platformData: { sources: ['agent'], agent: { hostname: 'existing' } },
+ }),
+ );
+ // readStringArray(['', ' ', ' \t ']) → every entry blank after trim →
+ // length 0 → returns undefined (false arm); mergePlatformData then falls
+ // back to existingSources ['agent'].
+ expect(pd(merged).sources).toEqual(['agent']);
+ expect((pd(merged).agent as Record<string, unknown>).hostname).toBe('incoming');
+ });
+});
+
+// ===========================================================================
+// buildDisk — the `total > 0 ? (used/total)*100 : (asNumber(fallback?.usage)
+// ?? 0)` false arm. This is the zero-vs-undefined distinction: an explicitly
+// zero metric.total is preserved by `??` (zero is not nullish), so the ratio
+// branch is skipped in favour of the fallback-usage default.
+// ===========================================================================
+
+describe('buildDisk zero-total usage fallback (via nodeFromResource)', () => {
+ it('uses fallback.usage when metric.current is absent and total is explicitly zero', () => {
+ const node = nodeFromResource(
+ agent({
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ proxmox: { nodeName: 'n1', disk: { usage: 7 } } as unknown as Resource['proxmox'],
+ disk: { total: 0, used: 0 } as unknown as Resource['disk'],
+ }),
+ );
+ // total === 0 (kept by ??) and metric.current absent → total > 0 is false →
+ // asNumber(fallback.usage) → 7.
+ expect(node?.disk.total).toBe(0);
+ expect(node?.disk.usage).toBe(7);
+ });
+
+ it('defaults usage to 0 when total is zero and no fallback usage exists', () => {
+ const node = nodeFromResource(
+ agent({
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ disk: { total: 0, used: 0 } as unknown as Resource['disk'],
+ }),
+ );
+ // No fallback at all → asNumber(undefined) ?? 0 → 0.
+ expect(node?.disk.usage).toBe(0);
+ });
+});