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.

Finish moving the last bespoke drawers onto the shared shape

[email protected]4aa3d7aa5f4c
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 4c9d934dec..eb045f0eea 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -5141,3 +5141,12 @@ saved-override retention. `ResourceTable.test.tsx` covers visible/reactive text
in both layouts. `browser-tests/guest-filesystem-thresholds.cjs` connects the
production hook, table and editors on desktop Chromium and phone WebKit,
including scoped refusal text, custom settings and same-VMID/mount separation.
+
+Frontend alert matching for PBS and PMG resources also keys on their
+`instanceId` (`getUnifiedResourceAlertKeys` in `frontend-modern/src/utils/alerts.ts`),
+the id `internal/alerts` writes as `ResourceID` for both (`pbs.ID`, `pmg.ID`).
+The platform tables already matched it; the drawers no longer depend on a
+metrics target being set to find the same alerts. Inside a guest drawer, a
+physical disk's agent temperature alerts (`agent:<id>/disk_temp:<device>`) are
+matched through the guest's own agent id. No alert is created, cleared or
+retyped by this; it changes which open alerts a drawer lists.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index d779595e2a..dc2495e166 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -854,14 +854,15 @@ acceptance.
### Stable physical-disk History composition
-Disk detail composes shared HistoryChart owners from stable disk-family catalog
+The disk drawer Overview (`DiskDrawerOverview`, also shown for a guest's own
+disks) composes the shared drawer history from stable disk-family catalog
entries, independently of the latest optional temperature/SMART fields. Matching
snapshots must not recreate chart DOM, reset inspection or restart reads. Stored
series retain their own sample provenance; current collection unavailability is
-still reported beside the SMART facts in the detail's single view (there is no
-History tab), and empty history is not a manufactured zero. The
+still reported beside the SMART facts on Overview (there is no History tab),
+and empty history is not a manufactured zero. The
shared target/range owner continues to cancel old selections and reject late
-responses. `DiskDetail.history-collection.test.tsx` and the production
+responses. `DiskDrawer.history-collection.test.tsx` and the production
`browser-tests/disk-history-collection.cjs` fixture verify these boundaries with
synthetic data; neither establishes native NAS health or installed acceptance.
@@ -10032,3 +10033,18 @@ share one panel in `DockerNativeTableShared.tsx`, Kubernetes records share
`KubernetesRecordDetail.tsx`, and hand-written `dl`/grid detail rows are
retired from Docker networks and storage usage, Proxmox replication, coverage
and recoverable points, and Agent Doctor.
+
+Full-width helper rows span the visible columns, never a guess. A
+`colspan={100}` windowing spacer or `colspan={99}` storage group row created
+phantom fixed-layout columns, and on phones (where hidden columns leave the
+visible percentages short of 100%) those columns took the rest of the table:
+rows and drawers on windowed Kubernetes tables stopped at 70% of the width.
+`components/shared/tableVisibleColumnSpan.ts` counts the header's visible
+cells (re-measuring on resize and header changes), and `PlatformWindowedRows`
+spacers, `StorageGroupRow` and the storage pool spacers use it.
+`DrawerAttentionSection` also owns `DrawerNoAlertsLine`, the one "No active
+alerts" line every drawer shows (with the optional availability note), and the
+attention card's subject wraps instead of truncating.
+`features/platformPage/platformDetailTimestampRow.ts` is the one drawer row for
+a reported timestamp (absolute time and age, wrapping, an optional sentinel
+year), replacing three copies.
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 8c59a9f97c..d1e21cc5bd 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -4416,3 +4416,13 @@ controls. `browser-tests/host-disk-usage.cjs` exercises the actual resource
HTTP/table/summary/drawer flow at desktop and touch widths. Disclosure adds no
measurement or storage operation. This is truthful presentation, not native
collector recovery or an installed performance result.
+
+Windowed platform tables keep their spacer rows to the visible columns:
+`PlatformWindowedRows` spacers span the header's visible cells
+(`components/shared/tableVisibleColumnSpan.ts`, re-measured on resize and
+header changes) instead of `colspan={100}`, which created phantom fixed-layout
+columns and left rows and drawers short of the table edge on phones. The
+windowing budget, runway and mounted-row counts are unchanged. The Docker host
+drawer loads its history charts lazily inside `Suspense` like the node and
+guest drawers, keeping them out of the table chunk, and its action history is
+fetched only when Manage opens.
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 0f83a1ac30..46a159ec6d 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -8295,14 +8295,15 @@
"test_prefixes": [],
"exact_files": [
"frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts",
- "frontend-modern/src/components/Storage/__tests__/DiskDetail.test.tsx",
+ "frontend-modern/src/components/Storage/__tests__/DiskDrawer.history-collection.test.tsx",
+ "frontend-modern/src/components/Storage/__tests__/DiskDrawer.test.tsx",
"frontend-modern/src/components/Storage/__tests__/DiskList.test.tsx",
"frontend-modern/src/components/Storage/__tests__/Storage.test.tsx",
"frontend-modern/src/components/Storage/__tests__/StorageGroupRow.test.tsx",
"frontend-modern/src/components/Storage/__tests__/StoragePoolDetail.test.tsx",
- "frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts",
"frontend-modern/src/components/Storage/__tests__/useStoragePoolsTableWindowing.test.ts",
"frontend-modern/src/components/Storage/code_standards.test.ts",
+ "frontend-modern/src/features/storageBackups/__tests__/diskDrawerPresentation.test.ts",
"frontend-modern/src/features/storageBackups/__tests__/diskPresentation.test.ts",
"frontend-modern/src/features/storageBackups/__tests__/resourceStorageMapping.test.ts",
"frontend-modern/src/features/storageBackups/__tests__/storageAdapters.test.ts",
@@ -8385,7 +8386,6 @@
"internal/unifiedresources/"
],
"owned_files": [
- "frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx",
"frontend-modern/src/components/Infrastructure/AvailabilityProbeStatusCard.tsx",
"frontend-modern/src/components/Infrastructure/ResourceActionHistory.tsx",
"frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx",
@@ -8405,7 +8405,6 @@
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDockerActionsState.ts",
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerHistoryState.ts",
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts",
- "frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx",
"frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx",
"frontend-modern/src/features/docker/DockerAlertsTable.tsx",
"frontend-modern/src/features/docker/DockerConfigsTable.tsx",
@@ -8576,7 +8575,6 @@
"label": "unified resource consumer proof",
"match_prefixes": [],
"match_files": [
- "frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx",
"frontend-modern/src/components/Infrastructure/AvailabilityProbeStatusCard.tsx",
"frontend-modern/src/components/Infrastructure/ResourceActionHistory.tsx",
"frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx",
@@ -8596,7 +8594,6 @@
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDockerActionsState.ts",
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerHistoryState.ts",
"frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts",
- "frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx",
"frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx",
"frontend-modern/src/features/docker/DockerAlertsTable.tsx",
"frontend-modern/src/features/docker/DockerConfigsTable.tsx",
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 8b4ba53e13..3eb530f37a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -363,9 +363,11 @@ whether the latest snapshot contains temperature or extended SMART values.
Temperature and ATA reallocated-sector charts, or temperature and NVMe
endurance/spare charts, query only the already-resolved canonical disk target.
A missing current field must not hide stored observations. An empty series is
-shown as no history samples, never a fabricated zero or current-value fallback.
+shown as no stored history in that range, never a fabricated zero or a plotted
+current-value fallback; the chart legend may still name the snapshot's reading,
+labelled current or last known.
Overview continues to report current collection availability; explicit
-unavailable/unsupported I/O still suppresses the existing live I/O section.
+unavailable/unsupported I/O still suppresses the disk drawer's I/O chart panels.
Catalog entries retain their identity across matching snapshots so ordinary
current-temperature changes cannot remount charts, drop inspection or restart
@@ -374,13 +376,21 @@ when the explicit target or range changes; a late cancelled response cannot
populate its replacement. This changes neither disk correlation nor collector,
retention, permission or entitlement policy, and proves no appliance recovery.
-Verification: `DiskDetail.test.tsx` and `useDiskDetailModel.test.ts` pin the
-catalog and matching-snapshot boundary; `DiskDetail.history-collection.test.tsx`
-uses the actual chart owner to cover absent current fields, stored zero versus
-empty, NVMe/ATA catalogs, request counts, preserved inspection and late former
-target responses. `frontend-modern/browser-tests/disk-history-collection.cjs`
-checks the production components/client/CSS with synthetic API data on desktop
-Chromium and touch/dark phone WebKit, not native NAS or installed acceptance.
+Verification: `DiskDrawer.test.tsx` and `diskDrawerPresentation.test.ts` pin
+the disk-family catalog, its identity across matching snapshots, explicit I/O
+suppression and current readings that are never invented;
+`DiskDrawer.history-collection.test.tsx` mounts the disk drawer over the actual
+drawer history owner to cover absent current fields, stored zero versus empty,
+NVMe/ATA catalogs, request counts, preserved range and inspection, a fresh read
+and cleared inspection on range or target change, late former-target responses
+and no read without a resolvable identity. An empty stored series reads "No
+stored history in this range"; the chart legend may still show the snapshot's
+own reading, labelled current or last known. The production disk Overview,
+drawer history, client and CSS are checked with synthetic API data by
+`frontend-modern/browser-tests/disk-history-collection.cjs` (desktop Chromium,
+touch/dark phone WebKit), `guest-storage-2263.cjs` (the Overview inside the
+guest drawer) and `history-touch.cjs` (touch, pointer and keyboard inspection),
+not native NAS or installed acceptance.
### Independent physical disk temperature
@@ -391,12 +401,14 @@ invented. When no detail readings or collection messages remain, the existing
accessible unavailable-details message is shown. This presentation does not
establish fresh collection, SMART health or native appliance acceptance.
-Verification: `DiskDetail.test.tsx` covers same-identity snapshot replacement
-through temperature-only, hot, missing and extended-SMART states;
+Verification: `DiskDrawer.test.tsx` covers same-identity snapshot replacement
+through temperature-only, hot, missing and extended-SMART states in one mounted
+drawer; `diskDrawerPresentation.test.ts` covers a temperature beside a missing
+or empty SMART object and invalid readings without invented counters;
`diskDetailPresentation.branchcov0724pm.test.ts` covers disk types, invalid
-readings, units and configured thresholds. The production detail fixture in
-`frontend-modern/browser-tests/disk-temperature.cjs` checks desktop and phone
-presentation with synthetic snapshots, including the predecessor's omission.
+readings, units and configured thresholds. The production disk drawer fixture
+in `frontend-modern/browser-tests/disk-temperature.cjs` checks desktop and
+phone presentation with synthetic snapshots.
### Pool detail capacity observations
@@ -7124,3 +7136,9 @@ Recoverable restore points, which had no drawer and lost their location on
phones, now open a record drawer with source, location, created, size, state,
verification and protection. Coverage posture, restore evidence and recovery
rules are unchanged.
+
+The guest drawer's physical disks now open the same disk Overview as the
+Storage tab, and the old disk detail, its local history range catalogue,
+metric cards, key/value rows and the storage detail presentation classes that
+only it used are removed. Storage group and spacer rows span the table's
+visible columns, so pool rows and drawers fill the table on phones.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index c6afe568e0..be83843243 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1032,7 +1032,6 @@ Compact Coverage age cells use the existing metadata-size text and reclaim numer
29. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`
30. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`
31. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerSupportDisclosure.tsx`
-32. `frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx`
33. `frontend-modern/src/features/docker/DockerConfigsTable.tsx`
34. `frontend-modern/src/features/docker/DockerContainersTable.tsx`
34a. `frontend-modern/src/features/docker/DockerContainerLifecycleControls.tsx`
@@ -1048,7 +1047,6 @@ Compact Coverage age cells use the existing metadata-size text and reclaim numer
41. `frontend-modern/src/features/docker/DockerTasksTable.tsx`
42. `frontend-modern/src/features/docker/DockerVolumesTable.tsx`
43. `frontend-modern/src/features/docker/dockerPageModel.ts`
-44. `frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx`
45. `frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx`
46. `frontend-modern/src/components/Infrastructure/ResourceActionHistory.tsx`
47. `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`
@@ -8629,3 +8627,19 @@ count and involved object and no longer offers maintenance windows; a
Secret's key names and values are never shown. Namespaces keep the object
drawer because they carry alerts. No resource identity, status or alert rule
changes.
+
+The remaining bespoke object drawers follow the guest drawer. The Proxmox Mail
+Gateway row opens the shared resource drawer (row status, Overview, Manage)
+with mail flow as its headless Mail tab, so a PMG has one drawer instead of
+two; the Ceph cluster drawer has the canonical header, Overview (alerts, Worth
+checking for health checks, down OSDs and full pools, capacity history, facts,
+pool and service cards, closed Details) and Manage. The Kubernetes cluster
+drawer's Deployments tab, which repeated the Workloads table with dead-end
+rows, is removed; its Namespaces tab opens the Workloads tab scoped to the
+cluster and namespace. The unreachable Docker Swarm tab and the drawer state
+nothing read any more are removed. PBS and PMG alerts are matched on their
+instance id too, so the drawer finds them without a metrics target. The
+Proxmox node and Docker host drawers gain the guest drawer's Open action,
+Docker host readings are withheld while it is offline or stale, its Manage
+lists operator state first and shows its action history, and a guest's own
+agent reports its physical disks' temperature alerts inside the guest drawer.
diff --git a/frontend-modern/browser-tests/disk-history-collection.cjs b/frontend-modern/browser-tests/disk-history-collection.cjs
index 6ae1fad795..8824d63dae 100644
--- a/frontend-modern/browser-tests/disk-history-collection.cjs
+++ b/frontend-modern/browser-tests/disk-history-collection.cjs
@@ -54,27 +54,26 @@ const parent = false;
if (url.pathname === '/api/metrics-store/history') {
const query = Object.fromEntries(url.searchParams);
requests.push(query);
- const value =
- query.metric === 'smart_temp'
- ? query.resourceId.includes('nas-b')
- ? 55
- : 42
- : query.metric === 'smart_percentage_used'
- ? 12
- : query.metric === 'smart_available_spare'
- ? 97
- : 0;
- const empty = query.range === '1h' && query.metric === 'smart_temp';
+ // The disk drawer reads every series of its one target at once.
+ const series = (value) => [
+ { timestamp: observedAt - 60000, value, min: value, max: value },
+ { timestamp: observedAt, value, min: value, max: value },
+ ];
+ const temperature = query.resourceId.includes('nas-b') ? 55 : 42;
return route.fulfill({
json: {
resourceType: query.resourceType,
resourceId: query.resourceId,
- metric: query.metric,
range: query.range,
- start: Date.now() - 60000,
+ start: Date.now() - 180000,
end: Date.now(),
source: 'store',
- points: empty ? [] : [{ timestamp: observedAt, value, min: value, max: value }],
+ metrics: {
+ smart_temp: query.range === '1h' ? [] : series(temperature),
+ smart_reallocated_sectors: series(0),
+ smart_percentage_used: series(12),
+ smart_available_spare: series(97),
+ },
},
});
}
@@ -100,6 +99,7 @@ const parent = false;
checks.push({ label, passed: false, error: error.message });
}
};
+ const plots = page.locator('[data-testid="guest-history-plot"]');
const screenshot = async (state) => {
const file = `${name}-${state}.png`;
await page.screenshot({
@@ -111,91 +111,98 @@ const parent = false;
browser: name,
state,
screenshot: file,
- visibleCharts: await page.locator('canvas[role="img"]').allTextContents(),
- selectedTabs: await page
- .getByRole('tab')
- .evaluateAll((tabs) =>
- tabs.map((tab) => ({
- label: tab.textContent,
- selected: tab.getAttribute('aria-selected'),
- border: getComputedStyle(tab).borderBottomColor,
- })),
- ),
+ visibleCharts: await plots.evaluateAll((items) =>
+ items.filter((el) => el.getBoundingClientRect().width > 0).map((el) => el.ariaLabel),
+ ),
overflow: await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
),
body: await page.locator('main').innerText(),
});
};
- const thermal = () => page.getByRole('img', { name: 'Temperature chart' });
- const description = async () =>
- thermal().evaluate(
- (el) => document.getElementById(el.getAttribute('aria-describedby')).textContent,
+ const chart = (label) => page.getByRole('img', { name: `${label} history`, exact: true });
+ const thermal = () => chart('Temperature');
+ const description = async (label = 'Temperature') =>
+ chart(label).evaluate(
+ (el) =>
+ document.getElementById(el.getAttribute('aria-describedby').split(' ')[0]).textContent,
);
+ // Snapshots arrive from the store, not from a click that moves focus.
+ const snapshot = (label) =>
+ page.getByRole('button', { name: label }).evaluate((button) => button.click());
+ const range = () => page.getByRole('combobox', { name: 'History range' });
await page.goto('http://127.0.0.1:5251/browser-tests/disk-history-collection.html');
if (phone) await page.evaluate(() => document.documentElement.classList.add('dark'));
- // Disk details have no tabs: SMART evidence, then History, in one view.
- const historySection = page.getByTestId('disk-detail-history');
+ // The disk Overview has no tabs: notices, then History, then the facts.
+ const historySection = page.getByTestId('guest-history-region');
await historySection.waitFor();
+ await page.waitForFunction(() =>
+ [...document.querySelectorAll('[data-testid="guest-history-plot"]')].some((el) =>
+ document.getElementById(el.getAttribute('aria-describedby').split(' ')[0])?.textContent.includes('42°C'),
+ ),
+ );
// A phone folds every chart after the first behind one button; open it,
// as a reader inspecting the disk's history would.
if (phone) {
- const fold = page.getByTestId('disk-detail-phone-toggle');
+ const fold = page.getByTestId('history-phone-toggle');
if (await fold.isVisible()) await fold.click();
}
await page.waitForTimeout(300);
await check('Stored ATA history is accessible before any current fields', async () => {
- assert.equal(await page.locator('canvas[role="img"]').count(), 2);
- assert.match(await description(), /42°C/);
+ assert.deepEqual(await plots.evaluateAll((items) => items.map((el) => el.ariaLabel)), [
+ 'Temperature history',
+ 'Reallocated sectors history',
+ ]);
+ assert.match(await description(), /Disk 42°C/);
+ assert.match(await description('Reallocated sectors'), /Reallocated 0 sectors/);
});
await check('History shows without a tab to select', async () => {
assert.equal(await page.getByRole('tab').count(), 0);
assert.equal(await historySection.isVisible(), true);
+ assert.equal(await chart('Reallocated sectors').isVisible(), true);
});
await screenshot('missing-current');
- await page.getByRole('button', { name: 'Restore current fields' }).click();
+ await snapshot('Restore current fields');
await thermal().waitFor();
- await page.getByRole('combobox', { name: 'Disk history range' }).selectOption('7d');
- await page.waitForFunction(
- () =>
- document
- .querySelector('canvas[aria-label="Temperature chart"]')
- ?.getAttribute('aria-describedby') &&
- document
- .getElementById(
- document
- .querySelector('canvas[aria-label="Temperature chart"]')
- .getAttribute('aria-describedby'),
- )
- .textContent.includes('42°C'),
- );
- if (phone) await thermal().tap({ position: { x: 80, y: 60 } });
- else {
- await thermal().focus();
- await thermal().press('End');
+ await range().selectOption('7d');
+ await page.waitForFunction(() => {
+ const el = document.querySelector('[aria-label="Temperature history"]');
+ const id = el?.getAttribute('aria-describedby')?.split(' ')[0];
+ return id && document.getElementById(id).textContent.includes('42°C');
+ });
+ const inspect = page.getByRole('slider', { name: 'Inspect Temperature history' });
+ if (phone) {
+ // A tap on the plot hands inspection to touch: the scrubber shows.
+ await thermal().tap({ position: { x: 120, y: 30 } });
+ await inspect.waitFor();
}
+ await inspect.focus();
+ await inspect.press('Home');
await page.waitForTimeout(100);
+ const firstObservation = await page.evaluate(
+ (time) => new Date(time).toLocaleString(),
+ observedAt - 60000,
+ );
await check('Stored zero and exact temperature can be inspected', async () => {
- assert.equal(await page.locator('[data-history-chart-tooltip]').count(), 2);
- assert.match(
- await page
- .locator('[data-history-chart-tooltip]')
- .allTextContents()
- .then((parts) => parts.join(' ')),
- /0 sectors/,
- );
+ assert.equal(await inspect.isVisible(), true);
+ assert.ok((await description()).startsWith(firstObservation), await description());
+ assert.match(await description(), /Disk 42°C/);
+ assert.match(await description('Reallocated sectors'), /Reallocated 0 sectors/);
});
+ const inspected = await description();
await thermal().evaluate((el) => (el.dataset.proofOwner = 'original'));
const reads = requests.length;
- await page.getByRole('button', { name: 'Update current fields' }).click();
+ await snapshot('Update current fields');
await page.waitForTimeout(200);
await check('Same-ID snapshot keeps mounted chart and makes no extra reads', async () => {
assert.equal(await thermal().getAttribute('data-proof-owner'), 'original');
assert.equal(requests.length, reads);
- assert.equal(await page.getByRole('combobox').inputValue(), '7d');
+ assert.equal(await range().inputValue(), '7d');
+ assert.equal(await inspect.evaluate((el) => document.activeElement === el), true);
+ assert.equal(await description(), inspected);
});
await screenshot('updated-current');
- await page.getByRole('button', { name: 'Lose current fields' }).click();
+ await snapshot('Lose current fields');
await page.waitForTimeout(200);
await check(
'Missing current fields do not withdraw stored readings or invent live I/O',
@@ -204,7 +211,8 @@ const parent = false;
assert.equal(await thermal().getAttribute('data-proof-owner'), 'original');
assert.match(await description(), /42°C/);
assert.equal(requests.length, reads);
- assert.equal(await page.getByText('Live I/O (30m)').count(), 0);
+ assert.equal(await chart('Disk I/O').count(), 0);
+ assert.equal(await chart('Busy').count(), 0);
},
);
await screenshot('missing-again');
@@ -225,42 +233,50 @@ const parent = false;
[...document.querySelectorAll('main *')].filter(
(el) =>
el.children.length === 0 &&
- el.textContent.trim() === '42°C' &&
- !el.closest('[data-testid="disk-detail-history"]'),
+ el.textContent.trim().includes('42°C') &&
+ !el.closest('[data-testid="guest-history-region"]'),
).length,
),
0,
);
},
);
- await page.getByRole('combobox').selectOption('1h');
- await page.getByText('No history samples in this time range.').waitFor();
+ await range().selectOption('1h');
+ const thermalPanel = thermal().locator(
+ 'xpath=ancestor::*[@data-testid="guest-history-group-chart"][1]',
+ );
+ await thermalPanel.getByText('No stored history in this range').waitFor();
await check(
'Empty temperature is not zero and reallocated zero remains stored',
async () => {
assert.doesNotMatch(await description(), /0°C/);
- assert.equal(await page.locator('canvas[role="img"]').count(), 2);
+ assert.match(await description(), /No stored history observations\./);
+ assert.equal(await thermalPanel.locator('[data-history-series]').count(), 0);
+ assert.equal(await plots.count(), 2);
+ assert.match(await description('Reallocated sectors'), /Reallocated 0 sectors/);
},
);
await screenshot('empty-temperature');
- await page.getByRole('combobox').selectOption('7d');
- await page.getByRole('button', { name: 'Select NVMe B' }).click();
- await page.getByRole('img', { name: 'Available Spare chart' }).waitFor();
- await page.waitForTimeout(200);
+ await range().selectOption('7d');
+ await snapshot('Select NVMe B');
+ await chart('Wear').waitFor();
+ await page.waitForFunction(() => {
+ const el = document.querySelector('[aria-label="Temperature history"]');
+ const id = el?.getAttribute('aria-describedby')?.split(' ')[0];
+ return id && document.getElementById(id).textContent.includes('55°C');
+ });
await check(
'NVMe History uses explicit B target and its own metrics without live fields',
async () => {
- assert.equal(await page.locator('canvas[role="img"]').count(), 3);
- assert.equal(
- await page.getByRole('img', { name: 'Reallocated Sectors chart' }).count(),
- 0,
- );
+ assert.deepEqual(await plots.evaluateAll((items) => items.map((el) => el.ariaLabel)), [
+ 'Temperature history',
+ 'Wear history',
+ ]);
+ assert.equal(await chart('Reallocated sectors').count(), 0);
assert.match(await description(), /55°C/);
+ assert.match(await description('Wear'), /Spare 97\.0%/);
const own = requests.filter((r) => r.resourceId === 'disk:nas-b:nvme0n1');
- assert.equal(
- own.some((r) => r.metric === 'smart_available_spare'),
- true,
- );
+ assert.ok(own.length > 0);
assert.equal(
own.every((r) => r.resourceType === 'disk'),
true,
@@ -269,27 +285,32 @@ const parent = false;
);
await screenshot('nvme');
const beforeClear = requests.length;
- await page.getByRole('button', { name: 'Clear identity' }).click();
+ await snapshot('Clear identity');
await page.waitForTimeout(200);
await check(
'Unresolvable identity withdraws History and does not guess a target',
async () => {
assert.equal(await historySection.count(), 0);
- assert.equal(await page.locator('canvas[role="img"]').count(), 0);
+ assert.equal(await plots.count(), 0);
+ assert.equal(await page.getByTestId('disk-drawer-history-unavailable').isVisible(), true);
assert.equal(requests.length, beforeClear);
},
);
await screenshot('no-identity');
}
- await check('No page errors, off-origin data reads or horizontal overflow', async () => {
+ await check('No page errors, off-target reads or horizontal overflow', async () => {
assert.deepEqual(errors, []);
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth),
false,
);
assert.equal(
- requests.some((r) => ['diskread', 'diskwrite', 'disk'].includes(r.metric)),
- false,
+ requests.every(
+ (r) =>
+ r.resourceType === 'disk' &&
+ ['disk:nas-a:sda', 'disk:nas-b:nvme0n1'].includes(r.resourceId),
+ ),
+ true,
);
});
observations.push({ browser: name, version: browser.version(), checks, requests, errors });
@@ -309,7 +330,7 @@ const parent = false;
JSON.stringify({
parent,
checks: observations.flatMap((o) => o.checks ?? []).length,
- failed: failed.map((c) => c.label),
+ failed: failed.map((c) => `${c.label}: ${c.error}`),
}),
);
if (!parent) assert.equal(failed.length, 0);
diff --git a/frontend-modern/browser-tests/disk-history-collection.tsx b/frontend-modern/browser-tests/disk-history-collection.tsx
index 8c467a1c9d..d4a3301e93 100644
--- a/frontend-modern/browser-tests/disk-history-collection.tsx
+++ b/frontend-modern/browser-tests/disk-history-collection.tsx
@@ -1,10 +1,15 @@
-import { createSignal } from 'solid-js';
+import { createMemo, createSignal } from 'solid-js';
import { render } from 'solid-js/web';
-import { DiskDetail } from '../src/components/Storage/DiskDetail';
+import type { HistoryTimeRange } from '../src/api/charts';
+import { DiskDrawerOverview } from '../src/components/Storage/DiskDrawerOverview';
+import { GUEST_DRAWER_HISTORY_DEFAULT_RANGE } from '../src/components/Workloads/guestDrawerModel';
+import { extractPhysicalDiskPresentationData } from '../src/features/storageBackups/diskPresentation';
+import { useAlertsActivation } from '../src/stores/alertsActivation';
import type { Resource } from '../src/types/resource';
import '../src/index.css';
-// Only snapshots are synthetic: detail, history, client, inspection and CSS are production code.
+// Only snapshots are synthetic: the disk Overview, drawer history, client,
+// inspection and CSS are production code, wired as the disk drawers wire them.
const disk = (missing = false, nvme = false, hot = false): Resource => ({
id: nvme ? 'disk-b' : 'disk-a',
name: nvme ? 'NVMe B' : 'Archive A',
@@ -41,6 +46,7 @@ const disk = (missing = false, nvme = false, hot = false): Resource => ({
},
});
const [snapshot, setSnapshot] = createSignal(disk(true));
+const [range, setRange] = createSignal<HistoryTimeRange>(GUEST_DRAWER_HISTORY_DEFAULT_RANGE);
const controls = [
['Restore current fields', () => setSnapshot(disk())],
['Update current fields', () => setSnapshot(disk(false, false, true))],
@@ -57,8 +63,12 @@ const controls = [
}),
],
] as const;
-render(
- () => (
+const Fixture = () => {
+ const { getDiskTemperatureThresholds } = useAlertsActivation();
+ const diskData = createMemo(() =>
+ extractPhysicalDiskPresentationData(snapshot(), getDiskTemperatureThresholds),
+ );
+ return (
<main class="mx-auto max-w-5xl bg-surface p-3 text-base-content">
<h1 class="mb-3 text-lg font-semibold">Physical disk History</h1>
<div class="mb-4 flex flex-wrap gap-2">
@@ -68,8 +78,13 @@ render(
</button>
))}
</div>
- <DiskDetail disk={snapshot()} nodes={[]} />
+ <DiskDrawerOverview
+ disk={snapshot()}
+ diskData={diskData()}
+ historyRange={range()}
+ onHistoryRangeChange={setRange}
+ />
</main>
- ),
- document.getElementById('root')!,
-);
+ );
+};
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/frontend-modern/browser-tests/disk-live-refresh.tsx b/frontend-modern/browser-tests/disk-live-refresh.tsx
index e7a7dc87dc..6961572a15 100644
--- a/frontend-modern/browser-tests/disk-live-refresh.tsx
+++ b/frontend-modern/browser-tests/disk-live-refresh.tsx
@@ -1,4 +1,4 @@
-// Real DiskList/DiskDetail and keyed renderer, with synthetic collector snapshots.
+// Real DiskList/DiskDrawer and keyed renderer, with synthetic collector snapshots.
// This is browser behaviour evidence, not an installed SMART or appliance result.
import { createSignal } from 'solid-js';
import { render } from 'solid-js/web';
diff --git a/frontend-modern/browser-tests/disk-temperature.cjs b/frontend-modern/browser-tests/disk-temperature.cjs
index 860705782b..7deee88122 100644
--- a/frontend-modern/browser-tests/disk-temperature.cjs
+++ b/frontend-modern/browser-tests/disk-temperature.cjs
@@ -11,7 +11,6 @@ const { chromium, webkit } = require('playwright');
const server = await createServer({ root, configFile: path.join(root, 'vite.config.ts'), cacheDir: fs.mkdtempSync(path.join(artifacts, 'vite-')), server: { host: '127.0.0.1', port: 5225, strictPort: true } });
let browser;
const observations = [];
- const parent = process.argv.includes('--parent');
try {
await server.listen();
for (const [name, engine, width, height] of [['chromium', chromium, 1365, 900], ['webkit', webkit, 390, 844]]) {
@@ -23,48 +22,68 @@ const { chromium, webkit } = require('playwright');
const url = new URL(route.request().url());
if (url.origin !== 'http://127.0.0.1:5225') return route.abort();
if (!url.pathname.startsWith('/api/')) return route.continue();
+ if (url.pathname === '/api/metrics-store/history') {
+ const q = url.searchParams;
+ return route.fulfill({json: {resourceType: q.get('resourceType'), resourceId: q.get('resourceId'), range: q.get('range'), start: Date.now() - 86400000, end: Date.now(), source: 'store', metrics: {}}});
+ }
return route.fulfill({json: url.pathname === '/api/license/runtime-capabilities' ? {capabilities: [], limits: [], max_history_days: 7, hosted_mode: false, runtime: {build:'community'}, blocked_capabilities: []} : {data: [], enabled: false}});
});
await page.goto('http://127.0.0.1:5225/browser-tests/disk-temperature.html');
if (name === 'webkit') await page.evaluate(() => document.documentElement.classList.add('dark'));
+ const drawer = page.getByTestId('disk-drawer');
+ // The SMART health card in front holds the current reading.
+ const card = page.getByTestId('disk-drawer-health-card');
+ const details = page.getByTestId('disk-technical-details');
const fallback = page.getByText('Detailed SMART attributes are not available for this disk.', {exact:true});
- const value = text => page.getByText(text, {exact:true});
+ const value = text => card.getByText(text, {exact:true});
+ const verdict = label => drawer.getByRole('img', {name: label, exact: true});
+ await drawer.waitFor();
+ await drawer.evaluate(el => { el.dataset.proofOwner = 'retained'; });
async function state(phase, expected) {
- await value(expected).waitFor();
+ await page.getByText(expected, {exact:true}).first().waitFor();
+ // One disk throughout: snapshots replace the drawer's content, not the drawer.
+ assert.equal(await drawer.getAttribute('data-proof-owner'), 'retained');
const dimensions = await page.evaluate(() => ({scroll:document.documentElement.scrollWidth, width:innerWidth}));
assert.ok(dimensions.scroll <= dimensions.width + 1);
- await page.screenshot({path:path.join(artifacts, `${parent?'parent-':''}${name}-${phase}.png`),fullPage:true});
+ await page.screenshot({path:path.join(artifacts, `${name}-${phase}.png`),fullPage:true});
observations.push({name, version:browser.version(),phase,expected,dimensions});
}
- if (parent) {
- await state('temperature-hidden', 'Detailed SMART attributes are not available for this disk.');
- assert.equal(await value('42°C').count(),0);
- } else {
- await state('temperature-only','42°C');
- assert.equal(await fallback.count(),0);
- assert.equal(await value('Power-On Time').count(),0);
- assert.match(await value('42°C').getAttribute('class'), /text-green-600/);
- await page.getByRole('button',{name:'Hot reading'}).click();
- await state('hot','65°C');
- assert.match(await value('65°C').getAttribute('class'), /text-red-600/);
- await page.getByRole('button',{name:'Fahrenheit',exact:true}).click();
- await state('fahrenheit','149°F');
- assert.match(await value('149°F').getAttribute('class'), /text-red-600/);
- await page.getByRole('button',{name:'No reading',exact:true}).click();
- await state('missing','Detailed SMART attributes are not available for this disk.');
- assert.equal(await value('Temperature').count(),0);
- assert.equal(await fallback.getAttribute('role'),'status');
- await page.getByRole('button',{name:'Extended SMART',exact:true}).click();
- await state('extended','42°C');
- await value('4 days').waitFor();
- await value('Reallocated Sectors').waitFor();
- assert.equal(await value('0').count(),1);
- assert.equal(await value('Temperature').count(),1);
- }
+ await state('temperature-only','42°C');
+ assert.equal(await value('Temperature').count(),1);
+ assert.equal(await fallback.count(),0);
+ assert.equal(await page.getByText('Power-On Time', {exact:true}).count(),0);
+ assert.equal(await verdict('Running Hot').count(),0);
+ await page.getByRole('button',{name:'Hot reading'}).click();
+ await state('hot','65°C');
+ assert.equal(await value('65°C').count(),1);
+ assert.equal(await value('42°C').count(),0);
+ // A hot disk is stated by its verdict, judged under the disk heat policy.
+ assert.match(await verdict('Running Hot').getAttribute('class'), /red/);
+ assert.match(await page.getByTestId('disk-drawer-exceptions').innerText(), /Running Hot/);
+ await page.getByRole('button',{name:'Fahrenheit',exact:true}).click();
+ await state('fahrenheit','149°F');
+ assert.equal(await value('149°F').count(),1);
+ assert.match(await verdict('Running Hot').getAttribute('class'), /red/);
+ await page.getByRole('button',{name:'No reading',exact:true}).click();
+ await state('missing','Detailed SMART attributes are not available for this disk.');
+ assert.equal(await value('Temperature').count(),0);
+ assert.equal(await card.getByText(/°[CF]$/).count(),0);
+ assert.equal(await page.getByTestId('disk-drawer-notices').getAttribute('role'),'status');
+ await page.getByRole('button',{name:'Extended SMART',exact:true}).click();
+ await state('extended','42°C');
+ assert.equal(await fallback.count(),0);
+ assert.equal(await value('Temperature').count(),1);
+ // The reported counters sit in Details, which opens on request.
+ await details.locator('summary').click();
+ await details.getByText('4 days', {exact:true}).waitFor();
+ await details.getByText('Reallocated Sectors', {exact:true}).waitFor();
+ assert.equal(await details.getByText('0', {exact:true}).count(),1);
+ assert.equal(await details.getByText('Pending Sectors', {exact:true}).count(),0);
+ await page.screenshot({path:path.join(artifacts, `${name}-extended-details.png`),fullPage:true});
assert.deepEqual(errors,[]);
await browser.close(); browser=null;
}
- fs.writeFileSync(path.join(artifacts,parent?'parent.json':'result.json'),JSON.stringify({playwright:require('playwright/package.json').version,observations},null,2));
- console.log(JSON.stringify({result:'passed',states:observations.length,parent}));
+ fs.writeFileSync(path.join(artifacts,'result.json'),JSON.stringify({playwright:require('playwright/package.json').version,observations},null,2));
+ console.log(JSON.stringify({result:'passed',states:observations.length}));
} finally { if(browser) await browser.close(); await server.close(); }
})().catch(e=>{console.error(e);process.exitCode=1});
diff --git a/frontend-modern/browser-tests/disk-temperature.tsx b/frontend-modern/browser-tests/disk-temperature.tsx
index 986f7c8ba6..be19dc0f12 100644
--- a/frontend-modern/browser-tests/disk-temperature.tsx
+++ b/frontend-modern/browser-tests/disk-temperature.tsx
@@ -1,6 +1,6 @@
import { createSignal } from 'solid-js';
import { render } from 'solid-js/web';
-import { DiskDetail } from '../src/components/Storage/DiskDetail';
+import { DiskDrawer } from '../src/components/Storage/DiskDrawer';
import type { Resource } from '../src/types/resource';
import { temperatureStore } from '../src/utils/temperature';
import '../src/index.css';
@@ -30,7 +30,7 @@ const Fixture = () => {
return (
<main class="min-h-screen space-y-4 bg-surface p-4 text-base-content">
<h1>Physical disk Overview</h1>
- <p>Synthetic disk snapshots; production detail component.</p>
+ <p>Synthetic disk snapshots; production disk drawer.</p>
<div class="flex flex-wrap gap-2">
<button class="min-h-11 border px-3" onClick={() => reading(65)}>
Hot reading
@@ -49,7 +49,7 @@ const Fixture = () => {
</button>
</div>
<section class="max-w-3xl">
- <DiskDetail disk={disk()} nodes={[]} />
+ <DiskDrawer disk={disk()} onClose={() => {}} />
</section>
</main>
);
diff --git a/frontend-modern/browser-tests/guest-storage-2263.cjs b/frontend-modern/browser-tests/guest-storage-2263.cjs
index 5167f75cbc..60462ecd12 100644
--- a/frontend-modern/browser-tests/guest-storage-2263.cjs
+++ b/frontend-modern/browser-tests/guest-storage-2263.cjs
@@ -4,6 +4,8 @@ const assert = require('node:assert/strict');
const path = require('node:path');
const { chromium } = require('playwright');
+const OVERVIEW_MODULE = '/src/components/Storage/DiskDrawerOverview.tsx';
+
(async () => {
const root = '/workspace/frontend-modern';
const artifacts = path.join(root, 'browser-tests');
@@ -23,6 +25,7 @@ const { chromium } = require('playwright');
args: ['--no-sandbox'],
});
const requests = [];
+ // Requests for the disk Overview module, which loads only on expansion.
const detailRequests = [];
const historyReads = [];
const pageErrors = [];
@@ -56,7 +59,7 @@ const { chromium } = require('playwright');
console.error('requestfailed', request.url(), request.failure()),
);
page.on('request', (request) => {
- if (new URL(request.url()).pathname === '/src/components/Storage/DiskDetail.tsx') {
+ if (new URL(request.url()).pathname === OVERVIEW_MODULE) {
detailRequests.push({ width, url: request.url() });
}
});
@@ -84,24 +87,35 @@ const { chromium } = require('playwright');
}
if (url.pathname === '/api/metrics-store/history') {
const q = url.searchParams;
- historyReads.push({ width, metric: q.get('metric'), range: q.get('range') });
+ historyReads.push({
+ width,
+ resourceId: q.get('resourceId'),
+ metric: q.get('metric'),
+ range: q.get('range'),
+ });
const end = Date.now();
+ // Disk reads spike inside their buckets; every other series is flat.
+ const series = (metric) =>
+ [0, 1, 2].map((i) => ({
+ timestamp: end - (2 - i) * 300_000,
+ value: 40 + i,
+ min: metric === 'diskread' ? 10 + i : 40 + i,
+ max: metric === 'diskread' ? 90 + i : 40 + i,
+ }));
+ // The disk Overview reads every series of its one disk in one request.
return route.fulfill({
json: {
resourceType: q.get('resourceType'),
resourceId: q.get('resourceId'),
- metric: q.get('metric'),
range: q.get('range'),
start: end - 600_000,
end,
source: 'store',
- // Disk reads spike inside their buckets; every other series is flat.
- points: [0, 1, 2].map((i) => ({
- timestamp: end - (2 - i) * 300_000,
- value: 40 + i,
- min: q.get('metric') === 'diskread' ? 10 + i : 40 + i,
- max: q.get('metric') === 'diskread' ? 90 + i : 40 + i,
- })),
+ metrics: Object.fromEntries(
+ ['smart_temp', 'smart_reallocated_sectors', 'diskread', 'diskwrite', 'disk'].map(
+ (metric) => [metric, series(metric)],
+ ),
+ ),
},
});
}
@@ -109,7 +123,7 @@ const { chromium } = require('playwright');
return route.continue();
});
let releaseDetail;
- await page.route('**/src/components/Storage/DiskDetail.tsx*', async (route) => {
+ await page.route(`**${OVERVIEW_MODULE}*`, async (route) => {
await new Promise((resolve) => {
releaseDetail = resolve;
});
@@ -117,32 +131,6 @@ const { chromium } = require('playwright');
});
// Disk charts poll every 10-30 seconds; the clock drives that here.
await page.clock.install();
- // Canvas text is not in the DOM: record each chart's drawn labels since
- // its last clear, so the time axis can be checked for overlap.
- await page.addInitScript(() => {
- const proto = CanvasRenderingContext2D.prototype;
- const clear = proto.clearRect;
- const fill = proto.fillText;
- const fillShape = proto.fill;
- proto.clearRect = function (...args) {
- this.canvas.__labels = [];
- this.canvas.__fills = [];
- return clear.apply(this, args);
- };
- proto.fill = function (...args) {
- (this.canvas.__fills ||= []).push(String(this.fillStyle));
- return fillShape.apply(this, args);
- };
- proto.fillText = function (text, x, y, ...rest) {
- (this.canvas.__labels ||= []).push({
- text: String(text),
- x,
- width: this.measureText(String(text)).width,
- time: this.textAlign === 'center' && this.textBaseline === 'bottom',
- });
- return fill.call(this, text, x, y, ...rest);
- };
- });
await page.goto('http://127.0.0.1:5199/browser-tests/guest-storage-2263.html', {
waitUntil: 'domcontentloaded',
timeout: 120_000,
@@ -155,22 +143,22 @@ const { chromium } = require('playwright');
assert.equal(
detailRequests.filter((request) => request.width === width).length,
0,
- 'SMART history module must not load before disk expansion',
+ 'the disk Overview module must not load before disk expansion',
);
await page.screenshot({
path: path.join(artifacts, `guest-storage-2263-collapsed-${width}.png`),
fullPage: true,
});
- await page.locator('[data-testid="guest-physical-disk"] summary').focus();
+ await page.locator('[data-testid="guest-physical-disk"] > summary').focus();
const detailRequest = page.waitForRequest(
- (request) => new URL(request.url()).pathname === '/src/components/Storage/DiskDetail.tsx',
+ (request) => new URL(request.url()).pathname === OVERVIEW_MODULE,
);
await page.keyboard.press('Enter');
await detailRequest;
assert.equal(
- await page.getByText('Reallocated Sectors').first().count(),
+ await page.getByTestId('disk-drawer-overview').count(),
0,
- 'SMART detail must remain suspended while its module is loading',
+ 'the disk Overview must remain suspended while its module is loading',
);
assert.equal(
await page.getByRole('status').filter({ hasText: 'Loading SMART details…' }).count(),
@@ -179,7 +167,7 @@ const { chromium } = require('playwright');
);
assert.equal(
await page
- .locator('[data-testid="guest-physical-disk"] summary')
+ .locator('[data-testid="guest-physical-disk"] > summary')
.evaluate((summary) => summary === document.activeElement),
true,
'keyboard focus remains on disk summary',
@@ -189,11 +177,14 @@ const { chromium } = require('playwright');
fullPage: true,
});
releaseDetail();
- await page.getByText('Reallocated Sectors').first().waitFor();
+ const overview = page.getByTestId('disk-drawer-overview');
+ await overview.waitFor();
+ // An out-of-range SMART counter is lifted into Worth checking.
+ await page.getByTestId('disk-drawer-exceptions').getByText('CRC Errors').waitFor();
assert.equal(
detailRequests.filter((request) => request.width === width).length,
1,
- 'SMART history module loads once after disk expansion',
+ 'the disk Overview module loads once after disk expansion',
);
await page.screenshot({
path: path.join(artifacts, `guest-storage-2263-expanded-${width}.png`),
@@ -202,78 +193,79 @@ const { chromium } = require('playwright');
// The expanded disk shows its SMART evidence and History in one view,
// with no Overview/History tabs to switch between.
assert.equal(await page.getByRole('tab').count(), 0);
- assert.equal(await page.getByTestId('disk-detail-history').isVisible(), true);
+ const region = page.getByTestId('guest-history-region');
+ await region.waitFor();
+ await page.waitForFunction(
+ () => document.querySelectorAll('[data-history-series="smart_temp"]').length > 0,
+ );
const visibleCharts = () =>
page.evaluate(() =>
- Array.from(document.querySelectorAll('canvas'))
- .filter((canvas) => canvas.clientWidth > 0)
- .map((canvas) => canvas.getAttribute('aria-label')),
- );
- const phoneToggle = page.getByTestId('disk-detail-phone-toggle');
- if (width === 390) {
- // A phone shows the first chart; the rest fold behind one button and
- // read nothing until it is pressed.
- assert.deepEqual(await visibleCharts(), ['Temperature chart']);
- assert.equal(
- await phoneToggle.innerText(),
- 'Show Reallocated Sectors, Read, Write, Busy',
+ Array.from(document.querySelectorAll('[data-testid="guest-history-plot"]'))
+ .filter((plot) => plot.getBoundingClientRect().width > 0)
+ .map((plot) => plot.getAttribute('aria-label')),
);
+ const phoneToggle = page.getByTestId('history-phone-toggle');
+ const ownReads = () => historyReads.filter((r) => r.width === width);
+ // One read covers every chart of the disk, for its own target only.
+ assert.ok(ownReads().length >= 1);
+ for (const read of ownReads()) {
assert.deepEqual(
- [...new Set(historyReads.filter((r) => r.width === width).map((r) => r.metric))],
- ['smart_temp'],
+ { resourceId: read.resourceId, metric: read.metric, range: read.range },
+ { resourceId: 'disk-guest-101', metric: null, range: '24h' },
);
+ }
+ if (width === 390) {
+ // A phone shows the first chart; the rest fold behind one button.
+ assert.deepEqual(await visibleCharts(), ['Temperature history']);
+ assert.equal(await phoneToggle.innerText(), 'Show Disk I/O, Busy, Reallocated sectors');
await page.screenshot({
path: path.join(artifacts, `guest-storage-2263-phone-folded-${width}.png`),
fullPage: true,
});
- const unfolded = page.waitForRequest((request) =>
- request.url().includes('metric=diskread'),
- );
+ const before = ownReads().length;
await phoneToggle.click();
- await unfolded;
assert.equal(await phoneToggle.getAttribute('aria-expanded'), 'true');
assert.equal(await phoneToggle.innerText(), 'Show fewer charts');
- await page.getByRole('img', { name: 'Read chart' }).waitFor();
+ await page.getByRole('img', { name: 'Disk I/O history' }).waitFor();
await page.waitForTimeout(300);
+ // The folded charts were already read with the first one.
+ assert.equal(ownReads().length, before, 'unfolding starts no read of its own');
} else {
assert.equal(await phoneToggle.isVisible(), false, 'no fold above the phone breakpoint');
}
- assert.equal((await visibleCharts()).length, 5);
+ assert.deepEqual(await visibleCharts(), [
+ 'Temperature history',
+ 'Disk I/O history',
+ 'Busy history',
+ 'Reallocated sectors history',
+ ]);
// Spiky disk reads draw a min-max band behind their line; flat series do not.
- // The canvas reports the band's 20%-alpha fill back as rgba(..., 0.2).
- const fills = await page.evaluate(() =>
- Object.fromEntries(
- Array.from(document.querySelectorAll('canvas'), (canvas) => [
- canvas.getAttribute('aria-label'),
- canvas.__fills || [],
- ]),
+ assert.deepEqual(
+ await page.evaluate(() =>
+ Array.from(document.querySelectorAll('[data-history-band]'), (band) =>
+ band.getAttribute('data-history-band'),
+ ),
),
+ ['diskread'],
);
- assert.ok(
- fills['Read chart'].some((fill) => /, 0\.2\)$/.test(fill)),
- `Read chart band: ${JSON.stringify(fills['Read chart'])}`,
- );
- for (const flat of ['Temperature chart', 'Write chart', 'Busy chart']) {
- assert.ok(
- !fills[flat].some((fill) => /, 0\.2\)$/.test(fill)),
- `${flat} must not draw a band: ${JSON.stringify(fills[flat])}`,
- );
- }
- // Each chart's time labels stand apart, however narrow its card.
+ // Each chart's window times stand apart, however narrow its panel.
const timeLabels = await page.evaluate(() =>
- Array.from(document.querySelectorAll('canvas'), (canvas) => ({
- chart: canvas.getAttribute('aria-label'),
- width: canvas.clientWidth,
- labels: (canvas.__labels || []).filter((label) => label.time),
- })),
+ Array.from(document.querySelectorAll('[data-testid="guest-history-group-chart"]'), (panel) => {
+ const times = Array.from(
+ panel.querySelectorAll('[data-testid="guest-history-time-window"] time'),
+ (time) => time.getBoundingClientRect(),
+ );
+ return {
+ chart: panel.querySelector('[data-testid="guest-history-plot"]').getAttribute('aria-label'),
+ width: panel.clientWidth,
+ labels: times.map((rect) => ({ left: rect.left, right: rect.right })),
+ };
+ }),
);
for (const chart of timeLabels) {
- assert.ok(chart.labels.length >= 2, `${chart.chart} has its first and last time`);
- const sorted = [...chart.labels].sort((a, b) => a.x - b.x);
- for (let i = 1; i < sorted.length; i++) {
- const gap = sorted[i].x - sorted[i - 1].x - (sorted[i].width + sorted[i - 1].width) / 2;
- assert.ok(gap >= 4, `${chart.chart} time labels touch: ${JSON.stringify(sorted)}`);
- }
+ assert.equal(chart.labels.length, 2, `${chart.chart} has its first and last time`);
+ const [first, last] = chart.labels;
+ assert.ok(last.left - first.right >= 4, `${chart.chart} time labels touch: ${JSON.stringify(chart)}`);
}
console.log(
JSON.stringify({
@@ -281,19 +273,23 @@ const { chromium } = require('playwright');
timeLabels: timeLabels.map((chart) => [chart.chart, chart.width, chart.labels.length]),
}),
);
- await page.locator('[data-testid="guest-physical-disk"] summary').click();
- await page.getByText('Reallocated Sectors').first().waitFor({ state: 'hidden' });
+ await page.screenshot({
+ path: path.join(artifacts, `guest-storage-2263-expanded-charts-${width}.png`),
+ fullPage: true,
+ });
+ await page.locator('[data-testid="guest-physical-disk"] > summary').click();
+ await overview.waitFor({ state: 'hidden' });
assert.equal(
- await page.getByText('Reallocated Sectors').first().isVisible(),
+ await overview.isVisible(),
false,
- 'pointer closes the expanded SMART detail',
+ 'pointer closes the expanded disk Overview',
);
- await page.locator('[data-testid="guest-physical-disk"] summary').click();
- await page.getByText('Reallocated Sectors').first().waitFor();
+ await page.locator('[data-testid="guest-physical-disk"] > summary').click();
+ await overview.waitFor();
assert.equal(
detailRequests.filter((request) => request.width === width).length,
1,
- 'reopening a disk does not reload the SMART module',
+ 'reopening a disk does not reload the disk Overview module',
);
// A hidden Overview (another drawer tab) must stop the open disk's reads.
const reads = () => historyReads.filter((read) => read.width === width).length;
@@ -314,24 +310,23 @@ const { chromium } = require('playwright');
);
await page.getByRole('button', { name: 'Show overview' }).click();
await resumed;
- await page.getByText('Reallocated Sectors').first().waitFor();
+ await overview.waitFor();
assert.ok(
- await page.locator('[data-testid="disk-detail-history"] canvas').first().isVisible(),
+ await page.locator('[data-history-series="smart_temp"]').first().isVisible(),
'charts return with their readings',
);
- // A resize asks for the same series at a new point cap: the charts keep
- // their readings and show no loading state while it is read.
- const spinners = () => page.getByLabel('Loading history').count();
+ // The drawer history reads a fixed point cap, so a resize keeps the
+ // charts and their readings on screen without another read.
+ const spinners = () => page.getByText('Loading history', { exact: true }).count();
const resizedReads = reads();
- const resizedRead = page.waitForRequest((request) =>
- request.url().includes('/api/metrics-store/history'),
- );
await page.setViewportSize({ width: width - 200, height: width === 390 ? 844 : 900 });
- await resizedRead;
- assert.equal(await spinners(), 0, 'a resize keeps the charts on screen');
await page.waitForTimeout(300);
- assert.ok(reads() > resizedReads, 'the resized charts read at their new cap');
- assert.equal(await spinners(), 0, 'no spinner after the resized read');
+ assert.equal(await spinners(), 0, 'a resize keeps the charts on screen');
+ assert.equal(reads(), resizedReads, 'a resize starts no read');
+ assert.ok(
+ await page.locator('[data-history-series="smart_temp"]').first().isVisible(),
+ 'the resized charts keep their readings',
+ );
await page.setViewportSize({ width, height: width === 390 ? 844 : 900 });
await page.waitForTimeout(300);
await page.screenshot({
diff --git a/frontend-modern/browser-tests/guest-storage-2263.tsx b/frontend-modern/browser-tests/guest-storage-2263.tsx
index 74bb59741f..30d0b2c141 100644
--- a/frontend-modern/browser-tests/guest-storage-2263.tsx
+++ b/frontend-modern/browser-tests/guest-storage-2263.tsx
@@ -1,8 +1,10 @@
// #2263 browser fixture: mount the production guest overview and its real
-// resource query, not a reimplementation of the disk/RAID presentation.
+// resource query, not a reimplementation of the disk/RAID presentation. An
+// opened disk shows the disk drawer's Overview, which reads active alerts from
+// the app runtime, so the fixture mounts inside the shared offline runtime.
import { createSignal, Show } from 'solid-js';
-import { render } from 'solid-js/web';
import { GuestDrawerOverview } from '../src/components/Workloads/GuestDrawerOverview';
+import { renderInAppRuntime } from './fixtureRuntime';
import '../src/index.css';
type Mode = 'linked' | 'none' | 'error';
@@ -56,7 +58,7 @@ const overviewProps = {
normalizedTags: [], backupPresentation: null, workloadActionAgentTitle: '',
};
-render(() => (
+renderInAppRuntime(() => (
<main class="mx-auto max-w-3xl space-y-4 p-4">
<h1 class="text-lg font-semibold">Guest storage browser fixture</h1>
<nav class="flex gap-2" aria-label="Fixture states">
@@ -78,4 +80,4 @@ render(() => (
<GuestDrawerOverview {...overviewProps} guest={errorGuest as any} />
</Show>
</main>
-), document.getElementById('root')!);
+));
diff --git a/frontend-modern/browser-tests/history-touch.cjs b/frontend-modern/browser-tests/history-touch.cjs
index abb8a8706c..d29f37628f 100644
--- a/frontend-modern/browser-tests/history-touch.cjs
+++ b/frontend-modern/browser-tests/history-touch.cjs
@@ -14,7 +14,6 @@ const { chromium, webkit } = require('playwright');
cacheDir: fs.mkdtempSync(path.join(artifacts, 'vite-')),
server: { host: '127.0.0.1', port: 5227, strictPort: true },
});
- const parent = false;
let browser;
const observations = [];
const timestamp = Date.parse('2026-10-02T10:00:00Z');
@@ -30,7 +29,6 @@ const { chromium, webkit } = require('playwright');
['webkit-phone', webkit, true, true],
];
for (const [name, engine, touch, dark] of configs) {
- if (parent && !touch) continue;
browser = await engine.launch(engine === chromium ? { headless: true, channel: 'chromium', args: ['--no-sandbox'] } : { headless: true });
const page = await browser.newPage({
viewport: touch ? { width: 390, height: 844 } : { width: 1365, height: 900 },
@@ -47,13 +45,17 @@ const { chromium, webkit } = require('playwright');
if (!url.pathname.startsWith('/api/')) return route.continue();
if (url.pathname === '/api/metrics-store/history') {
requests.push(Object.fromEntries(url.searchParams));
- // The client checks a reply names the series it asked for.
+ // Each drawer reads every series of its one target in one request;
+ // the reply window is the stored samples' own span.
const q = url.searchParams;
const times = samples.map(sample => sample.timestamp);
+ const metrics = q.get('resourceType') === 'disk'
+ ? Object.fromEntries(['smart_temp', 'diskread', 'diskwrite', 'disk'].map(metric => [metric, samples]))
+ : { usage: samples };
return route.fulfill({ json: {
- resourceType: q.get('resourceType'), resourceId: q.get('resourceId'), metric: q.get('metric'), range: q.get('range'),
+ resourceType: q.get('resourceType'), resourceId: q.get('resourceId'), range: q.get('range'),
start: times.length ? Math.min(...times) : Date.now() - 86400000, end: times.length ? Math.max(...times) : Date.now(),
- points: samples, source: 'store',
+ metrics, source: 'store',
} });
}
return route.fulfill({ json: url.pathname === '/api/license/runtime-capabilities'
@@ -64,123 +66,130 @@ const { chromium, webkit } = require('playwright');
if (dark) await page.evaluate(() => document.documentElement.classList.add('dark'));
const disk = page.getByRole('region', { name: 'Disk fixture' });
const pool = page.getByRole('region', { name: 'Pool fixture' });
+ const busy = disk.getByRole('img', { name: 'Busy history', exact: true });
+ const panel = chart => chart.locator('xpath=ancestor::*[@data-testid="guest-history-group-chart"][1]');
+ // The plot's description names the inspected observation, or the count.
+ const description = chart => chart.evaluate(el => document.getElementById(el.getAttribute('aria-describedby').split(' ')[0]).textContent);
+ const readoutTime = chart => panel(chart).getByTestId('guest-history-hover-time').textContent();
+ const settled = (label, count) => page.waitForFunction(([label, count]) => [...document.querySelectorAll('[data-testid="guest-history-plot"]')].some(el => el.getAttribute('aria-label') === label && document.getElementById(el.getAttribute('aria-describedby').split(' ')[0]).textContent.includes(count)), [label, count]);
// A phone folds the disk's charts after the first behind one button.
- if (touch) await disk.getByTestId('disk-detail-phone-toggle').click();
- const busy = disk.getByRole('img', { name: 'Busy chart', exact: true });
- const description = chart => chart.evaluate(el => document.getElementById(el.getAttribute('aria-describedby')).textContent);
- await page.waitForFunction(() => [...document.querySelectorAll('canvas')].some(el => el.getAttribute('aria-label') === 'Busy chart' && document.getElementById(el.getAttribute('aria-describedby')).textContent.includes('3 data points')));
- const tooltip = chart => chart.locator('..').locator('[data-history-chart-tooltip]');
- const live = chart => chart.locator('..').locator('[aria-live="polite"]');
+ if (touch) {
+ await settled('Temperature history', '3 stored observation times');
+ await disk.getByTestId('history-phone-toggle').click();
+ }
+ await settled('Busy history', '3 stored observation times');
async function inspect(chart, fraction) {
await chart.scrollIntoViewIfNeeded();
const box = await chart.boundingBox();
- // Percent labels reserve 40px at left; the time label reserves less than
- // 25px at right. These interior positions are nearest to each real sample.
- const x = box.x + 45 + (box.width - 70) * fraction;
+ // The plot spans 34-352 of its 360-unit viewBox; the reply window is
+ // the samples' span, so these fractions sit on the real samples.
+ const x = box.x + (box.width * (34 + fraction * 318)) / 360;
const y = box.y + box.height / 2;
if (touch) await page.touchscreen.tap(x, y);
else await page.mouse.move(x, y);
await page.waitForTimeout(80);
- return (await tooltip(chart).count()) ? await tooltip(chart).textContent() : null;
+ return description(chart);
}
async function record(phase, chart, text) {
const dimensions = await page.evaluate(() => ({ scroll: document.documentElement.scrollWidth, width: innerWidth }));
assert.ok(dimensions.scroll <= dimensions.width + 1, JSON.stringify(dimensions));
- observations.push({ name, browser: browser.version(), touch, dark, phase, text, description: await description(chart), dimensions });
- await page.screenshot({ path: path.join(artifacts, `${parent ? 'parent-' : ''}${name}-${phase}.png`) });
+ // An empty range has no observation time to name.
+ const readout = (await panel(chart).getByTestId('guest-history-hover-time').count()) ? await readoutTime(chart) : null;
+ observations.push({ name, browser: browser.version(), touch, dark, phase, text, readout, dimensions });
+ await page.screenshot({ path: path.join(artifacts, `${name}-${phase}.png`) });
}
- if (parent) {
- for (const [phase, fraction, expected] of [['first', 0.04, '10.0%'], ['middle', 0.5, '20.0%']]) {
- const text = await inspect(busy, fraction);
- if (phase === 'first') assert.ok(!text?.includes(expected), `predecessor unexpectedly inspected the first tap: ${text}`);
- await record(phase, busy, text);
- }
- } else {
- for (const [phase, fraction, expected] of [['first', 0.04, '10.0%'], ['middle', 0.5, '20.0%'], ['last', 0.96, '30.0%']]) {
- const text = await inspect(busy, fraction);
- assert.ok(text?.includes(expected), `${name} ${phase}: ${text}`);
- assert.equal(await live(busy).textContent(), '', 'pointer inspection must not speak keyboard announcements');
- assert.equal(await disk.locator('[data-history-chart-tooltip]').count(), 3, 'live I/O group shares inspection');
- await record(phase, busy, text);
- }
- if (touch) {
- const read = disk.getByRole('img', { name: 'Read chart', exact: true });
- assert.ok((await inspect(read, 0.5))?.includes('20.0 B/s'));
- assert.ok((await tooltip(busy).textContent()).includes('20.0%'), 'a peer blur must not clear the new group tap');
- assert.equal(await live(read).textContent(), '');
- await inspect(busy, 0.5);
- // A hybrid device may switch back to a real mouse after a tap.
- await busy.scrollIntoViewIfNeeded();
- const box = await busy.boundingBox();
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
- assert.ok((await tooltip(busy).textContent()).includes('20.0%'));
- await page.mouse.move(0, 0);
- assert.equal(await tooltip(busy).count(), 0);
- }
- await busy.focus();
- for (const [key, expected] of [['Home', '10.0%'], ['ArrowRight', '20.0%'], ['End', '30.0%']]) {
- await page.keyboard.press(key);
- assert.ok((await live(busy).textContent()).includes(expected));
- }
- await page.keyboard.press('Escape');
- assert.equal(await tooltip(busy).count(), 0);
- await page.getByRole('button', { name: 'After charts' }).focus();
- assert.equal(await live(busy).textContent(), '');
+ for (const [phase, fraction, expected] of [['first', 0, 'Busy 10.0%'], ['middle', 0.5, 'Busy 20.0%'], ['last', 1, 'Busy 30.0%']]) {
+ const text = await inspect(busy, fraction);
+ assert.ok(text.includes(expected), `${name} ${phase}: ${text}`);
+ assert.match(await readoutTime(busy), /^Stored · /, 'the readout names an inspected time');
+ // Each panel inspects on its own: the I/O panel keeps its latest reading.
+ assert.match(await readoutTime(disk.getByRole('img', { name: 'Disk I/O history', exact: true })), /^Latest stored · /);
+ await record(phase, busy, text);
+ }
+ if (touch) {
+ const read = disk.getByRole('img', { name: 'Disk I/O history', exact: true });
+ assert.match(await inspect(read, 0.5), /Read 20(\.0)? B\/s/);
+ assert.match(await readoutTime(read), /^Stored · /);
+ // The touched panel exposes its scrubber for touch inspection.
+ assert.ok(await panel(read).getByRole('slider').isVisible());
+ await inspect(busy, 0.5);
+ // A hybrid device may switch back to a real mouse after a tap.
+ await busy.scrollIntoViewIfNeeded();
+ const box = await busy.boundingBox();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ assert.ok((await description(busy)).includes('Busy 20.0%'));
+ await page.mouse.move(0, 0);
+ assert.ok((await description(busy)).startsWith('3 stored observation times'));
+ }
+ // The keyboard steps through the stored observations, then lets go.
+ const scrubber = panel(busy).getByRole('slider', { name: 'Inspect Busy history' });
+ await scrubber.focus();
+ for (const [key, expected] of [['Home', 'Busy 10.0%'], ['ArrowRight', 'Busy 20.0%'], ['End', 'Busy 30.0%']]) {
+ await page.keyboard.press(key);
+ assert.ok((await scrubber.getAttribute('aria-valuetext')).includes(expected));
+ assert.ok((await description(busy)).includes(expected));
+ }
+ await page.getByRole('button', { name: 'After charts' }).focus();
+ assert.ok((await description(busy)).startsWith('3 stored observation times'));
+ assert.match(await readoutTime(busy), /^Latest stored · /);
- if (touch && engine === chromium) {
- await busy.scrollIntoViewIfNeeded();
- await inspect(busy, 0.5);
- const box = await busy.boundingBox();
- const session = await page.context().newCDPSession(page);
- await busy.evaluate(el => {
- el.dataset.cancelCount = '0';
- el.addEventListener('pointercancel', () => el.dataset.cancelCount = String(Number(el.dataset.cancelCount) + 1));
- });
- const scrollMetrics = await page.evaluate(() => ({ before: scrollY, maximum: document.documentElement.scrollHeight - innerHeight }));
- assert.ok(scrollMetrics.maximum > scrollMetrics.before + 200, 'the fixture must have room to scroll');
- const before = scrollMetrics.before;
- const x = box.x + box.width / 2, y = box.y + box.height / 2;
- await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y, id: 1 }] });
- for (let step = 1; step <= 5; step++) {
- await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y - step * 20, id: 1 }] });
- await page.waitForTimeout(50);
- }
- await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
- await page.waitForTimeout(300);
- const after = await page.evaluate(() => scrollY);
- fs.writeFileSync(path.join(artifacts, 'pan-control.json'), JSON.stringify({before, after, pointerCancels: await busy.getAttribute('data-cancel-count'), touchAction: await busy.evaluate(el => getComputedStyle(el).touchAction)},null,2));
- assert.ok(after > before + 40, `native pan must scroll: ${before} -> ${after}`);
- assert.ok(Number(await busy.getAttribute('data-cancel-count')) > 0);
- assert.equal(await tooltip(busy).count(), 0, 'native scrolling must not select a reading');
- observations.push({ name, phase: 'native-vertical-pan', before, after, maximum: scrollMetrics.maximum, pointerCancels: Number(await busy.getAttribute('data-cancel-count')), touchAction: await busy.evaluate(el => getComputedStyle(el).touchAction) });
- await session.detach();
+ if (touch && engine === chromium) {
+ await busy.scrollIntoViewIfNeeded();
+ await inspect(busy, 0.5);
+ const box = await busy.boundingBox();
+ const session = await page.context().newCDPSession(page);
+ await busy.evaluate(el => {
+ el.dataset.cancelCount = '0';
+ el.addEventListener('pointercancel', () => el.dataset.cancelCount = String(Number(el.dataset.cancelCount) + 1));
+ });
+ const scrollMetrics = await page.evaluate(() => ({ before: scrollY, maximum: document.documentElement.scrollHeight - innerHeight }));
+ assert.ok(scrollMetrics.maximum > scrollMetrics.before + 200, 'the fixture must have room to scroll');
+ const before = scrollMetrics.before;
+ const x = box.x + box.width / 2, y = box.y + box.height / 2;
+ await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y, id: 1 }] });
+ for (let step = 1; step <= 5; step++) {
+ await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y - step * 20, id: 1 }] });
+ await page.waitForTimeout(50);
}
-
- const usage = pool.getByRole('img', { name: 'Usage chart', exact: true });
- await usage.waitFor();
- await page.waitForFunction(() => [...document.querySelectorAll('canvas')].some(el => el.getAttribute('aria-label') === 'Usage chart' && document.getElementById(el.getAttribute('aria-describedby')).textContent.includes('3 data points')));
- assert.ok((await inspect(usage, 0.04))?.includes('10.0%'));
- await record('pool-first', usage, await tooltip(usage).textContent());
- assert.equal(await pool.getByLabel('Capacity history range').inputValue(), '7d');
- samples = [point(0)];
- await pool.getByLabel('Capacity history range').selectOption('24h');
- await page.waitForFunction(() => [...document.querySelectorAll('canvas')].some(el => el.getAttribute('aria-label') === 'Usage chart' && document.getElementById(el.getAttribute('aria-describedby')).textContent.includes('1 data point')));
- assert.ok((await inspect(usage, 0.5))?.includes('0.0%'));
- await record('pool-zero-singleton', usage, await tooltip(usage).textContent());
- samples = [];
- await pool.getByLabel('Capacity history range').selectOption('7d');
- await pool.getByText('No history samples in this time range.', { exact: true }).waitFor();
- assert.equal(await inspect(usage, 0.5), null);
- assert.equal(await live(usage).textContent(), '');
- await record('pool-empty', usage, null);
- assert.ok(requests.some(request => request.resourceType === 'disk' && request.resourceId === 'fixture-disk'));
- assert.ok(requests.some(request => request.resourceType === 'storage' && request.resourceId === 'fixture-pool'));
+ await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ await page.waitForTimeout(300);
+ const after = await page.evaluate(() => scrollY);
+ const touchAction = await busy.evaluate(el => getComputedStyle(el).touchAction);
+ fs.writeFileSync(path.join(artifacts, 'pan-control.json'), JSON.stringify({before, after, pointerCancels: await busy.getAttribute('data-cancel-count'), touchAction},null,2));
+ assert.ok(after > before + 40, `native pan must scroll: ${before} -> ${after}`);
+ assert.ok(Number(await busy.getAttribute('data-cancel-count')) > 0);
+ assert.ok((await description(busy)).startsWith('3 stored observation times'), 'native scrolling must not select a reading');
+ observations.push({ name, phase: 'native-vertical-pan', before, after, maximum: scrollMetrics.maximum, pointerCancels: Number(await busy.getAttribute('data-cancel-count')), touchAction });
+ await session.detach();
}
+
+ const usage = pool.getByRole('img', { name: 'Capacity history', exact: true });
+ await usage.waitFor();
+ await settled('Capacity history', '3 stored observation times');
+ assert.ok((await inspect(usage, 0)).includes('Used 10.0%'));
+ await record('pool-first', usage, await description(usage));
+ const poolRange = pool.getByRole('combobox', { name: 'History range' });
+ assert.equal(await poolRange.inputValue(), '24h');
+ samples = [point(0)];
+ await poolRange.selectOption('7d');
+ await settled('Capacity history', '1 stored observation time');
+ await panel(usage).getByText('Single observation. No trend yet.').waitFor();
+ // A measured zero is a stored reading.
+ assert.ok((await inspect(usage, 0.5)).includes('Used 0.0%'));
+ await record('pool-zero-singleton', usage, await description(usage));
+ samples = [];
+ await poolRange.selectOption('12h');
+ await panel(usage).getByText('No stored history in this range').waitFor();
+ assert.ok((await inspect(usage, 0.5)).startsWith('No stored history observations.'));
+ assert.equal(await panel(usage).locator('[data-history-series], [data-history-observation]').count(), 0);
+ await record('pool-empty', usage, await description(usage));
+ assert.ok(requests.some(request => request.resourceType === 'disk' && request.resourceId === 'fixture-disk'));
+ assert.ok(requests.some(request => request.resourceType === 'storage' && request.resourceId === 'fixture-pool'));
assert.deepEqual(errors, []);
await browser.close(); browser = null;
}
- fs.writeFileSync(path.join(artifacts, parent ? 'parent.json' : 'result.json'), JSON.stringify({ playwright, expectedPlaywright, parent, observations }, null, 2));
- console.log(JSON.stringify({ result: 'passed', parent, observations: observations.length }));
+ fs.writeFileSync(path.join(artifacts, 'result.json'), JSON.stringify({ playwright, expectedPlaywright, observations }, null, 2));
+ console.log(JSON.stringify({ result: 'passed', observations: observations.length }));
} finally {
if (browser) await browser.close();
await server.close();
diff --git a/frontend-modern/browser-tests/history-touch.tsx b/frontend-modern/browser-tests/history-touch.tsx
index c5eef346b3..bb5cbe1902 100644
--- a/frontend-modern/browser-tests/history-touch.tsx
+++ b/frontend-modern/browser-tests/history-touch.tsx
@@ -1,7 +1,12 @@
+import { createMemo, createSignal } from 'solid-js';
import { render } from 'solid-js/web';
-import { DiskDetail } from '../src/components/Storage/DiskDetail';
+import type { HistoryTimeRange } from '../src/api/charts';
+import { DiskDrawerOverview } from '../src/components/Storage/DiskDrawerOverview';
import { StoragePoolDetail } from '../src/components/Storage/StoragePoolDetail';
+import { GUEST_DRAWER_HISTORY_DEFAULT_RANGE } from '../src/components/Workloads/guestDrawerModel';
+import { extractPhysicalDiskPresentationData } from '../src/features/storageBackups/diskPresentation';
import type { StorageRecord } from '../src/features/storageBackups/models';
+import { useAlertsActivation } from '../src/stores/alertsActivation';
import type { Resource } from '../src/types/resource';
import '../src/index.css';
@@ -37,24 +42,42 @@ const pool: StorageRecord = {
observedAt: Date.now(),
};
-render(
- () => (
+// The disk and pool drawers' Overviews, wired as their drawers wire them.
+const Fixture = () => {
+ const { getDiskTemperatureThresholds } = useAlertsActivation();
+ const diskData = createMemo(() =>
+ extractPhysicalDiskPresentationData(disk, getDiskTemperatureThresholds),
+ );
+ const [diskRange, setDiskRange] = createSignal<HistoryTimeRange>(
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ );
+ const [poolRange, setPoolRange] = createSignal<HistoryTimeRange>(
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ );
+ return (
<main class="min-h-screen space-y-4 bg-surface p-4 text-base-content">
<h1>Storage History touch verification</h1>
- <p>Synthetic stored samples in production disk and pool details.</p>
+ <p>Synthetic stored samples in production disk and pool drawer Overviews.</p>
<section aria-label="Disk fixture" class="max-w-3xl">
- <DiskDetail disk={disk} nodes={[]} />
+ <DiskDrawerOverview
+ disk={disk}
+ diskData={diskData()}
+ historyRange={diskRange()}
+ onHistoryRangeChange={setDiskRange}
+ />
</section>
<section aria-label="Pool fixture" class="max-w-3xl">
- <table class="w-full table-fixed">
- <tbody>
- <StoragePoolDetail record={pool} physicalDisks={[]} summarySeriesId="fixture-pool" />
- </tbody>
- </table>
+ <StoragePoolDetail
+ record={pool}
+ physicalDisks={[]}
+ historyRange={poolRange()}
+ onHistoryRangeChange={setPoolRange}
+ />
</section>
<button class="min-h-11 border px-3">After charts</button>
<div style={{ height: '1000px' }} aria-hidden="true" />
</main>
- ),
- document.getElementById('root')!,
-);
+ );
+};
+
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/frontend-modern/browser-verification/7ba1d11053bdab2f.json b/frontend-modern/browser-verification/7ba1d11053bdab2f.json
new file mode 100644
index 0000000000..e62553f9dc
--- /dev/null
+++ b/frontend-modern/browser-verification/7ba1d11053bdab2f.json
@@ -0,0 +1,165 @@
+{
+ "version": 1,
+ "base_sha": "345babc6a88ccb4d51c7679240e9949fb3f29305",
+ "verified_at": "2026-10-22T15:00:08Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx",
+ "frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx",
+ "frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx",
+ "frontend-modern/src/components/Infrastructure/resourceDetailDrawerKubernetesModel.ts",
+ "frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts",
+ "frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts",
+ "frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx",
+ "frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx",
+ "frontend-modern/src/components/Storage/DiskDetail.tsx",
+ "frontend-modern/src/components/Storage/DiskDrawerOverview.tsx",
+ "frontend-modern/src/components/Storage/StorageDetailKeyValueRow.tsx",
+ "frontend-modern/src/components/Storage/StorageDetailMetricCard.tsx",
+ "frontend-modern/src/components/Storage/StorageGroupRow.tsx",
+ "frontend-modern/src/components/Storage/StoragePoolDetail.tsx",
+ "frontend-modern/src/components/Storage/StoragePoolsTable.tsx",
+ "frontend-modern/src/components/Storage/historyRangeAccess.ts",
+ "frontend-modern/src/components/Storage/physicalDiskAlertOwner.ts",
+ "frontend-modern/src/components/Storage/useDiskDetailModel.ts",
+ "frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx",
+ "frontend-modern/src/components/Workloads/GuestPhysicalDisks.tsx",
+ "frontend-modern/src/components/Workloads/NodeDrawer.tsx",
+ "frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx",
+ "frontend-modern/src/components/shared/DrawerAttentionSection.tsx",
+ "frontend-modern/src/components/shared/tableVisibleColumnSpan.ts",
+ "frontend-modern/src/features/docker/DockerHostActionHistory.tsx",
+ "frontend-modern/src/features/docker/DockerHostDrawer.tsx",
+ "frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx",
+ "frontend-modern/src/features/docker/DockerNativeTableShared.tsx",
+ "frontend-modern/src/features/kubernetes/KubernetesRecordDetail.tsx",
+ "frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx",
+ "frontend-modern/src/features/platformPage/PlatformWindowedRows.tsx",
+ "frontend-modern/src/features/platformPage/platformDetailTimestampRow.ts",
+ "frontend-modern/src/features/proxmox/ProxmoxCephClusterDrawer.tsx",
+ "frontend-modern/src/features/proxmox/ProxmoxCephTable.tsx",
+ "frontend-modern/src/features/proxmox/ProxmoxMailGatewayDrawer.tsx",
+ "frontend-modern/src/features/proxmox/ProxmoxMailGatewayTable.tsx",
+ "frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx",
+ "frontend-modern/src/features/proxmox/proxmoxCephClusterDrawerModel.ts",
+ "frontend-modern/src/features/storageBackups/detailPresentation.ts",
+ "frontend-modern/src/features/storageBackups/diskDetailPresentation.ts",
+ "frontend-modern/src/routing/resourceLinks.ts",
+ "frontend-modern/src/utils/alerts.ts",
+ "frontend-modern/src/utils/k8sDeploymentPresentation.ts",
+ "frontend-modern/src/utils/k8sNamespacePresentation.ts",
+ "frontend-modern/src/utils/swarmPresentation.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx": "deleted",
+ "frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx": "53dfd478dfa19b48690d73e95ba1ac1c962431fa35773f18faa7252570d2118f",
+ "frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx": "74c00c3b336ca3caf26f631dca421630198417f28f5fc1b211697618cce44ce1",
+ "frontend-modern/src/components/Infrastructure/resourceDetailDrawerKubernetesModel.ts": "6397a10b3ea5819b7286b0feaa1819c7c3bb046cacb3ac9a286055e3b7f0c9fa",
+ "frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts": "e737d7455eeb06e515e180a1fb8fb68506e55962f2209d120b8df9cacd50dd3b",
+ "frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts": "29616270c07da8a563a0ce8e38a4aac6a0169c0c2f16e81d1caecb63d8813705",
+ "frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx": "deleted",
+ "frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx": "3a782aa51be6211a9beee5233f40b48b577140486dd94ba89b5adffd35210ca2",
+ "frontend-modern/src/components/Storage/DiskDetail.tsx": "deleted",
+ "frontend-modern/src/components/Storage/DiskDrawerOverview.tsx": "a699a963c037b36d679c7a51ed8dfa76e922174d3337b79f526bbf7c80aa2619",
+ "frontend-modern/src/components/Storage/StorageDetailKeyValueRow.tsx": "deleted",
+ "frontend-modern/src/components/Storage/StorageDetailMetricCard.tsx": "deleted",
+ "frontend-modern/src/components/Storage/StorageGroupRow.tsx": "2dcfd529381a2393b6c12504f33e853c0f14c16c2d90171d5b5cb2838d5d1a74",
+ "frontend-modern/src/components/Storage/StoragePoolDetail.tsx": "abee496e510522979e0889f765ab5a2a9dba788abf1215e1a63ca8c490db62ac",
+ "frontend-modern/src/components/Storage/StoragePoolsTable.tsx": "2ec83e04838923b1e8a74340fe6fa3238e1bab0d8b4acffba4495832f88b72f1",
+ "frontend-modern/src/components/Storage/historyRangeAccess.ts": "deleted",
+ "frontend-modern/src/components/Storage/physicalDiskAlertOwner.ts": "bde3739c41326ee7d47f93adbd11a89fd7192bcce0ccb0f99f4ccbb55cfee01e",
+ "frontend-modern/src/components/Storage/useDiskDetailModel.ts": "deleted",
+ "frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx": "3ca83640464b13e0c49ab54b440f395f3af83874c8d44a48c458bf9550d3875f",
+ "frontend-modern/src/components/Workloads/GuestPhysicalDisks.tsx": "3ee47a7b34de2a350d330bc127d729444b81e92dd6d51722166e1b1233e14eb5",
+ "frontend-modern/src/components/Workloads/NodeDrawer.tsx": "2dcaf4bcfd8777557909d3ddfafa236392860268e542b1aa3abdb17a14f940fe",
+ "frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx": "98b16da0b2a678e30d7a61ddb146ccea5bb985518c82932e8cc55aea9f66bec6",
+ "frontend-modern/src/components/shared/DrawerAttentionSection.tsx": "83a76280ee637c9c9e988679b98234342b7b115da311e907454d2785310d7a28",
+ "frontend-modern/src/components/shared/tableVisibleColumnSpan.ts": "f3bc52eb6e2e35de391c644bf35c9728a9539f33c093e93d6cff1169518a73eb",
+ "frontend-modern/src/features/docker/DockerHostActionHistory.tsx": "3ecb0dd428297b92d91126d844a4bfb41bf87ff20f038a96b3e1bad4c6f071e4",
+ "frontend-modern/src/features/docker/DockerHostDrawer.tsx": "e473913e5b4613133b2ceda6adcf9ee7c7d1c6bd8c36077f182659a6cec1024e",
+ "frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx": "d14a26ab211cc9c45773d65131c460d908943f9ba12a1ec5b47003a3f5b6c284",
+ "frontend-modern/src/features/docker/DockerNativeTableShared.tsx": "af202ae8b37418228115d128a89518fb45725c8dc5d096c6dca23290485e763f",
+ "frontend-modern/src/features/kubernetes/KubernetesRecordDetail.tsx": "b8ab41b3f3c71e41b9049d6544f28ec52c7548d07d5ea3c3a3597d98864143bb",
+ "frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx": "c66634825cd279b75279b2369c9b2c573aff021297b7911dc33192881d6dfdf5",
+ "frontend-modern/src/features/platformPage/PlatformWindowedRows.tsx": "2aac5d0330e771d534a4c524b0b32b3f6b9c8a485959d8e28fa91217e773b66e",
+ "frontend-modern/src/features/platformPage/platformDetailTimestampRow.ts": "a47dd97405c76ce80e65524fc187c2b902a3db12e9a19738a2a8b9bdd55d1510",
+ "frontend-modern/src/features/proxmox/ProxmoxCephClusterDrawer.tsx": "87ac240db9cdaecca27695ccfad30d0dec06858e871c876f7de80bd27218b98a",
+ "frontend-modern/src/features/proxmox/ProxmoxCephTable.tsx": "0f22ac8cae1bfb9ca72a28a29f4dc661c801a764c00172a9a0782724854c07b5",
+ "frontend-modern/src/features/proxmox/ProxmoxMailGatewayDrawer.tsx": "b7f2d0f8761d85fbd1c12fa5b639b8f33a0da64361a5de12a20218e457b88c20",
+ "frontend-modern/src/features/proxmox/ProxmoxMailGatewayTable.tsx": "6ec79b6d518601d58c7a89eeffa6a83e3d83f78bf5623e94cdca4d08d31fb81d",
+ "frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx": "1dcc1cc315ab58042f5fff8dba013d310dc8b9c874446540185665525ae5540e",
+ "frontend-modern/src/features/proxmox/proxmoxCephClusterDrawerModel.ts": "f3457e574e508c29657e85330426e1b61b3d89cd844f3d7998ddc996bd021796",
+ "frontend-modern/src/features/storageBackups/detailPresentation.ts": "deleted",
+ "frontend-modern/src/features/storageBackups/diskDetailPresentation.ts": "c4e879504e1ad74a0df106ad5b71f7007d701b3246e485ec9d8811262880e358",
+ "frontend-modern/src/routing/resourceLinks.ts": "759667ff8d79a3732bd2bbf5d3a9ea986fd3df1060cfb02a390fa30d7079d360",
+ "frontend-modern/src/utils/alerts.ts": "410a18ac197c3c3ef2ee14e2dc5701b833017abd969bc9d884b2a43bd7fb6393",
+ "frontend-modern/src/utils/k8sDeploymentPresentation.ts": "deleted",
+ "frontend-modern/src/utils/k8sNamespacePresentation.ts": "a38afc64df761c166bc098e3b6f04a4c218e704906a18e1cf8337ca8e7338432",
+ "frontend-modern/src/utils/swarmPresentation.ts": "deleted"
+ },
+ "routes": [
+ "/proxmox/overview",
+ "/proxmox/storage",
+ "/proxmox/storage?tab=disks",
+ "/proxmox/replication",
+ "/proxmox/backups/date",
+ "/proxmox/backups/coverage",
+ "/proxmox/ceph",
+ "/proxmox/mail",
+ "/docker/overview",
+ "/docker/images",
+ "/docker/storage",
+ "/docker/networks",
+ "/docker/swarm",
+ "/kubernetes/overview",
+ "/kubernetes/nodes",
+ "/kubernetes/workloads",
+ "/kubernetes/services",
+ "/kubernetes/storage",
+ "/kubernetes/configuration",
+ "/kubernetes/events",
+ "/truenas/overview",
+ "/truenas/storage",
+ "/truenas/storage?kind=disks",
+ "/truenas/services",
+ "/truenas/apps",
+ "/truenas/vms",
+ "/truenas/shares",
+ "/truenas/protection",
+ "/vmware/overview",
+ "/vmware/storage",
+ "/vmware/networks",
+ "/vmware/health",
+ "/vmware/activity",
+ "/standalone/machines",
+ "/standalone/availability"
+ ],
+ "viewports": [
+ {
+ "width": 1440,
+ "height": 900
+ },
+ {
+ "width": 390,
+ "height": 844
+ }
+ ],
+ "states": [
+ "Embedded production build of this change on the full mock estate, signed in through the real login; first drawer of every expandable table on every route opened at both widths (116 drawers) and compared with the same probe on origin/main before this series",
+ "Every drawer has the shared collapse header (92/114 before, 116/116 after); drawer dot equals row dot everywhere (16 mismatches before, 0 after); tab sets are only Overview/Manage plus Mail (PMG) and Namespaces (Kubernetes cluster); no History tab",
+ "Phone drawers fill their table: Kubernetes deployment and pod drawers 253/271px of 362 before, 362/362 after; storage pool and disk drawers full width",
+ "Proxmox Mail Gateway opens the shared resource drawer with Overview (alerts, Worth checking, four charts, closed Details), Manage and Mail; Ceph cluster opens Overview (Worth checking for MDS daemons, capacity history, facts, Pools and Services cards, closed Details) and Manage",
+ "Clipped drawer values across all drawers 27 before, 4 after; no console or page errors on any route"
+ ],
+ "interactions": [
+ "Disclosure button and whole-row click open each drawer; a second row closes the first",
+ "Header click collapses the drawer; Overview -> Manage -> Overview keeps Overview",
+ "Kubernetes cluster drawer Namespaces tab opens; phone charts show the first panel with a Show toggle"
+ ],
+ "browser": {
+ "client": "playwright 1.62.1",
+ "engine": "Chromium",
+ "version": "chromium-1234 headless"
+ },
+ "scope": "Full authenticated application on a mock estate; mock data, not live provider connections."
+}
diff --git a/frontend-modern/scripts/canonical-platform-audit.mjs b/frontend-modern/scripts/canonical-platform-audit.mjs
index 9506ce1eab..458a15dfbe 100644
--- a/frontend-modern/scripts/canonical-platform-audit.mjs
+++ b/frontend-modern/scripts/canonical-platform-audit.mjs
@@ -116,8 +116,6 @@ const ALLOWLIST = new Set([
'src/utils/updatesPresentation.ts',
'src/utils/alertThresholdsPresentation.ts',
'src/utils/environmentLockPresentation.ts',
- 'src/utils/swarmPresentation.ts',
- 'src/utils/k8sDeploymentPresentation.ts',
'src/utils/k8sNamespacePresentation.ts',
'src/components/shared/EnvironmentLockBadge.tsx',
'src/utils/workloadGuestPresentation.ts',
@@ -1032,20 +1030,6 @@ const HELPER_RULES = [
message:
'Do not define local alert email-provider vocabulary, placeholders, or action copy in component code. Use @/utils/alertEmailPresentation instead.',
},
- {
- rule: 'canonical-docker/no-local-swarm-empty-state-copy',
- regex:
- /Loading Swarm services\.\.\.|No services match your filters|No Swarm services found|Enable Swarm service collection in the container runtime agent \(includeServices\) and wait for the next report\.|Try clearing the search\./g,
- message:
- 'Do not define local Swarm services loading or empty-state copy in component code. Use @/utils/swarmPresentation instead.',
- },
- {
- rule: 'canonical-k8s/no-local-deployments-empty-state-copy',
- regex:
- /Loading deployments\.\.\.|Fetching unified resources\.|No deployments match your filters|Try clearing the search or namespace filter\.|No deployments found|Enable the Kubernetes agent deployment collection, then wait for the next report\./g,
- message:
- 'Do not define local Kubernetes deployments loading or empty-state copy in component code. Use @/utils/k8sDeploymentPresentation instead.',
- },
{
rule: 'canonical-k8s/no-local-namespaces-empty-state-copy',
regex:
diff --git a/frontend-modern/scripts/shared-template-registry.json b/frontend-modern/scripts/shared-template-registry.json
index e2e4bae93b..6518fa718d 100644
--- a/frontend-modern/scripts/shared-template-registry.json
+++ b/frontend-modern/scripts/shared-template-registry.json
@@ -211,7 +211,6 @@
{ "path": "src/features/platformPage/PlatformResourceDetailTableRow.tsx" },
{ "path": "src/features/proxmox/ProxmoxCephTable.tsx" },
{ "path": "src/features/proxmox/ProxmoxCoverageTable.tsx" },
- { "path": "src/features/proxmox/ProxmoxMailGatewayTable.tsx" },
{ "path": "src/features/proxmox/ProxmoxNodesTable.tsx" },
{ "path": "src/features/truenas/TrueNASAlertsTable.tsx" },
{ "path": "src/features/truenas/TrueNASProtectionTable.tsx" },
@@ -340,8 +339,7 @@
{ "path": "src/components/Workloads/NodeDrawer.tsx" },
{ "path": "src/components/shared/DetailSectionTable.tsx" },
{ "path": "src/features/docker/DockerHostDrawer.tsx" },
- { "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx" },
- { "path": "src/features/proxmox/ProxmoxMailGatewayDrawer.tsx" }
+ { "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx" }
],
"forbiddenPatterns": [],
"proof": [
@@ -450,8 +448,7 @@
{ "path": "src/components/shared/cards/SystemInfoCard.tsx" },
{ "path": "src/components/shared/cards/TemperaturesCard.tsx" },
{ "path": "src/components/Workloads/DrawerDiskListCard.tsx" },
- { "path": "src/features/docker/DockerHostDrawerOverview.tsx" },
- { "path": "src/features/storageBackups/detailPresentation.ts" }
+ { "path": "src/features/docker/DockerHostDrawerOverview.tsx" }
],
"proof": [
"src/components/shared/SharedPrimitives.guardrails.test.ts",
@@ -1576,7 +1573,6 @@
{ "path": "src/components/Alerts/EmailProviderSelect.tsx" },
{ "path": "src/components/Alerts/WebhookConfigForm.tsx" },
{ "path": "src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx" },
- { "path": "src/components/Kubernetes/K8sDeploymentsDrawer.tsx" },
{ "path": "src/components/OrgSwitcher.tsx" },
{ "path": "src/components/Settings/AIChatMaintenanceSection.tsx" },
{ "path": "src/components/Settings/AIModelSelectionSection.tsx" },
@@ -1597,7 +1593,6 @@
{ "path": "src/components/Settings/RecoverySettingsPanel.tsx" },
{ "path": "src/components/Settings/RolesEditorDialog.tsx" },
{ "path": "src/components/Settings/SystemLogsPanel.tsx" },
- { "path": "src/components/Storage/DiskDetail.tsx" },
{ "path": "src/components/Storage/StoragePageControls.tsx" },
{ "path": "src/components/Workloads/GuestDrawerHistory.tsx" },
{ "path": "src/components/shared/FilterBar/AddFilterMenu.tsx" },
@@ -2077,10 +2072,7 @@
"export": "PlatformDetailTable"
},
"requiredConsumers": [
- { "path": "src/components/Docker/SwarmServicesDrawer.tsx" },
- { "path": "src/components/Kubernetes/K8sDeploymentsDrawer.tsx" },
{ "path": "src/components/Kubernetes/K8sNamespacesDrawer.tsx" },
- { "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx" },
{ "path": "src/features/proxmox/ProxmoxCoverageTable.tsx" },
{ "path": "src/features/proxmox/ProxmoxMailGatewayDrawer.tsx" }
],
@@ -2592,9 +2584,9 @@
"requiredConsumers": [
{ "path": "src/components/Kubernetes/K8sNamespacesDrawer.tsx" },
{ "path": "src/features/proxmox/ProxmoxBackupServersTable.tsx" },
- { "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx" },
{ "path": "src/features/proxmox/ProxmoxMailGatewayDrawer.tsx" },
- { "path": "src/features/proxmox/ProxmoxMailGatewayTable.tsx" }
+ { "path": "src/features/proxmox/ProxmoxMailGatewayTable.tsx" },
+ { "path": "src/features/proxmox/proxmoxCephClusterDrawerModel.ts" }
],
"forbiddenPatterns": [
{
@@ -2605,10 +2597,6 @@
"path": "src/features/proxmox/ProxmoxBackupServersTable.tsx",
"patterns": ["row.backupCount.toLocaleString()"]
},
- {
- "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx",
- "patterns": ["pool.objects.toLocaleString()"]
- },
{
"path": "src/features/proxmox/ProxmoxMailGatewayDrawer.tsx",
"patterns": ["function formatNumber", "Math.round(value).toLocaleString()"]
@@ -2616,6 +2604,10 @@
{
"path": "src/features/proxmox/ProxmoxMailGatewayTable.tsx",
"patterns": ["const formatLocaleCount", "value.toLocaleString()"]
+ },
+ {
+ "path": "src/features/proxmox/proxmoxCephClusterDrawerModel.ts",
+ "patterns": ["pool.objects.toLocaleString()"]
}
],
"proof": [
@@ -2635,7 +2627,6 @@
"requiredConsumers": [
{ "path": "src/features/docker/DockerNativeTableShared.tsx" },
{ "path": "src/features/docker/DockerServicesTable.tsx" },
- { "path": "src/components/Docker/SwarmServicesDrawer.tsx" },
{ "path": "src/features/kubernetes/KubernetesAutoscalingTable.tsx" },
{ "path": "src/features/kubernetes/KubernetesControllersTable.tsx" },
{ "path": "src/features/kubernetes/KubernetesDeploymentsTable.tsx" },
@@ -2656,13 +2647,6 @@
"path": "src/features/docker/DockerServicesTable.tsx",
"patterns": ["const replicaCount", "<span class=\"tabular-nums\">{value ?? 0}</span>"]
},
- {
- "path": "src/components/Docker/SwarmServicesDrawer.tsx",
- "patterns": [
- "<span class=\"tabular-nums\">{desired()}</span>",
- "<span class=\"tabular-nums\">{running()}</span>"
- ]
- },
{
"path": "src/features/kubernetes/KubernetesAutoscalingTable.tsx",
"patterns": [
@@ -2769,11 +2753,11 @@
},
"requiredConsumers": [
{ "path": "src/features/proxmox/ProxmoxBackupServersTable.tsx" },
- { "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx" },
{ "path": "src/features/proxmox/ProxmoxCephTable.tsx" },
{ "path": "src/features/proxmox/ProxmoxMailGatewayDrawer.tsx" },
{ "path": "src/features/proxmox/ProxmoxNodesTable.tsx" },
- { "path": "src/features/truenas/TrueNASSystemsTable.tsx" }
+ { "path": "src/features/truenas/TrueNASSystemsTable.tsx" },
+ { "path": "src/features/proxmox/proxmoxCephClusterDrawerModel.ts" }
],
"forbiddenPatterns": [
{
@@ -2785,8 +2769,8 @@
]
},
{
- "path": "src/features/proxmox/ProxmoxCephClusterDrawer.tsx",
- "patterns": ["clamped.toFixed(1)}%"]
+ "path": "src/features/proxmox/proxmoxCephClusterDrawerModel.ts",
+ "patterns": ["clamped.toFixed(1)}%", "percentUsed.toFixed(1)}%"]
},
{
"path": "src/features/proxmox/ProxmoxCephTable.tsx",
@@ -3081,8 +3065,6 @@
"export": "SearchInput"
},
"requiredConsumers": [
- { "path": "src/components/Docker/SwarmServicesDrawer.tsx" },
- { "path": "src/components/Kubernetes/K8sDeploymentsDrawer.tsx" },
{ "path": "src/components/Kubernetes/K8sNamespacesDrawer.tsx" },
{ "path": "src/components/Settings/SettingsPageShell.tsx" },
{ "path": "src/components/shared/FilterBar/FilterBar.tsx" }
@@ -4264,12 +4246,12 @@
{
"id": "platform-table-local-swarm-count-spans",
"category": "platform-table-text-value",
- "summary": "Docker Swarm table drawers must not render desired/running service counts with local tabular spans.",
+ "summary": "Docker Swarm tables must not render desired/running service counts with local tabular spans.",
"canonical": {
"path": "src/features/platformPage/sharedPlatformPage.tsx",
"export": "PlatformTableNumberValue"
},
- "scopes": ["src/components/Docker"],
+ "scopes": ["src/features/docker"],
"extensions": [".tsx"],
"allPatterns": ["desiredTasks", "runningTasks", "class=\"tabular-nums\""],
"legacyReason": "Retired migration debt. Swarm desired/running count cells must route through PlatformTableNumberValue so drawer tables and platform tables share numeric cell rendering.",
diff --git a/frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx b/frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx
deleted file mode 100644
index 911d4ebea3..0000000000
--- a/frontend-modern/src/components/Docker/SwarmServicesDrawer.tsx
+++ /dev/null
@@ -1,394 +0,0 @@
-import type { Component } from 'solid-js';
-import { For, Show, createMemo, createResource, createSignal } from 'solid-js';
-import { apiFetchJSON } from '@/utils/apiClient';
-import { Card } from '@/components/shared/Card';
-import { SearchInput } from '@/components/shared/SearchInput';
-import { StatusDot } from '@/components/shared/StatusDot';
-import { TableRow, TableHead, TableCell } from '@/components/shared/Table';
-import { EmptyState } from '@/components/shared/EmptyState';
-import { getSimpleStatusIndicator } from '@/utils/status';
-import { asTrimmedString } from '@/utils/stringUtils';
-import {
- PlatformDetailTable,
- PlatformDetailTableBody,
- PlatformDetailTableHeader,
- PlatformTableNumberValue,
- getPlatformTableCellClassForKind,
- getPlatformTableHeadClassForKind,
-} from '@/features/platformPage/sharedPlatformPage';
-import {
- formatSwarmClusterId,
- formatSwarmClusterSummary,
- formatSwarmControlLabel,
- formatSwarmRoleLabel,
- formatSwarmStateLabel,
- getSwarmDrawerPresentation,
- getSwarmServicesEmptyState,
- getSwarmServicesLoadingState,
-} from '@/utils/swarmPresentation';
-
-const PAGE_LIMIT = 100;
-const MAX_PAGES = 20;
-
-type SwarmInfo = {
- nodeId?: string;
- nodeRole?: string;
- localState?: string;
- controlAvailable?: boolean;
- clusterId?: string;
- clusterName?: string;
- scope?: string;
- error?: string;
-};
-
-type DockerServiceUpdate = {
- state?: string;
- message?: string;
- completedAt?: string;
-};
-
-type DockerServicePort = {
- name?: string;
- protocol?: string;
- targetPort?: number;
- publishedPort?: number;
- publishMode?: string;
-};
-
-type DockerServiceResource = {
- id: string;
- name?: string;
- status?: string;
- docker?: {
- serviceId?: string;
- stack?: string;
- image?: string;
- mode?: string;
- desiredTasks?: number;
- runningTasks?: number;
- completedTasks?: number;
- serviceUpdate?: DockerServiceUpdate;
- endpointPorts?: DockerServicePort[];
- };
-};
-
-type ResourcesListResponse = {
- data?: DockerServiceResource[];
- meta?: {
- totalPages?: number;
- };
-};
-
-const buildServicesUrl = (cluster: string, page: number) => {
- const params = new URLSearchParams();
- params.set('type', 'docker-service');
- params.set('cluster', cluster);
- params.set('page', String(page));
- params.set('limit', String(PAGE_LIMIT));
- return `/api/resources?${params.toString()}`;
-};
-
-const fetchAllServices = async (cluster: string): Promise<DockerServiceResource[]> => {
- const first = await apiFetchJSON<ResourcesListResponse>(buildServicesUrl(cluster, 1), {
- cache: 'no-store',
- });
- const firstData = Array.isArray(first?.data) ? first.data : [];
- const totalPages = Number.isFinite(first?.meta?.totalPages)
- ? Math.max(1, Number(first.meta?.totalPages))
- : 1;
-
- const services: DockerServiceResource[] = [...firstData];
-
- const cappedPages = Math.min(totalPages, MAX_PAGES);
- if (cappedPages > 1) {
- const requests: Array<Promise<ResourcesListResponse>> = [];
- for (let page = 2; page <= cappedPages; page += 1) {
- requests.push(
- apiFetchJSON<ResourcesListResponse>(buildServicesUrl(cluster, page), { cache: 'no-store' }),
- );
- }
-
- const settled = await Promise.allSettled(requests);
- for (const result of settled) {
- if (result.status !== 'fulfilled') continue;
- const data = Array.isArray(result.value?.data) ? result.value.data : [];
- services.push(...data);
- }
- }
-
- return Array.from(new Map(services.map((s) => [s.id, s])).values());
-};
-
-const formatUpdate = (update?: DockerServiceUpdate) => {
- const state = asTrimmedString(update?.state) ?? '';
- const message = asTrimmedString(update?.message) ?? '';
- if (!state && !message) return '—';
- if (state && message) return `${state}: ${message}`;
- return state || message;
-};
-
-const formatPorts = (ports?: DockerServicePort[]) => {
- if (!ports || ports.length === 0) return '—';
- return ports
- .map((p) => {
- const target = typeof p.targetPort === 'number' ? String(p.targetPort) : '';
- const published = typeof p.publishedPort === 'number' ? String(p.publishedPort) : '';
- const proto = asTrimmedString(p.protocol) || 'tcp';
- if (published && target) return `${published}->${target}/${proto}`;
- if (target) return `${target}/${proto}`;
- return '';
- })
- .filter(Boolean)
- .join(', ');
-};
-
-export const SwarmServicesDrawer: Component<{ cluster: string; swarm?: SwarmInfo }> = (props) => {
- const [search, setSearch] = createSignal('');
- const drawerPresentation = getSwarmDrawerPresentation();
-
- const clusterKey = createMemo(() => asTrimmedString(props.cluster) ?? '');
-
- const [services] = createResource(
- clusterKey,
- async (cluster) => {
- if (!cluster) return [];
- return fetchAllServices(cluster);
- },
- { initialValue: [] },
- );
-
- const filteredServices = createMemo(() => {
- const term = (asTrimmedString(search()) ?? '').toLowerCase();
- return services()
- .filter((svc) => {
- if (!term) return true;
- const name = asTrimmedString(svc.name) || svc.id;
- const stack = asTrimmedString(svc.docker?.stack) ?? '';
- const image = asTrimmedString(svc.docker?.image) ?? '';
- return [name, stack, image].some((value) => value.toLowerCase().includes(term));
- })
- .sort((a, b) => {
- const aName = (asTrimmedString(a.name) || a.id).toLowerCase();
- const bName = (asTrimmedString(b.name) || b.id).toLowerCase();
- if (aName !== bName) return aName < bName ? -1 : 1;
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
- });
- });
-
- const swarm = createMemo(() => props.swarm);
- const clusterName = createMemo(
- () =>
- asTrimmedString(swarm()?.clusterName) || asTrimmedString(swarm()?.clusterId) || clusterKey(),
- );
- const clusterId = createMemo(() => asTrimmedString(swarm()?.clusterId) ?? '');
-
- const headingId = () => `swarm-services-drawer-heading-${clusterKey() || 'cluster'}`;
-
- return (
- <section class="space-y-3" aria-labelledby={headingId()}>
- <h2 id={headingId()} class="sr-only">
- {clusterName() || 'Swarm cluster'} services
- </h2>
- <Card padding="md">
- <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
- <div class="min-w-0">
- <div class="text-sm font-semibold text-base-content">{drawerPresentation.title}</div>
- <div class="text-xs text-muted truncate" title={clusterName()}>
- {formatSwarmClusterSummary(clusterName())}
- </div>
- </div>
-
- <div class="flex flex-wrap items-center gap-2">
- <div class="w-48">
- <SearchInput
- value={search}
- onChange={setSearch}
- placeholder={drawerPresentation.searchPlaceholder}
- inputClass="py-1 text-xs font-medium shadow-xs"
- typeToSearch
- clearOnEscape
- />
- </div>
- </div>
- </div>
-
- <Show when={clusterId()}>
- <div class="mt-2 text-[10px] text-muted truncate" title={clusterId()}>
- {formatSwarmClusterId(clusterId())}
- </div>
- </Show>
-
- <Show
- when={
- asTrimmedString(swarm()?.nodeRole) ||
- asTrimmedString(swarm()?.localState) ||
- typeof swarm()?.controlAvailable === 'boolean'
- }
- >
- <div class="mt-2 flex flex-wrap gap-2 text-[11px]">
- <Show when={asTrimmedString(swarm()?.nodeRole)}>
- <span class="inline-flex items-center rounded-sm bg-surface-alt px-2 py-0.5 text-base-content">
- {formatSwarmRoleLabel(asTrimmedString(swarm()?.nodeRole))}
- </span>
- </Show>
- <Show when={asTrimmedString(swarm()?.localState)}>
- <span class="inline-flex items-center rounded-sm bg-surface-alt px-2 py-0.5 text-base-content">
- {formatSwarmStateLabel(asTrimmedString(swarm()?.localState))}
- </span>
- </Show>
- <Show when={typeof swarm()?.controlAvailable === 'boolean'}>
- <span class="inline-flex items-center rounded-sm bg-surface-alt px-2 py-0.5 text-base-content">
- {formatSwarmControlLabel(swarm()?.controlAvailable)}
- </span>
- </Show>
- </div>
- </Show>
-
- <Show when={asTrimmedString(swarm()?.error)}>
- <div class="mt-2 rounded-sm border border-amber-200 bg-amber-50 px-2 py-1.5 text-[10px] text-amber-800 dark:border-amber-700 dark:bg-amber-900/25 dark:text-amber-200">
- {asTrimmedString(swarm()?.error)}
- </div>
- </Show>
- </Card>
-
- <Show
- when={services.loading}
- fallback={
- <Show
- when={filteredServices().length > 0}
- fallback={
- <Card padding="lg">
- <EmptyState {...getSwarmServicesEmptyState(services().length > 0)} />
- </Card>
- }
- >
- <Card padding="none" tone="card" class="overflow-hidden">
- <PlatformDetailTable class="min-w-0 table-fixed text-xs">
- <PlatformDetailTableHeader>
- <TableHead class={`${getPlatformTableHeadClassForKind('name')} md:w-[18%]`}>
- {drawerPresentation.serviceColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} hidden md:w-[13%] sm:table-cell`}
- >
- {drawerPresentation.stackColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} swarm-service-detail-column md:w-[22%]`}
- >
- {drawerPresentation.imageColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} swarm-service-detail-column md:w-[10%]`}
- >
- {drawerPresentation.modeColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} md:w-[8%]`}
- >
- {drawerPresentation.desiredColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} md:w-[8%]`}
- >
- {drawerPresentation.runningColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} hidden md:w-[12%] sm:table-cell`}
- >
- {drawerPresentation.updateColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} swarm-service-detail-column md:w-[9%]`}
- >
- {drawerPresentation.portsColumnLabel}
- </TableHead>
- </PlatformDetailTableHeader>
- <PlatformDetailTableBody>
- <For each={filteredServices()}>
- {(svc) => {
- const name = () => asTrimmedString(svc.name) || svc.id;
- const stack = () => asTrimmedString(svc.docker?.stack) || '—';
- const image = () => asTrimmedString(svc.docker?.image) || '—';
- const mode = () => asTrimmedString(svc.docker?.mode) || '—';
- const desired = () => svc.docker?.desiredTasks ?? 0;
- const running = () => svc.docker?.runningTasks ?? 0;
- const update = () => formatUpdate(svc.docker?.serviceUpdate);
- const ports = () => formatPorts(svc.docker?.endpointPorts);
- const status = () => getSimpleStatusIndicator(svc.status);
-
- return (
- <TableRow class="text-[11px] sm:text-xs">
- <TableCell class={getPlatformTableCellClassForKind('name')}>
- <div class="flex items-center gap-2 min-w-0">
- <StatusDot
- size="sm"
- variant={status().variant}
- title={svc.status || 'unknown'}
- ariaHidden
- />
- <span class="font-semibold text-base-content truncate" title={name()}>
- {name()}
- </span>
- </div>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content sm:table-cell`}
- >
- <span class="block truncate" title={stack()}>
- {stack()}
- </span>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} swarm-service-detail-column text-base-content`}
- >
- <span class="block truncate" title={image()}>
- {image()}
- </span>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} swarm-service-detail-column text-base-content`}
- >
- {mode()}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content`}
- >
- <PlatformTableNumberValue value={desired()} />
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content`}
- >
- <PlatformTableNumberValue value={running()} />
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content sm:table-cell`}
- >
- <span class="block truncate" title={update()}>
- {update()}
- </span>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} swarm-service-detail-column text-base-content`}
- >
- <span class="block truncate font-mono text-[11px]" title={ports()}>
- {ports()}
- </span>
- </TableCell>
- </TableRow>
- );
- }}
- </For>
- </PlatformDetailTableBody>
- </PlatformDetailTable>
- </Card>
- </Show>
- }
- >
- <Card padding="lg">
- <div class="text-xs text-muted">{getSwarmServicesLoadingState().text}</div>
- </Card>
- </Show>
- </section>
- );
-};
diff --git a/frontend-modern/src/components/Docker/__tests__/SwarmServicesDrawer.test.tsx b/frontend-modern/src/components/Docker/__tests__/SwarmServicesDrawer.test.tsx
deleted file mode 100644
index 7e38d3d0df..0000000000
--- a/frontend-modern/src/components/Docker/__tests__/SwarmServicesDrawer.test.tsx
+++ /dev/null
@@ -1,902 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen, fireEvent, cleanup, waitFor } from '@solidjs/testing-library';
-
-// ── Hoisted mocks ──────────────────────────────────────────────────────
-
-const { apiFetchJSONMock } = vi.hoisted(() => ({
- apiFetchJSONMock: vi.fn(),
-}));
-
-// ── Module mocks ───────────────────────────────────────────────────────
-
-vi.mock('@/utils/apiClient', () => ({
- apiFetchJSON: apiFetchJSONMock,
-}));
-
-vi.mock('@/components/shared/Card', () => ({
- Card: (props: any) => (
- <div data-testid="card" class={props.class}>
- {props.children}
- </div>
- ),
-}));
-
-vi.mock('@/components/shared/Table', () => ({
- Table: (props: any) => (
- <table data-testid="table" class={props.class}>
- {props.children}
- </table>
- ),
- TableHeader: (props: any) => <thead class={props.class}>{props.children}</thead>,
- TableBody: (props: any) => <tbody class={props.class}>{props.children}</tbody>,
- TableRow: (props: any) => <tr class={props.class}>{props.children}</tr>,
- TableHead: (props: any) => <th class={props.class}>{props.children}</th>,
- TableCell: (props: any) => (
- <td class={props.class} title={props.title}>
- {props.children}
- </td>
- ),
-}));
-
-vi.mock('@/components/shared/EmptyState', () => ({
- EmptyState: (props: any) => (
- <div data-testid="empty-state">
- <span data-testid="empty-title">{props.title}</span>
- <span data-testid="empty-description">{props.description}</span>
- </div>
- ),
-}));
-
-// ── Import after mocks ─────────────────────────────────────────────────
-
-import { SwarmServicesDrawer } from '../SwarmServicesDrawer';
-
-// ── Helpers ─────────────────────────────────────────────────────────────
-
-type DockerServiceResource = {
- id: string;
- name?: string;
- status?: string;
- docker?: {
- serviceId?: string;
- stack?: string;
- image?: string;
- mode?: string;
- desiredTasks?: number;
- runningTasks?: number;
- completedTasks?: number;
- serviceUpdate?: { state?: string; message?: string; completedAt?: string };
- endpointPorts?: Array<{
- name?: string;
- protocol?: string;
- targetPort?: number;
- publishedPort?: number;
- publishMode?: string;
- }>;
- };
-};
-
-function makeService(overrides: Partial<DockerServiceResource> = {}): DockerServiceResource {
- return {
- id: 'svc-1',
- name: 'my-service',
- status: 'running',
- docker: {
- serviceId: 'svc-1',
- stack: 'my-stack',
- image: 'nginx:latest',
- mode: 'replicated',
- desiredTasks: 3,
- runningTasks: 3,
- completedTasks: 0,
- serviceUpdate: undefined,
- endpointPorts: [],
- },
- ...overrides,
- };
-}
-
-function mockApiResponse(data: DockerServiceResource[], totalPages = 1) {
- apiFetchJSONMock.mockResolvedValueOnce({ data, meta: { totalPages } });
-}
-
-// ── Tests ───────────────────────────────────────────────────────────────
-
-afterEach(() => {
- cleanup();
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('SwarmServicesDrawer', () => {
- describe('swarm info card', () => {
- it('shows cluster name when swarm info is provided', async () => {
- mockApiResponse([]);
- render(() => (
- <SwarmServicesDrawer
- cluster="cluster-1"
- swarm={{ clusterName: 'Production Swarm', clusterId: 'abc123' }}
- />
- ));
-
- expect(screen.getByText('Cluster: Production Swarm')).toBeInTheDocument();
- // Flush pending createResource microtask
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('falls back to clusterId when clusterName is empty', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="cluster-1" swarm={{ clusterId: 'abc123' }} />);
-
- expect(screen.getByText('Cluster: abc123')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('falls back to cluster prop when swarm has no name or id', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="my-cluster" swarm={{}} />);
-
- expect(screen.getByText('Cluster: my-cluster')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('shows "No Swarm cluster detected" when cluster prop is empty', () => {
- // Empty cluster = falsy source = resource not fetched
- render(() => <SwarmServicesDrawer cluster="" />);
-
- expect(screen.getByText('No Swarm cluster detected')).toBeInTheDocument();
- });
-
- it('displays cluster ID when available', async () => {
- mockApiResponse([]);
- render(() => (
- <SwarmServicesDrawer
- cluster="c1"
- swarm={{ clusterId: 'swarm-id-xyz', clusterName: 'Prod' }}
- />
- ));
-
- expect(screen.getByText(/Cluster ID:/)).toBeInTheDocument();
- expect(screen.getByText(/swarm-id-xyz/)).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('does not display cluster ID section when clusterId is empty', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ clusterName: 'Prod' }} />);
-
- expect(screen.queryByText(/Cluster ID:/)).not.toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('shows node role badge', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ nodeRole: 'manager' }} />);
-
- expect(screen.getByText('Role: manager')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('shows local state badge', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ localState: 'active' }} />);
-
- expect(screen.getByText('State: active')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('shows control available badge', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ controlAvailable: true }} />);
-
- expect(screen.getByText('Control: available')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('shows control unavailable badge', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ controlAvailable: false }} />);
-
- expect(screen.getByText('Control: unavailable')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('shows swarm error message', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ error: 'Node is draining' }} />);
-
- expect(screen.getByText('Node is draining')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
-
- it('does not show error section when error is empty', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" swarm={{ error: '' }} />);
-
- // No amber error box rendered
- const errorBoxes = document.querySelectorAll('.bg-amber-50');
- expect(errorBoxes.length).toBe(0);
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
- });
-
- describe('loading state', () => {
- it('shows loading message while services are being fetched', async () => {
- // Use a controllable promise — resolve before cleanup to prevent SolidJS scheduler corruption
- let resolveLoading!: (v: unknown) => void;
- apiFetchJSONMock.mockReturnValueOnce(
- new Promise((resolve) => {
- resolveLoading = resolve;
- }),
- );
-
- try {
- render(() => <SwarmServicesDrawer cluster="c1" />);
- expect(screen.getByText('Loading Swarm services...')).toBeInTheDocument();
- } finally {
- // Always resolve before cleanup to prevent SolidJS scheduler corruption
- resolveLoading({ data: [], meta: { totalPages: 1 } });
- await new Promise((r) => setTimeout(r, 0));
- }
- });
- });
-
- describe('empty states', () => {
- it('shows "No Swarm services found" when API returns empty data', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- // Wait for resource to resolve
- await waitFor(() => {
- expect(screen.getByTestId('empty-state')).toBeInTheDocument();
- });
-
- expect(screen.getByTestId('empty-title')).toHaveTextContent('No Swarm services found');
- });
-
- it('shows "No services match your filters" when search filters everything out', async () => {
- mockApiResponse([makeService({ id: 'svc-1', name: 'nginx' })]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('nginx')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search services...');
- fireEvent.input(input, { target: { value: 'nonexistent-service-xyz' } });
-
- expect(screen.getByTestId('empty-title')).toHaveTextContent('No services match your filters');
- });
- });
-
- describe('services table', () => {
- it('renders service rows with correct data', async () => {
- const svc = makeService({
- id: 'svc-1',
- name: 'web-frontend',
- status: 'running',
- docker: {
- stack: 'prod',
- image: 'nginx:1.25',
- mode: 'replicated',
- desiredTasks: 3,
- runningTasks: 2,
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('web-frontend')).toBeInTheDocument();
- });
-
- expect(screen.getByText('prod')).toBeInTheDocument();
- expect(screen.getByText('nginx:1.25')).toBeInTheDocument();
- expect(screen.getByText('replicated')).toBeInTheDocument();
- expect(screen.getByText('3')).toBeInTheDocument();
- expect(screen.getByText('2')).toBeInTheDocument();
- });
-
- it('uses the shared platform table spacing and divider contract', async () => {
- mockApiResponse([makeService({ id: 'svc-1', name: 'web-frontend' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('web-frontend')).toBeInTheDocument();
- });
-
- expect(screen.getByTestId('table')).toHaveClass('table-fixed');
- expect(container.querySelector('thead tr')).toHaveClass('bg-surface-alt');
- expect(container.querySelector('tbody')).toHaveClass('divide-y', 'divide-border');
- expect(container.querySelector('tbody')).not.toHaveClass('divide-border-subtle');
- expect(container.querySelector('th')).toHaveClass('px-1.5', 'py-0.5');
- });
-
- it('uses service id as name when name is empty', async () => {
- const svc = makeService({ id: 'svc-abc', name: '' });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-abc')).toBeInTheDocument();
- });
- });
-
- it('shows dash for missing optional fields', async () => {
- const svc = makeService({
- id: 'svc-1',
- name: 'bare-svc',
- docker: {
- stack: undefined,
- image: undefined,
- mode: undefined,
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('bare-svc')).toBeInTheDocument();
- });
-
- // Stack, image, mode should all show '—'
- const dashes = screen.getAllByText('—');
- expect(dashes.length).toBeGreaterThanOrEqual(3);
- });
-
- it('shows 0 for desiredTasks and runningTasks when missing', async () => {
- const svc = makeService({
- id: 'svc-1',
- name: 'zero-svc',
- docker: { desiredTasks: undefined, runningTasks: undefined },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('zero-svc')).toBeInTheDocument();
- });
-
- const zeros = screen.getAllByText('0');
- expect(zeros.length).toBeGreaterThanOrEqual(2);
- });
- });
-
- describe('search filtering', () => {
- it('filters by service name', async () => {
- mockApiResponse([
- makeService({ id: '1', name: 'nginx-proxy' }),
- makeService({ id: '2', name: 'redis-cache' }),
- ]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('nginx-proxy')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search services...');
- fireEvent.input(input, { target: { value: 'redis' } });
-
- expect(screen.queryByText('nginx-proxy')).not.toBeInTheDocument();
- expect(screen.getByText('redis-cache')).toBeInTheDocument();
- });
-
- it('filters by stack name', async () => {
- mockApiResponse([
- makeService({ id: '1', name: 'svc-a', docker: { stack: 'monitoring' } }),
- makeService({ id: '2', name: 'svc-b', docker: { stack: 'app' } }),
- ]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-a')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search services...');
- fireEvent.input(input, { target: { value: 'monitoring' } });
-
- expect(screen.getByText('svc-a')).toBeInTheDocument();
- expect(screen.queryByText('svc-b')).not.toBeInTheDocument();
- });
-
- it('filters by image name', async () => {
- mockApiResponse([
- makeService({ id: '1', name: 'svc-a', docker: { image: 'postgres:15' } }),
- makeService({ id: '2', name: 'svc-b', docker: { image: 'nginx:latest' } }),
- ]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-a')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search services...');
- fireEvent.input(input, { target: { value: 'postgres' } });
-
- expect(screen.getByText('svc-a')).toBeInTheDocument();
- expect(screen.queryByText('svc-b')).not.toBeInTheDocument();
- });
-
- it('search is case-insensitive', async () => {
- mockApiResponse([makeService({ id: '1', name: 'MyService' })]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('MyService')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search services...');
- fireEvent.input(input, { target: { value: 'MYSERVICE' } });
-
- expect(screen.getByText('MyService')).toBeInTheDocument();
- });
-
- it('shows all services when search is cleared', async () => {
- mockApiResponse([
- makeService({ id: '1', name: 'alpha' }),
- makeService({ id: '2', name: 'beta' }),
- ]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('alpha')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search services...');
- fireEvent.input(input, { target: { value: 'alpha' } });
- expect(screen.queryByText('beta')).not.toBeInTheDocument();
-
- fireEvent.input(input, { target: { value: '' } });
- expect(screen.getByText('alpha')).toBeInTheDocument();
- expect(screen.getByText('beta')).toBeInTheDocument();
- });
- });
-
- describe('sorting', () => {
- it('sorts services alphabetically by name', async () => {
- mockApiResponse([
- makeService({ id: '1', name: 'zebra' }),
- makeService({ id: '2', name: 'alpha' }),
- makeService({ id: '3', name: 'middle' }),
- ]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('zebra')).toBeInTheDocument();
- });
-
- // Check DOM order: alpha < middle < zebra
- const rows = container.querySelectorAll('tr');
- const names = Array.from(rows)
- .map((row) => row.querySelector('.font-semibold')?.textContent)
- .filter(Boolean);
-
- expect(names).toEqual(['alpha', 'middle', 'zebra']);
- });
- });
-
- describe('formatUpdate helper', () => {
- it('shows dash when no service update', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-no-update',
- docker: { serviceUpdate: undefined },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-no-update')).toBeInTheDocument();
- });
-
- // Update column should have '—'
- const dashes = screen.getAllByText('—');
- expect(dashes.length).toBeGreaterThanOrEqual(1);
- });
-
- it('shows "state: message" when both are present', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-updating',
- docker: {
- serviceUpdate: { state: 'updating', message: 'rolling back' },
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('updating: rolling back')).toBeInTheDocument();
- });
- });
-
- it('shows only state when message is empty', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-state-only',
- docker: {
- serviceUpdate: { state: 'completed', message: '' },
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('completed')).toBeInTheDocument();
- });
- });
-
- it('shows only message when state is empty', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-msg-only',
- docker: {
- serviceUpdate: { state: '', message: 'rollback complete' },
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('rollback complete')).toBeInTheDocument();
- });
- });
- });
-
- describe('formatPorts helper', () => {
- it('shows dash when no ports', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-no-ports',
- docker: { endpointPorts: [] },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-no-ports')).toBeInTheDocument();
- });
-
- // Ports column should show '—'
- const dashes = screen.getAllByText('—');
- expect(dashes.length).toBeGreaterThanOrEqual(1);
- });
-
- it('formats published->target/protocol for a single port', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-port',
- docker: {
- endpointPorts: [{ publishedPort: 8080, targetPort: 80, protocol: 'tcp' }],
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('8080->80/tcp')).toBeInTheDocument();
- });
- });
-
- it('formats multiple ports comma-separated', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-multi-ports',
- docker: {
- endpointPorts: [
- { publishedPort: 8080, targetPort: 80, protocol: 'tcp' },
- { publishedPort: 8443, targetPort: 443, protocol: 'tcp' },
- ],
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('8080->80/tcp, 8443->443/tcp')).toBeInTheDocument();
- });
- });
-
- it('shows only target/protocol when publishedPort is missing', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-target-only',
- docker: {
- endpointPorts: [{ targetPort: 3000 }],
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('3000/tcp')).toBeInTheDocument();
- });
- });
-
- it('defaults protocol to tcp when not specified', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-default-proto',
- docker: {
- endpointPorts: [{ publishedPort: 80, targetPort: 80 }],
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('80->80/tcp')).toBeInTheDocument();
- });
- });
-
- it('uses specified protocol (udp)', async () => {
- const svc = makeService({
- id: '1',
- name: 'svc-udp',
- docker: {
- endpointPorts: [{ publishedPort: 53, targetPort: 53, protocol: 'udp' }],
- },
- });
- mockApiResponse([svc]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('53->53/udp')).toBeInTheDocument();
- });
- });
- });
-
- describe('statusTone helper (via DOM classes)', () => {
- it('applies green class for running status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-running', status: 'running' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-running')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-emerald-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies green class for online status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-online', status: 'online' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-online')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-emerald-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies green class for healthy status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-healthy', status: 'healthy' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-healthy')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-emerald-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies amber class for warning status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-warn', status: 'warning' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-warn')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-amber-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies amber class for degraded status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-degraded', status: 'degraded' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-degraded')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-amber-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies red class for offline status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-offline', status: 'offline' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-offline')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-red-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies red class for stopped status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-stopped', status: 'stopped' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-stopped')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-red-500');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies slate class for unknown status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-unknown', status: 'something-else' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-unknown')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-slate-400');
- expect(dot).toBeInTheDocument();
- });
-
- it('applies slate class for empty status', async () => {
- mockApiResponse([makeService({ id: '1', name: 'svc-empty', status: '' })]);
- const { container } = render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('svc-empty')).toBeInTheDocument();
- });
-
- const dot = container.querySelector('.bg-slate-400');
- expect(dot).toBeInTheDocument();
- });
- });
-
- describe('API interaction', () => {
- it('builds correct URL with cluster, page, and limit params', async () => {
- mockApiResponse([]);
- render(() => <SwarmServicesDrawer cluster="my-cluster" />);
-
- await waitFor(() => {
- expect(apiFetchJSONMock).toHaveBeenCalled();
- });
-
- const url = apiFetchJSONMock.mock.calls[0][0] as string;
- expect(url).toContain('type=docker-service');
- expect(url).toContain('cluster=my-cluster');
- expect(url).toContain('page=1');
- expect(url).toContain('limit=100');
- });
-
- it('does not fetch when cluster is empty', async () => {
- render(() => <SwarmServicesDrawer cluster="" />);
-
- // Flush multiple microtask cycles to let SolidJS evaluate source signal
- await new Promise<void>((resolve) => queueMicrotask(() => resolve()));
- await new Promise<void>((resolve) => queueMicrotask(() => resolve()));
-
- // Empty cluster = falsy source signal = fetcher not called
- expect(apiFetchJSONMock).not.toHaveBeenCalled();
- });
-
- it('fetches multiple pages when totalPages > 1', async () => {
- // First page response
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: 'svc-1', name: 'page1-svc' })],
- meta: { totalPages: 3 },
- });
- // Pages 2 and 3
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: 'svc-2', name: 'page2-svc' })],
- meta: { totalPages: 3 },
- });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: 'svc-3', name: 'page3-svc' })],
- meta: { totalPages: 3 },
- });
-
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('page1-svc')).toBeInTheDocument();
- });
-
- expect(screen.getByText('page2-svc')).toBeInTheDocument();
- expect(screen.getByText('page3-svc')).toBeInTheDocument();
- expect(apiFetchJSONMock).toHaveBeenCalledTimes(3);
- });
-
- it('deduplicates services by id across pages', async () => {
- const svc = makeService({ id: 'dup-svc', name: 'duplicated' });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [svc],
- meta: { totalPages: 2 },
- });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [svc], // same id
- meta: { totalPages: 2 },
- });
-
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('duplicated')).toBeInTheDocument();
- });
-
- // Only one row should appear (deduped)
- const matches = screen.getAllByText('duplicated');
- expect(matches).toHaveLength(1);
- });
-
- it('handles failed page fetches gracefully (Promise.allSettled)', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: 'svc-ok', name: 'ok-svc' })],
- meta: { totalPages: 3 },
- });
- // Page 2 fails
- apiFetchJSONMock.mockRejectedValueOnce(new Error('network error'));
- // Page 3 succeeds
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: 'svc-3', name: 'page3-svc' })],
- meta: { totalPages: 3 },
- });
-
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('ok-svc')).toBeInTheDocument();
- });
-
- expect(screen.getByText('page3-svc')).toBeInTheDocument();
- });
-
- it('caps pagination at MAX_PAGES (20)', async () => {
- // First page says there are 25 total pages, but component caps at 20
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: 'svc-1', name: 'first-page' })],
- meta: { totalPages: 25 },
- });
- // Mock pages 2-20 (19 additional pages)
- for (let i = 2; i <= 20; i++) {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeService({ id: `svc-${i}`, name: `page${i}-svc` })],
- meta: { totalPages: 25 },
- });
- }
-
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('first-page')).toBeInTheDocument();
- });
-
- // Should have fetched exactly 20 pages (1 initial + 19 additional), not 25
- expect(apiFetchJSONMock).toHaveBeenCalledTimes(20);
- });
- });
-
- describe('table headers', () => {
- it('renders all expected column headers', async () => {
- mockApiResponse([makeService()]);
- render(() => <SwarmServicesDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('Service')).toBeInTheDocument();
- });
-
- expect(screen.getByText('Stack')).toBeInTheDocument();
- expect(screen.getByText('Image')).toBeInTheDocument();
- expect(screen.getByText('Mode')).toBeInTheDocument();
- expect(screen.getByText('Desired')).toBeInTheDocument();
- expect(screen.getByText('Running')).toBeInTheDocument();
- expect(screen.getByText('Update')).toBeInTheDocument();
- expect(screen.getByText('Ports')).toBeInTheDocument();
- });
- });
-});
diff --git a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx
index c57b1d7fb2..038b37188d 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx
@@ -9,10 +9,8 @@ import { Subtabs } from '@/components/shared/Subtabs';
import { WebInterfaceLink } from '@/components/shared/WebInterfaceLink';
import type { StatusIndicator } from '@/utils/status';
import { ReportMergeModal } from './ReportMergeModal';
-import { ProxmoxMailGatewayDrawer } from '@/features/proxmox/ProxmoxMailGatewayDrawer';
-import { K8sDeploymentsDrawer } from '@/components/Kubernetes/K8sDeploymentsDrawer';
+import { ProxmoxMailGatewayMailFlow } from '@/features/proxmox/ProxmoxMailGatewayDrawer';
import { K8sNamespacesDrawer } from '@/components/Kubernetes/K8sNamespacesDrawer';
-import { SwarmServicesDrawer } from '@/components/Docker/SwarmServicesDrawer';
import { ResourceDetailDrawerDebugTab } from './ResourceDetailDrawerDebugTab';
import {
ResourceAccessDisclosure,
@@ -47,27 +45,23 @@ interface ResourceDetailDrawerProps {
resolveResourceLabel?: (resourceId: string) => string | null | undefined;
initialShowAccessContext?: boolean;
initialShowHostDetails?: boolean;
- initialShowTrueNASDetails?: boolean;
onResourceActionSettled?: () => void | Promise<void>;
}
const TabAvailabilityNotice: Component<{ message: string }> = (props) => (
- <div class="rounded-sm border border-dashed border-border bg-surface-hover p-4 text-sm text-muted">
+ <InlineNotice tone="info" role="status">
{props.message}
- </div>
+ </InlineNotice>
);
-type SpecializedDrawerTab = 'mail' | 'namespaces' | 'deployments' | 'swarm';
+type SpecializedDrawerTab = 'mail' | 'namespaces';
export const getSpecializedTabAvailabilityMessage = (tab: SpecializedDrawerTab): string => {
switch (tab) {
case 'mail':
return 'PMG resources only.';
case 'namespaces':
- case 'deployments':
return 'Kubernetes clusters only.';
- case 'swarm':
- return 'Docker runtimes with Swarm only.';
}
};
@@ -81,11 +75,14 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {
resolveResourceLabel: props.resolveResourceLabel,
initialShowAccessContext: props.initialShowAccessContext,
initialShowHostDetails: props.initialShowHostDetails,
- initialShowTrueNASDetails: props.initialShowTrueNASDetails,
});
const headingId = () => `resource-detail-drawer-heading-${props.resource.id}`;
const statusIndicator = () => props.statusIndicator ?? drawer.statusIndicator();
const customUrl = () => props.resource.customUrl?.trim() ?? '';
+ // The Kubernetes page scopes its rows by cluster id, or by name when no id
+ // is reported, the same value its cluster table writes into the URL.
+ const kubernetesScopeCluster = () =>
+ drawer.kubernetesMeta()?.clusterId?.trim() || drawer.kubernetesClusterName();
// The health issue is the first "Worth checking" item on Overview, so the
// header names the subject only; source and identity badges say what the
// row cannot (an agent merged with PVE, an Unraid host).
@@ -235,7 +232,7 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {
<TabAvailabilityNotice message={getSpecializedTabAvailabilityMessage('mail')} />
}
>
- <ProxmoxMailGatewayDrawer instanceRow={props.resource} />
+ <ProxmoxMailGatewayMailFlow resource={props.resource} />
</Show>
</Show>
</div>
@@ -252,48 +249,7 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {
>
<K8sNamespacesDrawer
cluster={drawer.kubernetesClusterName()}
- onOpenDeployments={(ns) => {
- drawer.setK8sDeploymentsPrefillNamespace((ns || '').trim());
- drawer.setActiveTab('deployments');
- }}
- />
- </Show>
- </Show>
- </div>
-
- {/* Kubernetes Deployments Tab */}
- <div class={`[overflow-anchor:none] ${drawer.activeTab() === 'deployments' ? '' : 'hidden'}`}>
- {/* Mount on-demand to avoid background fetching when the tab isn't open. */}
- <Show when={drawer.activeTab() === 'deployments'}>
- <Show
- when={props.resource.type === 'k8s-cluster'}
- fallback={
- <TabAvailabilityNotice
- message={getSpecializedTabAvailabilityMessage('deployments')}
- />
- }
- >
- <K8sDeploymentsDrawer
- cluster={drawer.kubernetesClusterName()}
- initialNamespace={drawer.k8sDeploymentsPrefillNamespace() || null}
- />
- </Show>
- </Show>
- </div>
-
- {/* Docker Swarm Tab */}
- <div class={`[overflow-anchor:none] ${drawer.activeTab() === 'swarm' ? '' : 'hidden'}`}>
- {/* Mount on-demand to avoid background fetching when the tab isn't open. */}
- <Show when={drawer.activeTab() === 'swarm'}>
- <Show
- when={props.resource.type === 'docker-host' && drawer.dockerSwarmClusterKey()}
- fallback={
- <TabAvailabilityNotice message={getSpecializedTabAvailabilityMessage('swarm')} />
- }
- >
- <SwarmServicesDrawer
- cluster={drawer.dockerSwarmClusterKey()}
- swarm={drawer.dockerSwarmInfo()}
+ scopeCluster={kubernetesScopeCluster()}
/>
</Show>
</Show>
@@ -343,7 +299,6 @@ export const ResourceDetailDrawer: Component<ResourceDetailDrawerProps> = (props
resolveResourceLabel={props.resolveResourceLabel}
initialShowAccessContext={props.initialShowAccessContext}
initialShowHostDetails={props.initialShowHostDetails}
- initialShowTrueNASDetails={props.initialShowTrueNASDetails}
onResourceActionSettled={props.onResourceActionSettled}
/>
)}
diff --git a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx
index 4d6ffd29de..ceb7593639 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx
@@ -19,7 +19,6 @@ import {
isDrawerAvailabilityHealthy,
} from '@/components/Workloads/drawerOverviewModel';
import { DrawerExceptionList } from '@/components/Workloads/DrawerExceptionList';
-import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { formatUptime, formatRelativeTime } from '@/utils/format';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { SystemInfoCard } from '@/components/shared/cards/SystemInfoCard';
@@ -50,6 +49,7 @@ import {
import {
DrawerAttentionSection,
type DrawerAttentionItem,
+ DrawerNoAlertsLine,
} from '@/components/shared/DrawerAttentionSection';
import {
RESOURCE_CHANGE_KIND_ORDER,
@@ -406,12 +406,7 @@ export const ResourceDetailDrawerOverviewTab: Component<ResourceDetailDrawerOver
<div class="space-y-3">
<DrawerAttentionSection items={attentionItems()} />
<Show when={attentionItems().length === 0}>
- <p data-testid="drawer-no-attention" class="text-xs text-muted">
- <span class="font-medium text-base-content">{ALERTS_EMPTY_STATE}</span>
- <Show when={availabilityHealthy()}>
- <span> · availability checks passing</span>
- </Show>
- </p>
+ <DrawerNoAlertsLine availabilityPassing={availabilityHealthy()} />
</Show>
<DrawerExceptionList testId="resource-drawer-exceptions" rows={exceptionRows()} />
{/* Stored history leads the reading path: the charts answer "is this
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx
index 8b05fc9d39..03af08b94a 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx
@@ -213,8 +213,6 @@ describe('ResourceDetailDrawer runtime and identity cards', () => {
it('uses terse availability notices for specialized tabs', () => {
expect(getSpecializedTabAvailabilityMessage('mail')).toBe('PMG resources only.');
expect(getSpecializedTabAvailabilityMessage('namespaces')).toBe('Kubernetes clusters only.');
- expect(getSpecializedTabAvailabilityMessage('deployments')).toBe('Kubernetes clusters only.');
- expect(getSpecializedTabAvailabilityMessage('swarm')).toBe('Docker runtimes with Swarm only.');
});
it('keeps host detail cards behind a secondary overview disclosure', async () => {
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx
index 75d2e2df95..56e1e3466d 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx
@@ -21,14 +21,12 @@ vi.mock('@solidjs/router', async () => {
});
vi.mock('@/components/Kubernetes/K8sNamespacesDrawer', () => ({
- K8sNamespacesDrawer: (props: { cluster: string }) => (
- <div data-testid="k8s-namespaces-drawer" data-cluster={props.cluster} />
- ),
-}));
-
-vi.mock('@/components/Kubernetes/K8sDeploymentsDrawer', () => ({
- K8sDeploymentsDrawer: (props: { cluster: string }) => (
- <div data-testid="k8s-deployments-drawer" data-cluster={props.cluster} />
+ K8sNamespacesDrawer: (props: { cluster: string; scopeCluster?: string }) => (
+ <div
+ data-testid="k8s-namespaces-drawer"
+ data-cluster={props.cluster}
+ data-scope-cluster={props.scopeCluster}
+ />
),
}));
@@ -99,7 +97,8 @@ describe('ResourceDetailDrawer kubernetes capabilities', () => {
expect(queryByText('K8s Node CPU/Memory')).toBeNull();
expect(queryByText('Node Telemetry (Agent)')).toBeNull();
expect(screen.getByRole('tab', { name: 'Namespaces' })).toBeInTheDocument();
- expect(screen.getByRole('tab', { name: 'Deployments' })).toBeInTheDocument();
+ // Deployments live on Kubernetes > Workloads; the drawer does not repeat them.
+ expect(screen.queryByRole('tab', { name: 'Deployments' })).toBeNull();
});
it('uses the canonical Kubernetes cluster name for drawer fetch keys', async () => {
@@ -112,13 +111,31 @@ describe('ResourceDetailDrawer kubernetes capabilities', () => {
'cluster-a',
);
});
+ // Without a reported cluster id the page scopes by the cluster name.
+ expect(screen.getByTestId('k8s-namespaces-drawer')).toHaveAttribute(
+ 'data-scope-cluster',
+ 'cluster-a',
+ );
+ });
+
+ it('scopes namespace links by the cluster id the Kubernetes page filters on', async () => {
+ const resource = buildKubernetesResource();
+ resource.platformData = {
+ ...resource.platformData,
+ kubernetes: { clusterId: 'cluster-a-uid', clusterName: 'cluster-a' },
+ };
+ render(() => <ResourceDetailDrawer resource={resource} />);
- await fireEvent.click(screen.getByRole('tab', { name: 'Deployments' }));
+ await fireEvent.click(screen.getByRole('tab', { name: 'Namespaces' }));
await waitFor(() => {
- expect(screen.getByTestId('k8s-deployments-drawer')).toHaveAttribute(
- 'data-cluster',
- 'cluster-a',
+ expect(screen.getByTestId('k8s-namespaces-drawer')).toHaveAttribute(
+ 'data-scope-cluster',
+ 'cluster-a-uid',
);
});
+ expect(screen.getByTestId('k8s-namespaces-drawer')).toHaveAttribute(
+ 'data-cluster',
+ 'cluster-a',
+ );
});
});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.test.ts
index d726813be1..db82f97c49 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.test.ts
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.test.ts
@@ -227,8 +227,18 @@ describe('buildKubernetesControllerSection', () => {
expect(section?.label).toBe('Job');
expect(section?.testId).toBe('resource-kubernetes-controller-section');
expect(section?.rows).toEqual([
- { label: 'Started', value: `${absolute('2026-05-24T12:55:00Z')} (36m ago)`, wrap: true },
- { label: 'Completed', value: `${absolute('2026-05-24T13:00:00Z')} (31m ago)`, wrap: true },
+ {
+ label: 'Started',
+ value: `${absolute('2026-05-24T12:55:00Z')} (36m ago)`,
+ title: '2026-05-24T12:55:00Z',
+ wrap: true,
+ },
+ {
+ label: 'Completed',
+ value: `${absolute('2026-05-24T13:00:00Z')} (31m ago)`,
+ title: '2026-05-24T13:00:00Z',
+ wrap: true,
+ },
{ label: 'Duration', value: '5m' },
{ label: 'Target', value: '10 completions' },
{ label: 'Active', value: '1' },
@@ -267,6 +277,7 @@ describe('buildKubernetesControllerSection', () => {
expect(section?.rows[0]).toEqual({
label: 'Started',
value: `${absolute('2026-05-24T13:29:30Z')} (1m ago)`,
+ title: '2026-05-24T13:29:30Z',
wrap: true,
});
expect(section?.rows[3]).toEqual({ label: 'Failed', value: '0', tone: 'default' });
@@ -295,8 +306,18 @@ describe('buildKubernetesControllerSection', () => {
expect(section?.label).toBe('CronJob');
expect(section?.rows).toEqual([
{ label: 'Schedule', value: '0 2 * * *', valueClass: 'font-mono' },
- { label: 'Last run', value: `${absolute('2026-05-24T02:00:00Z')} (11h ago)`, wrap: true },
- { label: 'Last success', value: `${absolute('2026-05-23T02:00:00Z')} (1d ago)`, wrap: true },
+ {
+ label: 'Last run',
+ value: `${absolute('2026-05-24T02:00:00Z')} (11h ago)`,
+ title: '2026-05-24T02:00:00Z',
+ wrap: true,
+ },
+ {
+ label: 'Last success',
+ value: `${absolute('2026-05-23T02:00:00Z')} (1d ago)`,
+ title: '2026-05-23T02:00:00Z',
+ wrap: true,
+ },
{ label: 'Suspended', value: 'Yes', tone: 'warning' },
{ label: 'Active', value: '0' },
{ label: 'Namespace', value: 'batch', wrap: true },
diff --git a/frontend-modern/src/components/Infrastructure/resourceDetailDrawerKubernetesModel.ts b/frontend-modern/src/components/Infrastructure/resourceDetailDrawerKubernetesModel.ts
index 55298ef882..d9b6286fd8 100644
--- a/frontend-modern/src/components/Infrastructure/resourceDetailDrawerKubernetesModel.ts
+++ b/frontend-modern/src/components/Infrastructure/resourceDetailDrawerKubernetesModel.ts
@@ -10,12 +10,9 @@ import {
type DetailSection,
type DetailValueTone,
} from '@/components/shared/detailSectionModel';
-import {
- formatPlatformTableDateTimeValue,
- formatPlatformTableDurationValue,
- formatPlatformTableRelativeTimeValue,
-} from '@/features/platformPage/sharedPlatformPage';
+import { formatPlatformTableDurationValue } from '@/features/platformPage/sharedPlatformPage';
import { drawerContentCardTestId } from './resourceDetailDrawerOverviewModel';
+import { makeDetailTimestampRow } from '@/features/platformPage/platformDetailTimestampRow';
export type ResourceDetailDrawerKubernetesSection = DetailSection;
@@ -246,27 +243,9 @@ const autoscalerAtLimitRow = (current?: number, max?: number): DetailRow | null
};
const dangerWhenPositive = (count: number): DetailValueTone => (count > 0 ? 'danger' : 'default');
-// Kubernetes reports controller timestamps as RFC 3339 strings. The table row
-// only has room for an age, so the expansion carries the absolute time first
-// and the age after it: "Oct 2, 2026, 09:13 PM (1h ago)". The value wraps
-// because a phone-width detail cell is too narrow for both on one line. The
-// age is measured from `now`, which an open drawer passes from the shared
-// relative-time clock so the age keeps moving while the drawer stays open.
-const timestampRow = (
- label: string,
- timestamp: string | null | undefined,
- now: number | undefined,
-): DetailRow | null => {
- const raw = asString(timestamp);
- if (!raw) return null;
- const absolute = formatPlatformTableDateTimeValue(raw, {
- emptyText: '',
- dateTimeFormat: { year: 'numeric' },
- });
- if (!absolute) return makeRow(label, raw, { wrap: true });
- const relative = formatPlatformTableRelativeTimeValue(raw, { emptyText: '', now });
- return makeRow(label, relative ? `${absolute} (${relative})` : absolute, { wrap: true });
-};
+// Kubernetes reports controller timestamps as RFC 3339 strings; the drawer
+// shows the absolute time and its age (see makeDetailTimestampRow).
+const timestampRow = makeDetailTimestampRow;
const elapsedSeconds = (start?: string | null, end?: string | null): number | undefined => {
const startedAt = Date.parse(asString(start) ?? '');
diff --git a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts
index 91cb75ef5e..f55864e026 100644
--- a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts
+++ b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts
@@ -76,21 +76,12 @@ import {
buildResourceIdentityView,
buildSourceSections,
} from './resourceDetailDrawerIdentityModel';
-import {
- buildVMwareDetailsSummary,
- buildVMwareDetailSections,
-} from './resourceDetailDrawerVmwareModel';
-import {
- buildTrueNASDetailsSummary,
- buildTrueNASDetailSections,
-} from './resourceDetailDrawerTrueNASModel';
-import {
- buildKubernetesDetailsSummary,
- buildKubernetesDetailSections,
-} from './resourceDetailDrawerKubernetesModel';
+import { buildVMwareDetailSections } from './resourceDetailDrawerVmwareModel';
+import { buildTrueNASDetailSections } from './resourceDetailDrawerTrueNASModel';
+import { buildKubernetesDetailSections } from './resourceDetailDrawerKubernetesModel';
import { getResourceHealthIssuePresentation } from './resourceHealthPresentation';
-type DrawerTab = 'overview' | 'manage' | 'mail' | 'namespaces' | 'deployments' | 'swarm' | 'debug';
+type DrawerTab = 'overview' | 'manage' | 'mail' | 'namespaces' | 'debug';
interface UseResourceDetailDrawerDerivedStateOptions {
resource: Resource;
@@ -220,11 +211,6 @@ export const useResourceDetailDrawerDerivedState = (
});
const dockerUpdateActionsDisabled = createMemo(() => shouldHideDockerUpdateActions());
const dockerUpdateActionsLoading = createMemo(() => !areSystemSettingsLoaded());
- const dockerSwarmInfo = createMemo(() => dockerHostData()?.swarm);
- const dockerSwarmClusterKey = createMemo(() => {
- const swarm = dockerSwarmInfo();
- return (swarm?.clusterName || swarm?.clusterId || '').trim();
- });
const resourceDependencies = createMemo(() => resourceIntelligence()?.dependencies ?? []);
const resourceDependents = createMemo(() => resourceIntelligence()?.dependents ?? []);
@@ -333,19 +319,11 @@ export const useResourceDetailDrawerDerivedState = (
const vmwareDetailSections = createMemo(() =>
buildVMwareDetailSections(resource().type, vmwareData()),
);
- const hasVMwareDetails = createMemo(() => vmwareDetailSections().length > 0);
- const vmwareDetailsSummary = createMemo(() =>
- buildVMwareDetailsSummary(resource().type, vmwareData()),
- );
const { getTrueNASDiskTemperatureThresholds } = useAlertsActivation();
const trueNASDetailSections = createMemo(() =>
buildTrueNASDetailSections(resource(), getTrueNASDiskTemperatureThresholds),
);
- const hasTrueNASDetails = createMemo(() => trueNASDetailSections().length > 0);
- const trueNASDetailsSummary = createMemo(() => buildTrueNASDetailsSummary(resource()));
const kubernetesDetailSections = createMemo(() => buildKubernetesDetailSections(resource()));
- const hasKubernetesDetails = createMemo(() => kubernetesDetailSections().length > 0);
- const kubernetesDetailsSummary = createMemo(() => buildKubernetesDetailsSummary(resource()));
const metricsHistoryTarget = createMemo(() => getResourceMetricsHistoryTarget(resource()));
const metricsHistoryCurrentMetrics = createMemo(() =>
getResourceMetricsHistoryCurrentMetrics(resource()),
@@ -388,15 +366,12 @@ export const useResourceDetailDrawerDerivedState = (
{ id: 'overview' as DrawerTab, label: 'Overview' },
{ id: 'manage' as DrawerTab, label: 'Manage' },
...(resource().type === 'pmg' ? [{ id: 'mail' as DrawerTab, label: 'Mail' }] : []),
+ // Deployments and Swarm services have their own platform tabs
+ // (Kubernetes > Workloads, Docker > Swarm), so the drawer does not
+ // repeat them; namespaces scope those tabs from here.
...(resource().type === 'k8s-cluster'
? [{ id: 'namespaces' as DrawerTab, label: 'Namespaces' }]
: []),
- ...(resource().type === 'k8s-cluster'
- ? [{ id: 'deployments' as DrawerTab, label: 'Deployments' }]
- : []),
- ...(resource().type === 'docker-host' && dockerSwarmClusterKey()
- ? [{ id: 'swarm' as DrawerTab, label: 'Swarm' }]
- : []),
];
if (debugEnabled()) {
base.push({ id: 'debug' as DrawerTab, label: 'Debug' });
@@ -442,8 +417,6 @@ export const useResourceDetailDrawerDerivedState = (
dockerHostCommandActive,
dockerUpdateActionsDisabled,
dockerUpdateActionsLoading,
- dockerSwarmInfo,
- dockerSwarmClusterKey,
resourceDependencies,
resourceDependents,
resourceCorrelations,
@@ -485,14 +458,8 @@ export const useResourceDetailDrawerDerivedState = (
metricsHistoryGroups,
hasMetricsHistory,
guestReadPrecaution,
- hasVMwareDetails,
- vmwareDetailsSummary,
vmwareDetailSections,
- hasTrueNASDetails,
- trueNASDetailsSummary,
trueNASDetailSections,
- hasKubernetesDetails,
- kubernetesDetailsSummary,
kubernetesDetailSections,
relatedLinks,
hasRuntimeOperationalContext,
diff --git a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts
index 0f43140e7c..0fc00f58c4 100644
--- a/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts
+++ b/frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts
@@ -8,7 +8,7 @@ import { useResourceDetailDrawerHistoryState } from './useResourceDetailDrawerHi
import { useResourceDetailDrawerDerivedState } from './useResourceDetailDrawerDerivedState';
import type { ResourceDetailDrawerPresentation } from './resourceDetailDrawerPresentation';
-type DrawerTab = 'overview' | 'manage' | 'mail' | 'namespaces' | 'deployments' | 'swarm' | 'debug';
+type DrawerTab = 'overview' | 'manage' | 'mail' | 'namespaces' | 'debug';
export interface UseResourceDetailDrawerStateOptions {
resource: Resource;
@@ -16,7 +16,6 @@ export interface UseResourceDetailDrawerStateOptions {
presentation?: ResourceDetailDrawerPresentation;
initialShowAccessContext?: boolean;
initialShowHostDetails?: boolean;
- initialShowTrueNASDetails?: boolean;
}
export const useResourceDetailDrawerState = (options: UseResourceDetailDrawerStateOptions) => {
@@ -40,14 +39,8 @@ export const useResourceDetailDrawerState = (options: UseResourceDetailDrawerSta
options.initialShowHostDetails === true,
);
const [showServiceDetails, setShowServiceDetails] = createSignal(false);
- const [showVMwareDetails, setShowVMwareDetails] = createSignal(false);
- const [showTrueNASDetails, setShowTrueNASDetails] = createSignal(
- options.initialShowTrueNASDetails === true,
- );
- const [showKubernetesDetails, setShowKubernetesDetails] = createSignal(false);
const [showPbsJobDetail, setShowPbsJobDetail] = createSignal(false);
const [showPmgMailFlowDetail, setShowPmgMailFlowDetail] = createSignal(false);
- const [k8sDeploymentsPrefillNamespace, setK8sDeploymentsPrefillNamespace] = createSignal('');
const history = useResourceDetailDrawerHistoryState({
get resource() {
@@ -141,18 +134,10 @@ export const useResourceDetailDrawerState = (options: UseResourceDetailDrawerSta
setShowHostDetails,
showServiceDetails,
setShowServiceDetails,
- showVMwareDetails,
- setShowVMwareDetails,
- showTrueNASDetails,
- setShowTrueNASDetails,
- showKubernetesDetails,
- setShowKubernetesDetails,
showPbsJobDetail,
setShowPbsJobDetail,
showPmgMailFlowDetail,
setShowPmgMailFlowDetail,
- k8sDeploymentsPrefillNamespace,
- setK8sDeploymentsPrefillNamespace,
...history,
...derived,
...dockerActions,
diff --git a/frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx b/frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx
deleted file mode 100644
index 925a72c72e..0000000000
--- a/frontend-modern/src/components/Kubernetes/K8sDeploymentsDrawer.tsx
+++ /dev/null
@@ -1,359 +0,0 @@
-import type { Component } from 'solid-js';
-import { For, Show, createMemo, createResource, createSignal, createEffect } from 'solid-js';
-import { useNavigate } from '@solidjs/router';
-import { apiFetchJSON } from '@/utils/apiClient';
-import { Card } from '@/components/shared/Card';
-import { FormSelect } from '@/components/shared/FormSelect';
-import {
- filterGroupClass,
- filterLabelClass,
- filterSelectClass,
-} from '@/components/shared/FilterToolbar';
-import { SearchInput } from '@/components/shared/SearchInput';
-import { StatusDot } from '@/components/shared/StatusDot';
-import { TableRow, TableHead, TableCell } from '@/components/shared/Table';
-import { EmptyState } from '@/components/shared/EmptyState';
-import { buildKubernetesPath } from '@/routing/resourceLinks';
-import {
- PlatformDetailTable,
- PlatformDetailTableBody,
- PlatformDetailTableHeader,
- PlatformResponsiveTableLabel,
- getPlatformTableCellClassForKind,
- getPlatformTableHeadClassForKind,
-} from '@/features/platformPage/sharedPlatformPage';
-import {
- getK8sDeploymentsDrawerPresentation,
- getK8sDeploymentsEmptyState,
- getK8sDeploymentsLoadingState,
-} from '@/utils/k8sDeploymentPresentation';
-import { getSimpleStatusIndicator } from '@/utils/status';
-import { asTrimmedString } from '@/utils/stringUtils';
-
-const PAGE_LIMIT = 100;
-const MAX_PAGES = 20;
-
-type K8sDeploymentResource = {
- id: string;
- name?: string;
- status?: string;
- kubernetes?: {
- namespace?: string;
- desiredReplicas?: number;
- updatedReplicas?: number;
- readyReplicas?: number;
- availableReplicas?: number;
- };
-};
-
-type ResourcesListResponse = {
- data?: K8sDeploymentResource[];
- meta?: {
- totalPages?: number;
- };
-};
-
-const buildDeploymentsUrl = (cluster: string, page: number) => {
- const params = new URLSearchParams();
- params.set('type', 'k8s-deployment');
- params.set('cluster', cluster);
- params.set('page', String(page));
- params.set('limit', String(PAGE_LIMIT));
- return `/api/resources?${params.toString()}`;
-};
-
-const fetchAllDeployments = async (cluster: string): Promise<K8sDeploymentResource[]> => {
- const first = await apiFetchJSON<ResourcesListResponse>(buildDeploymentsUrl(cluster, 1), {
- cache: 'no-store',
- });
- const firstData = Array.isArray(first?.data) ? first.data : [];
- const totalPages = Number.isFinite(first?.meta?.totalPages)
- ? Math.max(1, Number(first.meta?.totalPages))
- : 1;
-
- const deployments: K8sDeploymentResource[] = [...firstData];
-
- const cappedPages = Math.min(totalPages, MAX_PAGES);
- if (cappedPages > 1) {
- const requests: Array<Promise<ResourcesListResponse>> = [];
- for (let page = 2; page <= cappedPages; page += 1) {
- requests.push(
- apiFetchJSON<ResourcesListResponse>(buildDeploymentsUrl(cluster, page), {
- cache: 'no-store',
- }),
- );
- }
-
- const settled = await Promise.allSettled(requests);
- for (const result of settled) {
- if (result.status !== 'fulfilled') continue;
- const data = Array.isArray(result.value?.data) ? result.value.data : [];
- deployments.push(...data);
- }
- }
-
- return Array.from(new Map(deployments.map((d) => [d.id, d])).values());
-};
-
-export const K8sDeploymentsDrawer: Component<{
- cluster: string;
- initialNamespace?: string | null;
-}> = (props) => {
- const navigate = useNavigate();
- const [namespace, setNamespace] = createSignal('');
- const [search, setSearch] = createSignal('');
- const [lastAppliedNamespace, setLastAppliedNamespace] = createSignal('');
- const drawerPresentation = getK8sDeploymentsDrawerPresentation();
-
- const clusterName = createMemo(() => asTrimmedString(props.cluster) ?? '');
-
- const [deployments] = createResource(
- clusterName,
- async (cluster) => {
- if (!cluster) return [];
- return fetchAllDeployments(cluster);
- },
- { initialValue: [] },
- );
-
- const namespaceOptions = createMemo(() => {
- const set = new Set<string>();
- for (const dep of deployments()) {
- const ns = asTrimmedString(dep.kubernetes?.namespace) ?? '';
- if (ns) set.add(ns);
- }
- return Array.from(set).sort((a, b) => a.localeCompare(b));
- });
-
- createEffect(() => {
- // Allow other drawer tabs (e.g., Namespaces) to prefill the namespace filter.
- const next = asTrimmedString(props.initialNamespace) ?? '';
- if (!next) return;
- if (next.toLowerCase() === (asTrimmedString(lastAppliedNamespace()) ?? '').toLowerCase())
- return;
- const exists = namespaceOptions().some((ns) => ns.toLowerCase() === next.toLowerCase());
- if (exists) {
- setNamespace(next);
- setLastAppliedNamespace(next);
- }
- });
-
- createEffect(() => {
- const current = asTrimmedString(namespace()) ?? '';
- if (!current) return;
- const exists = namespaceOptions().some((ns) => ns.toLowerCase() === current.toLowerCase());
- if (!exists) {
- setNamespace('');
- }
- });
-
- const filteredDeployments = createMemo(() => {
- const ns = asTrimmedString(namespace()) ?? '';
- const term = (asTrimmedString(search()) ?? '').toLowerCase();
-
- return deployments()
- .filter((dep) => {
- if (ns && (asTrimmedString(dep.kubernetes?.namespace) ?? '') !== ns) return false;
- if (!term) return true;
- const name = asTrimmedString(dep.name) || dep.id;
- return name.toLowerCase().includes(term);
- })
- .sort((a, b) => {
- const aName = (asTrimmedString(a.name) || a.id).toLowerCase();
- const bName = (asTrimmedString(b.name) || b.id).toLowerCase();
- if (aName !== bName) return aName < bName ? -1 : 1;
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
- });
- });
-
- const openPods = (_ns?: string) => {
- if (!clusterName()) return;
- navigate(buildKubernetesPath('workloads'));
- };
-
- const headingId = () => `k8s-deployments-drawer-heading-${clusterName() || 'cluster'}`;
-
- return (
- <section class="space-y-3" aria-labelledby={headingId()}>
- <h2 id={headingId()} class="sr-only">
- {clusterName() || 'Kubernetes cluster'} deployments
- </h2>
- <Card padding="md">
- <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
- <div class="min-w-0">
- <div class="text-sm font-semibold text-base-content">{drawerPresentation.title}</div>
- <div class="text-xs text-muted">{drawerPresentation.description}</div>
- </div>
-
- <div class="flex flex-wrap items-center gap-2">
- <div class="w-48">
- <SearchInput
- value={search}
- onChange={setSearch}
- placeholder={drawerPresentation.searchPlaceholder}
- inputClass="py-1 text-xs font-medium shadow-xs"
- typeToSearch
- clearOnEscape
- />
- </div>
-
- <Show when={namespaceOptions().length > 0}>
- <FormSelect
- id="k8s-deployments-namespace"
- label={drawerPresentation.namespaceFilterLabel}
- fieldBaseClass={filterGroupClass}
- labelClass={filterLabelClass}
- selectBaseClass={filterSelectClass}
- selectClass="min-w-40"
- value={namespace()}
- aria-label={drawerPresentation.namespaceFilterLabel}
- onChange={(e) => setNamespace(e.currentTarget.value)}
- >
- <option value="">{drawerPresentation.allNamespacesLabel}</option>
- <For each={namespaceOptions()}>{(ns) => <option value={ns}>{ns}</option>}</For>
- </FormSelect>
- </Show>
-
- <button
- type="button"
- onClick={() => openPods(namespace() || undefined)}
- class="rounded-md border border-border px-3 py-1 text-xs font-semibold shadow-xs hover:bg-surface-hover"
- >
- {drawerPresentation.openPodsLabel}
- </button>
- </div>
- </div>
- </Card>
-
- <Show
- when={deployments.loading}
- fallback={
- <Show
- when={filteredDeployments().length > 0}
- fallback={
- <Card padding="lg">
- <EmptyState {...getK8sDeploymentsEmptyState(deployments().length > 0)} />
- </Card>
- }
- >
- <Card padding="none" tone="card" class="overflow-hidden">
- <PlatformDetailTable class="min-w-0 table-fixed text-xs">
- <PlatformDetailTableHeader>
- <TableHead class={`${getPlatformTableHeadClassForKind('name')} md:w-[26%]`}>
- {drawerPresentation.deploymentColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('text')} hidden md:w-[16%] sm:table-cell`}
- >
- {drawerPresentation.namespaceColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} k8s-deployment-detail-column md:w-[10%]`}
- >
- {drawerPresentation.desiredColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} k8s-deployment-detail-column md:w-[10%]`}
- >
- {drawerPresentation.updatedColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} md:w-[10%]`}
- >
- {drawerPresentation.readyColumnLabel}
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} md:w-[10%]`}
- >
- {drawerPresentation.availableColumnLabel}
- </TableHead>
- <TableHead class={`${getPlatformTableHeadClassForKind('text')} md:w-[18%]`}>
- {drawerPresentation.actionsColumnLabel}
- </TableHead>
- </PlatformDetailTableHeader>
- <PlatformDetailTableBody>
- <For each={filteredDeployments()}>
- {(dep) => {
- const name = () => asTrimmedString(dep.name) || dep.id;
- const ns = () => asTrimmedString(dep.kubernetes?.namespace) || '—';
- const desired = () => dep.kubernetes?.desiredReplicas ?? 0;
- const updated = () => dep.kubernetes?.updatedReplicas ?? 0;
- const ready = () => dep.kubernetes?.readyReplicas ?? 0;
- const available = () => dep.kubernetes?.availableReplicas ?? 0;
- const status = () => getSimpleStatusIndicator(dep.status);
-
- return (
- <TableRow class="text-[11px] sm:text-xs">
- <TableCell class={getPlatformTableCellClassForKind('name')}>
- <div class="flex items-center gap-2 min-w-0">
- <StatusDot
- size="sm"
- variant={status().variant}
- title={dep.status || 'unknown'}
- ariaHidden
- />
- <span class="font-semibold text-base-content truncate" title={name()}>
- {name()}
- </span>
- </div>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content sm:table-cell`}
- >
- <span class="block truncate" title={ns()}>
- {ns()}
- </span>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} k8s-deployment-detail-column text-base-content tabular-nums`}
- >
- {desired()}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} k8s-deployment-detail-column text-base-content tabular-nums`}
- >
- {updated()}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content tabular-nums`}
- >
- {ready()}
- <span class="k8s-deployment-ready-total">/{desired()}</span>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content tabular-nums`}
- >
- {available()}
- </TableCell>
- <TableCell class={getPlatformTableCellClassForKind('text')}>
- <button
- type="button"
- aria-label={drawerPresentation.viewPodsLabel}
- onClick={() => openPods(dep.kubernetes?.namespace)}
- class="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-semibold text-base-content shadow-xs hover:bg-surface-hover"
- >
- <PlatformResponsiveTableLabel
- compact="Pods"
- full={drawerPresentation.viewPodsLabel}
- />
- </button>
- </TableCell>
- </TableRow>
- );
- }}
- </For>
- </PlatformDetailTableBody>
- </PlatformDetailTable>
- </Card>
- </Show>
- }
- >
- <Card padding="lg">
- <EmptyState {...getK8sDeploymentsLoadingState()} />
- </Card>
- </Show>
- </section>
- );
-};
-
-export default K8sDeploymentsDrawer;
diff --git a/frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx b/frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx
index ba4d786c04..b5ed3c8c99 100644
--- a/frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx
+++ b/frontend-modern/src/components/Kubernetes/K8sNamespacesDrawer.tsx
@@ -7,7 +7,7 @@ import { SearchInput } from '@/components/shared/SearchInput';
import { TableRow, TableHead, TableCell } from '@/components/shared/Table';
import { EmptyState } from '@/components/shared/EmptyState';
import { StatusDot } from '@/components/shared/StatusDot';
-import { buildKubernetesPath } from '@/routing/resourceLinks';
+import { buildKubernetesPath, buildKubernetesRouteSearch } from '@/routing/resourceLinks';
import {
PlatformDetailTable,
PlatformDetailTableBody,
@@ -37,20 +37,28 @@ type NamespacesResponse = {
data: NamespaceRow[];
};
+const EMPTY_RESPONSE: NamespacesResponse = { cluster: '', data: [] };
+
export const K8sNamespacesDrawer: Component<{
+ /** The cluster name the namespaces endpoint aggregates by. */
cluster: string;
- onOpenDeployments?: (namespace: string | null) => void;
+ /**
+ * The value the Kubernetes page scopes its rows by: the cluster id, or the
+ * name when no id is reported. Defaults to `cluster`.
+ */
+ scopeCluster?: string;
}> = (props) => {
const navigate = useNavigate();
const [search, setSearch] = createSignal('');
const drawerPresentation = getK8sNamespacesDrawerPresentation();
const clusterName = createMemo(() => asTrimmedString(props.cluster) ?? '');
+ const scopeCluster = createMemo(() => asTrimmedString(props.scopeCluster) || clusterName());
const [namespaces] = createResource(
clusterName,
async (cluster) => {
- if (!cluster) return { cluster: '', data: [] } as NamespacesResponse;
+ if (!cluster) return EMPTY_RESPONSE;
const params = new URLSearchParams();
params.set('cluster', cluster);
return apiFetchJSON<NamespacesResponse>(
@@ -58,16 +66,23 @@ export const K8sNamespacesDrawer: Component<{
{ cache: 'no-store' },
);
},
- { initialValue: { cluster: '', data: [] } as NamespacesResponse },
+ { initialValue: EMPTY_RESPONSE },
);
+ // Solid rethrows a resource's error when it is read, so every read checks
+ // the state first; otherwise a failed fetch would escape to the nearest
+ // error boundary instead of showing the failure state below.
+ const failed = () => namespaces.state === 'errored';
const loadError = createMemo(() => {
- const err = namespaces.error;
- if (!err) return '';
- return (err as Error)?.message || 'Failed to fetch namespaces';
+ if (!failed()) return '';
+ return (namespaces.error as Error)?.message || 'Failed to fetch namespaces';
});
- const rows = createMemo(() => (Array.isArray(namespaces()?.data) ? namespaces()!.data : []));
+ const rows = createMemo(() => {
+ if (failed()) return [];
+ const data = namespaces()?.data;
+ return Array.isArray(data) ? data : [];
+ });
const filteredRows = createMemo(() => {
const term = (asTrimmedString(search()) ?? '').toLowerCase();
@@ -75,46 +90,44 @@ export const K8sNamespacesDrawer: Component<{
return rows().filter((row) => row.namespace.toLowerCase().includes(term));
});
- const openPods = (_namespace: string | null) => {
+ // Pods and deployments both live on the Workloads tab, which reads the
+ // cluster and namespace scope from its URL.
+ const openWorkloads = (namespace: string | null) => {
if (!clusterName()) return;
- navigate(buildKubernetesPath('workloads'));
+ navigate(
+ `${buildKubernetesPath('workloads')}${buildKubernetesRouteSearch({
+ cluster: scopeCluster(),
+ namespace,
+ })}`,
+ );
};
const headingId = () => `k8s-namespaces-drawer-heading-${clusterName() || 'cluster'}`;
return (
<section class="space-y-3" aria-labelledby={headingId()}>
- <h2 id={headingId()} class="sr-only">
+ <h3 id={headingId()} class="sr-only">
{clusterName() || 'Kubernetes cluster'} namespaces
- </h2>
- <Card padding="md">
- <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
- <div class="min-w-0">
- <div class="text-sm font-semibold text-base-content">{drawerPresentation.title}</div>
- <div class="text-xs text-muted">{drawerPresentation.description}</div>
- </div>
-
- <div class="flex flex-wrap items-center gap-2">
- <div class="w-48">
- <SearchInput
- value={search}
- onChange={setSearch}
- placeholder={drawerPresentation.searchPlaceholder}
- inputClass="py-1 text-xs font-medium shadow-xs"
- typeToSearch
- clearOnEscape
- />
- </div>
- <button
- type="button"
- onClick={() => openPods(null)}
- class="rounded-md border border-border bg-surface px-3 py-1 text-xs font-semibold shadow-xs hover:bg-surface-hover"
- >
- {drawerPresentation.openAllPodsLabel}
- </button>
- </div>
+ </h3>
+ <div class="flex flex-wrap items-center justify-end gap-2">
+ <div class="w-48">
+ <SearchInput
+ value={search}
+ onChange={setSearch}
+ placeholder={drawerPresentation.searchPlaceholder}
+ inputClass="py-1 text-xs font-medium shadow-xs"
+ typeToSearch
+ clearOnEscape
+ />
</div>
- </Card>
+ <button
+ type="button"
+ onClick={() => openWorkloads(null)}
+ class="rounded-md border border-border bg-surface px-3 py-1 text-xs font-semibold shadow-xs hover:bg-surface-hover"
+ >
+ {drawerPresentation.openAllWorkloadsLabel}
+ </button>
+ </div>
<Show
when={!namespaces.loading}
@@ -171,17 +184,17 @@ export const K8sNamespacesDrawer: Component<{
return (
<TableRow class="text-[11px] sm:text-xs">
<TableCell class={getPlatformTableCellClassForKind('name')}>
- <div class="flex items-center gap-2 min-w-0">
+ <div class="flex items-start gap-2 min-w-0">
<StatusDot
size="sm"
variant={podIndicator().variant}
title={podIndicator().label}
ariaHidden
+ class="mt-1"
/>
- <span
- class="font-semibold text-base-content truncate"
- title={row.namespace}
- >
+ {/* Namespace names are compared and copied, so
+ they wrap rather than truncate. */}
+ <span class="min-w-0 whitespace-normal font-semibold text-base-content wrap-anywhere">
{row.namespace}
</span>
</div>
@@ -217,32 +230,17 @@ export const K8sNamespacesDrawer: Component<{
</span>
</TableCell>
<TableCell class={getPlatformTableCellClassForKind('text')}>
- <div class="flex flex-wrap items-center gap-2">
- <button
- type="button"
- aria-label={drawerPresentation.openPodsLabel}
- onClick={() => openPods(row.namespace)}
- class="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-semibold text-base-content shadow-xs hover:bg-surface-hover"
- >
- <PlatformResponsiveTableLabel
- compact="Pods"
- full={drawerPresentation.openPodsLabel}
- />
- </button>
- <Show when={props.onOpenDeployments}>
- <button
- type="button"
- aria-label={drawerPresentation.viewDeploymentsLabel}
- onClick={() => props.onOpenDeployments?.(row.namespace)}
- class="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-semibold text-base-content shadow-xs hover:bg-surface-hover"
- >
- <PlatformResponsiveTableLabel
- compact="Deployments"
- full={drawerPresentation.viewDeploymentsLabel}
- />
- </button>
- </Show>
- </div>
+ <button
+ type="button"
+ aria-label={`${drawerPresentation.openWorkloadsLabel} in ${row.namespace}`}
+ onClick={() => openWorkloads(row.namespace)}
+ class="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-semibold text-base-content shadow-xs hover:bg-surface-hover"
+ >
+ <PlatformResponsiveTableLabel
+ compact="Open"
+ full={drawerPresentation.openWorkloadsLabel}
+ />
+ </button>
</TableCell>
</TableRow>
);
diff --git a/frontend-modern/src/components/Kubernetes/__tests__/K8sDeploymentsDrawer.test.tsx b/frontend-modern/src/components/Kubernetes/__tests__/K8sDeploymentsDrawer.test.tsx
deleted file mode 100644
index 12a9c524f1..0000000000
--- a/frontend-modern/src/components/Kubernetes/__tests__/K8sDeploymentsDrawer.test.tsx
+++ /dev/null
@@ -1,899 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen, fireEvent, cleanup, waitFor } from '@solidjs/testing-library';
-
-// ── Hoisted mocks ──────────────────────────────────────────────────────
-
-const { apiFetchJSONMock, navigateMock } = vi.hoisted(() => ({
- apiFetchJSONMock: vi.fn(),
- navigateMock: vi.fn(),
-}));
-
-// ── Module mocks ───────────────────────────────────────────────────────
-
-vi.mock('@/utils/apiClient', () => ({
- apiFetchJSON: apiFetchJSONMock,
-}));
-
-vi.mock('@solidjs/router', async () => {
- const actual = await vi.importActual<typeof import('@solidjs/router')>('@solidjs/router');
- return {
- ...actual,
- useNavigate: () => navigateMock,
- };
-});
-
-vi.mock('@/components/shared/Card', () => ({
- Card: (props: any) => (
- <div data-testid="card" class={props.class}>
- {props.children}
- </div>
- ),
-}));
-
-vi.mock('@/components/shared/Table', () => ({
- Table: (props: any) => (
- <table data-testid="table" class={props.class}>
- {props.children}
- </table>
- ),
- TableHeader: (props: any) => <thead class={props.class}>{props.children}</thead>,
- TableBody: (props: any) => <tbody class={props.class}>{props.children}</tbody>,
- TableRow: (props: any) => <tr class={props.class}>{props.children}</tr>,
- TableHead: (props: any) => <th class={props.class}>{props.children}</th>,
- TableCell: (props: any) => (
- <td class={props.class} title={props.title}>
- {props.children}
- </td>
- ),
-}));
-
-vi.mock('@/components/shared/EmptyState', () => ({
- EmptyState: (props: any) => (
- <div data-testid="empty-state">
- <span data-testid="empty-title">{props.title}</span>
- <span data-testid="empty-description">{props.description}</span>
- </div>
- ),
-}));
-
-// ── Import after mocks ─────────────────────────────────────────────────
-
-import { K8sDeploymentsDrawer } from '../K8sDeploymentsDrawer';
-
-// ── Helpers ─────────────────────────────────────────────────────────────
-
-type K8sDeploymentResource = {
- id: string;
- name?: string;
- status?: string;
- kubernetes?: {
- namespace?: string;
- desiredReplicas?: number;
- updatedReplicas?: number;
- readyReplicas?: number;
- availableReplicas?: number;
- };
-};
-
-function makeDeployment(overrides: Partial<K8sDeploymentResource> = {}): K8sDeploymentResource {
- return {
- id: 'dep-1',
- name: 'my-deployment',
- status: 'running',
- kubernetes: {
- namespace: 'default',
- desiredReplicas: 3,
- updatedReplicas: 3,
- readyReplicas: 3,
- availableReplicas: 3,
- },
- ...overrides,
- };
-}
-
-function mockApiResponse(data: K8sDeploymentResource[], totalPages = 1) {
- apiFetchJSONMock.mockResolvedValueOnce({ data, meta: { totalPages } });
-}
-
-// ── Tests ───────────────────────────────────────────────────────────────
-
-afterEach(() => {
- cleanup();
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('K8sDeploymentsDrawer', () => {
- describe('loading state', () => {
- it('shows loading message while deployments are being fetched', async () => {
- let resolveLoading!: (v: unknown) => void;
- apiFetchJSONMock.mockReturnValueOnce(
- new Promise((resolve) => {
- resolveLoading = resolve;
- }),
- );
-
- try {
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
- expect(screen.getByText('Loading deployments...')).toBeInTheDocument();
- } finally {
- resolveLoading({ data: [], meta: { totalPages: 1 } });
- await new Promise((r) => setTimeout(r, 0));
- }
- });
- });
-
- describe('empty states', () => {
- it('shows "No deployments found" when API returns empty data', async () => {
- mockApiResponse([]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- // Wait for loading to finish — the "No deployments found" title replaces "Loading deployments..."
- await waitFor(() => {
- expect(screen.getByTestId('empty-title')).toHaveTextContent('No deployments found');
- });
-
- expect(screen.getByTestId('empty-description')).toHaveTextContent(
- 'Enable the Kubernetes agent deployment collection',
- );
- });
-
- it('shows "No deployments match your filters" when search filters everything', async () => {
- mockApiResponse([makeDeployment({ id: 'dep-1', name: 'nginx' })]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('nginx')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search deployments...');
- fireEvent.input(input, { target: { value: 'nonexistent-xyz' } });
-
- expect(screen.getByTestId('empty-title')).toHaveTextContent(
- 'No deployments match your filters',
- );
- expect(screen.getByTestId('empty-description')).toHaveTextContent(
- 'Try clearing the search or namespace filter.',
- );
- });
- });
-
- describe('deployments table', () => {
- it('renders deployment rows with correct data', async () => {
- const dep = makeDeployment({
- id: 'dep-1',
- name: 'web-frontend',
- status: 'running',
- kubernetes: {
- namespace: 'prod-ns',
- desiredReplicas: 5,
- updatedReplicas: 4,
- readyReplicas: 3,
- availableReplicas: 2,
- },
- });
- mockApiResponse([dep]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('web-frontend')).toBeInTheDocument();
- });
-
- // Namespace appears in both the dropdown option and the table cell — assert exactly 2
- const nsCells = screen.getAllByText('prod-ns');
- expect(nsCells.length).toBe(2); // 1 in dropdown + 1 in table row
- expect(screen.getByText('5')).toBeInTheDocument();
- expect(screen.getByText('4')).toBeInTheDocument();
- expect(screen.getByText('3')).toBeInTheDocument();
- expect(screen.getByText('2')).toBeInTheDocument();
- });
-
- it('uses the shared platform table spacing and divider contract', async () => {
- mockApiResponse([makeDeployment({ id: 'dep-1', name: 'web-frontend' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('web-frontend')).toBeInTheDocument();
- });
-
- expect(screen.getByTestId('table')).toHaveClass('table-fixed');
- expect(container.querySelector('thead tr')).toHaveClass('bg-surface-alt');
- expect(container.querySelector('tbody')).toHaveClass('divide-y', 'divide-border');
- expect(container.querySelector('tbody')).not.toHaveClass('divide-border-subtle');
- expect(container.querySelector('th')).toHaveClass('px-1.5', 'py-0.5');
- });
-
- it('uses deployment id as name when name is empty', async () => {
- const dep = makeDeployment({ id: 'dep-abc', name: '' });
- mockApiResponse([dep]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-abc')).toBeInTheDocument();
- });
- });
-
- it('shows dash for missing namespace', async () => {
- const dep = makeDeployment({
- id: 'dep-1',
- name: 'no-ns-dep',
- kubernetes: { namespace: undefined },
- });
- mockApiResponse([dep]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('no-ns-dep')).toBeInTheDocument();
- });
-
- const dashes = screen.getAllByText('—');
- expect(dashes.length).toBeGreaterThanOrEqual(1);
- });
-
- it('shows 0 for replica counts when missing', async () => {
- const dep = makeDeployment({
- id: 'dep-1',
- name: 'zero-dep',
- kubernetes: {
- namespace: 'default',
- desiredReplicas: undefined,
- updatedReplicas: undefined,
- readyReplicas: undefined,
- availableReplicas: undefined,
- },
- });
- mockApiResponse([dep]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('zero-dep')).toBeInTheDocument();
- });
-
- const zeros = screen.getAllByText('0');
- expect(zeros.length).toBeGreaterThanOrEqual(4);
- });
-
- it('renders all expected column headers', async () => {
- mockApiResponse([makeDeployment()]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('Deployment')).toBeInTheDocument();
- });
-
- // "Namespace" appears in both the label and table header — check via th elements
- const headers = Array.from(container.querySelectorAll('th')).map((th) => th.textContent);
- expect(headers).toContain('Namespace');
- expect(headers).toContain('Desired');
- expect(headers).toContain('Updated');
- expect(headers).toContain('Ready');
- expect(headers).toContain('Available');
- expect(headers).toContain('Actions');
- });
- });
-
- describe('search filtering', () => {
- it('filters by deployment name', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'nginx-proxy', kubernetes: { namespace: 'default' } }),
- makeDeployment({ id: '2', name: 'redis-cache', kubernetes: { namespace: 'default' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('nginx-proxy')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search deployments...');
- fireEvent.input(input, { target: { value: 'redis' } });
-
- expect(screen.queryByText('nginx-proxy')).not.toBeInTheDocument();
- expect(screen.getByText('redis-cache')).toBeInTheDocument();
- });
-
- it('search is case-insensitive', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'MyDeployment', kubernetes: { namespace: 'default' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('MyDeployment')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search deployments...');
- fireEvent.input(input, { target: { value: 'MYDEPLOYMENT' } });
-
- expect(screen.getByText('MyDeployment')).toBeInTheDocument();
- });
-
- it('shows all deployments when search is cleared', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'alpha', kubernetes: { namespace: 'default' } }),
- makeDeployment({ id: '2', name: 'beta', kubernetes: { namespace: 'default' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('alpha')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search deployments...');
- fireEvent.input(input, { target: { value: 'alpha' } });
- expect(screen.queryByText('beta')).not.toBeInTheDocument();
-
- fireEvent.input(input, { target: { value: '' } });
- expect(screen.getByText('alpha')).toBeInTheDocument();
- expect(screen.getByText('beta')).toBeInTheDocument();
- });
-
- it('falls back to id for search when name is empty', async () => {
- mockApiResponse([
- makeDeployment({ id: 'dep-id-abc', name: '', kubernetes: { namespace: 'default' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-id-abc')).toBeInTheDocument();
- });
-
- const input = screen.getByPlaceholderText('Search deployments...');
- fireEvent.input(input, { target: { value: 'dep-id' } });
-
- expect(screen.getByText('dep-id-abc')).toBeInTheDocument();
- });
- });
-
- describe('namespace filtering', () => {
- it('shows namespace dropdown when namespaces exist', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-a', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'dep-b', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-a')).toBeInTheDocument();
- });
-
- const select = screen.getByLabelText('Namespace') as HTMLSelectElement;
- expect(select).toBeInTheDocument();
-
- // Check "All namespaces" default option
- const options = select.querySelectorAll('option');
- expect(options[0]).toHaveTextContent('All namespaces');
- expect(options[1]).toHaveTextContent('production');
- expect(options[2]).toHaveTextContent('staging');
- });
-
- it('filters deployments by selected namespace', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'prod-dep', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'stage-dep', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('prod-dep')).toBeInTheDocument();
- });
-
- const select = screen.getByLabelText('Namespace');
- fireEvent.change(select, { target: { value: 'production' } });
-
- expect(screen.getByText('prod-dep')).toBeInTheDocument();
- expect(screen.queryByText('stage-dep')).not.toBeInTheDocument();
- });
-
- it('sorts namespace options alphabetically', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-1', kubernetes: { namespace: 'zebra' } }),
- makeDeployment({ id: '2', name: 'dep-2', kubernetes: { namespace: 'alpha' } }),
- makeDeployment({ id: '3', name: 'dep-3', kubernetes: { namespace: 'middle' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-1')).toBeInTheDocument();
- });
-
- const select = screen.getByLabelText('Namespace') as HTMLSelectElement;
- const options = Array.from(select.querySelectorAll('option')).map((o) => o.textContent);
- // First option is "All namespaces", then sorted
- expect(options).toEqual(['All namespaces', 'alpha', 'middle', 'zebra']);
- });
-
- it('deduplicates namespace options', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-1', kubernetes: { namespace: 'default' } }),
- makeDeployment({ id: '2', name: 'dep-2', kubernetes: { namespace: 'default' } }),
- makeDeployment({ id: '3', name: 'dep-3', kubernetes: { namespace: 'kube-system' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-1')).toBeInTheDocument();
- });
-
- const select = screen.getByLabelText('Namespace') as HTMLSelectElement;
- const options = Array.from(select.querySelectorAll('option')).map((o) => o.textContent);
- expect(options).toEqual(['All namespaces', 'default', 'kube-system']);
- });
-
- it('does not show namespace dropdown when no namespaces exist', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-1', kubernetes: { namespace: '' } })]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-1')).toBeInTheDocument();
- });
-
- expect(screen.queryByLabelText('Namespace')).not.toBeInTheDocument();
- });
-
- it('combines namespace and search filters', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'nginx-prod', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'nginx-stage', kubernetes: { namespace: 'staging' } }),
- makeDeployment({ id: '3', name: 'redis-prod', kubernetes: { namespace: 'production' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('nginx-prod')).toBeInTheDocument();
- });
-
- // Filter by namespace
- const select = screen.getByLabelText('Namespace');
- fireEvent.change(select, { target: { value: 'production' } });
-
- // Then also search
- const input = screen.getByPlaceholderText('Search deployments...');
- fireEvent.input(input, { target: { value: 'nginx' } });
-
- expect(screen.getByText('nginx-prod')).toBeInTheDocument();
- expect(screen.queryByText('nginx-stage')).not.toBeInTheDocument();
- expect(screen.queryByText('redis-prod')).not.toBeInTheDocument();
- });
- });
-
- describe('sorting', () => {
- it('sorts deployments alphabetically by name', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'zebra', kubernetes: { namespace: 'default' } }),
- makeDeployment({ id: '2', name: 'alpha', kubernetes: { namespace: 'default' } }),
- makeDeployment({ id: '3', name: 'middle', kubernetes: { namespace: 'default' } }),
- ]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('zebra')).toBeInTheDocument();
- });
-
- const rows = container.querySelectorAll('tr');
- const names = Array.from(rows)
- .map((row) => row.querySelector('.font-semibold')?.textContent)
- .filter(Boolean);
-
- expect(names).toEqual(['alpha', 'middle', 'zebra']);
- });
-
- it('uses id as tiebreaker when names are the same', async () => {
- // Invert markers: a-id gets higher replica count (99), z-id gets lower (11).
- // Only an id-based sort produces [a-id(99), z-id(11)]; namespace or replica
- // sorts would produce a different order, making the assertion uniquely prove
- // that id is the tiebreaker.
- mockApiResponse([
- makeDeployment({
- id: 'z-id',
- name: 'same',
- kubernetes: { namespace: 'ns-a', desiredReplicas: 11 },
- }),
- makeDeployment({
- id: 'a-id',
- name: 'same',
- kubernetes: { namespace: 'ns-z', desiredReplicas: 99 },
- }),
- ]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getAllByText('same').length).toBe(2);
- });
-
- // id asc → a-id (99) before z-id (11)
- const rows = container.querySelectorAll('tbody tr');
- expect(rows.length).toBe(2);
- expect(rows[0].textContent).toContain('99'); // a-id row (desiredReplicas=99)
- expect(rows[1].textContent).toContain('11'); // z-id row (desiredReplicas=11)
- });
- });
-
- describe('statusTone helper (via DOM classes)', () => {
- it('applies green class for running status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-running', status: 'running' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-running')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-emerald-500')).toBeInTheDocument();
- });
-
- it('applies green class for online status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-online', status: 'online' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-online')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-emerald-500')).toBeInTheDocument();
- });
-
- it('applies green class for healthy status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-healthy', status: 'healthy' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-healthy')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-emerald-500')).toBeInTheDocument();
- });
-
- it('applies amber class for warning status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-warn', status: 'warning' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-warn')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-amber-500')).toBeInTheDocument();
- });
-
- it('applies amber class for degraded status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-degraded', status: 'degraded' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-degraded')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-amber-500')).toBeInTheDocument();
- });
-
- it('applies red class for offline status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-offline', status: 'offline' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-offline')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-red-500')).toBeInTheDocument();
- });
-
- it('applies red class for stopped status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-stopped', status: 'stopped' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-stopped')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-red-500')).toBeInTheDocument();
- });
-
- it('applies slate class for unknown status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-unknown', status: 'something-else' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-unknown')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-slate-400')).toBeInTheDocument();
- });
-
- it('applies slate class for empty status', async () => {
- mockApiResponse([makeDeployment({ id: '1', name: 'dep-empty', status: '' })]);
- const { container } = render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-empty')).toBeInTheDocument();
- });
-
- expect(container.querySelector('.bg-slate-400')).toBeInTheDocument();
- });
- });
-
- describe('API interaction', () => {
- it('builds correct URL with cluster, page, and limit params', async () => {
- mockApiResponse([]);
- render(() => <K8sDeploymentsDrawer cluster="my-cluster" />);
-
- await waitFor(() => {
- expect(apiFetchJSONMock).toHaveBeenCalled();
- });
-
- const url = apiFetchJSONMock.mock.calls[0][0] as string;
- expect(url).toContain('type=k8s-deployment');
- expect(url).toContain('cluster=my-cluster');
- expect(url).toContain('page=1');
- expect(url).toContain('limit=100');
- });
-
- it('does not fetch when cluster is empty', async () => {
- render(() => <K8sDeploymentsDrawer cluster="" />);
-
- // Flush multiple microtask cycles to let SolidJS evaluate source signal
- await new Promise<void>((resolve) => queueMicrotask(() => resolve()));
- await new Promise<void>((resolve) => queueMicrotask(() => resolve()));
-
- expect(apiFetchJSONMock).not.toHaveBeenCalled();
- });
-
- it('fetches multiple pages when totalPages > 1', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-1', name: 'page1-dep' })],
- meta: { totalPages: 3 },
- });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-2', name: 'page2-dep' })],
- meta: { totalPages: 3 },
- });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-3', name: 'page3-dep' })],
- meta: { totalPages: 3 },
- });
-
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('page1-dep')).toBeInTheDocument();
- });
-
- expect(screen.getByText('page2-dep')).toBeInTheDocument();
- expect(screen.getByText('page3-dep')).toBeInTheDocument();
- expect(apiFetchJSONMock).toHaveBeenCalledTimes(3);
- });
-
- it('deduplicates deployments by id across pages', async () => {
- const dep = makeDeployment({ id: 'dup-dep', name: 'duplicated' });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [dep],
- meta: { totalPages: 2 },
- });
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [dep],
- meta: { totalPages: 2 },
- });
-
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('duplicated')).toBeInTheDocument();
- });
-
- const matches = screen.getAllByText('duplicated');
- expect(matches).toHaveLength(1);
- });
-
- it('handles failed page fetches gracefully (Promise.allSettled)', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-ok', name: 'ok-dep' })],
- meta: { totalPages: 3 },
- });
- apiFetchJSONMock.mockRejectedValueOnce(new Error('network error'));
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-3', name: 'page3-dep' })],
- meta: { totalPages: 3 },
- });
-
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('ok-dep')).toBeInTheDocument();
- });
-
- expect(screen.getByText('page3-dep')).toBeInTheDocument();
- });
-
- it('caps pagination at MAX_PAGES (20)', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-1', name: 'first-page' })],
- meta: { totalPages: 25 },
- });
- for (let i = 2; i <= 20; i++) {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: `dep-${i}`, name: `page${i}-dep` })],
- meta: { totalPages: 25 },
- });
- }
-
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('first-page')).toBeInTheDocument();
- });
-
- // Should have fetched exactly 20 pages (1 initial + 19 additional), not 25
- expect(apiFetchJSONMock).toHaveBeenCalledTimes(20);
- });
-
- it('handles non-array data gracefully', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: null,
- meta: { totalPages: 1 },
- });
-
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByTestId('empty-title')).toHaveTextContent('No deployments found');
- });
- });
-
- it('handles missing meta.totalPages gracefully', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- data: [makeDeployment({ id: 'dep-1', name: 'solo-dep' })],
- meta: {},
- });
-
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('solo-dep')).toBeInTheDocument();
- });
-
- // Should only fetch one page when totalPages is missing
- expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('navigation', () => {
- it('"Open Pods" button navigates to the Kubernetes Workloads tab', async () => {
- mockApiResponse([makeDeployment()]);
- render(() => <K8sDeploymentsDrawer cluster="my-cluster" />);
-
- await waitFor(() => {
- expect(screen.getByText('my-deployment')).toBeInTheDocument();
- });
-
- const openPodsBtn = screen.getByRole('button', { name: 'Open Pods' });
- fireEvent.click(openPodsBtn);
-
- expect(navigateMock).toHaveBeenCalledTimes(1);
- expect(navigateMock).toHaveBeenCalledWith('/kubernetes/workloads');
- });
-
- it('"Open Pods" routes to the Kubernetes Workloads tab regardless of selected namespace', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-a', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'dep-b', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-a')).toBeInTheDocument();
- });
-
- // Selecting a namespace narrows the in-drawer view but no longer
- // forwards as a URL filter (the platform-first Kubernetes Workloads tab
- // does not consume legacy ?namespace= query params).
- const select = screen.getByLabelText('Namespace');
- fireEvent.change(select, { target: { value: 'production' } });
-
- const openPodsBtn = screen.getByRole('button', { name: 'Open Pods' });
- fireEvent.click(openPodsBtn);
-
- expect(navigateMock).toHaveBeenCalledTimes(1);
- expect(navigateMock).toHaveBeenCalledWith('/kubernetes/workloads');
- });
-
- it('"View Pods" button on a row navigates to the Kubernetes Workloads tab', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-a', kubernetes: { namespace: 'kube-system' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-a')).toBeInTheDocument();
- });
-
- const viewPodsBtn = screen.getByRole('button', { name: 'View Pods' });
- fireEvent.click(viewPodsBtn);
-
- expect(navigateMock).toHaveBeenCalledTimes(1);
- expect(navigateMock).toHaveBeenCalledWith('/kubernetes/workloads');
- });
-
- it('does not navigate when cluster is empty', async () => {
- render(() => <K8sDeploymentsDrawer cluster="" />);
-
- const openPodsBtn = screen.getByRole('button', { name: 'Open Pods' });
- fireEvent.click(openPodsBtn);
-
- expect(navigateMock).not.toHaveBeenCalled();
- });
- });
-
- describe('initialNamespace prop', () => {
- it('prefills namespace filter when initialNamespace matches an existing namespace', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-prod', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'dep-stage', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" initialNamespace="production" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-prod')).toBeInTheDocument();
- });
-
- // Should filter to only production deployments
- expect(screen.queryByText('dep-stage')).not.toBeInTheDocument();
- });
-
- it('does not apply initialNamespace when it does not match any namespace', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-prod', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'dep-stage', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" initialNamespace="nonexistent" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-prod')).toBeInTheDocument();
- });
-
- // Both should be visible since nonexistent namespace is not applied
- expect(screen.getByText('dep-stage')).toBeInTheDocument();
- });
-
- it('case-mismatch initialNamespace is accepted but filters out all rows (documents bug)', async () => {
- // The component checks existence case-insensitively but filters case-sensitively.
- // When initialNamespace="production" but actual namespace is "Production",
- // the existence check passes and the filter value is set to "production",
- // but the row filter does an exact comparison and no rows match.
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-prod', kubernetes: { namespace: 'Production' } }),
- makeDeployment({ id: '2', name: 'dep-stage', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" initialNamespace="production" />);
-
- await waitFor(() => {
- expect(screen.getByTestId('empty-title')).toHaveTextContent(
- 'No deployments match your filters',
- );
- });
- });
-
- it('does not apply initialNamespace when it is empty', async () => {
- mockApiResponse([
- makeDeployment({ id: '1', name: 'dep-prod', kubernetes: { namespace: 'production' } }),
- makeDeployment({ id: '2', name: 'dep-stage', kubernetes: { namespace: 'staging' } }),
- ]);
- render(() => <K8sDeploymentsDrawer cluster="c1" initialNamespace="" />);
-
- await waitFor(() => {
- expect(screen.getByText('dep-prod')).toBeInTheDocument();
- });
-
- expect(screen.getByText('dep-stage')).toBeInTheDocument();
- });
- });
-
- describe('header card', () => {
- it('renders title and subtitle', async () => {
- mockApiResponse([]);
- render(() => <K8sDeploymentsDrawer cluster="c1" />);
-
- expect(screen.getByText('Deployments')).toBeInTheDocument();
- expect(screen.getByText('Desired state controllers (not Pods)')).toBeInTheDocument();
- await waitFor(() => expect(apiFetchJSONMock).toHaveBeenCalled());
- });
- });
-});
diff --git a/frontend-modern/src/components/Kubernetes/__tests__/K8sNamespacesDrawer.test.tsx b/frontend-modern/src/components/Kubernetes/__tests__/K8sNamespacesDrawer.test.tsx
index 064ea92fbc..e1465a80af 100644
--- a/frontend-modern/src/components/Kubernetes/__tests__/K8sNamespacesDrawer.test.tsx
+++ b/frontend-modern/src/components/Kubernetes/__tests__/K8sNamespacesDrawer.test.tsx
@@ -33,22 +33,24 @@ describe('K8sNamespacesDrawer', () => {
cleanup();
});
- it('navigates to the Kubernetes Workloads tab from the cluster summary', async () => {
+ it('opens the Workloads tab scoped to the whole cluster', async () => {
apiFetchJSONMock.mockResolvedValueOnce(makeResponse([{ namespace: 'default' }]));
- render(() => <K8sNamespacesDrawer cluster="cluster-a" />);
+ render(() => <K8sNamespacesDrawer cluster="cluster-a" scopeCluster="cluster-a-id" />);
await waitFor(() => {
expect(screen.getByText('default')).toBeInTheDocument();
});
- await fireEvent.click(screen.getByRole('button', { name: 'Open All Pods' }));
+ await fireEvent.click(screen.getByRole('button', { name: 'Open all workloads' }));
- expect(navigateMock).toHaveBeenCalledWith('/kubernetes/workloads');
+ expect(navigateMock).toHaveBeenCalledWith('/kubernetes/workloads?cluster=cluster-a-id');
});
- it('navigates to the Kubernetes Workloads tab from a namespace row', async () => {
- apiFetchJSONMock.mockResolvedValueOnce(makeResponse([{ namespace: 'kube-system' }]));
+ it('opens the workloads scoped to the cluster and namespace of the row', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce(
+ makeResponse([{ namespace: 'kube-system' }, { namespace: 'default' }]),
+ );
render(() => <K8sNamespacesDrawer cluster="cluster-a" />);
@@ -56,9 +58,46 @@ describe('K8sNamespacesDrawer', () => {
expect(screen.getByText('kube-system')).toBeInTheDocument();
});
- await fireEvent.click(screen.getByRole('button', { name: 'Open Pods' }));
+ // Each row's action names its namespace, so a screen reader can tell the
+ // rows' buttons apart. Pods and deployments share the Workloads tab.
+ await fireEvent.click(screen.getByRole('button', { name: 'Open workloads in kube-system' }));
+ expect(navigateMock).toHaveBeenLastCalledWith(
+ '/kubernetes/workloads?cluster=cluster-a&namespace=kube-system',
+ );
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Open workloads in default' }));
+ expect(navigateMock).toHaveBeenLastCalledWith(
+ '/kubernetes/workloads?cluster=cluster-a&namespace=default',
+ );
+ });
+
+ it('shows the failure state when the namespaces read fails', async () => {
+ apiFetchJSONMock.mockRejectedValueOnce(new Error('namespaces endpoint unavailable'));
+
+ render(() => <K8sNamespacesDrawer cluster="cluster-a" />);
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Failed to load namespaces');
+ expect(screen.getByRole('alert')).toHaveTextContent('namespaces endpoint unavailable');
+ });
+
+ it('wraps long namespace names instead of truncating them', async () => {
+ const longName = 'team-payments-reconciliation-batch-processing-production';
+ apiFetchJSONMock.mockResolvedValueOnce(makeResponse([{ namespace: longName }]));
+
+ render(() => <K8sNamespacesDrawer cluster="cluster-a" />);
+
+ const name = await screen.findByText(longName);
+ expect(name).toHaveClass('whitespace-normal', 'wrap-anywhere');
+ expect(name).not.toHaveClass('truncate');
+ });
+
+ it('does not repeat the tab label in a nested card header', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce(makeResponse([{ namespace: 'default' }]));
+
+ render(() => <K8sNamespacesDrawer cluster="cluster-a" />);
- expect(navigateMock).toHaveBeenCalledWith('/kubernetes/workloads');
+ await screen.findByText('default');
+ expect(screen.queryByText('Scope Pods and Deployments by namespace')).toBeNull();
});
it('uses the shared platform table spacing and divider contract', async () => {
@@ -79,7 +118,7 @@ describe('K8sNamespacesDrawer', () => {
it('does not navigate when cluster is empty', async () => {
render(() => <K8sNamespacesDrawer cluster="" />);
- await fireEvent.click(screen.getByRole('button', { name: 'Open All Pods' }));
+ await fireEvent.click(screen.getByRole('button', { name: 'Open all workloads' }));
expect(navigateMock).not.toHaveBeenCalled();
});
diff --git a/frontend-modern/src/components/Storage/DiskDetail.tsx b/frontend-modern/src/components/Storage/DiskDetail.tsx
deleted file mode 100644
index 7473a4f697..0000000000
--- a/frontend-modern/src/components/Storage/DiskDetail.tsx
+++ /dev/null
@@ -1,292 +0,0 @@
-import {
- Component,
- For,
- Show,
- createEffect,
- createMemo,
- createSignal,
- createUniqueId,
-} from 'solid-js';
-import type { Resource } from '@/types/resource';
-import { FormSelect } from '@/components/shared/FormSelect';
-import { filterSelectClass } from '@/components/shared/FilterToolbar';
-import { HistoryChart, HistoryChartHoverGroup } from '@/components/shared/HistoryChart';
-import { PhoneChartsToggle } from '@/components/shared/PhoneChartsToggle';
-import { useBreakpoint } from '@/hooks/useBreakpoint';
-import type { HistoryTimeRange } from '@/api/charts';
-import { maxHistoryDays } from '@/stores/license';
-import {
- getUnlockedHistoryRangeOptions,
- resolveHistoryRangeWithinLimit,
-} from '@/components/Storage/historyRangeAccess';
-import {
- DISK_DETAIL_HEADER_STACK_CLASS,
- DISK_DETAIL_HEALTH_LABEL_CLASS,
- DISK_DETAIL_HEALTH_ROW_CLASS,
- DISK_DETAIL_HEALTH_SUMMARY_CLASS,
- DISK_DETAIL_HISTORY_RANGE_OPTIONS,
- DISK_DETAIL_LIVE_CHARTS,
- getDiskAttributeCardValueTextClass,
- getDiskDetailHistoryFallbackMessage,
- getDiskDetailLiveBadgeLabel,
- getDiskDetailPhonePinnedChartLabels,
-} from '@/features/storageBackups/diskDetailPresentation';
-import {
- STORAGE_DETAIL_BADGE_CLASS,
- STORAGE_DETAIL_CARD_CLASS,
- STORAGE_DETAIL_EMPTY_CLASS,
- STORAGE_DETAIL_HEADER_ROW_CLASS,
- STORAGE_DISK_DETAIL_ATTRIBUTE_GRID_CLASS,
- STORAGE_DISK_DETAIL_HEADER_CLASS,
- STORAGE_DISK_DETAIL_HISTORY_GRID_CLASS,
- STORAGE_DISK_DETAIL_LIVE_GRID_CLASS,
- STORAGE_DISK_DETAIL_MODEL_CLASS,
- STORAGE_DISK_DETAIL_NODE_CLASS,
- STORAGE_DISK_DETAIL_ROOT_CLASS,
- STORAGE_DISK_DETAIL_SECTION_CLASS,
- STORAGE_DISK_DETAIL_SECTION_HEADING_CLASS,
- STORAGE_DISK_DETAIL_SERIAL_CLASS,
- STORAGE_DETAIL_META_ROW_CLASS,
- STORAGE_DETAIL_MONO_CHIP_CLASS,
- STORAGE_DETAIL_SECTION_TITLE_CLASS,
-} from '@/features/storageBackups/detailPresentation';
-import { getPhysicalDiskSourceBadgePresentation } from '@/features/storageBackups/diskPresentation';
-import { StorageDetailMetricCard } from './StorageDetailMetricCard';
-import { useDiskDetailModel } from './useDiskDetailModel';
-
-interface DiskDetailProps {
- disk: Resource;
- nodes: Resource[];
- /** Alert override keys of the machine whose agent reports the disk. */
- alertResourceIds?: string[];
- /** False pauses this disk's chart reads, e.g. while a drawer tab is hidden. */
- historyEnabled?: boolean;
-}
-
-export const DiskDetail: Component<DiskDetailProps> = (props) => {
- const {
- chartRange,
- setChartRange,
- diskData,
- historyResourceId,
- attributeCards,
- historyCharts,
- healthPresentation,
- metricResourceId,
- collectionMessages,
- liveIOAvailable,
- } = useDiskDetailModel({
- disk: () => props.disk,
- alertResourceIds: () => props.alertResourceIds,
- });
- const rangeOptions = createMemo(() =>
- getUnlockedHistoryRangeOptions(DISK_DETAIL_HISTORY_RANGE_OPTIONS, maxHistoryDays()),
- );
- const hasOverviewDetails = createMemo(
- () => collectionMessages().length > 0 || attributeCards().length > 0,
- );
-
- // On a phone five stacked charts push everything after them off screen: show
- // the first chart and any whose SMART card is out of bounds, fold the rest
- // behind one button. A pinned chart stays pinned after its card recovers, so
- // a reader mid-inspection does not lose it. Folded charts read nothing.
- const { isBelow } = useBreakpoint();
- const chartsId = createUniqueId();
- const [showAllOnPhone, setShowAllOnPhone] = createSignal(false);
- const pinnedLabels = new Set<string>();
- const phonePinned = createMemo(() => {
- for (const label of getDiskDetailPhonePinnedChartLabels(historyCharts(), attributeCards())) {
- pinnedLabels.add(label);
- }
- return new Set(pinnedLabels);
- });
- const foldedOnPhone = (label: string) => !showAllOnPhone() && !phonePinned().has(label);
- const showLiveIO = () => Boolean(metricResourceId() && liveIOAvailable());
- const phoneFoldedLabels = createMemo(() =>
- [
- ...historyCharts().map((chart) => chart.label),
- ...(showLiveIO() ? DISK_DETAIL_LIVE_CHARTS.map((chart) => chart.label) : []),
- ].filter(foldedOnPhone),
- );
- const chartReads = (label: string) =>
- props.historyEnabled !== false && !(isBelow('sm') && foldedOnPhone(label));
-
- createEffect(() => {
- const nextRange = resolveHistoryRangeWithinLimit(
- chartRange(),
- DISK_DETAIL_HISTORY_RANGE_OPTIONS,
- maxHistoryDays(),
- );
- if (nextRange !== chartRange()) {
- setChartRange(nextRange);
- }
- });
-
- return (
- <div class={STORAGE_DISK_DETAIL_ROOT_CLASS}>
- <div class={STORAGE_DISK_DETAIL_HEADER_CLASS}>
- <div class={DISK_DETAIL_HEADER_STACK_CLASS}>
- <div class={STORAGE_DETAIL_META_ROW_CLASS}>
- <span class={STORAGE_DISK_DETAIL_MODEL_CLASS}>
- {diskData().model || 'Unknown Disk'}
- </span>
- <span class={STORAGE_DETAIL_MONO_CHIP_CLASS}>{diskData().devPath}</span>
- <span class={STORAGE_DISK_DETAIL_NODE_CLASS}>{diskData().node}</span>
- <span
- class={getPhysicalDiskSourceBadgePresentation(props.disk).className}
- title="Data source"
- >
- {getPhysicalDiskSourceBadgePresentation(props.disk).label}
- </span>
- <Show when={diskData().serial}>
- <span class={STORAGE_DISK_DETAIL_SERIAL_CLASS}>S/N: {diskData().serial}</span>
- </Show>
- </div>
- {/* The verdict the row shows as a single word, with its reason in full. */}
- <div class={DISK_DETAIL_HEALTH_ROW_CLASS} data-testid="disk-detail-health">
- <span class={`${DISK_DETAIL_HEALTH_LABEL_CLASS} ${healthPresentation().tone}`}>
- {healthPresentation().label}
- </span>
- <Show when={healthPresentation().summary}>
- <span class={DISK_DETAIL_HEALTH_SUMMARY_CLASS}>{healthPresentation().summary}</span>
- </Show>
- </div>
- </div>
- </div>
-
- {/* One view: the SMART evidence behind the health verdict, then its
- trend and live I/O. There is no separate History tab. */}
- <div id={chartsId} class="space-y-3">
- <Show when={collectionMessages().length > 0}>
- <div class={STORAGE_DETAIL_EMPTY_CLASS} role="status">
- <For each={collectionMessages()}>{(message) => <p>{message}</p>}</For>
- </div>
- </Show>
-
- <Show when={attributeCards().length > 0}>
- <div class={STORAGE_DISK_DETAIL_ATTRIBUTE_GRID_CLASS}>
- <For each={attributeCards()}>
- {(card) => (
- <StorageDetailMetricCard
- label={card.label}
- value={card.value}
- valueClass={getDiskAttributeCardValueTextClass(card)}
- />
- )}
- </For>
- </div>
- </Show>
-
- <Show when={!hasOverviewDetails()}>
- <div class={STORAGE_DETAIL_EMPTY_CLASS} role="status">
- Detailed SMART attributes are not available for this disk.
- </div>
- </Show>
-
- <Show
- when={historyResourceId()}
- fallback={
- <div class={STORAGE_DETAIL_EMPTY_CLASS}>{getDiskDetailHistoryFallbackMessage()}</div>
- }
- >
- <div class={STORAGE_DISK_DETAIL_SECTION_CLASS} data-testid="disk-detail-history">
- <div class={STORAGE_DETAIL_HEADER_ROW_CLASS}>
- <h4 class={STORAGE_DETAIL_SECTION_TITLE_CLASS}>History</h4>
- <FormSelect
- label="Disk history range"
- labelClass="sr-only"
- fieldBaseClass="contents"
- value={chartRange()}
- onChange={(event) => setChartRange(event.currentTarget.value as HistoryTimeRange)}
- selectBaseClass={`${filterSelectClass} h-7 min-h-11 py-0 text-[11px] sm:min-h-0`}
- >
- <For each={rangeOptions()}>
- {(option) => <option value={option.value}>{option.label}</option>}
- </For>
- </FormSelect>
- </div>
- <HistoryChartHoverGroup>
- <div class={STORAGE_DISK_DETAIL_HISTORY_GRID_CLASS}>
- <For each={historyCharts()}>
- {(chart) => (
- <div
- class={`${STORAGE_DETAIL_CARD_CLASS} ${foldedOnPhone(chart.label) ? 'max-sm:hidden' : ''}`}
- data-phone-collapsed={foldedOnPhone(chart.label) ? 'true' : undefined}
- >
- <HistoryChart
- resourceType="disk"
- resourceId={historyResourceId()!}
- metric={chart.metric}
- label={chart.label}
- unit={chart.unit}
- height={120}
- color={chart.color}
- range={chartRange()}
- hideSelector={true}
- compact={true}
- hideLock={true}
- enabled={chartReads(chart.label)}
- />
- </div>
- )}
- </For>
- </div>
- </HistoryChartHoverGroup>
- </div>
- </Show>
-
- <Show when={showLiveIO()}>
- <div
- class={`${STORAGE_DISK_DETAIL_SECTION_CLASS} ${showAllOnPhone() ? '' : 'max-sm:hidden'}`}
- data-phone-collapsed={showAllOnPhone() ? undefined : 'true'}
- >
- <h4
- class={`${STORAGE_DETAIL_SECTION_TITLE_CLASS} ${STORAGE_DISK_DETAIL_SECTION_HEADING_CLASS}`}
- >
- Live I/O (30m)
- <span class={STORAGE_DETAIL_BADGE_CLASS}>{getDiskDetailLiveBadgeLabel()}</span>
- </h4>
- <HistoryChartHoverGroup>
- <div class={STORAGE_DISK_DETAIL_LIVE_GRID_CLASS}>
- <For each={DISK_DETAIL_LIVE_CHARTS}>
- {(chart) => (
- <div class={STORAGE_DETAIL_CARD_CLASS}>
- <HistoryChart
- resourceType="disk"
- resourceId={metricResourceId()!}
- metric={
- chart.series === 'read'
- ? 'diskread'
- : chart.series === 'write'
- ? 'diskwrite'
- : 'disk'
- }
- label={chart.label}
- unit={chart.unit}
- range="30m"
- hideSelector
- hideLock
- height={120}
- compact={true}
- enabled={chartReads(chart.label)}
- />
- </div>
- )}
- </For>
- </div>
- </HistoryChartHoverGroup>
- </div>
- </Show>
- <Show when={historyResourceId()}>
- <PhoneChartsToggle
- hiddenLabels={phoneFoldedLabels()}
- expanded={showAllOnPhone()}
- onToggle={() => setShowAllOnPhone((open) => !open)}
- controls={chartsId}
- testId="disk-detail-phone-toggle"
- />
- </Show>
- </div>
- </div>
- );
-};
diff --git a/frontend-modern/src/components/Storage/DiskDrawerOverview.tsx b/frontend-modern/src/components/Storage/DiskDrawerOverview.tsx
index e0b0f4f575..8aa16fe3bc 100644
--- a/frontend-modern/src/components/Storage/DiskDrawerOverview.tsx
+++ b/frontend-modern/src/components/Storage/DiskDrawerOverview.tsx
@@ -1,7 +1,10 @@
import { Component, For, Show, Suspense, createMemo, lazy } from 'solid-js';
import type { HistoryTimeRange } from '@/api/charts';
import type { DetailSection } from '@/components/shared/DetailSectionTable';
-import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
+import {
+ DrawerAttentionSection,
+ DrawerNoAlertsLine,
+} from '@/components/shared/DrawerAttentionSection';
import {
TechnicalDetailsDisclosure,
TechnicalDetailsSection,
@@ -31,7 +34,6 @@ import {
import type { PhysicalDiskPresentationData } from '@/features/storageBackups/diskPresentation';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
-import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { resolvePhysicalDiskHistoryResourceId } from './diskResourceUtils';
@@ -116,9 +118,7 @@ export const DiskDrawerOverview: Component<DiskDrawerOverviewProps> = (props) =>
}))}
/>
<Show when={(props.alerts ?? []).length === 0}>
- <p data-testid="drawer-no-attention" class="text-xs font-medium text-base-content">
- {ALERTS_EMPTY_STATE}
- </p>
+ <DrawerNoAlertsLine />
</Show>
<DrawerExceptionList testId="disk-drawer-exceptions" rows={exceptionRows()} />
diff --git a/frontend-modern/src/components/Storage/StorageDetailKeyValueRow.tsx b/frontend-modern/src/components/Storage/StorageDetailKeyValueRow.tsx
deleted file mode 100644
index 0520220d62..0000000000
--- a/frontend-modern/src/components/Storage/StorageDetailKeyValueRow.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { Component } from 'solid-js';
-import { InfoCardKeyValueRow } from '@/components/shared/InfoCardFrame';
-import {
- STORAGE_DETAIL_KEY_CLASS,
- STORAGE_DETAIL_VALUE_CLASS,
-} from '@/features/storageBackups/detailPresentation';
-
-type StorageDetailKeyValueRowProps = {
- label: string;
- value: string;
-};
-
-export const StorageDetailKeyValueRow: Component<StorageDetailKeyValueRowProps> = (props) => (
- <InfoCardKeyValueRow
- class="col-span-2 sm:col-span-1"
- desktopAt="sm"
- label={props.label}
- labelClass={STORAGE_DETAIL_KEY_CLASS}
- value={props.value}
- valueClass={`${STORAGE_DETAIL_VALUE_CLASS} wrap-break-word`}
- valueTitle={props.value}
- />
-);
-
-export default StorageDetailKeyValueRow;
diff --git a/frontend-modern/src/components/Storage/StorageDetailMetricCard.tsx b/frontend-modern/src/components/Storage/StorageDetailMetricCard.tsx
deleted file mode 100644
index c5737de1aa..0000000000
--- a/frontend-modern/src/components/Storage/StorageDetailMetricCard.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { Component } from 'solid-js';
-import {
- STORAGE_DETAIL_CARD_CLASS,
- STORAGE_DETAIL_INLINE_LABEL_CLASS,
-} from '@/features/storageBackups/detailPresentation';
-
-type StorageDetailMetricCardProps = {
- label: string;
- value: string;
- valueClass: string;
-};
-
-export const StorageDetailMetricCard: Component<StorageDetailMetricCardProps> = (props) => (
- <div class={STORAGE_DETAIL_CARD_CLASS}>
- <div class={`${STORAGE_DETAIL_INLINE_LABEL_CLASS} mb-0.5`}>{props.label}</div>
- <div class={`text-sm font-semibold ${props.valueClass}`}>{props.value}</div>
- </div>
-);
-
-export default StorageDetailMetricCard;
diff --git a/frontend-modern/src/components/Storage/StorageGroupRow.tsx b/frontend-modern/src/components/Storage/StorageGroupRow.tsx
index d9f45d5596..07f0a8a853 100644
--- a/frontend-modern/src/components/Storage/StorageGroupRow.tsx
+++ b/frontend-modern/src/components/Storage/StorageGroupRow.tsx
@@ -1,7 +1,8 @@
-import { Component, For, Show } from 'solid-js';
+import { Component, For, Show, createSignal } from 'solid-js';
import { EnhancedStorageBar } from './EnhancedStorageBar';
import type { StorageGroupedRecords } from './useStorageModel';
import { SummaryRowActionButton } from '@/components/shared/SummaryRowActionButton';
+import { createVisibleTableColumnSpan } from '@/components/shared/tableVisibleColumnSpan';
import {
buildStorageGroupRowPresentation,
STORAGE_GROUP_ROW_CELL_CLASS,
@@ -29,14 +30,19 @@ interface StorageGroupRowProps {
// from clearing an open pool elsewhere in the table.
export const StorageGroupRow: Component<StorageGroupRowProps> = (props) => {
const row = () => buildStorageGroupRowPresentation(props.group);
+ // Span the visible columns only; a larger span adds phantom fixed-layout
+ // columns that leave every pool row and drawer short of the edge on phones.
+ const [rowEl, setRowEl] = createSignal<HTMLTableRowElement | null>(null);
+ const columnSpan = createVisibleTableColumnSpan(rowEl);
return (
<tr
+ ref={setRowEl}
class={STORAGE_GROUP_ROW_CLASS}
data-summary-group-id={props.summaryGroupId ?? undefined}
onClick={() => props.onToggle()}
>
- <td colSpan={99} class={STORAGE_GROUP_ROW_CELL_CLASS}>
+ <td colSpan={columnSpan()} class={STORAGE_GROUP_ROW_CELL_CLASS}>
<div class={STORAGE_GROUP_ROW_CONTENT_CLASS}>
<SummaryRowActionButton
kind="disclosure"
diff --git a/frontend-modern/src/components/Storage/StoragePoolDetail.tsx b/frontend-modern/src/components/Storage/StoragePoolDetail.tsx
index ab45c26418..cdd130628e 100644
--- a/frontend-modern/src/components/Storage/StoragePoolDetail.tsx
+++ b/frontend-modern/src/components/Storage/StoragePoolDetail.tsx
@@ -6,7 +6,10 @@ import {
type DetailRow,
type DetailSection,
} from '@/components/shared/DetailSectionTable';
-import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
+import {
+ DrawerAttentionSection,
+ DrawerNoAlertsLine,
+} from '@/components/shared/DrawerAttentionSection';
import { StatusDot } from '@/components/shared/StatusDot';
import {
TechnicalDetailsDisclosure,
@@ -42,7 +45,6 @@ import {
import { useAlertsActivation } from '@/stores/alertsActivation';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
-import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { formatTemperature } from '@/utils/temperature';
import { useStoragePoolDetailModel } from './useStoragePoolDetailModel';
@@ -188,9 +190,7 @@ export const StoragePoolDetail: Component<StoragePoolDetailProps> = (props) => {
}))}
/>
<Show when={(props.alerts ?? []).length === 0}>
- <p data-testid="drawer-no-attention" class="text-xs font-medium text-base-content">
- {ALERTS_EMPTY_STATE}
- </p>
+ <DrawerNoAlertsLine />
</Show>
<DrawerExceptionList testId="storage-pool-drawer-exceptions" rows={exceptionRows()} />
diff --git a/frontend-modern/src/components/Storage/StoragePoolsTable.tsx b/frontend-modern/src/components/Storage/StoragePoolsTable.tsx
index 7877d58afb..0057628e44 100644
--- a/frontend-modern/src/components/Storage/StoragePoolsTable.tsx
+++ b/frontend-modern/src/components/Storage/StoragePoolsTable.tsx
@@ -1,4 +1,4 @@
-import { Component, For, Show, createMemo } from 'solid-js';
+import { Component, For, Show, createMemo, createSignal } from 'solid-js';
import {
Table,
TableBody,
@@ -22,6 +22,7 @@ import {
isStoragePoolColumnVisible,
} from '@/features/storageBackups/storagePagePresentation';
import { useObservedElementWidth } from '@/hooks/useObservedElementWidth';
+import { createVisibleTableColumnSpan } from '@/components/shared/tableVisibleColumnSpan';
import { resolveStorageRecordMetricResourceId } from '@/features/storageBackups/storageMetricsIdentity';
import type { StorageCapacityDeltaPresentation } from '@/features/storageBackups/storageCapacityDeltaPresentation';
import type { StorageAlertRowState } from '@/features/storageBackups/storageAlertState';
@@ -81,6 +82,9 @@ export const StoragePoolsTable: Component<StoragePoolsTableProps> = (props) => {
groups: model.groups,
expandedPoolId: () => props.expandedPoolId,
});
+ // Spacer rows span the visible columns only (see tableVisibleColumnSpan).
+ const [bodyEl, setBodyEl] = createSignal<HTMLTableSectionElement | null>(null);
+ const columnSpan = createVisibleTableColumnSpan(bodyEl);
return (
<Show
@@ -134,10 +138,16 @@ export const StoragePoolsTable: Component<StoragePoolsTableProps> = (props) => {
</For>
</TableRow>
</TableHeader>
- <TableBody ref={tableWindow.setBodyRef} class={STORAGE_POOLS_BODY_CLASS}>
+ <TableBody
+ ref={(body) => {
+ tableWindow.setBodyRef(body);
+ setBodyEl(body);
+ }}
+ class={STORAGE_POOLS_BODY_CLASS}
+ >
<Show when={tableWindow.topSpacerHeight() > 0}>
<TableRow aria-hidden="true" class="h-0 border-0!">
- <TableCell colspan={99} class="h-0 border-0! p-0! leading-0">
+ <TableCell colspan={columnSpan()} class="h-0 border-0! p-0! leading-0">
<svg
aria-hidden="true"
width="1"
@@ -187,7 +197,7 @@ export const StoragePoolsTable: Component<StoragePoolsTableProps> = (props) => {
</For>
<Show when={tableWindow.bottomSpacerHeight() > 0}>
<TableRow aria-hidden="true" class="h-0 border-0!">
- <TableCell colspan={99} class="h-0 border-0! p-0! leading-0">
+ <TableCell colspan={columnSpan()} class="h-0 border-0! p-0! leading-0">
<svg
aria-hidden="true"
width="1"
diff --git a/frontend-modern/src/components/Storage/__tests__/DiskDetail.history-collection.test.tsx b/frontend-modern/src/components/Storage/__tests__/DiskDetail.history-collection.test.tsx
deleted file mode 100644
index 63e7b64981..0000000000
--- a/frontend-modern/src/components/Storage/__tests__/DiskDetail.history-collection.test.tsx
+++ /dev/null
@@ -1,265 +0,0 @@
-import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
-import { createSignal } from 'solid-js';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- ChartsAPI,
- type MetricsHistoryParams,
- type SingleMetricHistoryResponse,
-} from '@/api/charts';
-import { DiskDetail } from '../DiskDetail';
-import type { Resource } from '@/types/resource';
-
-vi.mock('@/api/charts', () => ({ ChartsAPI: { getMetricsHistory: vi.fn() } }));
-vi.mock('@/stores/license', () => ({
- isRangeLocked: () => false,
- loadRuntimeCapabilities: vi.fn(),
- maxHistoryDays: () => 7,
-}));
-vi.mock('@/stores/alertsActivation', () => ({
- useAlertsActivation: () => ({ getDiskTemperatureThresholds: () => null }),
-}));
-const request = vi.mocked(ChartsAPI.getMetricsHistory);
-const context = {
- clearRect: vi.fn(),
- setTransform: vi.fn(),
- beginPath: vi.fn(),
- moveTo: vi.fn(),
- lineTo: vi.fn(),
- stroke: vi.fn(),
- fillText: vi.fn(),
- closePath: vi.fn(),
- fill: vi.fn(),
- arc: vi.fn(),
- save: vi.fn(),
- restore: vi.fn(),
- setLineDash: vi.fn(),
- measureText: () => ({ width: 20 }),
-};
-const disk = (missing = false, nvme = false): Resource => ({
- id: 'disk-a',
- type: 'physical_disk',
- name: 'Archive disk',
- displayName: 'Archive disk',
- platformId: 'nas-a',
- platformType: 'truenas',
- sourceType: 'api',
- status: 'online',
- lastSeen: 1000,
- identity: { hostname: 'nas-a' },
- metricsTarget: { resourceType: 'disk', resourceId: 'disk:nas-a:sda' },
- physicalDisk: {
- devPath: nvme ? '/dev/nvme0n1' : '/dev/sda',
- model: nvme ? 'NVMe' : 'Archive HDD',
- serial: 'SERIAL-A',
- diskType: nvme ? 'nvme' : 'hdd',
- temperature: missing ? undefined : 42,
- smart: missing
- ? undefined
- : nvme
- ? { percentageUsed: 12, availableSpare: 97 }
- : { reallocatedSectors: 0 },
- collection: {
- temperature: {
- state: missing ? 'unavailable' : 'available',
- reason: missing ? 'collection deadline exceeded' : undefined,
- },
- io: { state: 'unsupported', reason: 'per-member counters unavailable' },
- },
- },
-});
-const response = (
- params: MetricsHistoryParams,
- value = params.metric === 'smart_temp' ? 42 : 0,
-): SingleMetricHistoryResponse => ({
- resourceType: params.resourceType,
- resourceId: params.resourceId,
- metric: params.metric!,
- range: params.range!,
- start: 1000,
- end: 2000,
- source: 'store',
- points: [{ timestamp: 1000, value, min: value, max: value }],
-});
-const description = (canvas: HTMLElement) =>
- document.getElementById(canvas.getAttribute('aria-describedby')!)!;
-// History charts sit in the disk detail's single view; nothing to open.
-const openHistory = () => undefined;
-
-beforeEach(() => {
- request.mockReset().mockImplementation(async (params) => response(params));
- vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
- context as unknown as CanvasRenderingContext2D,
- );
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- disconnect() {}
- },
- );
-});
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-describe('Disk History independently of current collection', () => {
- it('loads stored ATA readings when current temperature and SMART are unavailable', async () => {
- render(() => <DiskDetail disk={disk(true)} nodes={[]} />);
- expect(screen.getByText(/Temperature is temporarily unavailable/)).toBeInTheDocument();
- openHistory();
- await waitFor(() =>
- expect(screen.getByRole('img', { name: 'Temperature chart' })).toBeInTheDocument(),
- );
- const thermal = screen.getByRole('img', { name: 'Temperature chart' });
- await waitFor(() => expect(description(thermal)).toHaveTextContent('42°C'));
- expect(
- description(screen.getByRole('img', { name: 'Reallocated Sectors chart' })),
- ).toHaveTextContent('0 sectors');
- expect(
- request.mock.calls.every(
- ([params]) => params.resourceType === 'disk' && params.resourceId === 'disk:nas-a:sda',
- ),
- ).toBe(true);
- expect(request.mock.calls.map(([params]) => params.metric)).not.toContain('diskread');
- expect(screen.queryByText('Live I/O (30m)')).not.toBeInTheDocument();
- });
-
- it('loads stored NVMe temperature and endurance without current SMART fields', async () => {
- render(() => <DiskDetail disk={disk(true, true)} nodes={[]} />);
- openHistory();
- await waitFor(() => expect(screen.getAllByRole('img')).toHaveLength(3));
- expect(screen.getByRole('img', { name: 'Life Used chart' })).toBeInTheDocument();
- expect(screen.getByRole('img', { name: 'Available Spare chart' })).toBeInTheDocument();
- expect(
- screen.queryByRole('img', { name: 'Reallocated Sectors chart' }),
- ).not.toBeInTheDocument();
- await waitFor(() =>
- expect(description(screen.getByRole('img', { name: 'Temperature chart' }))).toHaveTextContent(
- '42°C',
- ),
- );
- });
-
- it('preserves mounted charts and inspection without extra reads on matching snapshots', async () => {
- const [snapshot, setSnapshot] = createSignal(disk());
- render(() => <DiskDetail disk={snapshot()} nodes={[]} />);
- openHistory();
- fireEvent.change(screen.getByRole('combobox', { name: 'Disk history range' }), {
- target: { value: '7d' },
- });
- const thermal = screen.getByRole('img', { name: 'Temperature chart' });
- await waitFor(() => expect(description(thermal)).toHaveTextContent('42°C'));
- fireEvent.focus(thermal);
- expect(document.querySelector('[data-history-chart-tooltip]')).toHaveTextContent('42°C');
- const reads = request.mock.calls.length;
- setSnapshot({ ...disk(), physicalDisk: { ...disk().physicalDisk!, temperature: 65 } });
- expect(screen.getByRole('img', { name: 'Temperature chart' })).toBe(thermal);
- expect(document.querySelector('[data-history-chart-tooltip]')).toHaveTextContent('42°C');
- expect(screen.getByRole('combobox', { name: 'Disk history range' })).toHaveValue('7d');
- expect(request).toHaveBeenCalledTimes(reads);
- });
-
- it('keeps stored observations mounted after current fields disappear', async () => {
- const [snapshot, setSnapshot] = createSignal(disk());
- render(() => <DiskDetail disk={snapshot()} nodes={[]} />);
- openHistory();
- const thermal = screen.getByRole('img', { name: 'Temperature chart' });
- await waitFor(() => expect(description(thermal)).toHaveTextContent('42°C'));
- const reads = request.mock.calls.length;
- setSnapshot(disk(true));
- expect(screen.getByRole('img', { name: 'Temperature chart' })).toBe(thermal);
- expect(description(thermal)).toHaveTextContent('42°C');
- expect(screen.getByRole('img', { name: 'Reallocated Sectors chart' })).toBeInTheDocument();
- expect(request).toHaveBeenCalledTimes(reads);
- // The SMART cards share the view with the charts: the current reading is
- // withdrawn there while the stored observation stays on the chart.
- expect(screen.getByText(/Temperature is temporarily unavailable/)).toBeVisible();
- // 42°C survives only as the chart's stored reading, never as a current card.
- for (const reading of screen.getAllByText('42°C')) {
- expect(reading.closest('[data-testid="disk-detail-history"]')).not.toBeNull();
- }
- });
-
- it('ignores an old target completion and uses only the explicit new disk target', async () => {
- const pending: {
- params: MetricsHistoryParams;
- resolve: (value: SingleMetricHistoryResponse) => void;
- }[] = [];
- request.mockImplementation(
- (params) => new Promise((resolve) => pending.push({ params, resolve })),
- );
- const [snapshot, setSnapshot] = createSignal(disk());
- render(() => <DiskDetail disk={snapshot()} nodes={[]} />);
- openHistory();
- await waitFor(() =>
- expect(
- pending.filter(({ params }) => params.resourceId === 'disk:nas-a:sda').length,
- ).toBeGreaterThan(0),
- );
- setSnapshot({
- ...disk(),
- metricsTarget: { resourceType: 'disk', resourceId: 'disk:nas-b:sda' },
- });
- await waitFor(() =>
- expect(
- pending.filter(({ params }) => params.resourceId === 'disk:nas-b:sda').length,
- ).toBeGreaterThan(0),
- );
- for (const item of pending.filter(({ params }) => params.resourceId === 'disk:nas-b:sda'))
- item.resolve(response(item.params, 55));
- await waitFor(() =>
- expect(description(screen.getByRole('img', { name: 'Temperature chart' }))).toHaveTextContent(
- '55°C',
- ),
- );
- for (const item of pending.filter(({ params }) => params.resourceId === 'disk:nas-a:sda')) {
- expect(item.params.signal?.aborted).toBe(true);
- item.resolve(response(item.params, 99));
- }
- await Promise.resolve();
- expect(description(screen.getByRole('img', { name: 'Temperature chart' }))).toHaveTextContent(
- '55°C',
- );
- expect(
- description(screen.getByRole('img', { name: 'Temperature chart' })),
- ).not.toHaveTextContent('99°C');
- });
-
- it('distinguishes empty stored series from measured zero with no live fallback', async () => {
- request.mockImplementation(async (params) => ({
- ...response(params),
- points: params.metric === 'smart_temp' ? [] : response(params, 0).points,
- }));
- render(() => <DiskDetail disk={disk(true)} nodes={[]} />);
- openHistory();
- await waitFor(() =>
- expect(screen.getByText('No history samples in this time range.')).toBeInTheDocument(),
- );
- expect(
- description(screen.getByRole('img', { name: 'Temperature chart' })),
- ).not.toHaveTextContent('0°C');
- await waitFor(() =>
- expect(
- description(screen.getByRole('img', { name: 'Reallocated Sectors chart' })),
- ).toHaveTextContent('0 sectors'),
- );
- });
-
- it('makes no history request without a resolvable disk identity', () => {
- render(() => (
- <DiskDetail
- disk={{
- ...disk(true),
- id: '',
- metricsTarget: undefined,
- physicalDisk: { ...disk(true).physicalDisk!, serial: '', wwn: '' },
- }}
- nodes={[]}
- />
- ));
- expect(screen.getByText(/Historical disk charts are unavailable/)).toBeInTheDocument();
- expect(request).not.toHaveBeenCalled();
- });
-});
diff --git a/frontend-modern/src/components/Storage/__tests__/DiskDetail.test.tsx b/frontend-modern/src/components/Storage/__tests__/DiskDetail.test.tsx
deleted file mode 100644
index 9f260918bd..0000000000
--- a/frontend-modern/src/components/Storage/__tests__/DiskDetail.test.tsx
+++ /dev/null
@@ -1,278 +0,0 @@
-import { fireEvent, render, screen, within } from '@solidjs/testing-library';
-import { createSignal, type JSX } from 'solid-js';
-import { describe, expect, it, vi } from 'vitest';
-import { DiskDetail } from '@/components/Storage/DiskDetail';
-import type { Resource } from '@/types/resource';
-
-vi.mock('@/components/shared/HistoryChart', () => ({
- HistoryChartHoverGroup: (props: { children: JSX.Element }) => (
- <div data-testid="history-chart-hover-group">{props.children}</div>
- ),
- HistoryChart: (props: {
- resourceType: string;
- resourceId: string;
- metric: string;
- range?: string;
- enabled?: boolean;
- }) => (
- <div data-testid="history-chart" data-enabled={String(props.enabled !== false)}>
- {props.resourceType}:{props.resourceId}:{props.metric}:{props.range}
- </div>
- ),
-}));
-
-const buildDisk = (): Resource =>
- ({
- id: 'disk-1',
- type: 'physical_disk',
- name: 'disk-1',
- displayName: 'Archive HDD',
- platformId: 'cluster-main',
- platformType: 'proxmox-pve',
- sourceType: 'api',
- status: 'online',
- lastSeen: Date.now(),
- metricsTarget: { resourceType: 'disk', resourceId: 'agent-tower:sda' },
- identity: { hostname: 'tower' },
- canonicalIdentity: { hostname: 'tower' },
- platformData: {
- proxmox: { nodeName: 'tower', instance: 'cluster-main' },
- },
- physicalDisk: {
- devPath: '/dev/sda',
- model: 'Archive HDD',
- serial: 'SERIAL-1',
- diskType: 'hdd',
- temperature: 42,
- smart: {
- powerOnHours: 100,
- reallocatedSectors: 0,
- },
- },
- }) as unknown as Resource;
-
-const atPhoneWidth = (run: () => void) => {
- const width = window.innerWidth;
- Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 390 });
- try {
- run();
- } finally {
- Object.defineProperty(window, 'innerWidth', {
- configurable: true,
- writable: true,
- value: width,
- });
- }
-};
-// metric -> [reads, folded on a phone]
-const chartStates = (): Record<string, [string | undefined, string]> =>
- Object.fromEntries(
- screen
- .getAllByTestId('history-chart')
- .map((chart) => [
- chart.textContent!.split(':').at(-2),
- [
- chart.dataset.enabled,
- chart.closest('[data-phone-collapsed="true"]') ? 'folded' : 'shown',
- ],
- ]),
- );
-
-describe('DiskDetail', () => {
- it('shows the first chart on a phone and folds the rest behind one button that stops their reads', () => {
- atPhoneWidth(() => {
- render(() => <DiskDetail disk={buildDisk()} nodes={[]} />);
- expect(chartStates()).toEqual({
- smart_temp: ['true', 'shown'],
- smart_reallocated_sectors: ['false', 'folded'],
- diskread: ['false', 'folded'],
- diskwrite: ['false', 'folded'],
- disk: ['false', 'folded'],
- });
- const toggle = screen.getByTestId('disk-detail-phone-toggle');
- expect(toggle).toHaveTextContent('Show Reallocated Sectors, Read, Write, Busy');
- expect(toggle).toHaveAttribute('aria-expanded', 'false');
- expect(document.getElementById(toggle.getAttribute('aria-controls')!)).not.toBeNull();
- fireEvent.click(toggle);
- expect(new Set(Object.values(chartStates()).map(([reads]) => reads))).toEqual(
- new Set(['true']),
- );
- expect(document.querySelectorAll('[data-phone-collapsed="true"]')).toHaveLength(0);
- expect(toggle).toHaveTextContent('Show fewer charts');
- expect(toggle).toHaveAttribute('aria-expanded', 'true');
- });
- });
-
- it('keeps a chart whose SMART card is out of bounds on a phone', () => {
- const disk = buildDisk();
- (disk.physicalDisk as { smart: { reallocatedSectors: number } }).smart.reallocatedSectors = 8;
- atPhoneWidth(() => {
- render(() => <DiskDetail disk={disk} nodes={[]} />);
- expect(chartStates().smart_reallocated_sectors).toEqual(['true', 'shown']);
- expect(screen.getByTestId('disk-detail-phone-toggle')).toHaveTextContent(
- 'Show Read, Write, Busy',
- );
- });
- });
-
- it('reads every chart on a wider screen, where the fold does not apply', () => {
- render(() => <DiskDetail disk={buildDisk()} nodes={[]} />);
- expect(new Set(Object.values(chartStates()).map(([reads]) => reads))).toEqual(
- new Set(['true']),
- );
- });
-
- it('pauses every disk chart when its holder is hidden', () => {
- const [shown, setShown] = createSignal(true);
- render(() => <DiskDetail disk={buildDisk()} nodes={[]} historyEnabled={shown()} />);
- const states = () => screen.getAllByTestId('history-chart').map((c) => c.dataset.enabled);
- expect(states().length).toBeGreaterThan(0);
- expect(new Set(states())).toEqual(new Set(['true']));
- setShown(false);
- expect(new Set(states())).toEqual(new Set(['false']));
- });
-
- it('keeps disk detail range choices inside the current history entitlement', () => {
- render(() => <DiskDetail disk={buildDisk()} nodes={[]} />);
-
- // One view: no tab strip, the range picker sits beside the history charts.
- expect(screen.queryByRole('tab')).not.toBeInTheDocument();
-
- const rangeSelector = screen.getByRole('combobox', {
- name: 'Disk history range',
- }) as HTMLSelectElement;
-
- expect(Array.from(rangeSelector.options).map((option) => option.value)).toEqual([
- '1h',
- '6h',
- '12h',
- '24h',
- '7d',
- ]);
- // The same option names as every other history range picker.
- expect(Array.from(rangeSelector.options).map((option) => option.textContent)).toEqual([
- '1 hour',
- '6 hours',
- '12 hours',
- '24 hours',
- '7 days',
- ]);
- expect(Array.from(rangeSelector.options).map((option) => option.value)).not.toContain('14d');
- expect(Array.from(rangeSelector.options).map((option) => option.value)).not.toContain('90d');
- expect(screen.getAllByTestId('history-chart-hover-group')).toHaveLength(2);
- });
-
- it('shows explicit collection status and does not render misleading live I/O', () => {
- const disk = buildDisk();
- disk.physicalDisk!.collection = {
- serial: { state: 'available', source: 'smartctl' },
- temperature: {
- state: 'unavailable',
- source: 'smartctl',
- reason: 'collection deadline exceeded',
- },
- io: {
- state: 'unsupported',
- source: 'controller',
- reason: 'per-member counters unavailable',
- },
- controller: { state: 'available', source: 'linux-sysfs' },
- pool: { state: 'available', source: 'zpool-status' },
- };
-
- render(() => <DiskDetail disk={disk} nodes={[]} />);
-
- expect(
- screen.getByText('Temperature is temporarily unavailable: collection deadline exceeded'),
- ).toBeInTheDocument();
- // The retained value sits under its own label with no health tone.
- expect(screen.queryByText('Temperature')).not.toBeInTheDocument();
- expect(screen.getByText('Last known temperature')).toBeInTheDocument();
- expect(screen.getByText('42°C')).toHaveClass('text-muted');
- expect(
- screen.getByText('Disk I/O is unsupported: per-member counters unavailable'),
- ).toBeInTheDocument();
- expect(screen.queryByText('Live I/O (30m)')).not.toBeInTheDocument();
- expect(screen.queryByText(/:diskread:/)).not.toBeInTheDocument();
- expect(screen.queryByText(/:diskwrite:/)).not.toBeInTheDocument();
- });
-
- it('keeps standalone temperature readings visible through snapshot replacement', () => {
- const initial = buildDisk();
- delete initial.physicalDisk!.smart;
- const [disk, setDisk] = createSignal(initial);
- render(() => <DiskDetail disk={disk()} nodes={[]} />);
-
- expect(screen.getByText('42°C')).toBeInTheDocument();
- expect(screen.queryByText('Power-On Time')).not.toBeInTheDocument();
- expect(
- screen.queryByText('Detailed SMART attributes are not available for this disk.'),
- ).not.toBeInTheDocument();
-
- setDisk({ ...initial, physicalDisk: { ...initial.physicalDisk!, temperature: 65 } });
- expect(screen.getByText('65°C')).toHaveClass('text-red-600');
- expect(screen.queryByText('42°C')).not.toBeInTheDocument();
-
- setDisk({ ...initial, physicalDisk: { ...initial.physicalDisk!, temperature: 0 } });
- expect(screen.queryByText('Temperature')).not.toBeInTheDocument();
- expect(
- screen.getByText('Detailed SMART attributes are not available for this disk.'),
- ).toHaveAttribute('role', 'status');
-
- setDisk(buildDisk());
- expect(screen.getByText('42°C')).toBeInTheDocument();
- expect(screen.getByText('Power-On Time')).toBeInTheDocument();
- expect(screen.getByText('Reallocated Sectors')).toBeInTheDocument();
- });
-
- it('shows the health verdict and its reason in the drawer header', () => {
- const disk = buildDisk();
- disk.physicalDisk!.health = 'FAILED';
-
- render(() => <DiskDetail disk={disk} nodes={[]} />);
-
- const health = screen.getByTestId('disk-detail-health');
- expect(within(health).getByText('Replace Now')).toHaveClass('text-red-700');
- expect(within(health).getByText('Disk health has degraded to a critical state.')).toHaveClass(
- 'min-w-0',
- 'max-w-full',
- 'whitespace-normal',
- 'wrap-break-word',
- );
- });
-
- it('keeps the drawer header to the verdict alone when the disk is healthy', () => {
- const disk = buildDisk();
- disk.physicalDisk!.health = 'PASSED';
-
- render(() => <DiskDetail disk={disk} nodes={[]} />);
-
- const health = screen.getByTestId('disk-detail-health');
- expect(within(health).getByText('Healthy')).toBeInTheDocument();
- expect(within(health).queryByText('No active disk-health issues.')).not.toBeInTheDocument();
- });
-
- it('shows an explicit overview fallback when no detail readings are available', () => {
- const disk = buildDisk();
- delete disk.physicalDisk!.smart;
- delete disk.physicalDisk!.temperature;
-
- render(() => <DiskDetail disk={disk} nodes={[]} />);
-
- expect(
- screen.getByText('Detailed SMART attributes are not available for this disk.'),
- ).toHaveAttribute('role', 'status');
- });
-
- it('offers the stored disk-family catalog when current SMART and temperature disappear', () => {
- const disk = buildDisk();
- delete disk.physicalDisk!.temperature;
- delete disk.physicalDisk!.smart;
- disk.physicalDisk!.collection = { io: { state: 'unsupported' } };
- render(() => <DiskDetail disk={disk} nodes={[]} />);
- expect(screen.getAllByTestId('history-chart').map((chart) => chart.textContent)).toEqual([
- 'disk:agent-tower:sda:smart_temp:24h',
- 'disk:agent-tower:sda:smart_reallocated_sectors:24h',
- ]);
- });
-});
diff --git a/frontend-modern/src/components/Storage/__tests__/DiskDrawer.history-collection.test.tsx b/frontend-modern/src/components/Storage/__tests__/DiskDrawer.history-collection.test.tsx
new file mode 100644
index 0000000000..c3d243cb65
--- /dev/null
+++ b/frontend-modern/src/components/Storage/__tests__/DiskDrawer.history-collection.test.tsx
@@ -0,0 +1,335 @@
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ ChartsAPI,
+ type AggregatedMetricPoint,
+ type AllMetricsHistoryResponse,
+ type HistoryTimeRange,
+ type MetricsHistoryParams,
+} from '@/api/charts';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
+import type { Resource } from '@/types/resource';
+import { extractPhysicalDiskPresentationData } from '@/features/storageBackups/diskPresentation';
+import { DiskDrawer } from '../DiskDrawer';
+import { DiskDrawerOverview } from '../DiskDrawerOverview';
+
+// The disk drawer charts through the real drawer history owner; only the
+// history client, the plan limits and the alert thresholds are stubbed.
+vi.mock('@/api/charts', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/api/charts')>()),
+ ChartsAPI: { getMetricsHistory: vi.fn() },
+}));
+vi.mock('@/stores/license', () => ({
+ isRangeLocked: (range: HistoryTimeRange) => ['14d', '30d', '90d'].includes(range),
+ loadRuntimeCapabilities: vi.fn(async () => undefined),
+ maxHistoryDays: () => 7,
+}));
+vi.mock('@/stores/alertsActivation', () => ({
+ useAlertsActivation: () => ({ getDiskTemperatureThresholds: () => null }),
+}));
+vi.mock('@/components/Infrastructure/ResourceOperatorStateSection', () => ({
+ ResourceOperatorStateSection: () => <div data-testid="operator-state" />,
+}));
+
+const request = vi.mocked(ChartsAPI.getMetricsHistory);
+
+const OBSERVED_AT = 1_700_000_000_000;
+
+const disk = (missing = false, nvme = false): Resource => ({
+ id: 'disk-a',
+ type: 'physical_disk',
+ name: 'Archive disk',
+ displayName: 'Archive disk',
+ platformId: 'nas-a',
+ platformType: 'truenas',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1000,
+ identity: { hostname: 'nas-a' },
+ metricsTarget: { resourceType: 'disk', resourceId: 'disk:nas-a:sda' },
+ physicalDisk: {
+ devPath: nvme ? '/dev/nvme0n1' : '/dev/sda',
+ model: nvme ? 'NVMe' : 'Archive HDD',
+ serial: 'SERIAL-A',
+ diskType: nvme ? 'nvme' : 'hdd',
+ temperature: missing ? undefined : 42,
+ smart: missing
+ ? undefined
+ : nvme
+ ? { percentageUsed: 12, availableSpare: 97 }
+ : { reallocatedSectors: 0 },
+ collection: {
+ temperature: {
+ state: missing ? 'unavailable' : 'available',
+ reason: missing ? 'collection deadline exceeded' : undefined,
+ },
+ io: { state: 'unsupported', reason: 'per-member counters unavailable' },
+ },
+ },
+});
+
+const points = (value: number): AggregatedMetricPoint[] => [
+ { timestamp: OBSERVED_AT, value, min: value, max: value },
+ { timestamp: OBSERVED_AT + 60_000, value, min: value, max: value },
+];
+
+// The drawer reads every series of its one disk target in a single request.
+const response = (
+ params: MetricsHistoryParams,
+ temperature = 42,
+ metrics?: Record<string, AggregatedMetricPoint[]>,
+): AllMetricsHistoryResponse => ({
+ resourceType: params.resourceType,
+ resourceId: params.resourceId,
+ range: params.range!,
+ start: OBSERVED_AT - 60_000,
+ end: OBSERVED_AT + 120_000,
+ source: 'store',
+ metrics: metrics ?? {
+ smart_temp: points(temperature),
+ smart_reallocated_sectors: points(0),
+ smart_percentage_used: points(12),
+ smart_available_spare: points(97),
+ },
+});
+
+const chart = (label: string) => screen.getByRole('img', { name: `${label} history` });
+const chartLabels = () =>
+ screen.queryAllByTestId('guest-history-plot').map((plot) => plot.getAttribute('aria-label'));
+// The legend reading beside a series label, e.g. "Disk 42°C".
+const legendValue = (label: string, series: string) =>
+ within(panel(label)).getByText(series).nextElementSibling?.textContent;
+const description = (plot: Element) =>
+ plot
+ .getAttribute('aria-describedby')!
+ .split(' ')
+ .map((id) => document.getElementById(id)?.textContent ?? '')
+ .join(' ');
+const panel = (label: string) =>
+ chart(label).closest<HTMLElement>('[data-testid="guest-history-group-chart"]')!;
+const renderDrawer = (snapshot: () => Resource) =>
+ render(() => <DiskDrawer disk={snapshot()} onClose={() => {}} />);
+
+beforeEach(() => {
+ request.mockReset().mockImplementation(async (params) => response(params));
+});
+
+afterEach(() => {
+ cleanup();
+ resetCreateNonSuspendingQueryCacheForTest();
+});
+
+describe('Disk drawer History independently of current collection', () => {
+ it('loads stored ATA readings when current temperature and SMART are unavailable', async () => {
+ renderDrawer(() => disk(true));
+ expect(screen.getByTestId('disk-drawer-notices')).toHaveTextContent(
+ 'Temperature is temporarily unavailable: collection deadline exceeded',
+ );
+ await waitFor(() => expect(description(chart('Temperature'))).toContain('Disk 42°C'));
+ expect(description(chart('Reallocated sectors'))).toContain('Reallocated 0 sectors');
+ // The disk family picks the panels; unsupported I/O leaves its panels out.
+ expect(chartLabels()).toEqual(['Temperature history', 'Reallocated sectors history']);
+ expect(screen.queryByRole('img', { name: 'Disk I/O history' })).toBeNull();
+ expect(screen.queryByRole('img', { name: 'Busy history' })).toBeNull();
+ // Only the resolved canonical disk target is read.
+ expect(request.mock.calls.length).toBeGreaterThan(0);
+ for (const [params] of request.mock.calls) {
+ expect(params).toMatchObject({ resourceType: 'disk', resourceId: 'disk:nas-a:sda' });
+ }
+ });
+
+ it('loads stored NVMe temperature and endurance without current SMART fields', async () => {
+ renderDrawer(() => disk(true, true));
+ await waitFor(() => expect(description(chart('Temperature'))).toContain('Disk 42°C'));
+ expect(chartLabels()).toEqual(['Temperature history', 'Wear history']);
+ expect(description(chart('Wear'))).toContain('Life used 12.0%');
+ expect(description(chart('Wear'))).toContain('Spare 97.0%');
+ expect(screen.queryByRole('img', { name: 'Reallocated sectors history' })).toBeNull();
+ });
+
+ it('preserves mounted charts, range and inspection without extra reads on matching snapshots', async () => {
+ const [snapshot, setSnapshot] = createSignal(disk());
+ renderDrawer(snapshot);
+ const range = await screen.findByRole('combobox', { name: 'History range' });
+ fireEvent.change(range, { target: { value: '7d' } });
+ await waitFor(() =>
+ expect(request).toHaveBeenLastCalledWith(expect.objectContaining({ range: '7d' })),
+ );
+ const thermal = chart('Temperature');
+ await waitFor(() => expect(description(thermal)).toContain('Disk 42°C'));
+ // Inspect the older of the two stored observations.
+ const inspect = within(panel('Temperature')).getByRole('slider', {
+ name: 'Inspect Temperature history',
+ });
+ inspect.focus();
+ fireEvent.input(inspect, { target: { value: '0' } });
+ const inspected = description(thermal);
+ expect(inspected).toContain(new Date(OBSERVED_AT).toLocaleString());
+ const reads = request.mock.calls.length;
+
+ setSnapshot({ ...disk(), physicalDisk: { ...disk().physicalDisk!, temperature: 65 } });
+
+ expect(chart('Temperature')).toBe(thermal);
+ expect(document.activeElement).toBe(inspect);
+ expect(description(thermal)).toBe(inspected);
+ expect(screen.getByRole('combobox', { name: 'History range' })).toHaveValue('7d');
+ expect(screen.getByTestId('disk-drawer-health-card')).toHaveTextContent('65°C');
+ expect(request).toHaveBeenCalledTimes(reads);
+ });
+
+ it('drops inspection and reads again when the range or disk target changes', async () => {
+ const [snapshot, setSnapshot] = createSignal(disk());
+ renderDrawer(snapshot);
+ const thermal = await screen.findByRole('img', { name: 'Temperature history' });
+ await waitFor(() => expect(description(thermal)).toContain('2 stored observation times'));
+ const inspect = () =>
+ within(panel('Temperature')).getByRole('slider', { name: 'Inspect Temperature history' });
+ const inspectOldest = () => {
+ inspect().focus();
+ fireEvent.input(inspect(), { target: { value: '0' } });
+ expect(description(chart('Temperature'))).not.toContain('stored observation times');
+ };
+
+ inspectOldest();
+ let reads = request.mock.calls.length;
+ fireEvent.change(screen.getByRole('combobox', { name: 'History range' }), {
+ target: { value: '6h' },
+ });
+ await waitFor(() => expect(request).toHaveBeenCalledTimes(reads + 1));
+ expect(request).toHaveBeenLastCalledWith(
+ expect.objectContaining({ resourceId: 'disk:nas-a:sda', range: '6h' }),
+ );
+ await waitFor(() =>
+ expect(description(chart('Temperature'))).toContain('2 stored observation times'),
+ );
+
+ inspectOldest();
+ reads = request.mock.calls.length;
+ setSnapshot({
+ ...disk(),
+ metricsTarget: { resourceType: 'disk', resourceId: 'disk:nas-b:sda' },
+ });
+ await waitFor(() => expect(request).toHaveBeenCalledTimes(reads + 1));
+ expect(request).toHaveBeenLastCalledWith(
+ expect.objectContaining({ resourceId: 'disk:nas-b:sda', range: '6h' }),
+ );
+ await waitFor(() =>
+ expect(description(chart('Temperature'))).toContain('2 stored observation times'),
+ );
+ });
+
+ it('keeps stored observations mounted after current fields disappear', async () => {
+ const [snapshot, setSnapshot] = createSignal(disk());
+ renderDrawer(snapshot);
+ const thermal = await screen.findByRole('img', { name: 'Temperature history' });
+ await waitFor(() => expect(description(thermal)).toContain('Disk 42°C'));
+ const reads = request.mock.calls.length;
+
+ setSnapshot(disk(true));
+
+ expect(chart('Temperature')).toBe(thermal);
+ expect(description(thermal)).toContain('Disk 42°C');
+ expect(chart('Reallocated sectors')).toBeInTheDocument();
+ expect(request).toHaveBeenCalledTimes(reads);
+ // The current reading is withdrawn beside the charts, which keep the
+ // stored observation: 42°C survives only inside the history region.
+ expect(screen.getByTestId('disk-drawer-notices')).toHaveTextContent(
+ 'Temperature is temporarily unavailable',
+ );
+ expect(within(screen.getByTestId('disk-drawer-health-card')).queryByText(/°C/)).toBeNull();
+ const readings = screen.getAllByText('42°C');
+ expect(readings.length).toBeGreaterThan(0);
+ for (const reading of readings) {
+ expect(reading.closest('[data-testid="guest-history-region"]')).not.toBeNull();
+ }
+ });
+
+ it('ignores a former target completion and reads only the new disk target', async () => {
+ const pending: {
+ params: MetricsHistoryParams;
+ resolve: (value: AllMetricsHistoryResponse) => void;
+ }[] = [];
+ request.mockImplementation(
+ (params) => new Promise((resolve) => pending.push({ params, resolve })),
+ );
+ const [snapshot, setSnapshot] = createSignal(disk());
+ renderDrawer(snapshot);
+ const forTarget = (resourceId: string) =>
+ pending.filter(({ params }) => params.resourceId === resourceId);
+ await waitFor(() => expect(forTarget('disk:nas-a:sda').length).toBeGreaterThan(0));
+
+ setSnapshot({
+ ...disk(),
+ metricsTarget: { resourceType: 'disk', resourceId: 'disk:nas-b:sda' },
+ });
+ await waitFor(() => expect(forTarget('disk:nas-b:sda').length).toBeGreaterThan(0));
+ for (const item of forTarget('disk:nas-b:sda')) item.resolve(response(item.params, 55));
+ await waitFor(() => expect(description(chart('Temperature'))).toContain('Disk 55°C'));
+
+ for (const item of forTarget('disk:nas-a:sda')) {
+ expect(item.params.signal?.aborted).toBe(true);
+ item.resolve(response(item.params, 99));
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(description(chart('Temperature'))).toContain('Disk 55°C');
+ expect(description(chart('Temperature'))).not.toContain('99°C');
+ });
+
+ it('keeps an empty stored series apart from a measured zero', async () => {
+ request.mockImplementation(async (params) =>
+ response(params, 42, { smart_temp: [], smart_reallocated_sectors: points(0) }),
+ );
+ renderDrawer(() => disk(true));
+ await waitFor(() =>
+ expect(description(chart('Reallocated sectors'))).toContain('Reallocated 0 sectors'),
+ );
+ const thermal = panel('Temperature');
+ expect(within(thermal).getByText('No stored history in this range')).toBeInTheDocument();
+ expect(description(chart('Temperature'))).toContain('No stored history observations.');
+ expect(description(chart('Temperature'))).not.toContain('0°C');
+ // No reading is drawn or quoted for the empty series.
+ expect(legendValue('Temperature', 'Disk')).toBe('-');
+ expect(thermal.querySelector('[data-history-series]')).toBeNull();
+ // The measured zero is drawn as stored history.
+ expect(panel('Reallocated sectors').querySelector('[data-history-series]')).not.toBeNull();
+ });
+
+ it('labels a snapshot reading as current while no history is stored, never as history', async () => {
+ request.mockImplementation(async (params) => response(params, 42, {}));
+ renderDrawer(() => disk());
+ const thermal = await screen.findByRole('img', { name: 'Temperature history' });
+ await waitFor(() =>
+ expect(
+ within(panel('Temperature')).getByText('No stored history in this range'),
+ ).toBeInTheDocument(),
+ );
+ expect(description(thermal)).toContain('No stored history observations.');
+ const current = panel('Temperature').querySelector('[data-history-current="smart_temp"]');
+ expect(current).toHaveTextContent('42°C');
+ expect(current).toHaveTextContent('current');
+ });
+
+ it('makes no history request without a resolvable disk identity', () => {
+ // The guest drawer mounts the Overview for disks it lists; a record with
+ // no target, serial, WWN or ID has nothing stable to read history for.
+ const anonymous: Resource = {
+ ...disk(true),
+ id: '',
+ metricsTarget: undefined,
+ physicalDisk: { ...disk(true).physicalDisk!, serial: '', wwn: '' },
+ };
+ render(() => (
+ <DiskDrawerOverview
+ disk={anonymous}
+ diskData={extractPhysicalDiskPresentationData(anonymous, () => null)}
+ />
+ ));
+ expect(screen.getByTestId('disk-drawer-history-unavailable')).toHaveTextContent(
+ 'History is unavailable until Pulse can resolve a stable identity for this disk.',
+ );
+ expect(chartLabels()).toEqual([]);
+ expect(request).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/components/Storage/__tests__/DiskDrawer.test.tsx b/frontend-modern/src/components/Storage/__tests__/DiskDrawer.test.tsx
index cb368541b7..286ba55248 100644
--- a/frontend-modern/src/components/Storage/__tests__/DiskDrawer.test.tsx
+++ b/frontend-modern/src/components/Storage/__tests__/DiskDrawer.test.tsx
@@ -216,6 +216,83 @@ describe('DiskDrawer', () => {
);
});
+ it('charts the stored disk-family catalog when current SMART and temperature disappear', async () => {
+ historySpy.mockClear();
+ const [disk, setDisk] = createSignal(buildDisk());
+ renderDrawer(disk);
+ const chart = await screen.findByTestId('drawer-history');
+ const groups = historySpy.mock.lastCall![0].groups;
+
+ // The disk's family, not its latest readings, picks the panels.
+ setDisk(
+ buildDisk({
+ smart: undefined,
+ temperature: undefined,
+ collection: { io: { state: 'unsupported' } },
+ }),
+ );
+ expect(screen.getByTestId('drawer-history')).toBe(chart);
+ expect(chart).toHaveTextContent('disk:agent-tower:sda');
+ expect(chart).toHaveAttribute('data-metrics', 'smart_temp,smart_reallocated_sectors');
+ // No current reading is invented for a missing field.
+ expect(historySpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ currentMetrics: {
+ smart_temp: undefined,
+ smart_reallocated_sectors: undefined,
+ smart_percentage_used: undefined,
+ smart_available_spare: undefined,
+ },
+ }),
+ );
+
+ // A matching snapshot keeps the very same panels, so no chart remounts.
+ setDisk(buildDisk({ temperature: 65 }));
+ expect(historySpy.mock.lastCall![0].groups).toBe(groups);
+ });
+
+ it('keeps a standalone temperature visible through same-disk snapshot replacement', () => {
+ const [disk, setDisk] = createSignal(buildDisk({ smart: undefined }));
+ renderDrawer(disk);
+ const drawer = screen.getByTestId('disk-drawer');
+ const card = () => screen.getByTestId('disk-drawer-health-card');
+
+ // Temperature only: shown without the extended SMART object, and no
+ // counters are invented for it.
+ expect(within(card()).getByText('Temperature')).toBeInTheDocument();
+ expect(within(card()).getByText('42°C')).toBeInTheDocument();
+ expect(screen.queryByTestId('disk-drawer-notices')).toBeNull();
+ expect(screen.queryByText('Power-On Time')).toBeNull();
+ expect(screen.queryByText('Reallocated Sectors')).toBeNull();
+ expect(screen.queryByTestId('disk-drawer-smart-attributes')).toBeNull();
+
+ // Hot: the new reading replaces the old one and the verdict says so.
+ setDisk(buildDisk({ smart: undefined, temperature: 65 }));
+ expect(within(card()).getByText('65°C')).toBeInTheDocument();
+ expect(screen.queryByText('42°C')).toBeNull();
+ expect(screen.getByLabelText('Running Hot')).toBeInTheDocument();
+ expect(screen.getByTestId('disk-drawer-exceptions')).toHaveTextContent('Running Hot');
+
+ // Missing: no temperature row, and the accessible unavailable message.
+ setDisk(buildDisk({ smart: undefined, temperature: 0 }));
+ expect(within(card()).queryByText('Temperature')).toBeNull();
+ expect(screen.queryByText(/°C/)).toBeNull();
+ expect(screen.getByTestId('disk-drawer-notices')).toHaveAttribute('role', 'status');
+ expect(screen.getByTestId('disk-drawer-notices')).toHaveTextContent(
+ 'Detailed SMART attributes are not available for this disk.',
+ );
+
+ // Extended SMART: the temperature returns beside the reported counters.
+ setDisk(buildDisk());
+ expect(within(card()).getByText('42°C')).toBeInTheDocument();
+ expect(screen.queryByTestId('disk-drawer-notices')).toBeNull();
+ const details = screen.getByTestId('disk-technical-details');
+ expect(within(details).getByText('Power-On Time')).toBeInTheDocument();
+ expect(within(details).getByText('Reallocated Sectors')).toBeInTheDocument();
+ // The same drawer stayed mounted throughout.
+ expect(screen.getByTestId('disk-drawer')).toBe(drawer);
+ });
+
it('states plainly when a disk reports no SMART detail at all', () => {
renderDrawer(() => buildDisk({ smart: undefined, temperature: undefined }));
expect(screen.getByTestId('disk-drawer-notices')).toHaveTextContent(
diff --git a/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.branchcov0712.test.ts b/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.branchcov0712.test.ts
deleted file mode 100644
index 8f153ccbef..0000000000
--- a/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.branchcov0712.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- getHistoryRangeDays,
- resolveHistoryRangeWithinLimit,
- type HistoryRangeOption,
-} from '@/components/Storage/historyRangeAccess';
-import type { HistoryTimeRange } from '@/api/charts';
-
-const options: readonly HistoryRangeOption[] = [
- { value: '30m', label: '30m' },
- { value: '24h', label: '24h' },
- { value: '7d', label: '7d' },
- { value: '14d', label: '14d' },
- { value: '30d', label: '30d' },
- { value: '90d', label: '90d' },
-];
-
-describe('getHistoryRangeDays (branch coverage)', () => {
- it('returns 0 when the range token does not match the <number><m|h|d> shape', () => {
- // Hits the `!match` early-return guard from several malformed shapes.
- expect(getHistoryRangeDays('' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('abc' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('12' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('7w' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('ms' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays(' 24h' as HistoryTimeRange)).toBe(0);
- });
-
- it('returns 0 when the numeric portion parses to a non-positive value', () => {
- // `0m` matches the regex, but parseInt yields 0 which trips `value <= 0`.
- expect(getHistoryRangeDays('0m' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('0h' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('0d' as HistoryTimeRange)).toBe(0);
- expect(getHistoryRangeDays('00d' as HistoryTimeRange)).toBe(0);
- });
-
- it('converts minutes to a fractional day value', () => {
- // `case 'm'` arm: value / (24 * 60).
- expect(getHistoryRangeDays('30m')).toBeCloseTo(1 / 48);
- expect(getHistoryRangeDays('1m' as HistoryTimeRange)).toBeCloseTo(1 / (24 * 60));
- expect(getHistoryRangeDays('60m' as HistoryTimeRange)).toBeCloseTo(1 / 24);
- });
-
- it('converts hours to a fractional day value', () => {
- // `case 'h'` arm: value / 24.
- expect(getHistoryRangeDays('24h')).toBe(1);
- expect(getHistoryRangeDays('12h' as HistoryTimeRange)).toBe(0.5);
- expect(getHistoryRangeDays('1h' as HistoryTimeRange)).toBeCloseTo(1 / 24);
- });
-
- it('passes through whole-day values unchanged', () => {
- // `case 'd'` arm: returns value verbatim.
- expect(getHistoryRangeDays('7d')).toBe(7);
- expect(getHistoryRangeDays('30d')).toBe(30);
- expect(getHistoryRangeDays('90d')).toBe(90);
- });
-});
-
-describe('resolveHistoryRangeWithinLimit (branch coverage)', () => {
- it('returns the current range verbatim when it is already inside the unlocked set', () => {
- // `available.some(...) === true` branch.
- // With max 7d, the available set is ['30m','24h','7d']; '7d' is a member.
- expect(resolveHistoryRangeWithinLimit('7d', options, 7)).toBe('7d');
- // A locked current range that still happens to be unlocked (e.g. 24h at 7d cap).
- expect(resolveHistoryRangeWithinLimit('24h', options, 7)).toBe('24h');
- });
-
- it('clamps down to the highest unlocked range when the current range is locked out', () => {
- // `available.some(...) === false` then `available.length > 0` branch.
- expect(resolveHistoryRangeWithinLimit('90d', options, 7)).toBe('7d');
- expect(resolveHistoryRangeWithinLimit('30d', options, 1)).toBe('24h');
- });
-
- it('falls back to the first option when no option is unlocked but options exist', () => {
- // `available.length === 0` then `options.length > 0` branch -> options[0].value.
- // maxHistoryDays 0 excludes every standard option (30m alone is ~0.0208 days).
- expect(resolveHistoryRangeWithinLimit('7d', options, 0)).toBe('30m');
- expect(resolveHistoryRangeWithinLimit('90d', options, 0)).toBe('30m');
- });
-
- it("falls back to '24h' when both available and options are empty", () => {
- // `available.length === 0` then `options.length === 0` branch -> literal '24h'.
- expect(resolveHistoryRangeWithinLimit('7d', [], 7)).toBe('24h');
- expect(resolveHistoryRangeWithinLimit('90d', [], 0)).toBe('24h');
- });
-
- it('clamps down to the last option when the available set is a strict subset', () => {
- // Distinct from the first clamp test: a middle current range ('14d') locked
- // out at max 1 day resolves to the highest unlocked ('24h'), exercising the
- // `available[available.length - 1].value` indexing with a multi-element set.
- expect(resolveHistoryRangeWithinLimit('14d', options, 1)).toBe('24h');
- });
-});
diff --git a/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.test.ts b/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.test.ts
deleted file mode 100644
index aac0db1ef8..0000000000
--- a/frontend-modern/src/components/Storage/__tests__/historyRangeAccess.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- getHistoryRangeDays,
- getUnlockedHistoryRangeOptions,
- resolveHistoryRangeWithinLimit,
- type HistoryRangeOption,
-} from '@/components/Storage/historyRangeAccess';
-
-const options: readonly HistoryRangeOption[] = [
- { value: '30m', label: '30m' },
- { value: '24h', label: '24h' },
- { value: '7d', label: '7d' },
- { value: '14d', label: '14d' },
- { value: '30d', label: '30d' },
- { value: '90d', label: '90d' },
-];
-
-describe('historyRangeAccess', () => {
- it('converts chart range tokens to day windows', () => {
- expect(getHistoryRangeDays('30m')).toBeCloseTo(1 / 48);
- expect(getHistoryRangeDays('24h')).toBe(1);
- expect(getHistoryRangeDays('14d')).toBe(14);
- });
-
- it('filters range options to the runtime history entitlement', () => {
- expect(getUnlockedHistoryRangeOptions(options, 7).map((option) => option.value)).toEqual([
- '30m',
- '24h',
- '7d',
- ]);
- expect(getUnlockedHistoryRangeOptions(options, 14).map((option) => option.value)).toEqual([
- '30m',
- '24h',
- '7d',
- '14d',
- ]);
- expect(getUnlockedHistoryRangeOptions(options, 90).map((option) => option.value)).toEqual([
- '30m',
- '24h',
- '7d',
- '14d',
- '30d',
- '90d',
- ]);
- });
-
- it('clamps a selected range down to the highest unlocked range', () => {
- expect(resolveHistoryRangeWithinLimit('90d', options, 7)).toBe('7d');
- expect(resolveHistoryRangeWithinLimit('90d', options, 14)).toBe('14d');
- expect(resolveHistoryRangeWithinLimit('90d', options, 90)).toBe('90d');
- });
-});
diff --git a/frontend-modern/src/components/Storage/__tests__/physicalDiskAlertOwner.test.ts b/frontend-modern/src/components/Storage/__tests__/physicalDiskAlertOwner.test.ts
index db84a6600c..b61d4d0344 100644
--- a/frontend-modern/src/components/Storage/__tests__/physicalDiskAlertOwner.test.ts
+++ b/frontend-modern/src/components/Storage/__tests__/physicalDiskAlertOwner.test.ts
@@ -113,5 +113,14 @@ describe('physical disk alert owner', () => {
it('lists nothing while alert detection is off', () => {
expect(getPhysicalDiskAlerts(agentDisk, owners, active, false)).toEqual([]);
});
+
+ it("takes a known reporting agent's temperature key without a loaded machine", () => {
+ // A guest drawer lists the guest's own disks: no agent machine is loaded
+ // there, but the guest names the agent that reports their temperatures.
+ const ids = getPhysicalDiskAlerts(agentDisk, new Map(), active, true, 'host-tower').map(
+ (alert) => alert.id,
+ );
+ expect(ids).toEqual(['pve', 'own', 'agent']);
+ });
});
});
diff --git a/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts b/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts
deleted file mode 100644
index fdf27e5f76..0000000000
--- a/frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { renderHook } from '@solidjs/testing-library';
-import { createSignal } from 'solid-js';
-import { describe, expect, it } from 'vitest';
-import type { Resource } from '@/types/resource';
-import { useDiskDetailModel } from '@/components/Storage/useDiskDetailModel';
-
-const buildDisk = (overrides: Partial<Resource> = {}): Resource =>
- ({
- id: 'disk-1',
- type: 'physical_disk',
- name: 'disk-1',
- displayName: 'disk-1',
- platformId: 'cluster-main',
- platformType: 'proxmox-pve',
- sourceType: 'api',
- status: 'online',
- lastSeen: Date.now(),
- metricsTarget: { resourceType: 'disk', resourceId: 'agent-tower:sda' },
- identity: { hostname: 'tower' },
- canonicalIdentity: { hostname: 'tower' },
- platformData: {
- proxmox: { nodeName: 'tower', instance: 'cluster-main' },
- },
- physicalDisk: {
- devPath: '/dev/sda',
- model: 'Archive HDD',
- serial: 'SERIAL-1',
- diskType: 'hdd',
- temperature: 42,
- smart: {
- powerOnHours: 100,
- reallocatedSectors: 0,
- },
- },
- ...overrides,
- }) as unknown as Resource;
-
-describe('useDiskDetailModel', () => {
- it('builds canonical disk detail model state', () => {
- const [disk] = createSignal(buildDisk());
-
- const { result } = renderHook(() =>
- useDiskDetailModel({
- disk,
- }),
- );
-
- expect(result.chartRange()).toBe('24h');
- expect(result.historyResourceId()).toBe('agent-tower:sda');
- expect(result.metricResourceId()).toBe('agent-tower:sda');
- expect(result.attributeCards().length).toBeGreaterThan(0);
- expect(result.historyCharts().map((chart) => chart.metric)).toEqual([
- 'smart_temp',
- 'smart_reallocated_sectors',
- ]);
- });
-
- it('keeps historical charts available for api-backed disks without serial or wwn when a canonical disk target exists', () => {
- const [disk] = createSignal(
- buildDisk({
- metricsTarget: { resourceType: 'disk', resourceId: 'disk:truenas-main:sda' },
- physicalDisk: {
- devPath: '/dev/sda',
- model: 'Seagate IronWolf',
- serial: '',
- wwn: '',
- diskType: 'hdd',
- temperature: 39,
- },
- } as Partial<Resource>),
- );
- const { result } = renderHook(() =>
- useDiskDetailModel({
- disk,
- }),
- );
-
- expect(result.historyResourceId()).toBe('disk:truenas-main:sda');
- });
-
- it('disables live I/O only when the collector explicitly reports it unavailable', () => {
- const [disk] = createSignal(
- buildDisk({
- physicalDisk: {
- devPath: '/dev/sda',
- model: 'SAS archive disk',
- serial: 'ZR5TESTA0001',
- diskType: 'sas',
- temperature: 30,
- collection: {
- serial: { state: 'available', source: 'smartctl' },
- temperature: { state: 'available', source: 'smartctl' },
- io: {
- state: 'unsupported',
- source: 'controller',
- reason: 'per-member counters unavailable',
- },
- controller: { state: 'available', source: 'linux-sysfs' },
- pool: { state: 'available', source: 'zpool-status' },
- },
- },
- } as Partial<Resource>),
- );
- const { result } = renderHook(() => useDiskDetailModel({ disk }));
-
- expect(result.liveIOAvailable()).toBe(false);
- expect(result.collectionMessages()).toEqual([
- 'Disk I/O is unsupported: per-member counters unavailable',
- ]);
- });
-
- it('keeps catalog entries stable across matching current-field snapshots', () => {
- const initial = buildDisk();
- const [disk, setDisk] = createSignal(initial);
- const { result } = renderHook(() => useDiskDetailModel({ disk }));
- const charts = result.historyCharts();
- setDisk({ ...initial, physicalDisk: { ...initial.physicalDisk!, temperature: 65 } });
- expect(result.historyCharts()).toBe(charts);
- setDisk({
- ...initial,
- physicalDisk: { ...initial.physicalDisk!, temperature: undefined, smart: undefined },
- });
- expect(result.historyCharts()).toBe(charts);
- expect(result.historyResourceId()).toBe('agent-tower:sda');
- expect(result.attributeCards()).toEqual([]);
- });
-});
diff --git a/frontend-modern/src/components/Storage/historyRangeAccess.ts b/frontend-modern/src/components/Storage/historyRangeAccess.ts
deleted file mode 100644
index 00f6e94c92..0000000000
--- a/frontend-modern/src/components/Storage/historyRangeAccess.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import type { HistoryTimeRange } from '@/api/charts';
-
-export type HistoryRangeOption = {
- value: HistoryTimeRange;
- label: string;
-};
-
-export function getHistoryRangeDays(range: HistoryTimeRange): number {
- const match = range.match(/^(\d+)(m|h|d)$/);
- if (!match) return 0;
-
- const value = Number.parseInt(match[1], 10);
- if (!Number.isFinite(value) || value <= 0) return 0;
-
- switch (match[2]) {
- case 'm':
- return value / (24 * 60);
- case 'h':
- return value / 24;
- case 'd':
- return value;
- default:
- return 0;
- }
-}
-
-export function getUnlockedHistoryRangeOptions<T extends HistoryRangeOption>(
- options: readonly T[],
- maxHistoryDays: number,
-): T[] {
- return options.filter((option) => getHistoryRangeDays(option.value) <= maxHistoryDays);
-}
-
-export function resolveHistoryRangeWithinLimit<T extends HistoryRangeOption>(
- currentRange: HistoryTimeRange,
- options: readonly T[],
- maxHistoryDays: number,
-): HistoryTimeRange {
- const available = getUnlockedHistoryRangeOptions(options, maxHistoryDays);
- if (available.some((option) => option.value === currentRange)) {
- return currentRange;
- }
-
- if (available.length > 0) {
- return available[available.length - 1].value;
- }
-
- return options.length > 0 ? options[0].value : '24h';
-}
diff --git a/frontend-modern/src/components/Storage/physicalDiskAlertOwner.ts b/frontend-modern/src/components/Storage/physicalDiskAlertOwner.ts
index 3b5a634230..0cdb4e6a20 100644
--- a/frontend-modern/src/components/Storage/physicalDiskAlertOwner.ts
+++ b/frontend-modern/src/components/Storage/physicalDiskAlertOwner.ts
@@ -103,14 +103,19 @@ const ALERT_LEVEL_RANK: Record<Alert['level'], number> = { critical: 0, warning:
export const getPhysicalDiskExtraAlertKeys = (
disk: Resource,
owners: ReadonlyMap<string, Resource>,
+ /** The reporting agent when the caller knows it (a guest's own agent). */
+ reportingAgentId?: string,
): string[] => {
const keys = new Set<string>(
(disk.canonicalIdentity?.aliases ?? [])
.map((alias) => alias.trim())
.filter((alias) => alias.includes(':disk:')),
);
- const machine = findPhysicalDiskReportingMachine(disk, owners);
- const agentId = machine ? getExplicitAgentIdFromResource(machine)?.trim() : '';
+ const machine = reportingAgentId?.trim()
+ ? undefined
+ : findPhysicalDiskReportingMachine(disk, owners);
+ const agentId =
+ reportingAgentId?.trim() || (machine ? getExplicitAgentIdFromResource(machine)?.trim() : '');
const devPath = disk.physicalDisk?.devPath?.trim() ?? '';
if (agentId && devPath) {
const prefix = `${agentId.startsWith('agent:') ? agentId : `agent:${agentId}`}/disk_temp:`;
@@ -133,10 +138,11 @@ export const getPhysicalDiskAlerts = (
owners: ReadonlyMap<string, Resource>,
activeAlerts: Record<string, Alert>,
alertsEnabled: boolean,
+ reportingAgentId?: string,
): Alert[] => {
if (!alertsEnabled) return [];
const own = getAlertsForUnifiedResource(disk, activeAlerts, alertsEnabled);
- const extraKeys = new Set(getPhysicalDiskExtraAlertKeys(disk, owners));
+ const extraKeys = new Set(getPhysicalDiskExtraAlertKeys(disk, owners, reportingAgentId));
const ownIds = new Set(own.map((alert) => alert.id));
const extra = Object.values(activeAlerts).filter(
(alert) => !ownIds.has(alert.id) && extraKeys.has(alert.resourceId),
diff --git a/frontend-modern/src/components/Storage/useDiskDetailModel.ts b/frontend-modern/src/components/Storage/useDiskDetailModel.ts
deleted file mode 100644
index b5b6560850..0000000000
--- a/frontend-modern/src/components/Storage/useDiskDetailModel.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { Accessor, createMemo, createSignal } from 'solid-js';
-import type { HistoryTimeRange } from '@/api/charts';
-import {
- getPhysicalDiskCollectionMessages,
- extractPhysicalDiskPresentationData,
- getPhysicalDiskTemperatureThresholds,
- type PhysicalDiskPresentationData,
-} from '@/features/storageBackups/diskPresentation';
-import {
- getDiskDetailAttributeCards,
- getDiskDetailHealthPresentation,
- getDiskDetailHistoryCharts,
-} from '@/features/storageBackups/diskDetailPresentation';
-import { useAlertsActivation } from '@/stores/alertsActivation';
-import type { Resource } from '@/types/resource';
-import { resolvePhysicalDiskHistoryResourceId } from './diskResourceUtils';
-
-type UseDiskDetailModelOptions = {
- disk: Accessor<Resource>;
- /** Alert override keys of the machine whose agent reports the disk. */
- alertResourceIds?: Accessor<string[] | undefined>;
-};
-
-export const useDiskDetailModel = (options: UseDiskDetailModelOptions) => {
- const [chartRange, setChartRange] = createSignal<HistoryTimeRange>('24h');
- const { getDiskTemperatureThresholds } = useAlertsActivation();
-
- const diskData = createMemo<PhysicalDiskPresentationData>(() =>
- extractPhysicalDiskPresentationData(
- options.disk(),
- getDiskTemperatureThresholds,
- options.alertResourceIds?.(),
- ),
- );
- const historyResourceId = createMemo(() => resolvePhysicalDiskHistoryResourceId(options.disk()));
- const attributeCards = createMemo(() =>
- getDiskDetailAttributeCards(diskData(), getPhysicalDiskTemperatureThresholds(diskData())),
- );
- const historyCharts = createMemo(() => getDiskDetailHistoryCharts(diskData()));
- const healthPresentation = createMemo(() => getDiskDetailHealthPresentation(diskData()));
- const metricResourceId = createMemo(() => historyResourceId());
- const collectionMessages = createMemo(() => getPhysicalDiskCollectionMessages(diskData()));
- const liveIOAvailable = createMemo(() => {
- const state = diskData().collection?.io?.state;
- return !state || state === 'available';
- });
-
- return {
- chartRange,
- setChartRange,
- diskData,
- historyResourceId,
- attributeCards,
- historyCharts,
- healthPresentation,
- metricResourceId,
- collectionMessages,
- liveIOAvailable,
- };
-};
diff --git a/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx b/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx
index 7439655c96..302b7b15c8 100644
--- a/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx
+++ b/frontend-modern/src/components/Workloads/GuestDrawerOverview.tsx
@@ -1,4 +1,3 @@
-import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { For, Show, Suspense, createMemo, lazy } from 'solid-js';
@@ -11,7 +10,10 @@ import {
TechnicalDetailsDisclosure,
TechnicalDetailsSection,
} from '@/components/shared/TechnicalDetailsDisclosure';
-import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
+import {
+ DrawerAttentionSection,
+ DrawerNoAlertsLine,
+} from '@/components/shared/DrawerAttentionSection';
import { DrawerExceptionList } from './DrawerExceptionList';
import type { Alert } from '@/types/api';
import { AvailabilityProbeStatusCards } from '@/components/Infrastructure/AvailabilityProbeStatusCard';
@@ -462,12 +464,7 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
}))}
/>
<Show when={(props.alerts ?? []).length === 0}>
- <p data-testid="drawer-no-attention" class="text-xs text-muted">
- <span class="font-medium text-base-content">{ALERTS_EMPTY_STATE}</span>
- <Show when={availabilityHealthy()}>
- <span> · availability checks passing</span>
- </Show>
- </p>
+ <DrawerNoAlertsLine availabilityPassing={availabilityHealthy()} />
</Show>
<DrawerExceptionList testId="guest-drawer-exceptions" rows={exceptionRows()} />
@@ -502,6 +499,7 @@ export function GuestDrawerOverview(props: GuestDrawerOverviewProps) {
<Suspense fallback={null}>
<GuestPhysicalDisks
parentId={props.guest.canonicalResourceId ?? props.guest.id}
+ reportingAgentId={props.guest.agentId}
alertResourceIds={[
...(props.guest.agentId ? [props.guest.agentId] : []),
...(props.guest.canonicalResourceId ? [props.guest.canonicalResourceId] : []),
diff --git a/frontend-modern/src/components/Workloads/GuestPhysicalDisks.tsx b/frontend-modern/src/components/Workloads/GuestPhysicalDisks.tsx
index f26fc9cb82..2358115dab 100644
--- a/frontend-modern/src/components/Workloads/GuestPhysicalDisks.tsx
+++ b/frontend-modern/src/components/Workloads/GuestPhysicalDisks.tsx
@@ -1,5 +1,8 @@
-import { For, Show, Suspense, createSignal, lazy, type Component } from 'solid-js';
+import { For, Show, Suspense, createMemo, createSignal, lazy, type Component } from 'solid-js';
+import type { HistoryTimeRange } from '@/api/charts';
+import { getPhysicalDiskAlerts } from '@/components/Storage/physicalDiskAlertOwner';
import { InfoCardFrame } from '@/components/shared/InfoCardFrame';
+import { useWebSocket } from '@/contexts/appRuntime';
import { useUnifiedResources } from '@/hooks/useUnifiedResources';
import {
extractPhysicalDiskPresentationData,
@@ -13,24 +16,48 @@ import { useAlertsActivation } from '@/stores/alertsActivation';
import type { Resource } from '@/types/resource';
import { formatBytes } from '@/utils/format';
-// SMART history and chart controls are only needed after a disk row is opened.
-// Keep their Storage detail module out of the initial Workloads surface.
-const LazyDiskDetail = lazy(() =>
- import('@/components/Storage/DiskDetail').then(({ DiskDetail }) => ({ default: DiskDetail })),
+import { GUEST_DRAWER_HISTORY_DEFAULT_RANGE } from './guestDrawerModel';
+
+// An opened disk shows the Storage disk drawer's Overview, so a disk reads the
+// same here as on the Storage tab. Load it only once a disk row is opened, to
+// keep it out of the initial Workloads surface.
+const LazyDiskDrawerOverview = lazy(() =>
+ import('@/components/Storage/DiskDrawerOverview').then(({ DiskDrawerOverview }) => ({
+ default: DiskDrawerOverview,
+ })),
);
+// The disks' reporting machine is the open guest, not a loaded resource here:
+// alerts come from each disk's own identity, its Proxmox disk key and, when
+// the guest runs an agent, that agent's SMART temperature key.
+const NO_LOADED_DISK_OWNERS: ReadonlyMap<string, Resource> = new Map();
+
const GuestPhysicalDiskRow: Component<{
disk: Resource;
alertResourceIds: string[];
+ reportingAgentId?: string;
historyEnabled: boolean;
}> = (props) => {
const [expanded, setExpanded] = createSignal(false);
- const { getDiskTemperatureThresholds } = useAlertsActivation();
- const data = () =>
+ const [historyRange, setHistoryRange] = createSignal<HistoryTimeRange>(
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ );
+ const { activeAlerts } = useWebSocket();
+ const { detectionEnabled, getDiskTemperatureThresholds } = useAlertsActivation();
+ const data = createMemo(() =>
extractPhysicalDiskPresentationData(
props.disk,
getDiskTemperatureThresholds,
props.alertResourceIds,
+ ),
+ );
+ const alerts = () =>
+ getPhysicalDiskAlerts(
+ props.disk,
+ NO_LOADED_DISK_OWNERS,
+ activeAlerts,
+ detectionEnabled(),
+ props.reportingAgentId,
);
const health = () => getPhysicalDiskHealthStatus(data());
const temperature = () => getPhysicalDiskTemperaturePresentation(data());
@@ -77,10 +104,12 @@ const GuestPhysicalDiskRow: Component<{
</p>
}
>
- <LazyDiskDetail
+ <LazyDiskDrawerOverview
disk={props.disk}
- nodes={[]}
- alertResourceIds={props.alertResourceIds}
+ diskData={data()}
+ alerts={alerts()}
+ historyRange={historyRange()}
+ onHistoryRangeChange={setHistoryRange}
historyEnabled={props.historyEnabled}
/>
</Suspense>
@@ -98,6 +127,8 @@ export const GuestPhysicalDisks: Component<{
* applies, then the guest's canonical ID and override keys.
*/
alertResourceIds?: string[];
+ /** The guest's own agent, which reports these disks' SMART temperatures. */
+ reportingAgentId?: string;
/**
* False while the Overview holding these disks is hidden: an expanded disk's
* charts and the list's live refresh pause until it is shown again.
@@ -137,6 +168,7 @@ export const GuestPhysicalDisks: Component<{
<GuestPhysicalDiskRow
disk={disk}
alertResourceIds={props.alertResourceIds ?? []}
+ reportingAgentId={props.reportingAgentId}
historyEnabled={props.historyEnabled !== false}
/>
)}
diff --git a/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx b/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
index 9eef7b4938..d264afb1ea 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
@@ -138,6 +138,28 @@ describe('NodeDrawer', () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
+ it('opens the node web interface from the header, like the guest drawer', () => {
+ const onClose = vi.fn();
+ render(() => (
+ <NodeDrawer
+ node={makeNode()}
+ onClose={onClose}
+ webInterfaceUrl="https://pve-node-1.example:8006"
+ />
+ ));
+
+ const open = screen.getByRole('link', { name: 'Open web interface for pve-node-1' });
+ expect(open).toHaveAttribute('href', 'https://pve-node-1.example:8006');
+ expect(open).toHaveTextContent('Open');
+ fireEvent.click(open);
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it('shows no Open action when the node has no web interface', () => {
+ render(() => <NodeDrawer node={makeNode()} onClose={vi.fn()} webInterfaceUrl=" " />);
+ expect(screen.queryByRole('link', { name: /Open web interface/ })).toBeNull();
+ });
+
it('shows a guest-drawer style Proxmox node overview with detailed node context', () => {
render(() => (
<NodeDrawer
diff --git a/frontend-modern/src/components/Workloads/NodeDrawer.tsx b/frontend-modern/src/components/Workloads/NodeDrawer.tsx
index 699e1d6e97..780d800f8d 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawer.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawer.tsx
@@ -1,10 +1,13 @@
import { Show, createMemo, createSignal, type Component } from 'solid-js';
+import ExternalLinkIcon from 'lucide-solid/icons/external-link';
import type { HistoryTimeRange } from '@/api/charts';
import { ResourceOperatorStateSection } from '@/components/Infrastructure/ResourceOperatorStateSection';
+import { getDrawerHeaderActionButtonClass } from '@/components/shared/buttonModel';
import { DrawerSubjectHeading } from '@/components/shared/DrawerSubjectHeading';
import { ObjectDrawerHeader } from '@/components/shared/ObjectDrawerHeader';
import { Subtabs } from '@/components/shared/Subtabs';
+import { WebInterfaceLink } from '@/components/shared/WebInterfaceLink';
import { nodeOverrideIdCandidates } from '@/features/alerts/alertOverridesModel';
import { useAlertsActivation } from '@/stores/alertsActivation';
import type { Alert, Disk, Node } from '@/types/api';
@@ -30,6 +33,8 @@ interface NodeDrawerProps {
* name. `alerts` also lists its guests'; only these describe its metrics.
*/
ownAlerts?: Alert[];
+ /** The node's web interface, the same link its table row opens. */
+ webInterfaceUrl?: string;
onClose?: () => void;
}
@@ -82,6 +87,18 @@ export const NodeDrawer: Component<NodeDrawerProps> = (props) => {
<ObjectDrawerHeader
collapseLabel={`Collapse ${displayName()} details`}
onCollapse={onClose()}
+ actions={
+ <Show when={props.webInterfaceUrl?.trim()}>
+ <WebInterfaceLink
+ url={props.webInterfaceUrl}
+ ariaLabel={`Open web interface for ${displayName()}`}
+ class={getDrawerHeaderActionButtonClass()}
+ >
+ <ExternalLinkIcon class="h-3.5 w-3.5" aria-hidden="true" />
+ <span>Open</span>
+ </WebInterfaceLink>
+ </Show>
+ }
>
<DrawerSubjectHeading
headingId={headingId()}
diff --git a/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx b/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx
index 9cca889b20..ab884f8eda 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawerOverview.tsx
@@ -1,6 +1,5 @@
import { For, Show, Suspense, createMemo, lazy } from 'solid-js';
-import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { HelpIcon } from '@/components/shared/HelpIcon';
import {
@@ -9,7 +8,10 @@ import {
} from '@/components/shared/TechnicalDetailsDisclosure';
import { HOST_METRICS_HISTORY_GROUPS } from '@/components/shared/hostMetricsHistoryModel';
import type { HistoryTimeRange } from '@/api/charts';
-import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
+import {
+ DrawerAttentionSection,
+ DrawerNoAlertsLine,
+} from '@/components/shared/DrawerAttentionSection';
import { DrawerExceptionList } from './DrawerExceptionList';
import {
compactDetailRows,
@@ -569,9 +571,7 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
}))}
/>
<Show when={(props.alerts ?? []).length === 0}>
- <p data-testid="drawer-no-attention" class="text-xs font-medium text-base-content">
- {ALERTS_EMPTY_STATE}
- </p>
+ <DrawerNoAlertsLine />
</Show>
<DrawerExceptionList testId="node-drawer-exceptions" rows={exceptionRows()} />
@@ -609,7 +609,9 @@ export function NodeDrawerOverview(props: NodeDrawerOverviewProps) {
data-testid="node-drawer-facts"
class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted"
>
- <For each={facts()}>{(fact) => <span class="wrap-break-word">{fact}</span>}</For>
+ <For each={facts()}>
+ {(fact) => <span class="max-w-full whitespace-normal wrap-anywhere">{fact}</span>}
+ </For>
</div>
</Show>
diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestPhysicalDisks.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestPhysicalDisks.test.tsx
index 1bd12bfa35..09a178f6b4 100644
--- a/frontend-modern/src/components/Workloads/__tests__/GuestPhysicalDisks.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/GuestPhysicalDisks.test.tsx
@@ -1,5 +1,5 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
-import { createSignal, type JSX } from 'solid-js';
+import { createSignal } from 'solid-js';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { AlertsAPI } from '@/api/alerts';
import { useAlertsActivation } from '@/stores/alertsActivation';
@@ -18,18 +18,33 @@ const queryState = vi.hoisted(() => ({
realtimeEnabled: undefined as (() => boolean) | undefined,
}));
-// The expanded disk detail now shows its history charts in view; the chart
-// measures itself with ResizeObserver, which jsdom lacks. Its rendering is
-// covered by the HistoryChart and DiskDetail suites.
-vi.mock('@/components/shared/HistoryChart', () => ({
- HistoryChartHoverGroup: (props: { children: JSX.Element }) => <div>{props.children}</div>,
- HistoryChart: (props: { label: string; enabled?: boolean }) => (
- <div data-testid="history-chart" data-enabled={String(props.enabled !== false)}>
- {props.label}
+// An opened disk shows the Storage disk drawer's Overview, whose charts read
+// metrics history. Their rendering is covered by the GuestDrawerHistory and
+// DiskDrawer suites; here they only report what they were asked to chart.
+vi.mock('@/components/Workloads/GuestDrawerHistory', () => ({
+ GuestDrawerHistory: (props: {
+ target: { resourceType: string; resourceId: string } | null;
+ range: string;
+ enabled?: boolean;
+ groups?: Array<{ label: string }>;
+ }) => (
+ <div
+ data-testid="history-chart"
+ data-enabled={String(props.enabled !== false)}
+ data-range={props.range}
+ data-target={props.target?.resourceId ?? ''}
+ >
+ {(props.groups ?? []).map((group) => group.label).join(', ')}
</div>
),
}));
+const activeAlertsMock = vi.hoisted(() => ({}) as Record<string, unknown>);
+vi.mock('@/contexts/appRuntime', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/appRuntime')>()),
+ useWebSocket: () => ({ activeAlerts: activeAlertsMock }),
+}));
+
vi.mock('@/hooks/useUnifiedResources', () => ({
useUnifiedResources: (options: {
query: string;
@@ -69,10 +84,10 @@ const disk: Resource = {
};
describe('GuestPhysicalDisks', () => {
- // The first expansion lazy-loads the Storage disk detail; a cold transform of
- // that module can outlast findByText's default wait on a loaded machine.
+ // The first expansion lazy-loads the Storage disk Overview; a cold transform
+ // of that module can outlast findByText's default wait on a loaded machine.
beforeAll(async () => {
- await import('@/components/Storage/DiskDetail');
+ await import('@/components/Storage/DiskDrawerOverview');
}, 30_000);
beforeEach(() => {
@@ -83,7 +98,10 @@ describe('GuestPhysicalDisks', () => {
queryState.enabled = false;
queryState.realtimeEnabled = undefined;
});
- afterEach(cleanup);
+ afterEach(() => {
+ cleanup();
+ for (const id of Object.keys(activeAlertsMock)) delete activeAlertsMock[id];
+ });
it('shows the linked guest disk and loads its existing SMART detail on expansion', async () => {
queryState.resources = [disk, { ...disk, id: 'host-disk', parentId: 'pve-node-1' }];
@@ -100,14 +118,57 @@ describe('GuestPhysicalDisks', () => {
const row = within(card).getByTestId('guest-physical-disk') as HTMLDetailsElement;
row.open = true;
fireEvent(row, new Event('toggle'));
- // The SMART card and the disk's Reallocated Sectors history chart both
- // name the attribute once the detail is open.
- expect((await within(card).findAllByText('Reallocated Sectors')).length).toBeGreaterThan(0);
- expect(within(card).getByText('Pending Sectors')).toBeInTheDocument();
- expect(within(card).getByText('CRC Errors')).toBeInTheDocument();
+ // The same Overview the Storage tab's disk drawer shows: alerts line,
+ // charts, facts, SMART health card, then every attribute under Details.
+ const overview = await within(card).findByTestId('disk-drawer-overview');
+ expect(within(overview).getByTestId('drawer-no-attention')).toHaveTextContent(
+ 'No active alerts',
+ );
+ expect(await within(overview).findByTestId('history-chart')).toHaveAttribute(
+ 'data-range',
+ '24h',
+ );
+ expect(within(overview).getByTestId('disk-drawer-health-card')).toBeInTheDocument();
+ expect(within(overview).getByText('Reallocated Sectors')).toBeInTheDocument();
+ expect(within(overview).getByText('Pending Sectors')).toBeInTheDocument();
+ expect(within(overview).getByText('CRC Errors')).toBeInTheDocument();
expect(within(card).getAllByTestId('guest-physical-disk')).toHaveLength(1);
});
+ it("lists the disk's own open alerts in its Overview", async () => {
+ activeAlertsMock['disk-alert'] = {
+ id: 'disk-alert',
+ type: 'disk-health',
+ level: 'critical',
+ resourceId: 'disk-101-a',
+ resourceName: 'Guest SATA',
+ node: 'pve-node-1',
+ instance: 'cluster-a',
+ message: 'SMART health check failed',
+ value: 0,
+ threshold: 0,
+ startTime: '2026-10-20T10:00:00Z',
+ acknowledged: false,
+ };
+ activeAlertsMock['other-disk-alert'] = {
+ ...(activeAlertsMock['disk-alert'] as object),
+ id: 'other-disk-alert',
+ resourceId: 'disk-202-b',
+ message: 'Another disk failed',
+ };
+ queryState.resources = [disk];
+ render(() => <GuestPhysicalDisks parentId="vm-resource-101" />);
+ const row = screen.getByTestId('guest-physical-disk') as HTMLDetailsElement;
+ row.open = true;
+ fireEvent(row, new Event('toggle'));
+
+ const overview = await screen.findByTestId('disk-drawer-overview');
+ const attention = within(overview).getByTestId('drawer-attention-section');
+ expect(attention).toHaveTextContent('SMART health check failed');
+ expect(attention).not.toHaveTextContent('Another disk failed');
+ expect(within(overview).queryByTestId('drawer-no-attention')).toBeNull();
+ });
+
it('pauses an expanded disk and the live list while its Overview is hidden', async () => {
queryState.resources = [disk];
const [shown, setShown] = createSignal(true);
diff --git a/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx b/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx
index 4e665e2119..d8f58ac951 100644
--- a/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx
+++ b/frontend-modern/src/components/Workloads/__tests__/WorkloadsSurface.performance.contract.test.tsx
@@ -472,7 +472,7 @@ describe('Workloads platform-page embed contract', () => {
const proxmoxNodesSource = (await import('../../../features/proxmox/ProxmoxNodesTable.tsx?raw'))
.default;
expect(proxmoxNodesSource).toContain('NodeDrawer');
- expect(proxmoxNodesSource).toContain('data-inline-node-detail-for={node.id}');
+ expect(proxmoxNodesSource).toContain('data-inline-detail-for={node.id}');
});
});
diff --git a/frontend-modern/src/components/shared/DrawerAttentionSection.tsx b/frontend-modern/src/components/shared/DrawerAttentionSection.tsx
index fc3d5c6b5f..f88a593efc 100644
--- a/frontend-modern/src/components/shared/DrawerAttentionSection.tsx
+++ b/frontend-modern/src/components/shared/DrawerAttentionSection.tsx
@@ -1,5 +1,6 @@
import { For, Show, createSignal, createUniqueId, type Component } from 'solid-js';
+import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
import {
formatAlertSeverityLabel,
getAlertSeverityBadgeClass,
@@ -61,7 +62,7 @@ export const DrawerAttentionSection: Component<DrawerAttentionSectionProps> = (p
<Show when={item.subject || item.metric}>
<p class="flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-xs">
<Show when={item.subject}>
- <span class="truncate font-semibold text-base-content" title={item.subject}>
+ <span class="min-w-0 wrap-anywhere font-semibold text-base-content">
{item.subject}
</span>
</Show>
@@ -120,3 +121,17 @@ export const DrawerAttentionSection: Component<DrawerAttentionSectionProps> = (p
</Show>
);
};
+
+/**
+ * The line every drawer shows in place of the attention section when the
+ * object has no active alerts, so "nothing is wrong" reads the same in every
+ * drawer. `availabilityPassing` adds the one reassurance that is not an alert.
+ */
+export const DrawerNoAlertsLine: Component<{ availabilityPassing?: boolean }> = (props) => (
+ <p data-testid="drawer-no-attention" class="text-xs text-muted">
+ <span class="font-medium text-base-content">{ALERTS_EMPTY_STATE}</span>
+ <Show when={props.availabilityPassing}>
+ <span> · availability checks passing</span>
+ </Show>
+ </p>
+);
diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
index b298eda9c1..669860bfe8 100644
--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
@@ -211,6 +211,7 @@ import kubernetesStorageTableSource from '@/features/kubernetes/KubernetesStorag
import proxmoxBackupServersTableSource from '@/features/proxmox/ProxmoxBackupServersTable.tsx?raw';
import proxmoxBackupsTableSource from '@/features/proxmox/ProxmoxBackupsTable.tsx?raw';
import proxmoxCephClusterDrawerSource from '@/features/proxmox/ProxmoxCephClusterDrawer.tsx?raw';
+import proxmoxCephClusterDrawerModelSource from '@/features/proxmox/proxmoxCephClusterDrawerModel.ts?raw';
import proxmoxCephTableSource from '@/features/proxmox/ProxmoxCephTable.tsx?raw';
import proxmoxCoverageTableSource from '@/features/proxmox/ProxmoxCoverageTable.tsx?raw';
import proxmoxMailGatewayTableSource from '@/features/proxmox/ProxmoxMailGatewayTable.tsx?raw';
@@ -224,8 +225,6 @@ import availabilityChecksTableSource from '@/features/standalone/AvailabilityChe
import agentsMachinesTableSource from '@/features/standalone/AgentsMachinesTable.tsx?raw';
import agentMachineTableModelSource from '@/features/standalone/agentMachineTableModel.ts?raw';
import proxmoxMailGatewayDrawerSource from '@/features/proxmox/ProxmoxMailGatewayDrawer.tsx?raw';
-import swarmServicesDrawerSource from '@/components/Docker/SwarmServicesDrawer.tsx?raw';
-import k8sDeploymentsDrawerSource from '@/components/Kubernetes/K8sDeploymentsDrawer.tsx?raw';
import k8sNamespacesDrawerSource from '@/components/Kubernetes/K8sNamespacesDrawer.tsx?raw';
import nodeGroupHeaderSource from '@/components/shared/NodeGroupHeader.tsx?raw';
import proxmoxVersionSource from '@/utils/proxmoxVersion.ts?raw';
@@ -235,7 +234,7 @@ import storagePoolRowSource from '@/components/Storage/StoragePoolRow.tsx?raw';
import storageContentCardSource from '@/components/Storage/StorageContentCard.tsx?raw';
import storagePoolsTableSource from '@/components/Storage/StoragePoolsTable.tsx?raw';
import storagePoolDetailSource from '@/components/Storage/StoragePoolDetail.tsx?raw';
-import diskDetailSource from '@/components/Storage/DiskDetail.tsx?raw';
+import diskDrawerOverviewSource from '@/components/Storage/DiskDrawerOverview.tsx?raw';
import diskListSource from '@/components/Storage/DiskList.tsx?raw';
import alertOverviewStatsCardsSource from '@/features/alerts/AlertOverviewStatsCards.tsx?raw';
import alertHistoryTableSectionSource from '@/features/alerts/AlertHistoryTableSection.tsx?raw';
@@ -721,7 +720,6 @@ describe('shared primitive guardrails', () => {
'src/components/Alerts/EmailProviderSelect.tsx',
'src/components/Alerts/WebhookConfigForm.tsx',
'src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx',
- 'src/components/Kubernetes/K8sDeploymentsDrawer.tsx',
'src/components/OrgSwitcher.tsx',
'src/components/Settings/AIChatMaintenanceSection.tsx',
'src/components/Settings/AIModelSelectionSection.tsx',
@@ -738,7 +736,6 @@ describe('shared primitive guardrails', () => {
'src/components/Settings/RecoverySettingsPanel.tsx',
'src/components/Settings/RolesEditorDialog.tsx',
'src/components/Settings/SystemLogsPanel.tsx',
- 'src/components/Storage/DiskDetail.tsx',
'src/components/Storage/StoragePageControls.tsx',
'src/components/Workloads/GuestDrawerHistory.tsx',
'src/components/shared/FilterBar/AddFilterMenu.tsx',
@@ -782,7 +779,6 @@ describe('shared primitive guardrails', () => {
addFilterMenuSource,
filterToolbarSource,
guestDrawerHistorySource,
- k8sDeploymentsDrawerSource,
orgSwitcherSource,
resourceDetailDrawerOverviewTabSource,
storagePageControlsSource,
@@ -1207,7 +1203,6 @@ describe('shared primitive guardrails', () => {
'src/components/shared/cards/TemperaturesCard.tsx',
'src/components/Workloads/DrawerDiskListCard.tsx',
'src/features/docker/DockerHostDrawerOverview.tsx',
- 'src/features/storageBackups/detailPresentation.ts',
];
const retiredFrameClass = 'rounded-sm border border-border bg-surface p-3 shadow-xs';
const registeredRule = registry.rules?.find(
@@ -1251,12 +1246,8 @@ describe('shared primitive guardrails', () => {
expect(readFrontendSource('src/components/shared/WebInterfaceUrlField.tsx')).toContain(
'getInfoCardFrameClass',
);
- expect(readFrontendSource('src/features/storageBackups/detailPresentation.ts')).toContain(
- 'INFO_CARD_FRAME_CLASS',
- );
for (const consumerPath of [
- 'src/components/Storage/StorageDetailKeyValueRow.tsx',
'src/components/shared/cards/DisksCard.tsx',
'src/components/shared/cards/HardwareCard.tsx',
'src/components/shared/cards/RootDiskCard.tsx',
@@ -1280,10 +1271,7 @@ describe('shared primitive guardrails', () => {
);
}
- for (const consumerPath of [
- 'src/components/Infrastructure/ResourceActionHistory.tsx',
- 'src/features/proxmox/ProxmoxMailGatewayDrawer.tsx',
- ]) {
+ for (const consumerPath of ['src/components/Infrastructure/ResourceActionHistory.tsx']) {
const source = readFrontendSource(consumerPath);
expect(source).toContain('InfoCardKeyValueRow');
expect(source).not.toMatch(
@@ -1306,7 +1294,7 @@ describe('shared primitive guardrails', () => {
it('charts object detail history in the detail itself, not behind a History tab', () => {
// Storage disk and pool details had only Overview and History, so with the
// charts in the one view they need no tab strip at all.
- for (const source of [diskDetailSource, storagePoolDetailSource]) {
+ for (const source of [diskDrawerOverviewSource, storagePoolDetailSource]) {
expect(source).not.toContain('@/components/shared/Subtabs');
expect(source).not.toContain("value: 'history', label: 'History'");
}
@@ -1332,11 +1320,11 @@ describe('shared primitive guardrails', () => {
expect(resourceDetailDrawerSource).toContain('@/components/shared/Subtabs');
expect(resourceDetailDrawerSource).toContain('tabs={drawer.tabs().map');
- // The pool drawer charts usage with the shared drawer history (range picker
- // in its toolbar); the guest drawer's embedded disk detail keeps its own.
- expect(diskDetailSource).toContain('filterSelectClass');
+ // Pool and disk drawers chart with the shared drawer history, whose range
+ // picker sits in its toolbar; neither keeps a storage-local picker.
expect(storagePoolDetailSource).toContain('GuestDrawerHistory');
- for (const storageDetailSource of [diskDetailSource, storagePoolDetailSource]) {
+ expect(diskDrawerOverviewSource).toContain('GuestDrawerHistory');
+ for (const storageDetailSource of [diskDrawerOverviewSource, storagePoolDetailSource]) {
expect(storageDetailSource).not.toContain('activeTab()');
expect(storageDetailSource).not.toContain('STORAGE_DETAIL_SELECT_CLASS');
expect(storageDetailSource).not.toContain('STORAGE_DETAIL_HEADER_SELECT_CLASS');
@@ -1508,8 +1496,6 @@ describe('shared primitive guardrails', () => {
aiCostDashboardSource,
proxmoxMailGatewayDrawerSource,
pulseDataGridSource,
- swarmServicesDrawerSource,
- k8sDeploymentsDrawerSource,
k8sNamespacesDrawerSource,
]) {
expect(source).toContain('<Table');
@@ -4284,7 +4270,6 @@ describe('shared primitive guardrails', () => {
resourceDetailDrawerSource,
dockerHostDrawerSource,
proxmoxCephClusterDrawerSource,
- proxmoxMailGatewayDrawerSource,
]) {
expect(drawerSource).toContain('@/components/shared/ObjectDrawerHeader');
expect(drawerSource).toContain('ObjectDrawerHeader');
@@ -6484,9 +6469,12 @@ describe('shared primitive guardrails', () => {
const platformIntegerConsumers: Array<[string, string]> = [
['src/components/Kubernetes/K8sNamespacesDrawer.tsx', k8sNamespacesDrawerSource],
['src/features/proxmox/ProxmoxBackupServersTable.tsx', proxmoxBackupServersTableSource],
- ['src/features/proxmox/ProxmoxCephClusterDrawer.tsx', proxmoxCephClusterDrawerSource],
['src/features/proxmox/ProxmoxMailGatewayDrawer.tsx', proxmoxMailGatewayDrawerSource],
['src/features/proxmox/ProxmoxMailGatewayTable.tsx', proxmoxMailGatewayTableSource],
+ [
+ 'src/features/proxmox/proxmoxCephClusterDrawerModel.ts',
+ proxmoxCephClusterDrawerModelSource,
+ ],
];
const platformIntegerConsumerPaths = platformIntegerConsumers.map(([path]) => path);
@@ -6506,10 +6494,6 @@ describe('shared primitive guardrails', () => {
path: 'src/features/proxmox/ProxmoxBackupServersTable.tsx',
patterns: ['row.backupCount.toLocaleString()'],
},
- {
- path: 'src/features/proxmox/ProxmoxCephClusterDrawer.tsx',
- patterns: ['pool.objects.toLocaleString()'],
- },
{
path: 'src/features/proxmox/ProxmoxMailGatewayDrawer.tsx',
patterns: ['function formatNumber', 'Math.round(value).toLocaleString()'],
@@ -6518,6 +6502,10 @@ describe('shared primitive guardrails', () => {
path: 'src/features/proxmox/ProxmoxMailGatewayTable.tsx',
patterns: ['const formatLocaleCount', 'value.toLocaleString()'],
},
+ {
+ path: 'src/features/proxmox/proxmoxCephClusterDrawerModel.ts',
+ patterns: ['pool.objects.toLocaleString()'],
+ },
]);
expect(localHelperGuard?.canonical?.path).toBe(
'src/features/platformPage/sharedPlatformPage.tsx',
@@ -6552,7 +6540,6 @@ describe('shared primitive guardrails', () => {
}
for (const source of [
proxmoxBackupServersTableSource,
- proxmoxCephClusterDrawerSource,
proxmoxMailGatewayDrawerSource,
proxmoxMailGatewayTableSource,
]) {
@@ -6674,7 +6661,6 @@ describe('shared primitive guardrails', () => {
const platformNumberValueConsumers: Array<[string, string]> = [
['src/features/docker/DockerNativeTableShared.tsx', dockerNativeTableSharedSource],
['src/features/docker/DockerServicesTable.tsx', dockerServicesTableSource],
- ['src/components/Docker/SwarmServicesDrawer.tsx', swarmServicesDrawerSource],
['src/features/kubernetes/KubernetesAutoscalingTable.tsx', kubernetesAutoscalingTableSource],
['src/features/kubernetes/KubernetesControllersTable.tsx', kubernetesControllersTableSource],
['src/features/kubernetes/KubernetesDeploymentsTable.tsx', kubernetesDeploymentsTableSource],
@@ -6704,13 +6690,6 @@ describe('shared primitive guardrails', () => {
path: 'src/features/docker/DockerServicesTable.tsx',
patterns: ['const replicaCount', '<span class="tabular-nums">{value ?? 0}</span>'],
},
- {
- path: 'src/components/Docker/SwarmServicesDrawer.tsx',
- patterns: [
- '<span class="tabular-nums">{desired()}</span>',
- '<span class="tabular-nums">{running()}</span>',
- ],
- },
{
path: 'src/features/kubernetes/KubernetesAutoscalingTable.tsx',
patterns: ['const numberValue', optionalNumberMarkupPattern],
@@ -6789,7 +6768,7 @@ describe('shared primitive guardrails', () => {
'runningTasks',
'class="tabular-nums"',
]);
- expect(localSwarmCountGuard?.scopes).toEqual(['src/components/Docker']);
+ expect(localSwarmCountGuard?.scopes).toEqual(['src/features/docker']);
expect(localSwarmCountGuard?.allowedPaths ?? []).toHaveLength(0);
expect(localSwarmCountGuard?.ignoredPaths ?? []).toHaveLength(0);
expect(localTrueNASCountGuard?.canonical?.path).toBe(
@@ -6976,11 +6955,14 @@ describe('shared primitive guardrails', () => {
);
const percentConsumers: Array<[string, string]> = [
['src/features/proxmox/ProxmoxBackupServersTable.tsx', proxmoxBackupServersTableSource],
- ['src/features/proxmox/ProxmoxCephClusterDrawer.tsx', proxmoxCephClusterDrawerSource],
['src/features/proxmox/ProxmoxCephTable.tsx', proxmoxCephTableSource],
['src/features/proxmox/ProxmoxMailGatewayDrawer.tsx', proxmoxMailGatewayDrawerSource],
['src/features/proxmox/ProxmoxNodesTable.tsx', proxmoxNodesTableSource],
['src/features/truenas/TrueNASSystemsTable.tsx', truenasSystemsTableSource],
+ [
+ 'src/features/proxmox/proxmoxCephClusterDrawerModel.ts',
+ proxmoxCephClusterDrawerModelSource,
+ ],
];
const temperatureConsumers: Array<[string, string]> = [
['src/features/docker/DockerHostsTable.tsx', dockerHostsTableSource],
@@ -7011,8 +6993,8 @@ describe('shared primitive guardrails', () => {
],
},
{
- path: 'src/features/proxmox/ProxmoxCephClusterDrawer.tsx',
- patterns: ['clamped.toFixed(1)}%'],
+ path: 'src/features/proxmox/proxmoxCephClusterDrawerModel.ts',
+ patterns: ['clamped.toFixed(1)}%', 'percentUsed.toFixed(1)}%'],
},
{
path: 'src/features/proxmox/ProxmoxCephTable.tsx',
@@ -8209,8 +8191,6 @@ describe('shared primitive guardrails', () => {
expect(registeredRule?.canonical?.path).toBe('src/components/shared/SearchInput.tsx');
expect(registeredRule?.canonical?.export).toBe('SearchInput');
expect(registeredRule?.requiredConsumers?.map((consumer) => consumer.path)).toEqual([
- 'src/components/Docker/SwarmServicesDrawer.tsx',
- 'src/components/Kubernetes/K8sDeploymentsDrawer.tsx',
'src/components/Kubernetes/K8sNamespacesDrawer.tsx',
'src/components/Settings/SettingsPageShell.tsx',
'src/components/shared/FilterBar/FilterBar.tsx',
@@ -8254,13 +8234,7 @@ describe('shared primitive guardrails', () => {
expect(searchInputEnhancementsModelSource).toContain('SEARCH_HISTORY_CLEAR_LABEL');
expect(searchInputEnhancementsModelSource).toContain('SEARCH_HISTORY_MENU_CLASS');
- for (const source of [
- swarmServicesDrawerSource,
- k8sDeploymentsDrawerSource,
- k8sNamespacesDrawerSource,
- settingsPageShellSource,
- filterBarSource,
- ]) {
+ for (const source of [k8sNamespacesDrawerSource, settingsPageShellSource, filterBarSource]) {
expect(source).toContain('SearchInput');
}
});
@@ -8711,7 +8685,7 @@ describe('shared primitive guardrails', () => {
expect(drawerAttentionSectionSource).toContain('item.title ?? item.message');
for (const liveAlertConsumer of [
'src/components/Workloads/NodeDrawerOverview.tsx',
- 'src/features/proxmox/ProxmoxMailGatewayDrawer.tsx',
+ 'src/features/proxmox/ProxmoxCephClusterDrawer.tsx',
]) {
const source = readFrontendSource(liveAlertConsumer);
expect(source).toContain('...getAlertAttentionCopy(alert, now)');
diff --git a/frontend-modern/src/components/shared/__tests__/historyChartModel.branchcov2.test.ts b/frontend-modern/src/components/shared/__tests__/historyChartModel.branchcov2.test.ts
index 573d919303..e6af57b899 100644
--- a/frontend-modern/src/components/shared/__tests__/historyChartModel.branchcov2.test.ts
+++ b/frontend-modern/src/components/shared/__tests__/historyChartModel.branchcov2.test.ts
@@ -18,7 +18,6 @@ import {
getHistoryChartTooltipLayout,
getHistoryChartYAxisLabels,
} from '@/components/shared/historyChartModel';
-import { DISK_DETAIL_HISTORY_RANGE_OPTIONS } from '@/features/storageBackups/diskDetailPresentation';
import { STORAGE_POOL_DETAIL_HISTORY_RANGE_OPTIONS } from '@/features/storageBackups/storagePoolDetailPresentation';
const pt = (timestamp: number, value: number, min: number, max: number): AggregatedMetricPoint => ({
@@ -600,14 +599,11 @@ describe('getHistoryChartTooltipLayout', () => {
});
describe('formatHistoryRangeOptionLabel', () => {
- it('names every range one way across drawer, disk and pool pickers', () => {
+ it('names every range one way across drawer and pool pickers', () => {
expect(formatHistoryRangeOptionLabel('1h')).toBe('1 hour');
expect(formatHistoryRangeOptionLabel('24h')).toBe('24 hours');
expect(formatHistoryRangeOptionLabel('7d')).toBe('7 days');
- for (const option of [
- ...DISK_DETAIL_HISTORY_RANGE_OPTIONS,
- ...STORAGE_POOL_DETAIL_HISTORY_RANGE_OPTIONS,
- ]) {
+ for (const option of STORAGE_POOL_DETAIL_HISTORY_RANGE_OPTIONS) {
expect(option.label).toBe(formatHistoryRangeOptionLabel(option.value));
}
});
diff --git a/frontend-modern/src/components/shared/tableVisibleColumnSpan.ts b/frontend-modern/src/components/shared/tableVisibleColumnSpan.ts
new file mode 100644
index 0000000000..c1d8a03567
--- /dev/null
+++ b/frontend-modern/src/components/shared/tableVisibleColumnSpan.ts
@@ -0,0 +1,67 @@
+import { createEffect, createSignal, onCleanup, type Accessor } from 'solid-js';
+
+/**
+ * Sum of the colspans of the visible cells in a table's header row.
+ *
+ * Fixed-layout tables give any width their column percentages leave over to
+ * every column that exists, and a cell spanning more columns than the header
+ * has (a `colspan={100}` spacer or group row) creates the missing ones. On a
+ * phone, where hidden columns leave the visible percentages short of 100%,
+ * those phantom columns took the rest of the table: every row and drawer
+ * stopped well short of the edge. Full-width helper rows span exactly the
+ * visible header cells instead.
+ */
+export const countVisibleHeaderColumns = (table: HTMLTableElement | null): number => {
+ const headerRow = table?.tHead?.rows[0];
+ if (!headerRow) return 0;
+ return Array.from(headerRow.cells).reduce(
+ (total, cell) =>
+ window.getComputedStyle(cell).display === 'none' ? total : total + cell.colSpan,
+ 0,
+ );
+};
+
+/**
+ * Tracks the visible header column count of the table containing `anchor`,
+ * re-measuring when the anchor mounts, the table's shell resizes, or a header
+ * cell is shown, hidden or re-spanned (column pickers, breakpoint tiers).
+ */
+export function createVisibleTableColumnSpan(
+ anchor: Accessor<HTMLElement | null | undefined>,
+ fallback = 1,
+): Accessor<number> {
+ const [span, setSpan] = createSignal(fallback);
+
+ createEffect(() => {
+ const table = anchor()?.closest('table') ?? null;
+ if (!table) return;
+ const measure = () => setSpan(countVisibleHeaderColumns(table) || fallback);
+ measure();
+
+ window.addEventListener('resize', measure);
+ const shell = table.closest('.table-scroll-shell') ?? table;
+ const resizeObserver =
+ typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : undefined;
+ resizeObserver?.observe(shell);
+ const headerRow = table.tHead?.rows[0];
+ const headerObserver =
+ headerRow && typeof MutationObserver === 'function'
+ ? new MutationObserver(measure)
+ : undefined;
+ if (headerRow && headerObserver) {
+ headerObserver.observe(headerRow, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['class', 'style', 'hidden', 'colspan'],
+ });
+ }
+ onCleanup(() => {
+ window.removeEventListener('resize', measure);
+ resizeObserver?.disconnect();
+ headerObserver?.disconnect();
+ });
+ });
+
+ return span;
+}
diff --git a/frontend-modern/src/features/docker/DockerHostActionHistory.tsx b/frontend-modern/src/features/docker/DockerHostActionHistory.tsx
new file mode 100644
index 0000000000..a97f58f566
--- /dev/null
+++ b/frontend-modern/src/features/docker/DockerHostActionHistory.tsx
@@ -0,0 +1,66 @@
+import { Show, createMemo, type Component } from 'solid-js';
+
+import { ActionAuditAPI } from '@/api/actionAudit';
+import { ResourceActionHistory } from '@/components/Infrastructure/ResourceActionHistory';
+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
+import type { ActionAuditListResponse } from '@/types/actionAudit';
+import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';
+
+type ActionAuditRequest = { id: string; limit: number };
+
+const timestampOf = (value: string | undefined): number => {
+ const parsed = Date.parse(value || '');
+ return Number.isFinite(parsed) ? parsed : 0;
+};
+
+/**
+ * The host's recent audited actions, read the way a resource drawer's Manage
+ * tab reads them. It mounts with Manage, so nothing is fetched until Manage
+ * opens, and it stays hidden where action history is not available.
+ */
+export const DockerHostActionHistory: Component<{ resourceId: string }> = (props) => {
+ const request = createMemo((): ActionAuditRequest | null => {
+ const id = props.resourceId.trim();
+ return id ? { id, limit: 5 } : null;
+ });
+ const state = createNonSuspendingQuery<ActionAuditListResponse, ActionAuditRequest>({
+ source: request,
+ fetcher: async (current) =>
+ ActionAuditAPI.listActionAudits({ resourceId: current.id, limit: current.limit }),
+ initialValue: { audits: [], count: 0, available: false },
+ });
+ const audits = createMemo(() =>
+ [...(state.value().audits ?? [])].sort(
+ (left, right) =>
+ timestampOf(right.updatedAt || right.createdAt) -
+ timestampOf(left.updatedAt || left.createdAt),
+ ),
+ );
+ const error = createMemo(() => {
+ const failure = state.error();
+ if (!failure) return '';
+ return (
+ getAPIReadAccessErrorMessage(failure) ||
+ (failure as Error)?.message ||
+ 'Failed to load action history'
+ );
+ });
+ const loadingLabel = () =>
+ state.loading()
+ ? 'Refreshing actions...'
+ : state.error()
+ ? 'Actions unavailable'
+ : 'Actions loaded';
+
+ return (
+ <Show when={state.value().available || audits().length > 0 || error()}>
+ <ResourceActionHistory
+ audits={audits()}
+ count={state.value().count ?? audits().length}
+ loadingLabel={loadingLabel()}
+ error={error()}
+ onRetry={state.refetch}
+ />
+ </Show>
+ );
+};
diff --git a/frontend-modern/src/features/docker/DockerHostDrawer.test.tsx b/frontend-modern/src/features/docker/DockerHostDrawer.test.tsx
index ac2eeecd49..ba9870e03a 100644
--- a/frontend-modern/src/features/docker/DockerHostDrawer.test.tsx
+++ b/frontend-modern/src/features/docker/DockerHostDrawer.test.tsx
@@ -6,6 +6,20 @@ import type { Resource } from '@/types/resource';
import { DockerHostDrawer } from './DockerHostDrawer';
const wsActiveAlerts = vi.hoisted(() => ({}) as Record<string, unknown>);
+const listActionAudits = vi.hoisted(() =>
+ vi.fn(async (_options?: { resourceId?: string; limit?: number }) => ({
+ audits: [] as unknown[],
+ count: 0,
+ available: false,
+ })),
+);
+
+vi.mock('@/api/actionAudit', () => ({ ActionAuditAPI: { listActionAudits } }));
+vi.mock('@/api/resourceOperatorState', () => ({
+ getResourceOperatorState: vi.fn().mockResolvedValue(null),
+ setResourceOperatorState: vi.fn(),
+ clearResourceOperatorState: vi.fn(),
+}));
vi.mock('@/contexts/appRuntime', async (importOriginal) => ({
...(await importOriginal<typeof import('@/contexts/appRuntime')>()),
@@ -19,10 +33,12 @@ vi.mock('@/components/Workloads/GuestDrawerHistory', () => ({
enabled?: boolean;
onRangeChange?: (range: string) => void;
alerts?: Record<string, unknown>;
+ currentMetrics?: Record<string, number | undefined>;
}) => (
<div
data-testid="docker-host-history"
data-alert-metrics={Object.keys(props.alerts ?? {}).join(',')}
+ data-live-metrics={props.currentMetrics ? 'shown' : 'withheld'}
data-target={props.target.resourceId}
data-range={props.range}
data-enabled={String(props.enabled)}
@@ -112,7 +128,7 @@ describe('DockerHostDrawer open alerts', () => {
});
describe('DockerHostDrawer history', () => {
- it("lists a container's memory alert but draws no trigger for it on the host's charts", () => {
+ it("lists a container's memory alert but draws no trigger for it on the host's charts", async () => {
wsActiveAlerts.container = {
...openAlert(
'container',
@@ -127,19 +143,129 @@ describe('DockerHostDrawer history', () => {
expect(screen.getByTestId('drawer-attention-section')).toHaveTextContent(
'Container memory at 97%',
);
- expect(screen.getByTestId('docker-host-history')).toHaveAttribute('data-alert-metrics', '');
+ expect(await screen.findByTestId('docker-host-history')).toHaveAttribute(
+ 'data-alert-metrics',
+ '',
+ );
});
- it('charts history on Overview with its range picker, and pauses it behind Manage', () => {
+ it('charts history on Overview with its range picker, and pauses it behind Manage', async () => {
render(() => <DockerHostDrawer host={host()} />);
expect(screen.queryByRole('tab', { name: 'History' })).toBeNull();
- const history = screen.getByTestId('docker-host-history');
+ const history = await screen.findByTestId('docker-host-history');
expect(history).toHaveAttribute('data-range', '24h');
expect(history).toHaveAttribute('data-range-picker', 'true');
expect(history).toHaveAttribute('data-enabled', 'true');
fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));
expect(screen.getByTestId('docker-host-history')).toHaveAttribute('data-enabled', 'false');
});
+
+ it('shows live readings for a reporting host', async () => {
+ render(() => <DockerHostDrawer host={{ ...host(), temperature: 48 } as Resource} />);
+ expect(await screen.findByTestId('docker-host-history')).toHaveAttribute(
+ 'data-live-metrics',
+ 'shown',
+ );
+ expect(screen.queryByTestId('docker-host-drawer-readings-withheld')).toBeNull();
+ });
+
+ it("does not present an offline host's last readings as live", async () => {
+ render(() => <DockerHostDrawer host={{ ...host(), status: 'offline' } as Resource} />);
+ expect(await screen.findByTestId('docker-host-history')).toHaveAttribute(
+ 'data-live-metrics',
+ 'withheld',
+ );
+ expect(screen.getByTestId('docker-host-drawer-readings-withheld')).toHaveTextContent(
+ 'Docker host is offline. Showing its history only.',
+ );
+ });
+
+ it("does not present a stale host's last readings as live", async () => {
+ render(() => (
+ <DockerHostDrawer
+ host={
+ {
+ ...host(),
+ health: {
+ verdict: 'stale',
+ reasons: [{ code: 'telemetry_stale', detail: '12m' }],
+ },
+ } as Resource
+ }
+ />
+ ));
+ expect(await screen.findByTestId('docker-host-history')).toHaveAttribute(
+ 'data-live-metrics',
+ 'withheld',
+ );
+ expect(screen.getByTestId('docker-host-drawer-readings-withheld')).toHaveTextContent(
+ 'No report for 12m. Showing its history only.',
+ );
+ });
+});
+
+describe('DockerHostDrawer header', () => {
+ it('opens the saved web interface from the header without collapsing the drawer', () => {
+ const onClose = vi.fn();
+ render(() => (
+ <DockerHostDrawer
+ host={host()}
+ onClose={onClose}
+ customUrl="https://portainer.example:9443"
+ />
+ ));
+ const open = screen.getByRole('link', { name: 'Open web interface for docker-1' });
+ expect(open).toHaveAttribute('href', 'https://portainer.example:9443');
+ expect(open).toHaveTextContent('Open');
+ fireEvent.click(open);
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it('shows no Open action without a saved web interface', () => {
+ render(() => <DockerHostDrawer host={host()} onClose={vi.fn()} />);
+ expect(screen.queryByRole('link', { name: /Open web interface/ })).toBeNull();
+ });
+});
+
+describe('DockerHostDrawer Manage', () => {
+ it('orders operator state, container updates, web interface URL, then action history', async () => {
+ listActionAudits.mockResolvedValueOnce({
+ audits: [
+ {
+ id: 'audit-1',
+ createdAt: '2026-10-20T10:00:00Z',
+ updatedAt: '2026-10-20T10:01:00Z',
+ state: 'completed',
+ request: { capabilityName: 'docker.container.update', requestedBy: 'admin' },
+ plan: { approvalPolicy: 'admin' },
+ },
+ ],
+ count: 1,
+ available: true,
+ });
+ render(() => <DockerHostDrawer host={host()} />);
+ expect(listActionAudits).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));
+
+ const manage = screen.getByTestId('docker-host-manage-tab');
+ const operator = within(manage).getByRole('region', { name: 'Operator overrides' });
+ const updates = within(manage).getByTestId('docker-host-management-actions');
+ const url = within(manage).getByText('Web Interface URL');
+ const history = await within(manage).findByTestId('resource-action-history-section');
+ expect(listActionAudits).toHaveBeenCalledWith({ resourceId: 'agent:docker-1', limit: 5 });
+ const follows = (first: Element, second: Element) =>
+ Boolean(first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(follows(operator, updates)).toBe(true);
+ expect(follows(updates, url)).toBe(true);
+ expect(follows(url, history)).toBe(true);
+ });
+
+ it('leaves action history out where the server does not offer it', async () => {
+ render(() => <DockerHostDrawer host={host()} />);
+ fireEvent.click(screen.getByRole('tab', { name: 'Manage' }));
+ await vi.waitFor(() => expect(listActionAudits).toHaveBeenCalled());
+ expect(screen.queryByTestId('resource-action-history-section')).toBeNull();
+ });
});
describe('DockerHostDrawer typed-helper summary mode', () => {
@@ -193,6 +319,12 @@ describe('DockerHostDrawer inventory', () => {
expect(details.open).toBe(false);
expect(within(details).getByText('Kernel')).toBeInTheDocument();
expect(within(details).queryByText('Updates')).toBeNull();
+ // Values a reader copies or compares wrap instead of hiding behind an ellipsis.
+ for (const value of ['6.1.0', 'Docker 27.3.1', 'Debian GNU/Linux 12', 'Direct API']) {
+ const cell = within(details).getByText(value);
+ expect(cell).toHaveClass('whitespace-normal');
+ expect(cell).not.toHaveClass('truncate');
+ }
});
it('lifts an offline host and states sizes, not used amounts that would read as live', () => {
diff --git a/frontend-modern/src/features/docker/DockerHostDrawer.tsx b/frontend-modern/src/features/docker/DockerHostDrawer.tsx
index 5bf6ee4ece..0fbc089089 100644
--- a/frontend-modern/src/features/docker/DockerHostDrawer.tsx
+++ b/frontend-modern/src/features/docker/DockerHostDrawer.tsx
@@ -1,9 +1,12 @@
import { Show, createMemo, createSignal, type Component } from 'solid-js';
+import ExternalLinkIcon from 'lucide-solid/icons/external-link';
import type { HistoryTimeRange } from '@/api/charts';
+import { getDrawerHeaderActionButtonClass } from '@/components/shared/buttonModel';
import { DrawerSubjectHeading } from '@/components/shared/DrawerSubjectHeading';
import { ObjectDrawerHeader } from '@/components/shared/ObjectDrawerHeader';
import { Subtabs } from '@/components/shared/Subtabs';
+import { WebInterfaceLink } from '@/components/shared/WebInterfaceLink';
import { getSimpleStatusIndicator } from '@/utils/status';
import { GUEST_DRAWER_HISTORY_DEFAULT_RANGE } from '@/components/Workloads/guestDrawerModel';
import { ResourceOperatorStateSection } from '@/components/Infrastructure/ResourceOperatorStateSection';
@@ -11,6 +14,7 @@ import { WebInterfaceUrlField } from '@/components/shared/WebInterfaceUrlField';
import type { Resource } from '@/types/resource';
import { asTrimmedString } from '@/utils/stringUtils';
+import { DockerHostActionHistory } from './DockerHostActionHistory';
import { DockerHostDrawerManagement, DockerHostDrawerOverview } from './DockerHostDrawerOverview';
import {
DOCKER_HOST_DRAWER_HISTORY_GROUPS,
@@ -41,6 +45,7 @@ export const DockerHostDrawer: Component<DockerHostDrawerProps> = (props) => {
const metadataId = createMemo(
() => asTrimmedString(props.host.docker?.hostSourceId) || asTrimmedString(props.host.id),
);
+ const customUrl = () => props.customUrl ?? props.host.customUrl ?? '';
return (
<section class="space-y-3" aria-labelledby={headingId()} data-testid="docker-host-drawer">
@@ -59,6 +64,18 @@ export const DockerHostDrawer: Component<DockerHostDrawerProps> = (props) => {
<ObjectDrawerHeader
collapseLabel={`Collapse ${displayName()} details`}
onCollapse={onClose()}
+ actions={
+ <Show when={customUrl().trim()}>
+ <WebInterfaceLink
+ url={customUrl()}
+ ariaLabel={`Open web interface for ${displayName()}`}
+ class={getDrawerHeaderActionButtonClass()}
+ >
+ <ExternalLinkIcon class="h-3.5 w-3.5" aria-hidden="true" />
+ <span>Open</span>
+ </WebInterfaceLink>
+ </Show>
+ }
>
<DrawerSubjectHeading
headingId={headingId()}
@@ -97,22 +114,24 @@ export const DockerHostDrawer: Component<DockerHostDrawerProps> = (props) => {
<div class={`[overflow-anchor:none] ${activeTab() === 'manage' ? '' : 'hidden'}`}>
<Show when={activeTab() === 'manage'}>
+ {/* The guest drawer's Manage order: operator state first, then this
+ platform's own controls, the web interface URL and action history. */}
<div class="space-y-3" data-testid="docker-host-manage-tab">
- <DockerHostDrawerManagement host={props.host} />
<ResourceOperatorStateSection
resourceId={props.host.id}
resourceType="docker-host"
platformType={props.host.platformType || 'docker'}
capabilities={props.host.capabilities}
/>
+ <DockerHostDrawerManagement host={props.host} />
<WebInterfaceUrlField
metadataKind="docker-host"
metadataId={metadataId()}
targetLabel={displayName()}
- title="Access"
- customUrl={props.customUrl ?? props.host.customUrl ?? ''}
+ customUrl={customUrl()}
onCustomUrlChange={props.onCustomUrlChange}
/>
+ <DockerHostActionHistory resourceId={props.host.id} />
</div>
</Show>
</div>
diff --git a/frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx b/frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx
index f9b7a51860..501efa71b4 100644
--- a/frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx
+++ b/frontend-modern/src/features/docker/DockerHostDrawerOverview.tsx
@@ -1,15 +1,19 @@
-import { For, Show, createMemo } from 'solid-js';
+import { For, Show, Suspense, createMemo, lazy } from 'solid-js';
import {
buildDrawerDiskListItems,
type DrawerDiskListItem,
} from '@/components/Workloads/DrawerDiskListCard';
import { AvailabilityProbeStatusCards } from '@/components/Infrastructure/AvailabilityProbeStatusCard';
+import { Button } from '@/components/shared/Button';
import { InfoCardFrame, InfoCardKeyValueRow } from '@/components/shared/InfoCardFrame';
+import { InlineNotice } from '@/components/shared/InlineNotice';
import { TechnicalDetailsDisclosure } from '@/components/shared/TechnicalDetailsDisclosure';
import { DrawerExceptionList } from '@/components/Workloads/DrawerExceptionList';
-import { ALERTS_EMPTY_STATE } from '@/utils/alertOverviewPresentation';
-import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
+import {
+ DrawerAttentionSection,
+ DrawerNoAlertsLine,
+} from '@/components/shared/DrawerAttentionSection';
import {
DetailSectionTable,
compactDetailRows,
@@ -20,6 +24,7 @@ import {
} from '@/components/shared/DetailSectionTable';
import { useResourceDetailDrawerDockerActionsState } from '@/components/Infrastructure/useResourceDetailDrawerDockerActionsState';
import { useWebSocket } from '@/contexts/appRuntime';
+import { getResourceStaleness } from '@/features/platformPage/resourceStaleness';
import { hostOverrideIdCandidates } from '@/features/alerts/alertOverridesModel';
import { alertTypeDisplayLabel } from '@/features/alerts/helpers';
import { getAlertAttentionCopy } from '@/features/alerts/metricAlertPresentation';
@@ -36,19 +41,27 @@ import {
} from '@/utils/format';
import { formatTemperature, getTemperatureTextClass } from '@/utils/temperature';
import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
+import { getSimpleStatusIndicator } from '@/utils/status';
import type { HistoryTimeRange } from '@/api/charts';
-import { GuestDrawerHistory } from '@/components/Workloads/GuestDrawerHistory';
import {
getAlertStatedRowLabels,
getDrawerChartAlerts,
isDrawerAvailabilityHealthy,
partitionDrawerExceptionRows,
} from '@/components/Workloads/drawerOverviewModel';
-import type {
- GuestDrawerHistoryGroupConfig,
- GuestDrawerHistoryTarget,
+import {
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ type GuestDrawerHistoryGroupConfig,
+ type GuestDrawerHistoryTarget,
} from '@/components/Workloads/guestDrawerModel';
+// Loaded once a host drawer opens, so the Docker table chunk does not carry it.
+const GuestDrawerHistory = lazy(() =>
+ import('@/components/Workloads/GuestDrawerHistory').then(({ GuestDrawerHistory }) => ({
+ default: GuestDrawerHistory,
+ })),
+);
+
interface DockerHostDrawerOverviewProps {
host: Resource;
historyTarget?: GuestDrawerHistoryTarget | null;
@@ -97,14 +110,21 @@ const getDetailTone = (valueClass: string | undefined): DetailValueTone => {
const toDetailRows = (rows: DockerOverviewRow[]): DetailRow[] =>
compactDetailRows(
rows.map((row) =>
+ // Details is where a reader goes for the full value; wrap rather than
+ // cut it off behind an ellipsis and a hover-only title.
makeDetailRow(row.label, row.value, {
title: row.title,
tone: getDetailTone(row.valueClass),
+ wrap: true,
}),
),
);
-export function DockerHostDrawerManagement(props: DockerHostDrawerOverviewProps) {
+/**
+ * The host's container update controls for Manage, built like the other
+ * Manage sections: a titled card, key facts, then its actions.
+ */
+export function DockerHostDrawerManagement(props: { host: Resource }) {
const now = useRelativeTimeNow();
const docker = () => props.host.docker;
const hostSourceId = createMemo(() => cleanText(docker()?.hostSourceId) || null);
@@ -132,7 +152,7 @@ export function DockerHostDrawerManagement(props: DockerHostDrawerOverviewProps)
return (
<Show when={hostSourceId() && !summaryOnly()}>
- <InfoCardFrame data-testid="docker-host-management-actions" class="max-w-md">
+ <InfoCardFrame data-testid="docker-host-management-actions">
<h3 class="mb-2 text-[11px] font-medium uppercase tracking-wide text-base-content">
Container updates
</h3>
@@ -150,50 +170,54 @@ export function DockerHostDrawerManagement(props: DockerHostDrawerOverviewProps)
<InfoCardKeyValueRow
label={titleCase(cleanText(hostCommand()?.type).replace(/_/g, ' ') || 'Command')}
value={titleCase(cleanText(hostCommand()?.status).replace(/_/g, ' ') || 'unknown')}
- valueClass={`truncate ${hostCommandActive() ? 'text-sky-700 dark:text-sky-300' : ''}`}
+ valueClass={hostCommandActive() ? 'text-sky-700 dark:text-sky-300' : undefined}
valueTitle={hostCommand()?.failureReason || hostCommand()?.message || undefined}
/>
</Show>
- <Show when={updateActions.dockerActionError()}>
- <div class="rounded-sm border border-red-200 bg-red-50 px-2 py-1.5 text-[10px] text-red-700 dark:border-red-700 dark:bg-red-900/25 dark:text-red-200">
- {updateActions.dockerActionError()}
- </div>
- </Show>
- <Show when={updateActions.dockerActionNote()}>
- <div class="rounded-sm border border-border bg-surface-hover px-2 py-1.5 text-[10px] text-base-content">
- {updateActions.dockerActionNote()}
- </div>
- </Show>
- <div class="flex flex-wrap items-center gap-2 border-t border-border pt-2">
- <button
- type="button"
+ </div>
+ <Show when={updateActions.dockerActionError()}>
+ {(message) => (
+ <InlineNotice tone="danger" role="alert" class="mt-2">
+ {message()}
+ </InlineNotice>
+ )}
+ </Show>
+ <Show when={updateActions.dockerActionNote()}>
+ {(message) => (
+ <InlineNotice tone="info" role="status" class="mt-2">
+ {message()}
+ </InlineNotice>
+ )}
+ </Show>
+ <div class="mt-2 flex flex-wrap items-center gap-2 border-t border-border pt-2">
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={
+ updateActions.dockerActionBusy() || updateActionsLoading() || hostCommandActive()
+ }
+ onClick={() => void updateActions.queueDockerUpdateCheck()}
+ title={updateActionsLoading() ? 'Loading settings...' : undefined}
+ >
+ Check updates
+ </Button>
+ <Show when={!updateAllHidden()}>
+ <Button
+ variant="primaryFlat"
+ size="sm"
disabled={
- updateActions.dockerActionBusy() || updateActionsLoading() || hostCommandActive()
+ updateActions.dockerActionBusy() ||
+ updateActionsLoading() ||
+ hostCommandActive() ||
+ updatesAvailable() <= 0
}
- onClick={() => void updateActions.queueDockerUpdateCheck()}
- class="rounded-md border border-border bg-surface px-2.5 py-1 text-[11px] font-semibold text-base-content hover:bg-surface-hover disabled:opacity-60"
- title={updateActionsLoading() ? 'Loading settings...' : undefined}
+ onClick={() => void updateActions.queueDockerUpdateAll()}
>
- Check updates
- </button>
- <Show when={!updateAllHidden()}>
- <button
- type="button"
- disabled={
- updateActions.dockerActionBusy() ||
- updateActionsLoading() ||
- hostCommandActive() ||
- updatesAvailable() <= 0
- }
- onClick={() => void updateActions.queueDockerUpdateAll()}
- class="rounded-md border border-sky-200 bg-sky-600 px-2.5 py-1 text-[11px] font-semibold text-white hover:bg-sky-700 disabled:opacity-60 disabled:hover:bg-sky-600 dark:border-sky-700 dark:bg-sky-600 dark:hover:bg-sky-500 dark:disabled:hover:bg-sky-600"
- >
- {updateActions.confirmUpdateAll()
- ? 'Confirm update'
- : `Update all${updatesAvailable() > 0 ? ` (${updatesAvailable()})` : ''}`}
- </button>
- </Show>
- </div>
+ {updateActions.confirmUpdateAll()
+ ? 'Confirm update'
+ : `Update all${updatesAvailable() > 0 ? ` (${updatesAvailable()})` : ''}`}
+ </Button>
+ </Show>
</div>
</InfoCardFrame>
</Show>
@@ -378,11 +402,12 @@ export function DockerHostDrawerOverview(props: DockerHostDrawerOverviewProps) {
{ tone: 'danger' },
)
: null,
- makeDetailRow('Runtime', runtimeLabel()),
- makeDetailRow('System', osLabel()),
+ makeDetailRow('Runtime', runtimeLabel(), { wrap: true }),
+ makeDetailRow('System', osLabel(), { wrap: true }),
makeDetailRow(
'Pulse coverage',
linkedAgentId() ? `Agent ${stripAgentPrefix(linkedAgentId())}` : 'Direct API',
+ { wrap: true },
),
typeof docker()?.updatesAvailableCount === 'number' &&
(docker()?.updatesAvailableCount ?? 0) > 0
@@ -413,6 +438,17 @@ export function DockerHostDrawerOverview(props: DockerHostDrawerOverviewProps) {
);
const exceptionRows = () => inventory().lifted;
const detailSections = () => inventory().details;
+ // The table withholds readings from an offline host and dims a stale one;
+ // the charts do the same instead of presenting the last numbers as live.
+ const liveReadingsWithheld = (): string | null => {
+ if (getSimpleStatusIndicator(props.host.status).variant === 'danger') {
+ return 'Docker host is offline. Showing its history only.';
+ }
+ const stale = getResourceStaleness(props.host);
+ if (stale) return `${stale.label}. Showing its history only.`;
+ return null;
+ };
+ const liveMetrics = () => (liveReadingsWithheld() ? undefined : props.currentMetrics);
const sizeFact = (
source: { total?: number; used?: number; free?: number } | undefined,
label: string,
@@ -430,7 +466,9 @@ export function DockerHostDrawerOverview(props: DockerHostDrawerOverviewProps) {
: undefined;
const observation = (source as { observation?: { state?: string } } | undefined)?.observation;
const current = !observation || observation.state === 'current';
- const reporting = props.host.status === 'online' || props.host.status === 'running';
+ const reporting =
+ (props.host.status === 'online' || props.host.status === 'running') &&
+ !liveReadingsWithheld();
return reporting && current && typeof used === 'number' && used >= 0
? `${formatBytes(used)} of ${formatBytes(total)} ${label}`
: `${formatBytes(total)} ${label}`;
@@ -478,26 +516,28 @@ export function DockerHostDrawerOverview(props: DockerHostDrawerOverviewProps) {
<div class="space-y-3">
<DrawerAttentionSection items={attentionItems()} />
<Show when={attentionItems().length === 0}>
- <p data-testid="drawer-no-attention" class="text-xs text-muted">
- <span class="font-medium text-base-content">{ALERTS_EMPTY_STATE}</span>
- <Show when={availabilityHealthy()}>
- <span> · availability checks passing</span>
- </Show>
- </p>
+ <DrawerNoAlertsLine availabilityPassing={availabilityHealthy()} />
</Show>
<DrawerExceptionList testId="docker-host-drawer-exceptions" rows={exceptionRows()} />
<Show when={props.historyTarget}>
- {(target) => (
+ <Show when={liveReadingsWithheld()}>
+ {(message) => (
+ <p data-testid="docker-host-drawer-readings-withheld" class="text-xs text-muted">
+ {message()}
+ </p>
+ )}
+ </Show>
+ <Suspense fallback={<div class="h-48" aria-hidden="true" />}>
<GuestDrawerHistory
- target={target()}
- range={props.historyRange ?? '24h'}
+ target={props.historyTarget ?? null}
+ range={props.historyRange ?? GUEST_DRAWER_HISTORY_DEFAULT_RANGE}
onRangeChange={props.onHistoryRangeChange}
enabled={props.historyEnabled ?? true}
groups={props.historyGroups}
- currentMetrics={props.currentMetrics}
+ currentMetrics={liveMetrics()}
alerts={chartAlerts()}
/>
- )}
+ </Suspense>
</Show>
{/* A failing check stays in front, after the charts as in every drawer. */}
<Show when={availabilityChecks().length > 0 && !availabilityHealthy()}>
@@ -513,7 +553,9 @@ export function DockerHostDrawerOverview(props: DockerHostDrawerOverviewProps) {
data-testid="docker-host-drawer-facts"
class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted"
>
- <For each={facts()}>{(fact) => <span class="wrap-break-word">{fact}</span>}</For>
+ <For each={facts()}>
+ {(fact) => <span class="max-w-full whitespace-normal wrap-anywhere">{fact}</span>}
+ </For>
</div>
</Show>
<Show when={detailSections().length > 0 || availabilityHealthy()}>
diff --git a/frontend-modern/src/features/docker/DockerNativeTableShared.tsx b/frontend-modern/src/features/docker/DockerNativeTableShared.tsx
index a2ab6db18b..5947c58858 100644
--- a/frontend-modern/src/features/docker/DockerNativeTableShared.tsx
+++ b/frontend-modern/src/features/docker/DockerNativeTableShared.tsx
@@ -20,8 +20,6 @@ import { asTrimmedString } from '@/utils/stringUtils';
import {
PlatformTableNumberValue,
formatPlatformTableBytesValue,
- formatPlatformTableDateTimeValue,
- formatPlatformTableRelativeTimeValue,
getPlatformTableCellClassForKind,
} from '@/features/platformPage/sharedPlatformPage';
import { RecordOwnerLink } from '@/features/platformPage/RecordOwnerLink';
@@ -30,6 +28,7 @@ import type { Resource } from '@/types/resource';
import { getPlatformStatusTextToneClass } from '@/features/platformPage/platformStatusTone';
import type { DockerResourceStatusFilter } from './dockerPageModel';
import { DockerImageReferenceText } from './DockerImageReferenceText';
+import { makeDetailTimestampRow } from '@/features/platformPage/platformDetailTimestampRow';
export type DockerNativeTableProps = {
resources: Resource[];
@@ -181,29 +180,13 @@ export const DockerNativeDetailPanel: Component<{
);
};
-// "Oct 2, 2026, 09:13 PM (1h ago)": the absolute time an operator compares
-// with logs, and the age that says whether it matters. Docker reports RFC 3339
-// stamps with nanoseconds, which never read at a glance.
+// Docker reports an unset time as the zero time (0001-01-01), so stamps
+// before 2000 are omitted rather than shown as a date.
export const dockerDetailTimestampRow = (
label: string,
timestamp: string | undefined,
now: number,
-): DetailRow | null => {
- const raw = asTrimmedString(timestamp);
- if (!raw) return null;
- const absolute = formatPlatformTableDateTimeValue(raw, {
- emptyText: '',
- // Docker reports an unset time as the zero time (0001-01-01).
- minYear: 2000,
- dateTimeFormat: { year: 'numeric' },
- });
- if (!absolute) return null;
- const relative = formatPlatformTableRelativeTimeValue(raw, { emptyText: '', now });
- return makeDetailRow(label, relative ? `${absolute} (${relative})` : absolute, {
- title: raw,
- wrap: true,
- });
-};
+): DetailRow | null => makeDetailTimestampRow(label, timestamp, now, { minYear: 2000 });
// Every label, one row each with its key above its value: keys such as
// com.docker.stack.namespace are too long for the label column, and the
diff --git a/frontend-modern/src/features/docker/__tests__/DockerHostsTable.test.tsx b/frontend-modern/src/features/docker/__tests__/DockerHostsTable.test.tsx
index ff8d6b0363..8868b688fb 100644
--- a/frontend-modern/src/features/docker/__tests__/DockerHostsTable.test.tsx
+++ b/frontend-modern/src/features/docker/__tests__/DockerHostsTable.test.tsx
@@ -431,7 +431,7 @@ describe('DockerHostsTable', () => {
const drawer = screen.getByTestId('docker-host-drawer');
fireEvent.click(within(drawer).getByRole('tab', { name: 'Manage' }));
- expect(within(drawer).getByText('Access')).toBeInTheDocument();
+ expect(within(drawer).getByText('Web Interface URL')).toBeInTheDocument();
const input = within(drawer).getByPlaceholderText('https://198.51.100.100:8080');
fireEvent.input(input, { target: { value: 'https://portainer.example:9443' } });
fireEvent.click(within(drawer).getByRole('button', { name: 'Save' }));
@@ -440,9 +440,12 @@ describe('DockerHostsTable', () => {
expect(updateDockerHostMetadataMock).toHaveBeenCalledWith('runtime-stable-id', {
customUrl: 'https://portainer.example:9443',
});
- expect(
- screen.getByRole('link', { name: 'Open web interface for docker-01' }),
- ).toHaveAttribute('href', 'https://portainer.example:9443');
+ // The row link and the drawer header's Open action follow the saved URL.
+ const links = screen.getAllByRole('link', { name: 'Open web interface for docker-01' });
+ expect(links).toHaveLength(2);
+ for (const link of links) {
+ expect(link).toHaveAttribute('href', 'https://portainer.example:9443');
+ }
});
});
diff --git a/frontend-modern/src/features/kubernetes/KubernetesRecordDetail.tsx b/frontend-modern/src/features/kubernetes/KubernetesRecordDetail.tsx
index 66cf314400..b08658d42f 100644
--- a/frontend-modern/src/features/kubernetes/KubernetesRecordDetail.tsx
+++ b/frontend-modern/src/features/kubernetes/KubernetesRecordDetail.tsx
@@ -4,13 +4,8 @@ import {
compactDetailRows,
compactDetailSections,
makeDetailRow,
- type DetailRow,
type DetailSection,
} from '@/components/shared/DetailSectionTable';
-import {
- formatPlatformTableDateTimeValue,
- formatPlatformTableRelativeTimeValue,
-} from '@/features/platformPage/sharedPlatformPage';
import { RecordOwnerLink } from '@/features/platformPage/RecordOwnerLink';
import type { ResourcePageSubject } from '@/features/platformNavigation/resourcePagePath';
import type { Resource } from '@/types/resource';
@@ -18,6 +13,7 @@ import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import type { StatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
import { kubernetesClusterLabel, mapKubernetesEventSeverity } from './kubernetesPageModel';
+import { makeDetailTimestampRow } from '@/features/platformPage/platformDetailTimestampRow';
// Events, ConfigMaps, Secrets, RBAC objects and namespace policies are
// records about a cluster, not objects Pulse monitors: they carry no alerts,
@@ -49,26 +45,7 @@ export const KubernetesRecordDetailPanel: Component<{
);
};
-// "Oct 2, 2026, 09:13 PM (1h ago)": the absolute time an operator compares
-// with `kubectl` output, and the age that says whether it still matters.
-export const kubernetesTimestampRow = (
- label: string,
- timestamp: string | undefined,
- now: number,
-): DetailRow | null => {
- const raw = asTrimmedString(timestamp);
- if (!raw) return null;
- const absolute = formatPlatformTableDateTimeValue(raw, {
- emptyText: '',
- dateTimeFormat: { year: 'numeric' },
- });
- if (!absolute) return makeDetailRow(label, raw, { wrap: true });
- const relative = formatPlatformTableRelativeTimeValue(raw, { emptyText: '', now });
- return makeDetailRow(label, relative ? `${absolute} (${relative})` : absolute, {
- title: raw,
- wrap: true,
- });
-};
+export const kubernetesTimestampRow = makeDetailTimestampRow;
/** Where an object lives: its kind, namespace and cluster, and when it was made. */
export const kubernetesObjectSection = (
diff --git a/frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx b/frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx
index 55e7f23629..1fb2760f36 100644
--- a/frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx
+++ b/frontend-modern/src/features/platformPage/PlatformResourceDetailTableRow.tsx
@@ -121,7 +121,6 @@ export const PlatformResourceDetailTableRow: Component<{
resolveResourceLabel?: (resourceId: string) => string | null | undefined;
initialShowAccessContext?: boolean;
initialShowHostDetails?: boolean;
- initialShowTrueNASDetails?: boolean;
onResourceActionSettled?: () => void | Promise<void>;
onClose?: () => void;
}> = (props) => {
@@ -140,7 +139,6 @@ export const PlatformResourceDetailTableRow: Component<{
resolveResourceLabel={props.resolveResourceLabel}
initialShowAccessContext={props.initialShowAccessContext}
initialShowHostDetails={props.initialShowHostDetails}
- initialShowTrueNASDetails={props.initialShowTrueNASDetails}
onResourceActionSettled={props.onResourceActionSettled}
onClose={props.onClose}
/>
diff --git a/frontend-modern/src/features/platformPage/PlatformWindowedRows.tsx b/frontend-modern/src/features/platformPage/PlatformWindowedRows.tsx
index 81dc870280..5397032089 100644
--- a/frontend-modern/src/features/platformPage/PlatformWindowedRows.tsx
+++ b/frontend-modern/src/features/platformPage/PlatformWindowedRows.tsx
@@ -9,6 +9,7 @@ import {
} from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
+import { createVisibleTableColumnSpan } from '@/components/shared/tableVisibleColumnSpan';
import { usePlatformWindowedItems } from './usePlatformWindowedItems';
export interface PlatformWindowedRowsProps<Row> {
@@ -20,6 +21,7 @@ export interface PlatformWindowedRowsProps<Row> {
* automatically; non-resource rows retain reference-keyed rendering.
*/
keyExtractor?: (item: Row) => string | number;
+ /** Fixed span for the spacer rows; by default they span the visible header cells. */
colSpan?: number;
estimatedRowHeight?: number;
enableThreshold?: number;
@@ -132,6 +134,13 @@ export function PlatformWindowedRows<Row>(props: PlatformWindowedRowsProps<Row>)
windowSize: props.windowSize,
});
+ // Spacer rows span exactly the visible columns: a larger span creates
+ // phantom columns that take the width a phone's visible column
+ // percentages leave over, so rows and drawers stop short of the edge.
+ const [spacerRow, setSpacerRow] = createSignal<HTMLTableRowElement | null>(null);
+ const visibleColumnSpan = createVisibleTableColumnSpan(spacerRow);
+ const spacerSpan = () => props.colSpan ?? visibleColumnSpan();
+
// Keep the For owner mounted when its window changes. Recreating it would
// discard editors and expanded detail state in rows retained by both windows.
const renderRows = (
@@ -148,13 +157,16 @@ export function PlatformWindowedRows<Row>(props: PlatformWindowedRowsProps<Row>)
return (
<Show when={windowing.isWindowed()} fallback={renderRows(renderItems, () => 0)}>
<tr
- ref={windowing.setAnchorRef}
+ ref={(row) => {
+ windowing.setAnchorRef(row);
+ setSpacerRow(row);
+ }}
aria-hidden="true"
data-platform-window-spacer="top"
style={{ height: `${windowing.topSpacerHeight()}px` }}
>
<td
- colspan={props.colSpan ?? 100}
+ colspan={spacerSpan()}
class="p-0!"
style={{ height: `${windowing.topSpacerHeight()}px` }}
/>
@@ -166,7 +178,7 @@ export function PlatformWindowedRows<Row>(props: PlatformWindowedRowsProps<Row>)
style={{ height: `${windowing.bottomSpacerHeight()}px` }}
>
<td
- colspan={props.colSpan ?? 100}
+ colspan={spacerSpan()}
class="p-0!"
style={{ height: `${windowing.bottomSpacerHeight()}px` }}
/>
diff --git a/frontend-modern/src/features/platformPage/__tests__/PlatformWindowedRows.test.tsx b/frontend-modern/src/features/platformPage/__tests__/PlatformWindowedRows.test.tsx
index 6aa10beb60..61a61ce65f 100644
--- a/frontend-modern/src/features/platformPage/__tests__/PlatformWindowedRows.test.tsx
+++ b/frontend-modern/src/features/platformPage/__tests__/PlatformWindowedRows.test.tsx
@@ -46,6 +46,34 @@ describe('PlatformWindowedRows', () => {
expect(container.querySelectorAll('[data-platform-window-spacer]')).toHaveLength(2);
});
+ it('spans spacer rows over the visible header cells only', () => {
+ // A wider span creates phantom fixed-layout columns that take the width a
+ // phone's visible column percentages leave over.
+ const items = () => Array.from({ length: 1_000 }, (_, index) => index);
+ const { container } = render(() => (
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th style={{ display: 'none' }}>Cluster</th>
+ <th colspan={2}>Ready</th>
+ </tr>
+ </thead>
+ <tbody>
+ <PlatformWindowedRows items={items}>
+ {(item) => <tr data-row-id={item} />}
+ </PlatformWindowedRows>
+ </tbody>
+ </table>
+ ));
+
+ const spacerCells = container.querySelectorAll<HTMLTableCellElement>(
+ '[data-platform-window-spacer] > td',
+ );
+ expect(spacerCells).toHaveLength(2);
+ for (const cell of spacerCells) expect(cell.colSpan).toBe(3);
+ });
+
it('preserves keyed row component state when live snapshots replace row objects', async () => {
let mounts = 0;
let disposals = 0;
diff --git a/frontend-modern/src/features/platformPage/__tests__/platformDetailTimestampRow.test.ts b/frontend-modern/src/features/platformPage/__tests__/platformDetailTimestampRow.test.ts
new file mode 100644
index 0000000000..68e123e686
--- /dev/null
+++ b/frontend-modern/src/features/platformPage/__tests__/platformDetailTimestampRow.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { makeDetailTimestampRow } from '../platformDetailTimestampRow';
+
+describe('makeDetailTimestampRow', () => {
+ // A second past the hour, so the fractional stamp below is a full hour old.
+ const now = Date.parse('2026-10-02T22:13:01Z');
+
+ it('shows the absolute time and its age, wrapping, with the raw stamp as its title', () => {
+ const row = makeDetailTimestampRow('Created', '2026-10-02T21:13:00.123456789Z', now);
+ expect(row?.label).toBe('Created');
+ expect(row?.value).toMatch(/2026/);
+ expect(row?.value).toMatch(/\(1h ago\)$/);
+ expect(row?.wrap).toBe(true);
+ expect(row?.title).toBe('2026-10-02T21:13:00.123456789Z');
+ });
+
+ it('omits empty stamps', () => {
+ expect(makeDetailTimestampRow('Created', ' ', now)).toBeNull();
+ expect(makeDetailTimestampRow('Created', undefined, now)).toBeNull();
+ });
+
+ it('reads an unparseable stamp as reported unless a sentinel year is set', () => {
+ expect(makeDetailTimestampRow('Seen', 'yesterday-ish', now)?.value).toBe('yesterday-ish');
+ expect(
+ makeDetailTimestampRow('Started', '0001-01-01T00:00:00Z', now, { minYear: 2000 }),
+ ).toBeNull();
+ });
+});
diff --git a/frontend-modern/src/features/platformPage/__tests__/platformOverviewLayout.guardrails.test.ts b/frontend-modern/src/features/platformPage/__tests__/platformOverviewLayout.guardrails.test.ts
index 6b2fc2829f..a3c2a0743f 100644
--- a/frontend-modern/src/features/platformPage/__tests__/platformOverviewLayout.guardrails.test.ts
+++ b/frontend-modern/src/features/platformPage/__tests__/platformOverviewLayout.guardrails.test.ts
@@ -175,10 +175,9 @@ const proxmoxBespokeTableSources = [
proxmoxReplicationTableSource,
];
-const proxmoxInlineDetailTableSources = [
- proxmoxCephClusterDrawerSource,
- proxmoxMailGatewayDrawerSource,
-];
+// The Ceph cluster drawer shows its pools and daemons as detail-section
+// cards, so only the Mail Gateway's node and domain tables remain here.
+const proxmoxInlineDetailTableSources = [proxmoxMailGatewayDrawerSource];
type JsxTag = ts.JsxOpeningElement | ts.JsxSelfClosingElement;
@@ -361,6 +360,10 @@ describe('platform overview layout guardrails', () => {
expect(source).not.toContain('<tbody');
expect(source).not.toContain('divide-y divide-border-subtle');
}
+ // Ceph pools and daemons are shared detail-section cards, not a hand list.
+ expect(proxmoxCephClusterDrawerSource).toContain('<TechnicalDetailsSection');
+ expect(proxmoxCephClusterDrawerSource).not.toContain('<dl');
+ expect(proxmoxCephClusterDrawerSource).not.toContain('<table');
});
it('keeps Mail Gateway drawer tables prioritized for narrow inline details', () => {
@@ -514,7 +517,6 @@ describe('platform overview layout guardrails', () => {
dockerTasksTableSource,
dockerVolumesTableSource,
proxmoxCoverageTableSource,
- proxmoxMailGatewayDrawerSource,
proxmoxRecoverableTableSource,
vsphereHostsTableSource,
kubernetesAutoscalingTableSource,
@@ -532,6 +534,10 @@ describe('platform overview layout guardrails', () => {
// A block span that ellipsizes in its own cell, toned or not.
expect(source).toMatch(/class=(?:"|\{`)block truncate\b/);
}
+ // Inside a drawer a phone cannot hover a clipped value, so the Mail
+ // Gateway's domain and node names wrap in their cells instead.
+ expect(proxmoxMailGatewayDrawerSource).not.toMatch(/class="[^"]*\btruncate\b/);
+ expect(proxmoxMailGatewayDrawerSource).toContain('block whitespace-normal wrap-anywhere');
});
it('keeps long tablet headers from clipping', () => {
diff --git a/frontend-modern/src/features/platformPage/__tests__/platformResourceTableDrawers.test.tsx b/frontend-modern/src/features/platformPage/__tests__/platformResourceTableDrawers.test.tsx
index da156d265b..764a627f8c 100644
--- a/frontend-modern/src/features/platformPage/__tests__/platformResourceTableDrawers.test.tsx
+++ b/frontend-modern/src/features/platformPage/__tests__/platformResourceTableDrawers.test.tsx
@@ -13,14 +13,12 @@ vi.mock('@/components/Infrastructure/ResourceDetailDrawer', () => ({
ResourceDetailDrawer: (props: {
resource: { id: string };
presentation?: string;
- initialShowTrueNASDetails?: boolean;
onClose?: () => void;
}) => (
<div
data-testid="resource-detail-drawer"
data-resource-id={props.resource.id}
data-presentation={props.presentation ?? 'full'}
- data-initial-show-truenas-details={String(props.initialShowTrueNASDetails ?? false)}
>
<button type="button" aria-label="Close resource drawer" onClick={() => props.onClose?.()} />
</div>
@@ -191,10 +189,6 @@ describe('platform resource table drawers', () => {
'data-resource-id',
pool.id,
);
- expect(screen.getByTestId('resource-detail-drawer')).toHaveAttribute(
- 'data-initial-show-truenas-details',
- 'false',
- );
});
it('opens canonical resource details from vSphere host rows', async () => {
diff --git a/frontend-modern/src/features/platformPage/platformDetailTimestampRow.ts b/frontend-modern/src/features/platformPage/platformDetailTimestampRow.ts
new file mode 100644
index 0000000000..bd26b8ec37
--- /dev/null
+++ b/frontend-modern/src/features/platformPage/platformDetailTimestampRow.ts
@@ -0,0 +1,39 @@
+import { makeDetailRow, type DetailRow } from '@/components/shared/detailSectionModel';
+import { asTrimmedString } from '@/utils/stringUtils';
+import {
+ formatPlatformTableDateTimeValue,
+ formatPlatformTableRelativeTimeValue,
+} from './sharedPlatformPage';
+
+/**
+ * A drawer row for a reported timestamp: "Oct 2, 2026, 09:13 PM (1h ago)".
+ * The absolute time is what an operator compares with logs or CLI output; the
+ * age says whether it still matters. Table rows only have room for the age, so
+ * drawers carry both, wrapping because a phone cell is too narrow for one
+ * line. `now` comes from the shared relative-time clock so an open drawer's
+ * ages keep moving. A stamp that does not parse reads as reported; with
+ * `minYear`, an earlier stamp is a provider's unset sentinel (Docker's
+ * 0001-01-01) and the row is omitted.
+ */
+export const makeDetailTimestampRow = (
+ label: string,
+ timestamp: string | null | undefined,
+ now: number | undefined,
+ options: { minYear?: number } = {},
+): DetailRow | null => {
+ const raw = asTrimmedString(timestamp);
+ if (!raw) return null;
+ const absolute = formatPlatformTableDateTimeValue(raw, {
+ emptyText: '',
+ minYear: options.minYear,
+ dateTimeFormat: { year: 'numeric' },
+ });
+ if (!absolute) {
+ return options.minYear === undefined ? makeDetailRow(label, raw, { wrap: true }) : null;
+ }
+ const relative = formatPlatformTableRelativeTimeValue(raw, { emptyText: '', now });
+ return makeDetailRow(label, relative ? `${absolute} (${relative})` : absolute, {
+ title: raw,
+ wrap: true,
+ });
+};
diff --git a/frontend-modern/src/features/proxmox/ProxmoxCephClusterDrawer.tsx b/frontend-modern/src/features/proxmox/ProxmoxCephClusterDrawer.tsx
index 9d04abd7bb..e532a605f1 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxCephClusterDrawer.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxCephClusterDrawer.tsx
@@ -1,374 +1,240 @@
-import { For, Show, createSignal, type Component } from 'solid-js';
-import { Card } from '@/components/shared/Card';
+import { For, Show, Suspense, createMemo, createSignal, lazy, type Component } from 'solid-js';
+import type { HistoryTimeRange } from '@/api/charts';
+import { useWebSocket } from '@/contexts/appRuntime';
+import { ResourceOperatorStateSection } from '@/components/Infrastructure/ResourceOperatorStateSection';
+import {
+ getResourceMetricsHistoryCurrentMetrics,
+ getResourceMetricsHistoryGroups,
+ getResourceMetricsHistoryTarget,
+} from '@/components/Infrastructure/resourceDetailDrawerMetricsHistoryModel';
+import { DetailSectionTable } from '@/components/shared/DetailSectionTable';
+import {
+ DrawerAttentionSection,
+ DrawerNoAlertsLine,
+} from '@/components/shared/DrawerAttentionSection';
import { DrawerSubjectHeading } from '@/components/shared/DrawerSubjectHeading';
-import { InlineDetailTableRow } from '@/components/shared/InlineDetailTableRow';
+import { InlineNotice } from '@/components/shared/InlineNotice';
import { ObjectDrawerHeader } from '@/components/shared/ObjectDrawerHeader';
-import { ProgressBar } from '@/components/shared/ProgressBar';
-import { StatusDot } from '@/components/shared/StatusDot';
-import { TableCell, TableHead, TableRow } from '@/components/shared/Table';
+import { Subtabs } from '@/components/shared/Subtabs';
import {
- PlatformDetailTable,
- PlatformDetailTableBody,
- PlatformDetailTableHeader,
- formatPlatformTableIntegerValue,
- formatPlatformTablePercentValue,
- getPlatformTableCellClassForKind,
- getPlatformTableHeadClassForKind,
- PlatformResponsiveTableLabel,
- PlatformTableNumberValue,
-} from '@/features/platformPage/sharedPlatformPage';
-import { PlatformResourceDetailToggleButton } from '@/features/platformPage/PlatformResourceDetailTableRow';
-import type { StatusIndicatorVariant } from '@/utils/status';
-import { formatBytes } from '@/utils/format';
-import { getMetricColorClass } from '@/utils/metricThresholds';
+ TechnicalDetailsDisclosure,
+ TechnicalDetailsSection,
+} from '@/components/shared/TechnicalDetailsDisclosure';
+import { DrawerExceptionList } from '@/components/Workloads/DrawerExceptionList';
+import { getDrawerChartAlerts } from '@/components/Workloads/drawerOverviewModel';
+import { GUEST_DRAWER_HISTORY_DEFAULT_RANGE } from '@/components/Workloads/guestDrawerModel';
+import { alertTypeDisplayLabel } from '@/features/alerts/helpers';
+import { getAlertAttentionCopy } from '@/features/alerts/metricAlertPresentation';
+import { useAlertsActivation } from '@/stores/alertsActivation';
+import type { Resource } from '@/types/resource';
+import { getAlertsForUnifiedResource, getOwnAlertsForUnifiedResource } from '@/utils/alerts';
+import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
+import type { StatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
-import type { Resource, ResourceCephServiceMeta } from '@/types/resource';
+import {
+ buildCephClusterContentSections,
+ buildCephClusterDetailSections,
+ getCephClusterExceptionRows,
+ getCephClusterFacts,
+} from './proxmoxCephClusterDrawerModel';
-// Inline drawer that renders below the clicked ceph row. Mirrors the
-// Pulse Workloads pattern (TableRow inserted under the clicked row,
-// spanning all columns), not a slide-over. Surfaces the per-pool and
-// per-service detail the row could only summarize as aggregates, plus
-// a capacity utilization diagram. Deliberately avoids stat-card
-// tiles — duplicating the row numbers in single-stat boxes adds
-// nothing.
+const GuestDrawerHistory = lazy(() =>
+ import('@/components/Workloads/GuestDrawerHistory').then(({ GuestDrawerHistory }) => ({
+ default: GuestDrawerHistory,
+ })),
+);
-function classifyHealth(status: string | undefined): {
- variant: StatusIndicatorVariant;
- label: string;
-} {
- const raw = (status ?? '').toUpperCase();
- if (raw === 'HEALTH_OK' || raw === 'OK') return { variant: 'success', label: 'Healthy' };
- if (raw === 'HEALTH_WARN' || raw === 'WARN') return { variant: 'warning', label: 'Warning' };
- if (raw === 'HEALTH_ERR' || raw === 'ERROR') return { variant: 'danger', label: 'Critical' };
- return { variant: 'muted', label: raw || 'Unknown' };
-}
+// The inline drawer under a Ceph cluster row, in the shape of every object
+// drawer: the row's own dot and name, Overview and Manage tabs, alerts first,
+// then what is worth checking, capacity history, the pools and daemons, a
+// facts line, and the identifiers behind a closed Details.
-function classifyService(svc: ResourceCephServiceMeta): {
- variant: StatusIndicatorVariant;
- label: string;
-} {
- if (svc.total === 0) return { variant: 'muted', label: 'None' };
- if (svc.running >= svc.total) return { variant: 'success', label: 'OK' };
- if (svc.running === 0) return { variant: 'danger', label: 'Down' };
- return { variant: 'warning', label: 'Partial' };
+interface ProxmoxCephClusterDrawerProps {
+ cluster: Resource;
+ /** The indicator behind the row's own health dot; the header repeats it. */
+ statusIndicator: StatusIndicator;
+ onClose: () => void;
}
-// Capacity utilization bar — matches the Workloads row convention:
-// the label sits on top of the fill, not in a legend below. Reuses
-// the shared metric color tokens (bg-metric-normal-bg / warning /
-// critical) so the green/amber/red match the rest of the app exactly
-// (raw bg-emerald-500 was brighter and clashed with the dark label
-// text overlay).
-function capacityToneFor(percent: number): string {
- return getMetricColorClass(percent, 'disk');
-}
+type CephClusterDrawerTab = 'overview' | 'manage';
-function CapacityBar(props: { used: number; total: number; percent: number }) {
- const clamped = Math.max(0, Math.min(100, props.percent));
- return (
- <ProgressBar
- value={clamped}
- class="h-5"
- fillClass={capacityToneFor(clamped)}
- label={
- <span class="absolute inset-0 flex items-center justify-center text-[10px] font-semibold text-base-content leading-none tabular-nums">
- {formatPlatformTablePercentValue(clamped)} · {formatBytes(props.used)} /{' '}
- {formatBytes(props.total)}
- </span>
- }
- />
+const CephClusterOverview: Component<{
+ cluster: Resource;
+ historyRange: HistoryTimeRange;
+ onHistoryRangeChange: (range: HistoryTimeRange) => void;
+ historyEnabled: boolean;
+}> = (props) => {
+ const now = useRelativeTimeNow();
+ const { activeAlerts } = useWebSocket();
+ const alertsActivation = useAlertsActivation();
+ const name = () => asTrimmedString(props.cluster.name) || props.cluster.id;
+ const alerts = createMemo(() =>
+ getAlertsForUnifiedResource(props.cluster, activeAlerts, alertsActivation.detectionEnabled()),
);
-}
+ const historyTarget = createMemo(() => getResourceMetricsHistoryTarget(props.cluster));
+ const historyGroups = createMemo(() => getResourceMetricsHistoryGroups(props.cluster));
+ // The charts describe the cluster itself, so only its own alerts draw a
+ // trigger line on them.
+ const chartAlerts = createMemo(() =>
+ getDrawerChartAlerts(
+ getOwnAlertsForUnifiedResource(
+ props.cluster,
+ activeAlerts,
+ alertsActivation.detectionEnabled(),
+ ),
+ historyGroups().flatMap((group) => group.series.map((series) => series.metric)),
+ ),
+ );
+ const exceptionRows = createMemo(() =>
+ getCephClusterExceptionRows(
+ props.cluster,
+ alerts().map((alert) => alert.message ?? ''),
+ ),
+ );
+ const contentSections = createMemo(() => buildCephClusterContentSections(props.cluster));
+ const hasPools = () => (props.cluster.ceph?.pools ?? []).length > 0;
+ const hasServices = () => (props.cluster.ceph?.services ?? []).length > 0;
+ const facts = createMemo(() => getCephClusterFacts(props.cluster));
+ const detailSections = createMemo(() => buildCephClusterDetailSections(props.cluster));
+ const detailSubtitle = () =>
+ detailSections()
+ .map((section) => section.label.toLowerCase())
+ .join(', ');
-function PoolUsageBar(props: { percent: number }) {
- const clamped = Math.max(0, Math.min(100, props.percent));
return (
- <ProgressBar
- value={clamped}
- class="h-4 w-full min-w-0 max-w-32 md:min-w-14"
- fillClass={capacityToneFor(clamped)}
- label={
- <span class="absolute inset-0 flex items-center justify-center text-[10px] font-semibold text-base-content leading-none tabular-nums">
- {formatPlatformTablePercentValue(clamped)}
- </span>
- }
- />
+ <div class="space-y-3" data-testid="ceph-cluster-drawer-overview">
+ <DrawerAttentionSection
+ items={alerts().map((alert) => ({
+ id: alert.id,
+ ...getAlertAttentionCopy(alert, now),
+ subject: asTrimmedString(alert.resourceName) || name(),
+ metric: alertTypeDisplayLabel(alert.type),
+ severity: alert.level,
+ acknowledged: alert.acknowledged,
+ }))}
+ />
+ <Show when={alerts().length === 0}>
+ <DrawerNoAlertsLine />
+ </Show>
+
+ <DrawerExceptionList testId="ceph-cluster-drawer-exceptions" rows={exceptionRows()} />
+
+ <Show when={historyTarget()}>
+ {(target) => (
+ <Suspense fallback={<div class="h-48" aria-hidden="true" />}>
+ <GuestDrawerHistory
+ target={target()}
+ range={props.historyRange}
+ onRangeChange={props.onHistoryRangeChange}
+ enabled={props.historyEnabled}
+ groups={historyGroups()}
+ currentMetrics={getResourceMetricsHistoryCurrentMetrics(props.cluster)}
+ alerts={chartAlerts()}
+ />
+ </Suspense>
+ )}
+ </Show>
+
+ <Show when={facts().length > 0}>
+ <div
+ data-testid="ceph-cluster-drawer-facts"
+ class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted"
+ >
+ <For each={facts()}>{(fact) => <span class="wrap-break-word">{fact}</span>}</For>
+ </div>
+ </Show>
+
+ <Show when={contentSections().length > 0}>
+ <TechnicalDetailsSection dataTestId="ceph-cluster-cards" sections={contentSections()} />
+ </Show>
+ <Show when={!hasPools() || !hasServices()}>
+ <InlineNotice tone="info" role="status" data-testid="ceph-cluster-content-empty">
+ {!hasPools() && !hasServices()
+ ? 'This cluster has not reported pools or services yet.'
+ : !hasPools()
+ ? 'This cluster has not reported any pools yet.'
+ : 'This cluster has not reported its services yet.'}
+ </InlineNotice>
+ </Show>
+
+ <Show when={detailSections().length > 0}>
+ <TechnicalDetailsDisclosure
+ dataTestId="ceph-cluster-technical-details"
+ title="Details"
+ keepMounted
+ subtitle={detailSubtitle()}
+ class="border-t border-border pt-2"
+ contentClass="mt-2"
+ >
+ <DetailSectionTable sections={detailSections()} />
+ </TechnicalDetailsDisclosure>
+ </Show>
+ </div>
);
-}
+};
-export const ProxmoxCephClusterDrawer: Component<{
- cluster: Resource;
- onClose: () => void;
-}> = (props) => {
- const meta = () => props.cluster.ceph;
- const health = () => classifyHealth(meta()?.healthStatus);
- const pools = () => meta()?.pools ?? [];
- const services = () => meta()?.services ?? [];
- const totalCapacity = () => props.cluster.disk?.total ?? 0;
- const usedCapacity = () => props.cluster.disk?.used ?? 0;
- const usagePercent = () => props.cluster.disk?.current ?? 0;
- const fsid = () => asTrimmedString(meta()?.fsid) || '—';
+const ProxmoxCephClusterDrawerContent: Component<ProxmoxCephClusterDrawerProps> = (props) => {
+ const [activeTab, setActiveTab] = createSignal<CephClusterDrawerTab>('overview');
+ const [historyRange, setHistoryRange] = createSignal<HistoryTimeRange>(
+ GUEST_DRAWER_HISTORY_DEFAULT_RANGE,
+ );
+ const name = () => asTrimmedString(props.cluster.name) || props.cluster.id;
const headingId = () => `proxmox-ceph-cluster-drawer-heading-${props.cluster.id}`;
- const [expandedPoolKey, setExpandedPoolKey] = createSignal<string | null>(null);
return (
- <section class="space-y-3" aria-labelledby={headingId()}>
- <ObjectDrawerHeader
- collapseLabel={`Collapse ${asTrimmedString(props.cluster.name) || props.cluster.id} details`}
- onCollapse={props.onClose}
- >
- <div class="min-w-0 space-y-1">
- <DrawerSubjectHeading
- headingId={headingId()}
- title={asTrimmedString(props.cluster.name) || props.cluster.id}
- statusVariant={health().variant}
- statusLabel={health().label}
- trailing={
- <span class="shrink-0 text-[10px] font-mono text-muted">
- {meta()?.healthStatus ?? ''}
- </span>
- }
- />
- <div class="font-mono text-[10px] text-muted">
- FSID <span class="break-all">{fsid()}</span>
- </div>
- <Show when={meta()?.healthMessage}>
- <p class="text-xs text-amber-700 dark:text-amber-300">{meta()?.healthMessage}</p>
- </Show>
- </div>
+ <section class="space-y-3" aria-labelledby={headingId()} data-testid="ceph-cluster-drawer">
+ <ObjectDrawerHeader collapseLabel={`Collapse ${name()} details`} onCollapse={props.onClose}>
+ <DrawerSubjectHeading
+ headingId={headingId()}
+ title={name()}
+ statusVariant={props.statusIndicator.variant}
+ statusLabel={props.statusIndicator.label}
+ />
</ObjectDrawerHeader>
- <CapacityBar used={usedCapacity()} total={totalCapacity()} percent={usagePercent()} />
+ <Subtabs
+ class="mb-1"
+ ariaLabel="Ceph cluster drawer sections"
+ value={activeTab()}
+ onChange={(value) => setActiveTab(value as CephClusterDrawerTab)}
+ tabs={[
+ { value: 'overview', label: 'Overview' },
+ { value: 'manage', label: 'Manage' },
+ ]}
+ />
- <div class="grid gap-3 lg:grid-cols-2">
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">Pools</h4>
- <span class="text-[10px] text-muted tabular-nums">
- {pools().length} pool{pools().length === 1 ? '' : 's'}
- </span>
- </div>
- <Show
- when={pools().length > 0}
- fallback={<p class="text-xs text-muted">No pools reported.</p>}
- >
- {/* In a narrow card five columns clip every value, and a clipped
- usage label reads as a different number ("0.1%" for 50.1%). The
- object count is the least actionable figure, so it yields its
- track there and stays in the pool expansion. */}
- <PlatformDetailTable class="min-w-0 table-fixed text-xs">
- <PlatformDetailTableHeader>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('name')} platform-table-mobile-w-30 md:w-[24%]`}
- >
- Pool
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} platform-table-phone-hidden md:w-[16%]`}
- >
- Objects
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} platform-table-mobile-w-25 md:w-[20%]`}
- >
- Stored
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} platform-table-mobile-w-25 md:w-[20%]`}
- >
- <PlatformResponsiveTableLabel compact="Avail" full="Available" />
- </TableHead>
- <TableHead
- class={`${getPlatformTableHeadClassForKind('numeric-value')} platform-table-mobile-w-20 md:w-[20%]`}
- >
- Used
- </TableHead>
- </PlatformDetailTableHeader>
- <PlatformDetailTableBody>
- <For each={pools()}>
- {(pool, index) => {
- const poolKey = () => pool.name || `pool-${index()}`;
- const isExpanded = () => expandedPoolKey() === poolKey();
- const detailRowId = () =>
- `proxmox-ceph-pool-detail-${props.cluster.id}-${index()}`;
- const toggle = () =>
- setExpandedPoolKey((current) => (current === poolKey() ? null : poolKey()));
- return (
- <>
- <TableRow class="cursor-pointer" onClick={toggle}>
- <TableCell
- class={`${getPlatformTableCellClassForKind('name')} font-medium text-base-content`}
- >
- <div class="flex min-w-0 items-center gap-1">
- <PlatformResourceDetailToggleButton
- expanded={isExpanded()}
- resourceLabel={pool.name || 'pool'}
- controlsId={detailRowId()}
- onToggle={toggle}
- />
- <span class="truncate" title={pool.name || '—'}>
- {pool.name || '—'}
- </span>
- </div>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content platform-table-phone-hidden`}
- >
- <PlatformTableNumberValue
- value={pool.objects}
- format={formatPlatformTableIntegerValue}
- />
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content tabular-nums`}
- >
- {formatBytes(pool.storedBytes)}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-muted tabular-nums`}
- >
- {formatBytes(pool.availableBytes)}
- </TableCell>
- <TableCell class={getPlatformTableCellClassForKind('numeric-value')}>
- <div class="flex items-center justify-end">
- <PoolUsageBar percent={pool.percentUsed} />
- </div>
- </TableCell>
- </TableRow>
- <Show when={isExpanded()}>
- <InlineDetailTableRow
- cellId={detailRowId()}
- colspan={5}
- data-inline-proxmox-ceph-pool-detail-for={poolKey()}
- >
- <dl class="grid gap-x-4 gap-y-2 text-[11px] sm:grid-cols-2">
- <div class="sm:col-span-2 text-xs font-semibold text-base-content">
- {pool.name || 'Pool'}
- </div>
- <div>
- <dt class="text-[10px] font-medium uppercase tracking-wide text-muted">
- Objects
- </dt>
- <dd class="font-mono text-base-content">
- {formatPlatformTableIntegerValue(pool.objects)}
- </dd>
- </div>
- <div>
- <dt class="text-[10px] font-medium uppercase tracking-wide text-muted">
- Stored
- </dt>
- <dd class="font-mono text-base-content">
- {formatBytes(pool.storedBytes)}
- </dd>
- </div>
- <div>
- <dt class="text-[10px] font-medium uppercase tracking-wide text-muted">
- Available
- </dt>
- <dd class="font-mono text-base-content">
- {formatBytes(pool.availableBytes)}
- </dd>
- </div>
- <div>
- <dt class="text-[10px] font-medium uppercase tracking-wide text-muted">
- Used
- </dt>
- <dd class="font-mono text-base-content">
- {formatPlatformTablePercentValue(pool.percentUsed)}
- </dd>
- </div>
- </dl>
- </InlineDetailTableRow>
- </Show>
- </>
- );
- }}
- </For>
- </PlatformDetailTableBody>
- </PlatformDetailTable>
- </Show>
- </Card>
+ {/* Hidden with CSS rather than unmounted, so switching tabs keeps the
+ scroll position; overflow-anchor stops the browser jumping. */}
+ <div class={`[overflow-anchor:none] ${activeTab() === 'overview' ? '' : 'hidden'}`}>
+ <CephClusterOverview
+ cluster={props.cluster}
+ historyRange={historyRange()}
+ onHistoryRangeChange={setHistoryRange}
+ historyEnabled={activeTab() === 'overview'}
+ />
+ </div>
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">Services</h4>
- <span class="text-[10px] text-muted tabular-nums">
- {services().length} daemon type{services().length === 1 ? '' : 's'}
- </span>
+ <div class={`[overflow-anchor:none] ${activeTab() === 'manage' ? '' : 'hidden'}`}>
+ <Show when={activeTab() === 'manage'}>
+ <div data-testid="ceph-cluster-manage-tab">
+ <ResourceOperatorStateSection
+ resourceId={props.cluster.id}
+ resourceType={props.cluster.type}
+ platformType={props.cluster.platformType}
+ capabilities={props.cluster.capabilities}
+ />
</div>
- <Show
- when={services().length > 0}
- fallback={<p class="text-xs text-muted">No services reported.</p>}
- >
- <PlatformDetailTable class="min-w-0 table-fixed text-xs">
- <PlatformDetailTableHeader>
- <TableHead class={getPlatformTableHeadClassForKind('name')}>Service</TableHead>
- <TableHead class={getPlatformTableHeadClassForKind('text')}>Status</TableHead>
- <TableHead class={getPlatformTableHeadClassForKind('numeric-value')}>
- <PlatformResponsiveTableLabel compact="Up" full="Running" />
- </TableHead>
- <TableHead class={getPlatformTableHeadClassForKind('numeric-value')}>
- Total
- </TableHead>
- </PlatformDetailTableHeader>
- <PlatformDetailTableBody>
- <For each={services()}>
- {(svc) => {
- const cls = classifyService(svc);
- return (
- <TableRow>
- <TableCell
- class={`${getPlatformTableCellClassForKind('name')} font-mono text-[11px] font-semibold text-base-content uppercase`}
- >
- {svc.type}
- </TableCell>
- <TableCell class={getPlatformTableCellClassForKind('text')}>
- <div class="flex items-center gap-2">
- <StatusDot
- size="sm"
- variant={cls.variant}
- title={cls.label}
- ariaHidden
- />
- <span class="text-[11px] font-medium text-base-content">
- {cls.label}
- </span>
- </div>
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content tabular-nums`}
- >
- {svc.running}
- </TableCell>
- <TableCell
- class={`${getPlatformTableCellClassForKind('numeric-value')} text-muted tabular-nums`}
- >
- {svc.total}
- </TableCell>
- </TableRow>
- );
- }}
- </For>
- </PlatformDetailTableBody>
- </PlatformDetailTable>
- </Show>
- </Card>
+ </Show>
</div>
-
- <Show when={(props.cluster.tags ?? []).length > 0}>
- <div class="flex flex-wrap items-center gap-1">
- <span class="text-[10px] uppercase tracking-wide text-muted">Tags</span>
- <For each={props.cluster.tags ?? []}>
- {(tag) => (
- <span class="inline-flex items-center rounded-xs bg-surface-alt px-1.5 py-0.5 text-[10px] font-mono text-base-content">
- {tag}
- </span>
- )}
- </For>
- </div>
- </Show>
</section>
);
};
+// Another cluster must not inherit this one's tab, range or operator form.
+export const ProxmoxCephClusterDrawer: Component<ProxmoxCephClusterDrawerProps> = (props) => (
+ <Show when={props.cluster.id} keyed>
+ {(_clusterId) => <ProxmoxCephClusterDrawerContent {...props} />}
+ </Show>
+);
+
export default ProxmoxCephClusterDrawer;
diff --git a/frontend-modern/src/features/proxmox/ProxmoxCephTable.tsx b/frontend-modern/src/features/proxmox/ProxmoxCephTable.tsx
index 7be8b00b05..7c76d35736 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxCephTable.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxCephTable.tsx
@@ -413,7 +413,8 @@ export const ProxmoxCephTable: Component<{
<>
<PlatformWindowedRows items={filtered} estimatedRowHeight={32}>
{(cluster) => {
- const ind = indicatorFor(classify(cluster));
+ // One verdict for the row's dot and the drawer header.
+ const ind = () => indicatorFor(classify(cluster));
const name = asTrimmedString(cluster.name) || cluster.id;
const isOpen = () => selectedId() === cluster.id;
const detailRowId = () => `proxmox-ceph-detail-${cluster.id}`;
@@ -443,18 +444,20 @@ export const ProxmoxCephTable: Component<{
</TableCell>
<TableCell
class={getPlatformTableCellClassForKind('text')}
- title={[ind.label, cluster.ceph?.healthStatus]
+ title={[ind().label, cluster.ceph?.healthStatus]
.filter(Boolean)
.join(' · ')}
>
<div class="flex items-center gap-2">
<StatusDot
size="sm"
- variant={ind.variant}
- title={ind.label}
+ variant={ind().variant}
+ title={ind().label}
ariaHidden
/>
- <span class={`text-[11px] font-medium ${ind.tone}`}>{ind.label}</span>
+ <span class={`text-[11px] font-medium ${ind().tone}`}>
+ {ind().label}
+ </span>
</div>
</TableCell>
<Show when={showQuorum()}>
@@ -512,7 +515,11 @@ export const ProxmoxCephTable: Component<{
colspan={visibleColumnCount()}
data-inline-detail-for={cluster.id}
>
- <ProxmoxCephClusterDrawer cluster={cluster} onClose={closeSelected} />
+ <ProxmoxCephClusterDrawer
+ cluster={cluster}
+ statusIndicator={{ variant: ind().variant, label: ind().label }}
+ onClose={closeSelected}
+ />
</InlineDetailTableRow>
</Show>
</>
diff --git a/frontend-modern/src/features/proxmox/ProxmoxMailGatewayDrawer.tsx b/frontend-modern/src/features/proxmox/ProxmoxMailGatewayDrawer.tsx
index abc1b9b9ed..81c9021994 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxMailGatewayDrawer.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxMailGatewayDrawer.tsx
@@ -1,15 +1,16 @@
-import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { For, Show, createMemo, createResource, type Component } from 'solid-js';
-import { DrawerAttentionSection } from '@/components/shared/DrawerAttentionSection';
-import { alertTypeDisplayLabel } from '@/features/alerts/helpers';
-import { getAlertAttentionCopy } from '@/features/alerts/metricAlertPresentation';
-import type { Alert } from '@/types/api';
-import { Card } from '@/components/shared/Card';
-import { DrawerSubjectHeading } from '@/components/shared/DrawerSubjectHeading';
-import { InfoCardKeyValueRow } from '@/components/shared/InfoCardFrame';
-import { ObjectDrawerHeader } from '@/components/shared/ObjectDrawerHeader';
+import {
+ compactDetailRows,
+ compactDetailSections,
+ makeDetailRow,
+ type DetailSection,
+} from '@/components/shared/DetailSectionTable';
+import { InfoCardFrame } from '@/components/shared/InfoCardFrame';
+import { InlineNotice } from '@/components/shared/InlineNotice';
+import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
import { StatusDot } from '@/components/shared/StatusDot';
import { TableCell, TableHead, TableRow } from '@/components/shared/Table';
+import { TechnicalDetailsSection } from '@/components/shared/TechnicalDetailsDisclosure';
import {
PlatformDetailTable,
PlatformDetailTableBody,
@@ -26,15 +27,22 @@ import type { StatusIndicatorVariant } from '@/utils/status';
import { formatBytes } from '@/utils/format';
import { asTrimmedString } from '@/utils/stringUtils';
import { apiFetch } from '@/utils/apiClient';
-import type { PMGInstance, PMGNodeStatus, PMGQueueStatus, PMGSpamBucket } from '@/types/api';
+import type {
+ PMGInstance,
+ PMGMailStats,
+ PMGNodeStatus,
+ PMGQuarantineTotals,
+ PMGQueueStatus,
+ PMGRelayDomain,
+ PMGSpamBucket,
+} from '@/types/api';
import type { Resource } from '@/types/resource';
-// Inline drawer for a single Proxmox Mail Gateway instance. Drops the
-// per-stat tile pattern in favor of stacked-bar diagrams that show the
-// SHAPE of mail flow + quarantine + spam-score distribution at a
-// glance, paired with proper info-dense tables for cluster nodes and
-// top domains. Fetches the full PMGInstance on first open from
-// /api/pmg/instances so the row keeps its slim payload.
+// The Mail tab of a Mail Gateway's resource drawer: mail flow, quarantine,
+// spam scores, per-node queues and the busiest domains. The drawer around it
+// owns the header, status, alerts and history, so this body is headless. It
+// fetches the full PMGInstance when the tab opens so the row keeps its slim
+// payload.
interface PMGInstancesResponse {
data: PMGInstance[];
@@ -50,21 +58,6 @@ async function fetchPMGInstance(id: string): Promise<PMGInstance | null> {
return payload?.data?.[0] ?? null;
}
-function classifyHealth(status: string | undefined): {
- variant: StatusIndicatorVariant;
- label: string;
-} {
- const raw = (status ?? '').toLowerCase();
- if (raw === 'online' || raw === 'ok' || raw === 'healthy') {
- return { variant: 'success', label: 'Healthy' };
- }
- if (raw === 'degraded' || raw === 'warning') return { variant: 'warning', label: 'Degraded' };
- if (raw === 'offline' || raw === 'error' || raw === 'critical') {
- return { variant: 'danger', label: 'Offline' };
- }
- return { variant: 'muted', label: raw || 'Unknown' };
-}
-
function classifyNode(node: PMGNodeStatus): { variant: StatusIndicatorVariant; label: string } {
const raw = (node.status ?? '').toLowerCase();
if (raw === 'online' || raw === 'ok') return { variant: 'success', label: 'Online' };
@@ -89,10 +82,16 @@ function queueCell(queue: PMGQueueStatus | undefined): { count: number; label: s
};
}
+const inOut = (inValue: number | undefined, outValue: number | undefined): string =>
+ `${formatPlatformTableIntegerValue(inValue ?? 0, '0')} / ${formatPlatformTableIntegerValue(outValue ?? 0, '0')}`;
+
+const bytesOrDash = (value: number | undefined): string =>
+ value && value > 0 ? formatBytes(value) : '—';
+
// StackedBar renders a horizontal stacked bar from labelled segments.
// Each segment carries a tone (color), value, and label; segments with
-// 0 value collapse out. A legend with name + count + share renders
-// below.
+// 0 value collapse out. An optional legend with name + count + share
+// renders below.
interface StackedSegment {
key: string;
label: string;
@@ -100,7 +99,7 @@ interface StackedSegment {
tone: string;
}
-function StackedBar(props: { segments: StackedSegment[]; ariaLabel: string }) {
+function StackedBar(props: { segments: StackedSegment[]; ariaLabel: string; legend?: boolean }) {
const total = createMemo(() => props.segments.reduce((sum, s) => sum + Math.max(0, s.value), 0));
const visible = createMemo(() => props.segments.filter((s) => s.value > 0));
return (
@@ -125,27 +124,29 @@ function StackedBar(props: { segments: StackedSegment[]; ariaLabel: string }) {
</For>
</div>
</Show>
- <div class="flex flex-wrap gap-x-3 gap-y-1 text-[11px]">
- <For each={props.segments}>
- {(seg) => {
- const share = total() > 0 ? (seg.value / total()) * 100 : 0;
- return (
- <div class="flex items-center gap-1.5">
- <span class={`inline-block h-2 w-2 rounded-xs ${seg.tone}`} aria-hidden="true" />
- <span class="text-muted">{seg.label}</span>
- <span class="text-base-content font-semibold tabular-nums">
- {formatPlatformTableIntegerValue(seg.value)}
- </span>
- <Show when={total() > 0}>
- <span class="text-muted tabular-nums text-[10px]">
- {formatPlatformTablePercentValue(share)}
+ <Show when={props.legend !== false}>
+ <div class="flex flex-wrap gap-x-3 gap-y-1 text-[11px]">
+ <For each={props.segments}>
+ {(seg) => {
+ const share = total() > 0 ? (seg.value / total()) * 100 : 0;
+ return (
+ <div class="flex items-center gap-1.5">
+ <span class={`inline-block h-2 w-2 rounded-xs ${seg.tone}`} aria-hidden="true" />
+ <span class="text-muted">{seg.label}</span>
+ <span class="text-base-content font-semibold tabular-nums">
+ {formatPlatformTableIntegerValue(seg.value)}
</span>
- </Show>
- </div>
- );
- }}
- </For>
- </div>
+ <Show when={total() > 0}>
+ <span class="text-muted tabular-nums text-[10px]">
+ {formatPlatformTablePercentValue(share)}
+ </span>
+ </Show>
+ </div>
+ );
+ }}
+ </For>
+ </div>
+ </Show>
</div>
);
}
@@ -186,316 +187,217 @@ function SpamHistogram(props: { buckets: PMGSpamBucket[] }) {
);
}
-// InOutBar shows paired values (e.g. mail in vs mail out) as two
-// adjacent half-bars sharing a max scale. The label sits ABOVE the
-// bar and the values sit ON the bar segments — matches the Workloads
-// MetricBar convention of writing the value on the fill.
-function InOutBar(props: {
- label: string;
- inValue: number;
- outValue: number;
- format?: (value: number) => string;
-}) {
- const format = props.format ?? formatPlatformTableIntegerValue;
- const max = Math.max(props.inValue, props.outValue, 1);
- const inWidth = (props.inValue / max) * 50;
- const outWidth = (props.outValue / max) * 50;
- return (
- <div class="space-y-1">
- <div class="text-[11px] text-muted">{props.label}</div>
- <div
- class="relative flex h-4 w-full overflow-hidden rounded-sm bg-surface-hover"
- title={`In ${format(props.inValue)} · Out ${format(props.outValue)}`}
- >
- <div class="relative bg-blue-500/60" style={{ width: `${inWidth}%` }} />
- <div class="w-px bg-surface" />
- <div class="relative bg-purple-500/60" style={{ width: `${outWidth}%` }} />
- <span class="pointer-events-none absolute inset-0 flex items-center justify-between px-1.5 text-[10px] font-semibold text-base-content leading-none tabular-nums">
- <span>In {format(props.inValue)}</span>
- <span>Out {format(props.outValue)}</span>
- </span>
- </div>
- </div>
+const inboundSegments = (stats: PMGMailStats): StackedSegment[] => {
+ const countIn = Math.max(0, stats.countIn ?? 0);
+ const spam = Math.max(0, stats.spamIn ?? 0);
+ const virus = Math.max(0, stats.virusIn ?? 0);
+ const bounces = Math.max(0, stats.bouncesIn ?? 0);
+ const greylist = Math.max(0, stats.greylistCount ?? 0);
+ const rbl = Math.max(0, stats.rblRejects ?? 0);
+ const pregreet = Math.max(0, stats.pregreetRejects ?? 0);
+ const clean = Math.max(0, countIn - (spam + virus + bounces));
+ return [
+ { key: 'clean', label: 'Clean', value: clean, tone: 'bg-metric-normal-bg' },
+ { key: 'spam', label: 'Spam', value: spam, tone: 'bg-metric-warning-bg' },
+ { key: 'virus', label: 'Virus', value: virus, tone: 'bg-metric-critical-bg' },
+ { key: 'bounces', label: 'Bounces', value: bounces, tone: 'bg-orange-500/60' },
+ { key: 'greylist', label: 'Greylist', value: greylist, tone: 'bg-blue-500/60' },
+ { key: 'rbl', label: 'RBL', value: rbl, tone: 'bg-purple-500/60' },
+ { key: 'pregreet', label: 'Pregreet', value: pregreet, tone: 'bg-slate-500/60' },
+ ];
+};
+
+const quarantineSegments = (quarantine: PMGQuarantineTotals): StackedSegment[] => [
+ { key: 'spam', label: 'Spam', value: quarantine.spam ?? 0, tone: 'bg-metric-warning-bg' },
+ { key: 'virus', label: 'Virus', value: quarantine.virus ?? 0, tone: 'bg-metric-critical-bg' },
+ {
+ key: 'attachment',
+ label: 'Attachment',
+ value: quarantine.attachment ?? 0,
+ tone: 'bg-orange-500/60',
+ },
+ {
+ key: 'blacklisted',
+ label: 'Blacklisted',
+ value: quarantine.blacklisted ?? 0,
+ tone: 'bg-slate-500/60',
+ },
+];
+
+const relayDomainLabel = (domain: PMGRelayDomain): string => {
+ const comment = asTrimmedString(domain.comment);
+ return comment ? `${domain.domain} (${comment})` : domain.domain;
+};
+
+// The mail-flow content cards: each figure is a detail row, and the two
+// pictures (inbound disposition, spam scores) sit under their card's rows.
+export const buildMailGatewayMailFlowSections = (instance: PMGInstance): DetailSection[] => {
+ const stats = instance.mailStats;
+ const quarantine = instance.quarantine;
+ const spamBuckets = instance.spamDistribution ?? [];
+ const relayDomains = (instance.relayDomains ?? []).filter((domain) =>
+ asTrimmedString(domain.domain),
);
-}
+ const timeframe = asTrimmedString(stats?.timeframe);
+ return compactDetailSections([
+ stats
+ ? {
+ label: timeframe ? `Mail flow (${timeframe})` : 'Mail flow',
+ testId: 'pmg-mail-flow-section',
+ rows: compactDetailRows([
+ makeDetailRow('Mail in / out', inOut(stats.countIn, stats.countOut)),
+ makeDetailRow('Spam in / out', inOut(stats.spamIn, stats.spamOut)),
+ makeDetailRow('Virus in / out', inOut(stats.virusIn, stats.virusOut)),
+ makeDetailRow('Bounces in / out', inOut(stats.bouncesIn, stats.bouncesOut)),
+ makeDetailRow(
+ 'Bytes in / out',
+ `${bytesOrDash(stats.bytesIn)} / ${bytesOrDash(stats.bytesOut)}`,
+ ),
+ makeDetailRow('Greylisted', formatPlatformTableIntegerValue(stats.greylistCount, '0')),
+ makeDetailRow('Junk in', formatPlatformTableIntegerValue(stats.junkIn, '0')),
+ makeDetailRow('RBL rejects', formatPlatformTableIntegerValue(stats.rblRejects, '0')),
+ makeDetailRow(
+ 'Pregreet rejects',
+ formatPlatformTableIntegerValue(stats.pregreetRejects, '0'),
+ ),
+ makeDetailRow(
+ 'Avg process',
+ stats.averageProcessTimeMs ? `${Math.round(stats.averageProcessTimeMs)}ms` : '—',
+ ),
+ ]),
+ footerContent: (
+ <StackedBar
+ segments={inboundSegments(stats)}
+ ariaLabel="Inbound mail disposition breakdown"
+ />
+ ),
+ }
+ : null,
+ quarantine
+ ? {
+ label: 'Quarantine',
+ testId: 'pmg-quarantine-section',
+ rows: compactDetailRows(
+ quarantineSegments(quarantine).map((segment) =>
+ makeDetailRow(segment.label, formatPlatformTableIntegerValue(segment.value, '0')),
+ ),
+ ),
+ footerContent: (
+ <StackedBar
+ segments={quarantineSegments(quarantine)}
+ ariaLabel="Quarantine breakdown by category"
+ legend={false}
+ />
+ ),
+ }
+ : null,
+ spamBuckets.length > 0
+ ? {
+ label: 'Spam scores',
+ testId: 'pmg-spam-scores-section',
+ rows: compactDetailRows([
+ makeDetailRow(
+ 'Buckets',
+ `${spamBuckets.length} bucket${spamBuckets.length === 1 ? '' : 's'}`,
+ ),
+ ]),
+ footerContent: <SpamHistogram buckets={spamBuckets} />,
+ }
+ : null,
+ relayDomains.length > 0
+ ? {
+ label: 'Relay domains',
+ testId: 'pmg-relay-domains-section',
+ rows: compactDetailRows([
+ makeDetailRow('Domains', relayDomains.map(relayDomainLabel).join(', '), {
+ wrap: true,
+ }),
+ ]),
+ }
+ : null,
+ ]);
+};
-export const ProxmoxMailGatewayDrawer: Component<{
- instanceRow: Resource;
- onClose?: () => void;
- /** Open alerts for this gateway, matched across its identity aliases by the table. */
- alerts?: Alert[];
-}> = (props) => {
- const id = () => {
- const meta = props.instanceRow.pmg;
- return asTrimmedString(meta?.instanceId) || props.instanceRow.id;
- };
+const CARD_HEADING_CLASS = 'text-[10px] font-semibold uppercase tracking-wide text-base-content';
+
+export const ProxmoxMailGatewayMailFlow: Component<{ resource: Resource }> = (props) => {
+ const id = () => asTrimmedString(props.resource.pmg?.instanceId) || props.resource.id;
const [instance, { refetch }] = createResource<PMGInstance | null, string>(id, fetchPMGInstance);
- const now = useRelativeTimeNow();
- const stats = createMemo(() => instance()?.mailStats);
- const quarantine = createMemo(() => instance()?.quarantine);
- const nodes = createMemo<PMGNodeStatus[]>(() => instance()?.nodes ?? []);
- const spamBuckets = createMemo<PMGSpamBucket[]>(() => instance()?.spamDistribution ?? []);
+ // Solid rethrows a resource's error when it is read, so every read goes
+ // through this guard and the failure renders as a notice below.
+ const failed = () => instance.state === 'errored';
+ const loaded = createMemo(() => (failed() ? undefined : instance()));
+ const nodes = createMemo<PMGNodeStatus[]>(() => loaded()?.nodes ?? []);
const topDomains = createMemo(() =>
- (instance()?.domainStats ?? [])
+ (loaded()?.domainStats ?? [])
.slice()
.sort((a, b) => (b.mailCount ?? 0) - (a.mailCount ?? 0))
.slice(0, 8),
);
- const relayDomains = createMemo(() => instance()?.relayDomains ?? []);
-
- // A reachable gateway with open alerts reads as needing attention, matching
- // its table row, rather than a green "Healthy" beside the alert below.
- const health = () => {
- const base = classifyHealth(instance()?.status ?? props.instanceRow.status);
- const open = (props.alerts ?? []).filter((alert) => !alert.acknowledged);
- if (open.length === 0 || base.variant === 'danger') return base;
- return {
- variant: open.some((alert) => alert.level === 'critical')
- ? ('danger' as const)
- : ('warning' as const),
- label: 'Needs attention',
- };
- };
- const name = () =>
- asTrimmedString(instance()?.name) ||
- asTrimmedString(props.instanceRow.name) ||
- props.instanceRow.id;
- const version = () =>
- asTrimmedString(instance()?.version) || asTrimmedString(props.instanceRow.pmg?.version) || '—';
- const hostname = () => asTrimmedString(instance()?.host);
-
- const inboundSegments = createMemo<StackedSegment[]>(() => {
- const s = stats();
- if (!s) return [];
- const countIn = Math.max(0, s.countIn ?? 0);
- const spam = Math.max(0, s.spamIn ?? 0);
- const virus = Math.max(0, s.virusIn ?? 0);
- const bounces = Math.max(0, s.bouncesIn ?? 0);
- const greylist = Math.max(0, s.greylistCount ?? 0);
- const rbl = Math.max(0, s.rblRejects ?? 0);
- const pregreet = Math.max(0, s.pregreetRejects ?? 0);
- const flagged = spam + virus + bounces;
- const clean = Math.max(0, countIn - flagged);
- return [
- { key: 'clean', label: 'Clean', value: clean, tone: 'bg-metric-normal-bg' },
- { key: 'spam', label: 'Spam', value: spam, tone: 'bg-metric-warning-bg' },
- { key: 'virus', label: 'Virus', value: virus, tone: 'bg-metric-critical-bg' },
- { key: 'bounces', label: 'Bounces', value: bounces, tone: 'bg-orange-500/60' },
- { key: 'greylist', label: 'Greylist', value: greylist, tone: 'bg-blue-500/60' },
- { key: 'rbl', label: 'RBL', value: rbl, tone: 'bg-purple-500/60' },
- { key: 'pregreet', label: 'Pregreet', value: pregreet, tone: 'bg-slate-500/60' },
- ];
+ const flowSections = createMemo(() => {
+ const value = loaded();
+ return value ? buildMailGatewayMailFlowSections(value) : [];
});
-
- const quarantineSegments = createMemo<StackedSegment[]>(() => {
- const q = quarantine();
- if (!q) return [];
- return [
- { key: 'spam', label: 'Spam', value: q.spam ?? 0, tone: 'bg-metric-warning-bg' },
- { key: 'virus', label: 'Virus', value: q.virus ?? 0, tone: 'bg-metric-critical-bg' },
- {
- key: 'attachment',
- label: 'Attachment',
- value: q.attachment ?? 0,
- tone: 'bg-orange-500/60',
- },
- {
- key: 'blacklisted',
- label: 'Blacklisted',
- value: q.blacklisted ?? 0,
- tone: 'bg-slate-500/60',
- },
- ];
- });
-
- const headingId = () => `proxmox-mail-gateway-drawer-heading-${id()}`;
+ const name = () =>
+ asTrimmedString(props.resource.displayName) ||
+ asTrimmedString(props.resource.name) ||
+ props.resource.id;
+ const facts = () =>
+ [
+ asTrimmedString(loaded()?.version) || asTrimmedString(props.resource.pmg?.version),
+ asTrimmedString(loaded()?.host),
+ ].filter((fact): fact is string => Boolean(fact));
return (
- <section class="space-y-3" aria-labelledby={headingId()}>
- <Show
- when={props.onClose}
- fallback={
- <div class="min-w-0 space-y-1">
- <DrawerSubjectHeading
- headingId={headingId()}
- title={name()}
- statusVariant={health().variant}
- statusLabel={health().label}
- trailing={<span class="shrink-0 text-[10px] font-mono text-muted">{version()}</span>}
- />
- <Show when={hostname()}>
- <div class="font-mono text-[10px] text-muted break-all">{hostname()}</div>
- </Show>
- </div>
- }
- >
- {(onClose) => (
- <ObjectDrawerHeader collapseLabel={`Collapse ${name()} details`} onCollapse={onClose()}>
- <div class="min-w-0 space-y-1">
- <DrawerSubjectHeading
- headingId={headingId()}
- title={name()}
- statusVariant={health().variant}
- statusLabel={health().label}
- trailing={
- <span class="shrink-0 text-[10px] font-mono text-muted">{version()}</span>
- }
- />
- <Show when={hostname()}>
- <div class="font-mono text-[10px] text-muted break-all">{hostname()}</div>
- </Show>
- </div>
- </ObjectDrawerHeader>
- )}
- </Show>
-
- {/* The exact problem first: a phone cannot hover the row's short reason. */}
- <DrawerAttentionSection
- items={(props.alerts ?? []).map((alert) => ({
- id: alert.id,
- ...getAlertAttentionCopy(alert, now),
- subject: name(),
- metric: alertTypeDisplayLabel(alert.type),
- severity: alert.level,
- acknowledged: alert.acknowledged,
- }))}
- />
-
+ <div class="space-y-3" data-testid="pmg-mail-flow">
<Show
- when={!instance.error}
+ when={!failed()}
fallback={
- <Card padding="md">
- <p class="text-xs text-red-600 dark:text-red-300">
- Failed to load Mail Gateway detail.
- </p>
- <button
- type="button"
- onClick={() => void refetch()}
- class="mt-2 inline-flex min-h-9 items-center rounded-md border border-border px-3 text-sm font-medium hover:bg-surface-hover"
- >
- Retry
- </button>
- </Card>
+ <InlineNotice
+ tone="danger"
+ role="alert"
+ actionLabel="Retry"
+ actionAriaLabel={`Retry loading mail flow for ${name()}`}
+ actionOnClick={() => void refetch()}
+ >
+ Could not load mail flow for {name()}.
+ </InlineNotice>
}
>
<Show
- when={instance() !== undefined}
- fallback={<p class="text-xs text-muted">Loading Mail Gateway detail…</p>}
+ when={loaded() !== undefined}
+ fallback={
+ <p role="status" class="flex items-center gap-2 text-xs text-muted">
+ <LoadingSpinner size="sm" tone="muted" />
+ Loading mail flow
+ </p>
+ }
>
<Show
- when={instance()}
- fallback={<p class="text-xs text-muted">No detail available for this instance.</p>}
+ when={loaded()}
+ fallback={
+ <InlineNotice tone="info" role="status">
+ This gateway has not reported mail flow yet.
+ </InlineNotice>
+ }
>
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
- Inbound disposition
- </h4>
- <span class="text-[10px] text-muted">{stats()?.timeframe ?? ''}</span>
- </div>
- <Show
- when={stats()}
- fallback={<p class="text-xs text-muted">No mail stats reported.</p>}
+ <Show when={facts().length > 0}>
+ <div
+ data-testid="pmg-mail-flow-facts"
+ class="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted"
>
- <StackedBar
- segments={inboundSegments()}
- ariaLabel="Inbound mail disposition breakdown"
- />
- <div class="mt-3 grid grid-cols-2 gap-x-4 gap-y-1 text-[11px] sm:grid-cols-4">
- <InOutBar
- label="Mail in / out"
- inValue={stats()!.countIn ?? 0}
- outValue={stats()!.countOut ?? 0}
- />
- <InOutBar
- label="Spam in / out"
- inValue={stats()!.spamIn ?? 0}
- outValue={stats()!.spamOut ?? 0}
- />
- <InOutBar
- label="Virus in / out"
- inValue={stats()!.virusIn ?? 0}
- outValue={stats()!.virusOut ?? 0}
- />
- <InOutBar
- label="Bounces in / out"
- inValue={stats()!.bouncesIn ?? 0}
- outValue={stats()!.bouncesOut ?? 0}
- />
- <InOutBar
- label="Bytes in / out"
- inValue={stats()!.bytesIn ?? 0}
- outValue={stats()!.bytesOut ?? 0}
- format={(v) => (v > 0 ? formatBytes(v) : '—')}
- />
- <InfoCardKeyValueRow
- class="col-span-2 text-[11px] sm:col-span-1"
- label="Greylist / Junk in"
- value={`${formatPlatformTableIntegerValue(stats()!.greylistCount)} / ${formatPlatformTableIntegerValue(stats()!.junkIn)}`}
- valueClass="font-mono text-[10px]"
- />
- <InfoCardKeyValueRow
- class="col-span-2 text-[11px] sm:col-span-1"
- label="RBL / Pregreet rejects"
- value={`${formatPlatformTableIntegerValue(stats()!.rblRejects)} / ${formatPlatformTableIntegerValue(stats()!.pregreetRejects)}`}
- valueClass="font-mono text-[10px]"
- />
- <InfoCardKeyValueRow
- class="col-span-2 text-[11px] sm:col-span-1"
- label="Avg process"
- value={
- stats()?.averageProcessTimeMs
- ? `${Math.round(stats()!.averageProcessTimeMs)}ms`
- : '—'
- }
- valueClass="font-mono text-[10px]"
- />
- </div>
- </Show>
- </Card>
-
- <div class="grid gap-3 lg:grid-cols-2">
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
- Quarantine
- </h4>
- </div>
- <Show
- when={quarantine()}
- fallback={<p class="text-xs text-muted">No quarantine data reported.</p>}
- >
- <StackedBar
- segments={quarantineSegments()}
- ariaLabel="Quarantine breakdown by category"
- />
- </Show>
- </Card>
+ <For each={facts()}>{(fact) => <span class="wrap-anywhere">{fact}</span>}</For>
+ </div>
+ </Show>
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
- Spam score distribution
- </h4>
- <span class="text-[10px] text-muted tabular-nums">
- {spamBuckets().length} bucket{spamBuckets().length === 1 ? '' : 's'}
- </span>
- </div>
- <Show
- when={spamBuckets().length > 0}
- fallback={<p class="text-xs text-muted">No spam score data.</p>}
- >
- <SpamHistogram buckets={spamBuckets()} />
- </Show>
- </Card>
- </div>
+ <Show when={flowSections().length > 0}>
+ <TechnicalDetailsSection dataTestId="pmg-mail-flow-cards" sections={flowSections()} />
+ </Show>
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
- Cluster nodes
- </h4>
+ <InfoCardFrame data-testid="pmg-cluster-nodes">
+ <div class="mb-2 flex items-baseline justify-between gap-2">
+ <h3 class={CARD_HEADING_CLASS}>Cluster nodes</h3>
<span class="text-[10px] text-muted tabular-nums">
{nodes().length} node{nodes().length === 1 ? '' : 's'}
</span>
@@ -545,14 +447,15 @@ export const ProxmoxMailGatewayDrawer: Component<{
return (
<TableRow>
<TableCell class={getPlatformTableCellClassForKind('name')}>
- <div class="flex items-center gap-2">
+ <div class="flex min-w-0 items-start gap-2">
<StatusDot
size="sm"
variant={cls.variant}
title={cls.label}
ariaHidden
+ class="mt-1"
/>
- <span class="font-mono text-[11px] font-semibold text-base-content">
+ <span class="min-w-0 whitespace-normal font-mono text-[11px] font-semibold text-base-content wrap-anywhere">
{node.name || '—'}
</span>
</div>
@@ -602,13 +505,11 @@ export const ProxmoxMailGatewayDrawer: Component<{
</PlatformDetailTableBody>
</PlatformDetailTable>
</Show>
- </Card>
+ </InfoCardFrame>
- <Card padding="md">
- <div class="mb-2 flex items-baseline justify-between">
- <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
- Top domains
- </h4>
+ <InfoCardFrame data-testid="pmg-top-domains">
+ <div class="mb-2 flex items-baseline justify-between gap-2">
+ <h3 class={CARD_HEADING_CLASS}>Top domains</h3>
<span class="text-[10px] text-muted tabular-nums">
top {formatPlatformTableIntegerValue(topDomains().length)}
</span>
@@ -652,7 +553,12 @@ export const ProxmoxMailGatewayDrawer: Component<{
<TableCell
class={`${getPlatformTableCellClassForKind('name')} font-mono text-[11px] text-base-content`}
>
- <span class="block truncate" title={domain.domain}>
+ {/* Domains are compared and copied, so they wrap
+ rather than truncate. */}
+ <span
+ class="block whitespace-normal wrap-anywhere"
+ data-testid="pmg-top-domain-name"
+ >
{domain.domain || '—'}
</span>
</TableCell>
@@ -683,7 +589,7 @@ export const ProxmoxMailGatewayDrawer: Component<{
<TableCell
class={`${getPlatformTableCellClassForKind('numeric-value')} text-muted tabular-nums`}
>
- {domain.bytes && domain.bytes > 0 ? formatBytes(domain.bytes) : '—'}
+ {bytesOrDash(domain.bytes)}
</TableCell>
</TableRow>
)}
@@ -691,28 +597,12 @@ export const ProxmoxMailGatewayDrawer: Component<{
</PlatformDetailTableBody>
</PlatformDetailTable>
</Show>
- </Card>
-
- <Show when={relayDomains().length > 0}>
- <div class="flex flex-wrap items-center gap-1">
- <span class="text-[10px] uppercase tracking-wide text-muted">Relay domains</span>
- <For each={relayDomains()}>
- {(rd) => (
- <span
- class="inline-flex items-center rounded-xs bg-surface-alt px-1.5 py-0.5 text-[10px] font-mono text-base-content"
- title={rd.comment || rd.domain}
- >
- {rd.domain}
- </span>
- )}
- </For>
- </div>
- </Show>
+ </InfoCardFrame>
</Show>
</Show>
</Show>
- </section>
+ </div>
);
};
-export default ProxmoxMailGatewayDrawer;
+export default ProxmoxMailGatewayMailFlow;
diff --git a/frontend-modern/src/features/proxmox/ProxmoxMailGatewayTable.tsx b/frontend-modern/src/features/proxmox/ProxmoxMailGatewayTable.tsx
index 27e4c7a9a7..067caa4dc7 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxMailGatewayTable.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxMailGatewayTable.tsx
@@ -1,8 +1,7 @@
import { For, Show, createMemo, type Component, type JSX } from 'solid-js';
-import { InlineDetailTableRow } from '@/components/shared/InlineDetailTableRow';
import { StatusDot } from '@/components/shared/StatusDot';
import { TableCell, TableHead, TableRow } from '@/components/shared/Table';
-import { getSimpleStatusIndicator } from '@/utils/status';
+import { getSimpleStatusIndicator, type StatusIndicator } from '@/utils/status';
import { getAlertsForResource } from '@/utils/alerts';
import { getResourceIdentityAliases } from '@/utils/resourceIdentity';
import { alertTypeDisplayLabel } from '@/features/alerts/helpers';
@@ -33,10 +32,10 @@ import { useObservedElementWidth } from '@/hooks/useObservedElementWidth';
import {
createPlatformResourceDetailState,
getPlatformResourceDetailRowInteractionProps,
+ PlatformResourceDetailTableRow,
PlatformResourceDetailToggleButton,
} from '@/features/platformPage/PlatformResourceDetailTableRow';
import type { Resource } from '@/types/resource';
-import { ProxmoxMailGatewayDrawer } from './ProxmoxMailGatewayDrawer';
type MailGatewayAlertColumn = 'queue' | 'deferred' | 'quarantine' | 'spam' | 'virus';
@@ -177,7 +176,9 @@ export const ProxmoxMailGatewayTable: Component<{
...getResourceIdentityAliases(resource),
];
// One scan of the active-alert map per gateway, shared by the filter, the
- // status counts, the row and its drawer.
+ // status counts and the row. The drawer lists the same alerts through the
+ // canonical resource matcher (PMG alerts carry the instance id, which is
+ // the resource's metrics target).
const openAlertsById = createMemo(() => {
const byId = new Map<string, Alert[]>();
for (const resource of props.resources) {
@@ -203,12 +204,17 @@ export const ProxmoxMailGatewayTable: Component<{
? resource.status
: 'warning';
};
- // The dot follows the most severe open alert, so a critical one reads red.
- const indicatorFor = (resource: Resource) => {
- const base = getSimpleStatusIndicator(effectiveStatus(resource));
- return openAlertsFor(resource)[0]?.level === 'critical'
- ? { ...base, variant: 'danger' as const }
- : base;
+ // The dot follows the most severe open alert, so a critical one reads red,
+ // and a reachable gateway with open alerts reads as needing attention. The
+ // drawer header repeats this indicator rather than judging again.
+ const indicatorFor = (resource: Resource): StatusIndicator => {
+ const base = getSimpleStatusIndicator(resource.status);
+ const alerts = openAlertsFor(resource);
+ if (alerts.length === 0 || base.variant === 'danger') return base;
+ return {
+ variant: alerts[0]?.level === 'critical' ? 'danger' : 'warning',
+ label: 'Needs attention',
+ };
};
const tableState = createPlatformTableFilterState({
resources: () => props.resources,
@@ -515,19 +521,14 @@ export const ProxmoxMailGatewayTable: Component<{
</AlertedMetric>
</TableCell>
</TableRow>
- <Show when={isOpen()}>
- <InlineDetailTableRow
- cellId={detailRowId()}
- colspan={visibleColumnCount()}
- data-inline-detail-for={instance.id}
- >
- <ProxmoxMailGatewayDrawer
- instanceRow={instance}
- onClose={() => detail.close(instance)}
- alerts={rowAlerts()}
- />
- </InlineDetailTableRow>
- </Show>
+ <PlatformResourceDetailTableRow
+ resource={instance}
+ statusIndicator={indicator()}
+ open={isOpen()}
+ detailRowId={detailRowId()}
+ colSpan={visibleColumnCount()}
+ onClose={() => detail.close(instance)}
+ />
</>
);
}}
diff --git a/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx b/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
index 12baa33eff..9f53349682 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
@@ -812,10 +812,11 @@ export const ProxmoxNodesTable: Component<{
<InlineDetailTableRow
cellId={detailRowId()}
colspan={visibleColumns().length}
- data-inline-node-detail-for={node.id}
+ data-inline-detail-for={node.id}
>
<NodeDrawer
node={selectedNode()}
+ webInterfaceUrl={externalUrl()}
onClose={() => setSelectedNodeId(null)}
alerts={getAlertsForResource(
alertResourceIds(),
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxCephTable.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxCephTable.test.tsx
index 36f8bab9b4..71443e2ab9 100644
--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxCephTable.test.tsx
+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxCephTable.test.tsx
@@ -1,5 +1,5 @@
-import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { Resource } from '@/types/resource';
import {
@@ -10,6 +10,16 @@ import {
} from '../ProxmoxCephTable';
import cephClusterDrawerSource from '../ProxmoxCephClusterDrawer.tsx?raw';
+const activeAlerts: Record<string, unknown> = {};
+
+vi.mock('@/contexts/appRuntime', () => ({
+ useWebSocket: () => ({ activeAlerts }),
+}));
+
+vi.mock('@/stores/alertsActivation', () => ({
+ useAlertsActivation: () => ({ detectionEnabled: () => true }),
+}));
+
const makeCluster = (id: string): Resource => ({
id,
type: 'ceph',
@@ -42,7 +52,10 @@ const makeCluster = (id: string): Resource => ({
},
});
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ for (const key of Object.keys(activeAlerts)) delete activeAlerts[key];
+});
describe('ProxmoxCephTable', () => {
it('keeps one phone projection of five values that each fit whole', () => {
@@ -81,7 +94,7 @@ describe('ProxmoxCephTable', () => {
expect(disclosure).toHaveAccessibleName('Expand details for ceph-main');
});
- it('exposes complete nested pool values through the disclosure control', async () => {
+ it('shows every pool figure in the pools card without a nested expansion', () => {
render(() => (
<ProxmoxCephTable
resources={[makeCluster('ceph-main')]}
@@ -91,15 +104,13 @@ describe('ProxmoxCephTable', () => {
/>
));
- const disclosure = screen.getByRole('button', { name: 'Expand details for rbd-primary' });
- await fireEvent.click(disclosure);
-
- const detail = document.querySelector('[data-inline-proxmox-ceph-pool-detail-for]');
- expect(detail).toHaveTextContent('1,764,309');
- expect(detail).toHaveTextContent('59.2%');
-
- await fireEvent.click(disclosure);
- expect(document.querySelector('[data-inline-proxmox-ceph-pool-detail-for]')).toBeNull();
+ const pools = screen.getByTestId('ceph-cluster-pools');
+ expect(pools).toHaveTextContent('rbd-primary');
+ expect(pools).toHaveTextContent('1,764,309 objects');
+ expect(pools).toHaveTextContent('59.2% used');
+ expect(screen.queryByRole('button', { name: /details for rbd-primary/ })).toBeNull();
+ // Pool names sit above their figures and wrap: they are compared and copied.
+ expect(within(pools).getByText('rbd-primary')).toHaveClass('whitespace-normal');
});
it('returns focus to the disclosure for a cluster opened by the user', async () => {
@@ -177,12 +188,51 @@ describe('ProxmoxCephTable', () => {
);
});
- it('drops the pool object count, not the usage figure, in a narrow card', () => {
- expect(cephClusterDrawerSource).toMatch(
- /platform-table-phone-hidden md:w-\[16%\]`\}\s*>\s*Objects/,
- );
- expect(cephClusterDrawerSource).toMatch(
- /platform-table-mobile-w-20 md:w-\[20%\]`\}\s*>\s*Used/,
- );
+ it("heads the drawer with the row's own health verdict", () => {
+ // A cluster without a reported health status reads healthy in its row, so
+ // the drawer header must not show a grey "Unknown" beside it.
+ const cluster = makeCluster('ceph-main');
+ cluster.ceph = { ...cluster.ceph!, healthStatus: '' };
+ render(() => (
+ <ProxmoxCephTable
+ resources={[cluster]}
+ emptyIcon={<span />}
+ emptyTitle="No Ceph clusters"
+ emptyDescription="No clusters"
+ />
+ ));
+
+ const heading = screen.getByRole('heading', { level: 2, name: 'ceph-main' });
+ expect(heading.parentElement?.querySelector('[aria-label="Healthy"]')).not.toBeNull();
+ expect(cephClusterDrawerSource).not.toContain('function classifyHealth');
+ expect(screen.getByRole('tab', { name: 'Overview' })).toBeInTheDocument();
+ expect(screen.getByRole('tab', { name: 'Manage' })).toBeInTheDocument();
+ expect(screen.getByTestId('drawer-no-attention')).toHaveTextContent('No active alerts');
+ });
+
+ it('lifts health warnings, down OSDs and full pools into Worth checking', () => {
+ const cluster = makeCluster('ceph-main');
+ cluster.ceph = {
+ ...cluster.ceph!,
+ healthStatus: 'HEALTH_WARN',
+ healthMessage: '1 osds down',
+ healthChecks: [{ code: 'OSD_DOWN', severity: 'HEALTH_WARN', summary: '1 osds down' }],
+ numOsdsUp: 3,
+ pools: [{ ...cluster.ceph!.pools![0], name: 'rbd-full', percentUsed: 93.4 }],
+ };
+ render(() => (
+ <ProxmoxCephTable
+ resources={[cluster]}
+ emptyIcon={<span />}
+ emptyTitle="No Ceph clusters"
+ emptyDescription="No clusters"
+ />
+ ));
+
+ const lifted = screen.getByTestId('ceph-cluster-drawer-exceptions');
+ expect(lifted).toHaveTextContent('1 osds down');
+ expect(lifted).toHaveTextContent('3 of 4 up, 4 in');
+ expect(lifted).toHaveTextContent('Pool rbd-full');
+ expect(lifted).toHaveTextContent('93.4% used');
});
});
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayDrawer.alertClock.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayDrawer.alertClock.test.tsx
deleted file mode 100644
index 233daaa6f5..0000000000
--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayDrawer.alertClock.test.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { cleanup, render, screen, within } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import type { Alert } from '@/types/api';
-import type { Resource } from '@/types/resource';
-import { ProxmoxMailGatewayDrawer } from '../ProxmoxMailGatewayDrawer';
-
-vi.mock('@/utils/apiClient', () => ({
- apiFetch: vi.fn(async () => new Response(JSON.stringify(null), { status: 200 })),
-}));
-
-const OPENED_AT = Date.parse('2026-10-07T10:00:00Z');
-
-const gateway = {
- id: 'pmg-unified-eu',
- type: 'pmg',
- name: 'mail-gateway-eu',
- displayName: 'mail-gateway-eu',
- platformType: 'proxmox-pmg',
- sourceType: 'api',
- status: 'online',
- lastSeen: OPENED_AT - 60_000,
- canonicalIdentity: {
- primaryId: 'agent:pmg-main',
- aliases: ['pmg-main', 'mail-gateway-eu'],
- },
- pmg: { instanceId: 'pmg-main', nodeCount: 1, mailCountTotal: 10, queueTotal: 3 },
-} as unknown as Resource;
-
-// A Pulse agent on the gateway host raises threshold alerts the row matches
-// through its identity aliases. The host stopped reporting a minute before the
-// drawer opened, so the alert's live status never changes again.
-const heldCpuAlert: Alert = {
- id: 'agent:pmg-main::metric-threshold:cpu',
- type: 'cpu',
- level: 'warning',
- resourceId: 'agent:pmg-main',
- resourceName: 'mail-gateway-eu',
- node: 'mail-gateway-eu',
- instance: 'pmg-main',
- message: 'Host cpu at 93.0%',
- value: 93,
- threshold: 90,
- startTime: '2026-10-07T09:40:00Z',
- lastSeen: new Date(OPENED_AT - 5 * 60_000).toISOString(),
- acknowledged: false,
- metricStatus: {
- phase: 'latched',
- value: 72,
- unit: '%',
- observedAt: new Date(OPENED_AT - 60_000).toISOString(),
- trigger: 90,
- recovery: 80,
- },
-};
-
-afterEach(() => {
- cleanup();
- vi.useRealTimers();
-});
-
-describe('ProxmoxMailGatewayDrawer alert attention clock', () => {
- it('turns a held reading stale and keeps its ages moving while the drawer stays open', () => {
- vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'], now: OPENED_AT });
-
- render(() => <ProxmoxMailGatewayDrawer instanceRow={gateway} alerts={[heldCpuAlert]} />);
- const attention = within(screen.getByTestId('drawer-attention-section'));
-
- expect(attention.getByText('CPU 72% now, back under the 90% alert level')).toHaveAttribute(
- 'title',
- expect.stringContaining('Last reading at or above 90%: 93%, 5 mins ago'),
- );
-
- // Past the ten-minute cut-off the reading is no longer "now".
- vi.advanceTimersByTime(10 * 60_000);
- expect(attention.queryByText(/now, back under/)).not.toBeInTheDocument();
- expect(attention.getByText('Last reading: CPU 72%, 11 mins ago')).toHaveAttribute(
- 'title',
- expect.stringContaining('Last reading at or above 90%: 93%, 15 mins ago'),
- );
-
- vi.advanceTimersByTime(5 * 60_000);
- expect(attention.getByText('Last reading: CPU 72%, 16 mins ago')).toHaveAttribute(
- 'title',
- expect.stringContaining('Last reading at or above 90%: 93%, 20 mins ago'),
- );
- });
-
- it('keeps a list of alerts without a live status in place across clock ticks', () => {
- vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'], now: OPENED_AT });
- // Mail Gateway alerts come from their own checks and carry no live status,
- // so their copy never depends on the clock.
- const messageAge: Alert = {
- id: 'pmg-main::pmg-main-oldest-message',
- type: 'message-age',
- level: 'warning',
- resourceId: 'pmg-main',
- resourceName: 'mail-gateway-eu',
- node: 'https://pmg.example:8006',
- instance: 'pmg-main',
- message: 'PMG mail-gateway-eu has messages queued for 41 minutes (threshold: 30 minutes)',
- value: 41,
- threshold: 30,
- startTime: '2026-10-07T09:40:00Z',
- lastSeen: '2026-10-07T09:59:00Z',
- acknowledged: false,
- };
-
- render(() => <ProxmoxMailGatewayDrawer instanceRow={gateway} alerts={[messageAge]} />);
- const attention = within(screen.getByTestId('drawer-attention-section'));
- const row = attention.getByText(messageAge.message).closest('li');
- expect(row).not.toBeNull();
-
- vi.advanceTimersByTime(5 * 60_000);
- expect(attention.getByText(messageAge.message).closest('li')).toBe(row);
- });
-});
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayDrawer.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayDrawer.test.tsx
new file mode 100644
index 0000000000..410b2dca94
--- /dev/null
+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayDrawer.test.tsx
@@ -0,0 +1,165 @@
+import { cleanup, fireEvent, render, screen, within } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { PMGInstance } from '@/types/api';
+import type { Resource } from '@/types/resource';
+import { ProxmoxMailGatewayMailFlow } from '../ProxmoxMailGatewayDrawer';
+
+const apiFetchMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/utils/apiClient', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/utils/apiClient')>()),
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}));
+
+const gateway = {
+ id: 'pmg-unified-eu',
+ type: 'pmg',
+ name: 'mail-gateway-eu',
+ displayName: 'mail-gateway-eu',
+ platformType: 'proxmox-pmg',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: Date.now(),
+ pmg: { instanceId: 'pmg-main', version: '8.1.2', nodeCount: 1 },
+} as unknown as Resource;
+
+const longDomain = 'customer-support-notifications.eu-west.example-holdings.co.uk';
+
+const instance: PMGInstance = {
+ id: 'pmg-main',
+ name: 'mail-gateway-eu',
+ host: 'https://pmg.example:8006',
+ status: 'online',
+ version: '8.1.2',
+ connectionHealth: 'healthy',
+ lastSeen: '2026-10-22T10:00:00Z',
+ lastUpdated: '2026-10-22T10:00:00Z',
+ mailStats: {
+ timeframe: 'day',
+ countTotal: 1500,
+ countIn: 1200,
+ countOut: 300,
+ spamIn: 140,
+ spamOut: 2,
+ virusIn: 3,
+ virusOut: 0,
+ bouncesIn: 12,
+ bouncesOut: 4,
+ bytesIn: 52_428_800,
+ bytesOut: 10_485_760,
+ greylistCount: 40,
+ junkIn: 9,
+ averageProcessTimeMs: 412.4,
+ rblRejects: 77,
+ pregreetRejects: 5,
+ updatedAt: '2026-10-22T10:00:00Z',
+ },
+ quarantine: { spam: 21, virus: 1, attachment: 2, blacklisted: 0 },
+ spamDistribution: [
+ { score: '0', count: 900 },
+ { score: '5', count: 30 },
+ { score: '10+', count: 8 },
+ ],
+ relayDomains: [{ domain: 'example.com', comment: 'Primary' }, { domain: 'example.org' }],
+ domainStats: [{ domain: longDomain, mailCount: 800, spamCount: 90, virusCount: 1, bytes: 1024 }],
+ nodes: [
+ {
+ name: 'pmg-node-1',
+ status: 'online',
+ role: 'master',
+ uptime: 86_400,
+ loadAvg: '0.12',
+ queueStatus: {
+ active: 1,
+ deferred: 2,
+ hold: 0,
+ incoming: 0,
+ total: 3,
+ oldestAge: 1800,
+ updatedAt: '2026-10-22T10:00:00Z',
+ },
+ },
+ ],
+};
+
+const respond = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+
+describe('ProxmoxMailGatewayMailFlow', () => {
+ beforeEach(() => apiFetchMock.mockReset());
+ afterEach(cleanup);
+
+ it('shows every mail-flow figure as content cards under the drawer header', async () => {
+ apiFetchMock.mockResolvedValue(respond({ data: [instance], meta: { total: 1 } }));
+
+ render(() => <ProxmoxMailGatewayMailFlow resource={gateway} />);
+
+ const flow = within(await screen.findByTestId('pmg-mail-flow-section'));
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/pmg/instances?id=pmg-main');
+ expect(flow.getByText('Mail flow (day)')).toBeInTheDocument();
+ expect(flow.getByText('1,200 / 300')).toBeInTheDocument();
+ expect(flow.getByText('140 / 2')).toBeInTheDocument();
+ expect(flow.getByText('412ms')).toBeInTheDocument();
+ expect(flow.getByText('RBL rejects').closest('tr')).toHaveTextContent('77');
+ expect(flow.getByRole('img', { name: 'Inbound mail disposition breakdown' })).toBeVisible();
+
+ const quarantine = within(screen.getByTestId('pmg-quarantine-section'));
+ expect(quarantine.getByText('Attachment')).toBeInTheDocument();
+ expect(quarantine.getByText('21')).toBeInTheDocument();
+
+ expect(
+ within(screen.getByTestId('pmg-spam-scores-section')).getByRole('img', {
+ name: 'Spam score distribution',
+ }),
+ ).toBeInTheDocument();
+ expect(
+ within(screen.getByTestId('pmg-relay-domains-section')).getByText(
+ 'example.com (Primary), example.org',
+ ),
+ ).toBeInTheDocument();
+
+ const nodes = within(screen.getByTestId('pmg-cluster-nodes'));
+ expect(nodes.getByText('pmg-node-1')).toBeInTheDocument();
+ expect(nodes.getByText('1/2/0/0')).toBeInTheDocument();
+
+ // Domains are compared and copied, so they wrap rather than truncate.
+ const domain = within(screen.getByTestId('pmg-top-domains')).getByText(longDomain);
+ expect(domain).toHaveClass('whitespace-normal', 'wrap-anywhere');
+ expect(domain).not.toHaveClass('truncate');
+
+ expect(screen.getByTestId('pmg-mail-flow-facts')).toHaveTextContent('8.1.2');
+ expect(screen.getByTestId('pmg-mail-flow-facts')).toHaveTextContent('https://pmg.example:8006');
+ // The drawer around this body owns the heading, status and alerts.
+ expect(screen.queryByRole('heading', { level: 2 })).toBeNull();
+ expect(screen.queryByTestId('drawer-attention-section')).toBeNull();
+ });
+
+ it('shows a shared error notice whose retry reads the gateway again', async () => {
+ apiFetchMock.mockResolvedValueOnce(respond({ error: 'boom' }, 502));
+
+ render(() => <ProxmoxMailGatewayMailFlow resource={gateway} />);
+
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('Could not load mail flow for mail-gateway-eu.');
+
+ apiFetchMock.mockResolvedValueOnce(respond({ data: [instance], meta: { total: 1 } }));
+ await fireEvent.click(
+ within(alert).getByRole('button', { name: 'Retry loading mail flow for mail-gateway-eu' }),
+ );
+
+ expect(await screen.findByTestId('pmg-mail-flow-section')).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(apiFetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('says plainly when the gateway has not reported mail flow', async () => {
+ apiFetchMock.mockResolvedValue(respond({ data: [], meta: { total: 0 } }));
+
+ render(() => <ProxmoxMailGatewayMailFlow resource={gateway} />);
+
+ expect(
+ await screen.findByText('This gateway has not reported mail flow yet.'),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.alerts.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.alerts.test.tsx
index ef9592e4ae..e2614416b3 100644
--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.alerts.test.tsx
+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.alerts.test.tsx
@@ -14,10 +14,28 @@ vi.mock('@/stores/alertsActivation', () => ({
useAlertsActivation: () => ({ detectionEnabled: () => true }),
}));
-vi.mock('@/utils/apiClient', () => ({
+vi.mock('@/utils/apiClient', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/utils/apiClient')>()),
apiFetch: vi.fn(async () => new Response(JSON.stringify(null), { status: 200 })),
}));
+// The row opens the canonical resource drawer; its remote reads stay quiet.
+vi.mock('@/api/resources', () => ({
+ ResourceAPI: {
+ getFacetBundle: vi.fn().mockResolvedValue({
+ capabilities: [],
+ relationships: [],
+ recentChanges: [],
+ }),
+ },
+}));
+
+vi.mock('@/api/ai', () => ({
+ AIAPI: {
+ getResourceIntelligence: vi.fn().mockResolvedValue(null),
+ },
+}));
+
const gateway = (id: string, name: string, instanceId: string): Resource =>
({
id,
@@ -29,6 +47,9 @@ const gateway = (id: string, name: string, instanceId: string): Resource =>
status: 'online',
lastSeen: Date.now(),
canonicalIdentity: { primaryId: `agent:${instanceId}`, aliases: [instanceId, name] },
+ // The backend points a gateway's metrics target at its PMG source id,
+ // which is the id its alerts carry.
+ metricsTarget: { resourceType: 'agent', resourceId: instanceId },
pmg: { instanceId, nodeCount: 1, mailCountTotal: 10, queueTotal: 3, queueDeferred: 1 },
}) as unknown as Resource;
@@ -73,12 +94,17 @@ describe('ProxmoxMailGatewayTable open alerts', () => {
expect(nameCell).not.toHaveTextContent('Message Age');
fireEvent.click(screen.getByRole('button', { name: /mail-gateway-eu/ }));
- const drawerMatches = (
- await screen.findAllByText(/queued for 41 minutes \(threshold: 30 minutes\)/)
- ).filter((element) => !element.closest('.sr-only'));
- expect(drawerMatches.length).toBeGreaterThan(0);
- expect(drawerMatches[0]).toBeVisible();
- expect(screen.getByText('Needs attention')).toBeInTheDocument();
+ // The row opens the gateway's resource drawer, whose Overview lists the
+ // same alert the row marks.
+ const attention = await screen.findByTestId('drawer-attention-section');
+ expect(attention).toHaveTextContent(/queued for 41 minutes \(threshold: 30 minutes\)/);
+ expect(attention).toBeVisible();
+ expect(screen.queryByTestId('drawer-no-attention')).toBeNull();
+ // The header dot repeats the row's verdict.
+ const heading = screen.getByRole('heading', { level: 2, name: 'mail-gateway-eu' });
+ expect(heading.parentElement?.querySelector('[aria-label="Needs attention"]')).not.toBeNull();
+ expect(screen.getByRole('tab', { name: 'Mail' })).toBeInTheDocument();
+ expect(screen.getAllByRole('heading', { level: 2 })).toHaveLength(1);
});
it('ignores acknowledged alerts', () => {
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.test.ts b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.test.ts
index b41669c681..6c1adff0a6 100644
--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.test.ts
+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxMailGatewayTable.test.ts
@@ -13,14 +13,16 @@ import mailGatewayDrawerSource from '../ProxmoxMailGatewayDrawer.tsx?raw';
import mailGatewayTableSource from '../ProxmoxMailGatewayTable.tsx?raw';
describe('ProxmoxMailGatewayTable phone presentation', () => {
- it('keeps compact drawer statistics on the shared responsive row contract', () => {
- expect(mailGatewayDrawerSource).toContain('InfoCardKeyValueRow');
+ it('keeps mail-flow figures on shared detail rows and card chrome', () => {
+ expect(mailGatewayDrawerSource).toContain('makeDetailRow(');
+ expect(mailGatewayDrawerSource).toContain('<TechnicalDetailsSection');
+ expect(mailGatewayDrawerSource).toContain('<InfoCardFrame');
+ expect(mailGatewayDrawerSource).not.toContain('function InOutBar');
+ expect(mailGatewayDrawerSource).not.toContain('<Card');
+ expect(mailGatewayDrawerSource).not.toContain('<h4');
expect(mailGatewayDrawerSource).not.toMatch(
/class="flex items-baseline justify-between[^\"]*">\s*<span class="text-muted">/,
);
- expect(
- mailGatewayDrawerSource.match(/class="col-span-2 text-\[11px\] sm:col-span-1"/g),
- ).toHaveLength(3);
});
it('keeps gateway names distinguishable with five phone tracks', () => {
@@ -69,13 +71,19 @@ describe('ProxmoxMailGatewayTable phone presentation', () => {
expect(widths.reduce((total, width) => total + width, 0)).toBeCloseTo(100, 1);
});
- it('matches gateway alerts across identity aliases and shows the problem in the drawer', () => {
+ it('matches gateway alerts across identity aliases and opens the one resource drawer', () => {
// Alerts are keyed by the PMG instance id, rows by the unified id.
expect(mailGatewayTableSource).toContain('getResourceIdentityAliases(resource)');
expect(mailGatewayTableSource).toContain(
'filterPlatformResources(resources, search, status, effectiveStatus)',
);
- expect(mailGatewayDrawerSource).toContain('<DrawerAttentionSection');
+ // The row opens the canonical resource drawer headed by its own dot; the
+ // Mail tab body is headless and leaves status and alerts to that drawer.
+ expect(mailGatewayTableSource).toContain('<PlatformResourceDetailTableRow');
+ expect(mailGatewayTableSource).toContain('statusIndicator={indicator()}');
+ expect(mailGatewayDrawerSource).not.toContain('DrawerAttentionSection');
+ expect(mailGatewayDrawerSource).not.toContain('ObjectDrawerHeader');
+ expect(mailGatewayDrawerSource).not.toContain('function classifyHealth');
});
it('keeps alerting rows single-line by marking the metric the alert is about', () => {
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx
index 89b48696e1..95a4569fd0 100644
--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx
+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx
@@ -794,8 +794,14 @@ describe('ProxmoxNodesTable', () => {
expect.objectContaining({
node: expect.objectContaining({ name: 'pve-node-1' }),
temperatureThresholds: { warning: 80, critical: 85 },
+ // The drawer header opens the same web interface as the row link.
+ webInterfaceUrl: 'https://pve-node-1:8006',
}),
);
+ // The standard detail-row marker the shared focus helpers look for.
+ expect(
+ screen.getByTestId('node-drawer').closest('[data-inline-detail-for="agent:pve-node-1"]'),
+ ).not.toBeNull();
await fireEvent.click(screen.getByRole('button', { name: 'Collapse details for pve-node-1' }));
expect(onShowGuests).toHaveBeenCalledTimes(1);
diff --git a/frontend-modern/src/features/proxmox/__tests__/proxmoxCephClusterDrawerModel.test.ts b/frontend-modern/src/features/proxmox/__tests__/proxmoxCephClusterDrawerModel.test.ts
new file mode 100644
index 0000000000..7eafc9e766
--- /dev/null
+++ b/frontend-modern/src/features/proxmox/__tests__/proxmoxCephClusterDrawerModel.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Resource } from '@/types/resource';
+import {
+ buildCephClusterContentSections,
+ buildCephClusterDetailSections,
+ getCephClusterExceptionRows,
+ getCephClusterFacts,
+} from '../proxmoxCephClusterDrawerModel';
+
+const cluster = (ceph: Partial<NonNullable<Resource['ceph']>> = {}): Resource =>
+ ({
+ id: 'ceph-main',
+ type: 'ceph',
+ name: 'ceph-main',
+ platformId: 'homelab',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1,
+ tags: ['prod'],
+ disk: { total: 10 * 1024 ** 4, used: 4 * 1024 ** 4, free: 6 * 1024 ** 4, current: 40 },
+ ceph: {
+ fsid: '8f1c2d3e-0000-4b8c-9d2e-1234567890ab',
+ healthStatus: 'HEALTH_OK',
+ numMons: 3,
+ numMgrs: 2,
+ numOsds: 4,
+ numOsdsUp: 4,
+ numOsdsIn: 4,
+ numPGs: 128,
+ pools: [
+ {
+ name: 'rbd',
+ storedBytes: 1024 ** 3,
+ availableBytes: 2 * 1024 ** 3,
+ objects: 1500,
+ percentUsed: 33.3,
+ },
+ ],
+ services: [
+ { type: 'mon', running: 3, total: 3 },
+ { type: 'mgr', running: 1, total: 2 },
+ ],
+ ...ceph,
+ },
+ }) as Resource;
+
+describe('proxmoxCephClusterDrawerModel', () => {
+ it('lifts nothing for a healthy cluster', () => {
+ expect(
+ getCephClusterExceptionRows(cluster({ services: [{ type: 'mon', running: 3, total: 3 }] })),
+ ).toEqual([]);
+ });
+
+ it('lifts each health check, down OSDs, short daemons and nearly full pools', () => {
+ const rows = getCephClusterExceptionRows(
+ cluster({
+ healthStatus: 'HEALTH_ERR',
+ healthChecks: [
+ { code: 'OSD_DOWN', severity: 'HEALTH_WARN', summary: '1 osds down' },
+ { code: 'POOL_FULL', severity: 'HEALTH_ERR', summary: '1 pool(s) full' },
+ ],
+ numOsdsUp: 3,
+ pools: [{ name: 'rbd', storedBytes: 1, availableBytes: 0, objects: 1, percentUsed: 97.1 }],
+ }),
+ );
+ expect(rows.map((row) => [row.label, row.value, row.tone])).toEqual([
+ ['Health', '1 osds down', 'warning'],
+ ['Health', '1 pool(s) full', 'danger'],
+ ['OSDs', '3 of 4 up, 4 in', 'warning'],
+ ['MGR daemons', '1 of 2 running', 'warning'],
+ ['Pool rbd', '97.1% used', 'danger'],
+ ]);
+ });
+
+ it('falls back to the health message when no checks are reported', () => {
+ const rows = getCephClusterExceptionRows(
+ cluster({ healthStatus: 'HEALTH_WARN', healthMessage: 'clock skew detected', services: [] }),
+ );
+ expect(rows).toEqual([
+ expect.objectContaining({ label: 'Health', value: 'clock skew detected', tone: 'warning' }),
+ ]);
+ });
+
+ it('leaves out a fact an open alert already states', () => {
+ const rows = getCephClusterExceptionRows(
+ cluster({
+ healthStatus: 'HEALTH_WARN',
+ healthChecks: [{ code: 'OSD_DOWN', severity: 'HEALTH_WARN', summary: '1 osds down' }],
+ services: [],
+ }),
+ ['Ceph cluster ceph-main: 1 osds down'],
+ );
+ expect(rows).toEqual([]);
+ });
+
+ it('keeps pools and daemons in view as content cards', () => {
+ const [pools, services] = buildCephClusterContentSections(cluster());
+ expect(pools.label).toBe('Pools (1)');
+ expect(pools.rows[0]).toMatchObject({
+ label: 'rbd',
+ layout: 'stacked',
+ wrap: true,
+ value: '33.3% used · 1.00 GB stored · 2.00 GB available · 1,500 objects',
+ });
+ expect(pools.rows[0].progress?.value).toBeCloseTo(33.3);
+ expect(services.rows.map((row) => [row.label, row.value, row.tone])).toEqual([
+ ['MON', '3 of 3 running', 'success'],
+ ['MGR', '1 of 2 running', 'warning'],
+ ]);
+ });
+
+ it('drops empty content cards so the drawer can say so plainly', () => {
+ expect(buildCephClusterContentSections(cluster({ pools: [], services: [] }))).toEqual([]);
+ });
+
+ it('keeps identifiers and raw health text behind Details, wrapping copyable values', () => {
+ const sections = buildCephClusterDetailSections(
+ cluster({ healthStatus: 'HEALTH_WARN', healthMessage: 'clock skew detected' }),
+ );
+ expect(sections.map((section) => section.label)).toEqual(['Cluster', 'Health', 'Topology']);
+ const fsid = sections[0].rows.find((row) => row.label === 'FSID');
+ expect(fsid).toMatchObject({ value: '8f1c2d3e-0000-4b8c-9d2e-1234567890ab', wrap: true });
+ expect(sections[0].rows.find((row) => row.label === 'Tags')?.value).toBe('prod');
+ expect(sections[1].rows.map((row) => row.label)).toEqual(['Status', 'Message']);
+ expect(sections[2].rows.find((row) => row.label === 'Placement groups')?.value).toBe('128');
+ });
+
+ it('states capacity, OSDs, quorum and placement groups in one facts line', () => {
+ expect(getCephClusterFacts(cluster())).toEqual([
+ '40.0% used · 4.00 TB of 10.0 TB',
+ 'OSDs 4 of 4 up, 4 in',
+ 'MON 3 · MGR 2',
+ '128 placement groups',
+ ]);
+ });
+});
diff --git a/frontend-modern/src/features/proxmox/__tests__/proxmoxDrawerPlacement.contract.test.ts b/frontend-modern/src/features/proxmox/__tests__/proxmoxDrawerPlacement.contract.test.ts
index 268e04a426..288f347bc3 100644
--- a/frontend-modern/src/features/proxmox/__tests__/proxmoxDrawerPlacement.contract.test.ts
+++ b/frontend-modern/src/features/proxmox/__tests__/proxmoxDrawerPlacement.contract.test.ts
@@ -11,6 +11,6 @@ describe('Proxmox drawer placement contract', () => {
expect(workloadPanelSource).not.toContain('NodeDrawer');
expect(proxmoxPageSurfaceSource).not.toContain('groupNodeDrawerMode');
expect(proxmoxNodesTableSource).toContain('NodeDrawer');
- expect(proxmoxNodesTableSource).toContain('data-inline-node-detail-for={node.id}');
+ expect(proxmoxNodesTableSource).toContain('data-inline-detail-for={node.id}');
});
});
diff --git a/frontend-modern/src/features/proxmox/proxmoxCephClusterDrawerModel.ts b/frontend-modern/src/features/proxmox/proxmoxCephClusterDrawerModel.ts
new file mode 100644
index 0000000000..f05dd9aefa
--- /dev/null
+++ b/frontend-modern/src/features/proxmox/proxmoxCephClusterDrawerModel.ts
@@ -0,0 +1,242 @@
+import {
+ compactDetailRows,
+ compactDetailSections,
+ makeDetailRow,
+ type DetailRow,
+ type DetailSection,
+ type DetailValueTone,
+} from '@/components/shared/detailSectionModel';
+import {
+ formatPlatformTableIntegerValue,
+ formatPlatformTablePercentValue,
+} from '@/features/platformPage/sharedPlatformPage';
+import type { Resource, ResourceCephPoolMeta, ResourceCephServiceMeta } from '@/types/resource';
+import { formatBytes } from '@/utils/format';
+import { getMetricColorClass, getMetricSeverity } from '@/utils/metricThresholds';
+import { asTrimmedString } from '@/utils/stringUtils';
+
+// What a Ceph cluster drawer shows, kept out of the component so the
+// "is this OK, and if not, what do I do" judgement is testable on its own:
+// the problems lifted into "Worth checking", the pools and daemons that stay
+// in view, a short facts line, and the long tail behind Details.
+
+const isHealthOk = (status: string | undefined): boolean => {
+ const raw = (status ?? '').trim().toUpperCase();
+ return raw === '' || raw === 'HEALTH_OK' || raw === 'OK';
+};
+
+const healthTone = (value: string | undefined): DetailValueTone =>
+ /ERR|CRIT/i.test(value ?? '') ? 'danger' : 'warning';
+
+const poolLabel = (pool: ResourceCephPoolMeta): string => asTrimmedString(pool.name) || 'Pool';
+
+const poolUsedTone = (pool: ResourceCephPoolMeta): DetailValueTone | undefined => {
+ const severity = getMetricSeverity(pool.percentUsed, 'disk');
+ if (severity === 'critical') return 'danger';
+ if (severity === 'warning') return 'warning';
+ return undefined;
+};
+
+const serviceLabel = (service: ResourceCephServiceMeta): string =>
+ (asTrimmedString(service.type) || 'service').toUpperCase();
+
+const serviceTone = (service: ResourceCephServiceMeta): DetailValueTone => {
+ if (service.total === 0) return 'muted';
+ if (service.running >= service.total) return 'success';
+ return service.running === 0 ? 'danger' : 'warning';
+};
+
+const serviceValue = (service: ResourceCephServiceMeta): string =>
+ service.total === 0 ? 'None reported' : `${service.running} of ${service.total} running`;
+
+const osdSummary = (resource: Resource): string | null => {
+ const ceph = resource.ceph;
+ if (!ceph || !(ceph.numOsds > 0)) return null;
+ return `${ceph.numOsdsUp} of ${ceph.numOsds} up, ${ceph.numOsdsIn} in`;
+};
+
+const capacitySummary = (resource: Resource): string | null => {
+ const percent = resource.disk?.current;
+ const total = resource.disk?.total ?? 0;
+ if (typeof percent !== 'number' || !Number.isFinite(percent)) return null;
+ if (total > 0) {
+ return `${formatPlatformTablePercentValue(percent)} used · ${formatBytes(resource.disk?.used ?? 0)} of ${formatBytes(total)}`;
+ }
+ return `${formatPlatformTablePercentValue(percent)} used`;
+};
+
+/**
+ * Problems a reader should act on, one line each. A row whose fact an open
+ * alert already states (`statedMessages`) stays out, so the alert is not
+ * repeated underneath itself.
+ */
+export const getCephClusterExceptionRows = (
+ resource: Resource,
+ statedMessages: readonly string[] = [],
+): DetailRow[] => {
+ const ceph = resource.ceph;
+ if (!ceph) return [];
+ const stated = statedMessages.map((message) => message.toLowerCase());
+ const isStated = (value: string) =>
+ stated.some((message) => message.includes(value.trim().toLowerCase()));
+
+ const healthRows: Array<DetailRow | null> = [];
+ const checks = (ceph.healthChecks ?? []).filter(
+ (check) => asTrimmedString(check.summary) || asTrimmedString(check.code),
+ );
+ if (checks.length > 0) {
+ for (const check of checks) {
+ healthRows.push(
+ makeDetailRow('Health', asTrimmedString(check.summary) || check.code, {
+ tone: healthTone(check.severity || ceph.healthStatus),
+ title: asTrimmedString(check.code),
+ wrap: true,
+ }),
+ );
+ }
+ } else if (!isHealthOk(ceph.healthStatus)) {
+ healthRows.push(
+ makeDetailRow('Health', asTrimmedString(ceph.healthMessage) || ceph.healthStatus, {
+ tone: healthTone(ceph.healthStatus),
+ wrap: true,
+ }),
+ );
+ }
+
+ const osds = osdSummary(resource);
+ const osdRow =
+ osds && (ceph.numOsdsUp < ceph.numOsds || ceph.numOsdsIn < ceph.numOsds)
+ ? makeDetailRow('OSDs', osds, { tone: ceph.numOsdsUp === 0 ? 'danger' : 'warning' })
+ : null;
+
+ const serviceRows = (ceph.services ?? [])
+ .filter((service) => service.total > 0 && service.running < service.total)
+ .map((service) =>
+ makeDetailRow(`${serviceLabel(service)} daemons`, serviceValue(service), {
+ tone: serviceTone(service),
+ }),
+ );
+
+ const poolRows = (ceph.pools ?? []).map((pool) => {
+ const tone = poolUsedTone(pool);
+ return tone
+ ? makeDetailRow(
+ `Pool ${poolLabel(pool)}`,
+ `${formatPlatformTablePercentValue(pool.percentUsed)} used`,
+ { tone, wrap: true },
+ )
+ : null;
+ });
+
+ return compactDetailRows([...healthRows, osdRow, ...serviceRows, ...poolRows]).filter(
+ (row) => !isStated(row.value),
+ );
+};
+
+/** The pools and daemons that stay in view: the cluster's own content. */
+export const buildCephClusterContentSections = (resource: Resource): DetailSection[] => {
+ const pools = resource.ceph?.pools ?? [];
+ const services = resource.ceph?.services ?? [];
+ return compactDetailSections([
+ {
+ label: `Pools (${pools.length})`,
+ testId: 'ceph-cluster-pools',
+ rows: pools.map((pool) => {
+ const percent = Math.max(0, Math.min(100, pool.percentUsed));
+ return {
+ // Pool names are compared and copied, so they sit above their
+ // figures and wrap rather than truncate.
+ label: poolLabel(pool),
+ layout: 'stacked' as const,
+ wrap: true,
+ tone: poolUsedTone(pool),
+ value: [
+ `${formatPlatformTablePercentValue(pool.percentUsed)} used`,
+ `${formatBytes(pool.storedBytes)} stored`,
+ `${formatBytes(pool.availableBytes)} available`,
+ `${formatPlatformTableIntegerValue(pool.objects, '0')} objects`,
+ ].join(' · '),
+ progress: {
+ value: percent,
+ fillClass: getMetricColorClass(percent, 'disk'),
+ ariaLabel: `${poolLabel(pool)} used`,
+ },
+ };
+ }),
+ },
+ {
+ label: 'Services',
+ testId: 'ceph-cluster-services',
+ rows: services.map((service) => ({
+ label: serviceLabel(service),
+ value: serviceValue(service),
+ tone: serviceTone(service),
+ })),
+ },
+ ]);
+};
+
+/** One short line of what the row does not say in full. */
+export const getCephClusterFacts = (resource: Resource): string[] => {
+ const ceph = resource.ceph;
+ const osds = osdSummary(resource);
+ return [
+ capacitySummary(resource) ?? '',
+ osds ? `OSDs ${osds}` : '',
+ ceph ? `MON ${ceph.numMons} · MGR ${ceph.numMgrs}` : '',
+ ceph && ceph.numPGs > 0
+ ? `${formatPlatformTableIntegerValue(ceph.numPGs)} placement groups`
+ : '',
+ ].filter((fact) => fact.length > 0);
+};
+
+/** The long tail: identifiers and raw health text, behind a closed Details. */
+export const buildCephClusterDetailSections = (resource: Resource): DetailSection[] => {
+ const ceph = resource.ceph;
+ const healthChecks = (ceph?.healthChecks ?? [])
+ .map((check) =>
+ [asTrimmedString(check.code), asTrimmedString(check.summary)].filter(Boolean).join(': '),
+ )
+ .filter(Boolean);
+ const poolHealth = ceph?.poolHealth;
+ const tags = (resource.tags ?? []).map((tag) => asTrimmedString(tag)).filter(Boolean);
+ return compactDetailSections([
+ {
+ label: 'Cluster',
+ testId: 'ceph-cluster-identity',
+ rows: compactDetailRows([
+ makeDetailRow('Name', asTrimmedString(resource.name) || resource.id, { wrap: true }),
+ makeDetailRow('FSID', asTrimmedString(ceph?.fsid), { wrap: true }),
+ makeDetailRow('Platform', asTrimmedString(resource.platformId), { wrap: true }),
+ makeDetailRow('Capacity', capacitySummary(resource)),
+ makeDetailRow('Tags', tags.join(', '), { wrap: true }),
+ ]),
+ },
+ {
+ label: 'Health',
+ testId: 'ceph-cluster-health',
+ rows: compactDetailRows([
+ makeDetailRow('Status', asTrimmedString(ceph?.healthStatus)),
+ makeDetailRow('Message', asTrimmedString(ceph?.healthMessage), { wrap: true }),
+ makeDetailRow('Checks', healthChecks.join(' · '), { wrap: true }),
+ makeDetailRow('Pool health', asTrimmedString(poolHealth?.summary), { wrap: true }),
+ makeDetailRow('Recommendation', asTrimmedString(poolHealth?.recommendation), {
+ wrap: true,
+ }),
+ ]),
+ },
+ {
+ label: 'Topology',
+ testId: 'ceph-cluster-topology',
+ rows: compactDetailRows([
+ makeDetailRow('Monitors', ceph ? String(ceph.numMons) : null),
+ makeDetailRow('Managers', ceph ? String(ceph.numMgrs) : null),
+ makeDetailRow('OSDs', osdSummary(resource)),
+ makeDetailRow(
+ 'Placement groups',
+ ceph && ceph.numPGs > 0 ? formatPlatformTableIntegerValue(ceph.numPGs) : null,
+ ),
+ ]),
+ },
+ ]);
+};
diff --git a/frontend-modern/src/features/storageBackups/__tests__/detailPresentation.test.ts b/frontend-modern/src/features/storageBackups/__tests__/detailPresentation.test.ts
deleted file mode 100644
index 4abe2b4f5f..0000000000
--- a/frontend-modern/src/features/storageBackups/__tests__/detailPresentation.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- STORAGE_DETAIL_EMPTY_CLASS,
- STORAGE_DETAIL_HEADER_ROW_CLASS,
- STORAGE_DISK_DETAIL_ATTRIBUTE_GRID_CLASS,
- STORAGE_DISK_DETAIL_HEADER_CLASS,
- STORAGE_DISK_DETAIL_HISTORY_GRID_CLASS,
- STORAGE_DISK_DETAIL_LIVE_GRID_CLASS,
- STORAGE_DISK_DETAIL_MODEL_CLASS,
- STORAGE_DISK_DETAIL_NODE_CLASS,
- STORAGE_DISK_DETAIL_SECTION_HEADING_CLASS,
-} from '@/features/storageBackups/detailPresentation';
-
-describe('detailPresentation', () => {
- it('exports the embedded disk detail shell classes', () => {
- expect(STORAGE_DETAIL_HEADER_ROW_CLASS).toContain('justify-between');
- expect(STORAGE_DETAIL_EMPTY_CLASS).toContain('text-muted');
- expect(STORAGE_DISK_DETAIL_HEADER_CLASS).toContain('border-b');
- expect(STORAGE_DISK_DETAIL_MODEL_CLASS).toContain('font-semibold');
- expect(STORAGE_DISK_DETAIL_NODE_CLASS).toBe('text-muted');
- expect(STORAGE_DISK_DETAIL_ATTRIBUTE_GRID_CLASS).toContain('min-w-[120px]');
- expect(STORAGE_DISK_DETAIL_LIVE_GRID_CLASS).toContain('sm:grid-cols-3');
- expect(STORAGE_DISK_DETAIL_HISTORY_GRID_CLASS).toContain('min-w-[250px]');
- expect(STORAGE_DISK_DETAIL_SECTION_HEADING_CLASS).toBe('flex items-center gap-2');
- });
-});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.branchcov0724pm.test.ts b/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.branchcov0724pm.test.ts
index 39c67706d2..269583ada2 100644
--- a/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.branchcov0724pm.test.ts
+++ b/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.branchcov0724pm.test.ts
@@ -3,7 +3,6 @@ import { temperatureStore } from '@/utils/temperature';
import type { PhysicalDiskPresentationData } from '@/features/storageBackups/diskPresentation';
import {
getDiskDetailAttributeCards,
- getDiskDetailHistoryCharts,
getLinkedDiskTemperatureTextClass,
} from '@/features/storageBackups/diskDetailPresentation';
@@ -134,39 +133,4 @@ describe('diskDetailPresentation.branchcov0724pm', () => {
expect(cards).toContainEqual({ label: 'CRC Errors', value: '42', ok: false });
});
});
-
- describe('getDiskDetailHistoryCharts disk-family catalog', () => {
- it('includes stored temperature and reallocated sectors independently of current values', () => {
- const charts = getDiskDetailHistoryCharts(
- makeDiskData({
- type: 'hdd',
- temperature: 0,
- smartAttributes: { reallocatedSectors: 3 },
- }),
- );
- expect(charts.map((c) => c.metric)).toEqual(['smart_temp', 'smart_reallocated_sectors']);
- expect(charts[1]).toMatchObject({
- metric: 'smart_reallocated_sectors',
- label: 'Reallocated Sectors',
- unit: 'sectors',
- color: '#f59e0b',
- });
- });
-
- it('omits the reallocated-sectors chart for an NVMe disk even when the field is set', () => {
- const charts = getDiskDetailHistoryCharts(
- makeDiskData({ type: 'nvme', smartAttributes: { reallocatedSectors: 3 } }),
- );
- expect(charts.find((c) => c.metric === 'smart_reallocated_sectors')).toBeUndefined();
- });
-
- it('keeps stored charts available when current SMART fields are absent', () => {
- expect(
- getDiskDetailHistoryCharts(makeDiskData({ type: 'hdd' })).map((chart) => chart.metric),
- ).toEqual(['smart_temp', 'smart_reallocated_sectors']);
- expect(
- getDiskDetailHistoryCharts(makeDiskData({ type: 'NVMe' })).map((chart) => chart.metric),
- ).toEqual(['smart_temp', 'smart_percentage_used', 'smart_available_spare']);
- });
- });
});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.test.ts b/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.test.ts
index a5f615a718..3a3fd88573 100644
--- a/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.test.ts
+++ b/frontend-modern/src/features/storageBackups/__tests__/diskDetailPresentation.test.ts
@@ -1,24 +1,11 @@
import { describe, expect, it } from 'vitest';
import {
- DISK_DETAIL_HISTORY_RANGE_OPTIONS,
- DISK_DETAIL_LIVE_CHARTS,
- getDiskAttributeCardValueTextClass,
- getDiskAttributeValueTextClass,
getDiskDetailAttributeCards,
- getDiskDetailHealthPresentation,
- getDiskDetailHistoryCharts,
- getDiskDetailHistoryFallbackMessage,
- getDiskDetailLiveBadgeLabel,
getLinkedDiskHealthDotVariant,
getLinkedDiskTemperatureTextClass,
} from '@/features/storageBackups/diskDetailPresentation';
describe('diskDetailPresentation', () => {
- it('returns canonical attribute tone classes', () => {
- expect(getDiskAttributeValueTextClass(true)).toBe('text-green-600 dark:text-green-400');
- expect(getDiskAttributeValueTextClass(false)).toBe('text-red-600 dark:text-red-400');
- });
-
it('labels a retained temperature as last known without a health tone', () => {
const disk = {
node: 'tower',
@@ -41,7 +28,6 @@ describe('diskDetailPresentation', () => {
{ warning: 50, critical: 55 },
);
expect(live).toEqual([{ label: 'Temperature', value: '72°C', ok: false }]);
- expect(getDiskAttributeCardValueTextClass(live[0])).toBe('text-red-600 dark:text-red-400');
const retained = getDiskDetailAttributeCards(
{
@@ -59,7 +45,6 @@ describe('diskDetailPresentation', () => {
expect(retained).toEqual([
{ label: 'Last known temperature', value: '72°C', ok: true, lastKnown: true },
]);
- expect(getDiskAttributeCardValueTextClass(retained[0])).toBe('text-muted');
});
it('returns canonical linked-disk state presentation', () => {
@@ -81,41 +66,6 @@ describe('diskDetailPresentation', () => {
);
});
- it('carries the row verdict and its reason into the drawer header', () => {
- const disk = {
- node: 'tower',
- instance: 'cluster-main',
- devPath: '/dev/sda',
- model: 'Archive HDD',
- serial: 'SERIAL-1',
- wwn: '',
- size: 1,
- health: 'PASSED',
- wearout: -1,
- type: 'hdd',
- temperature: 42,
- rpm: 7200,
- used: '',
- riskReasons: [] as string[],
- };
- expect(getDiskDetailHealthPresentation(disk)).toEqual({
- label: 'Healthy',
- summary: '',
- tone: 'text-emerald-700 dark:text-emerald-300',
- });
- expect(
- getDiskDetailHealthPresentation({
- ...disk,
- health: 'FAILED',
- riskReasons: ['SMART failed.'],
- }),
- ).toEqual({
- label: 'Replace Now',
- summary: 'SMART failed.',
- tone: 'text-red-700 dark:text-red-300',
- });
- });
-
it('builds canonical SATA and NVMe attribute cards', () => {
expect(
getDiskDetailAttributeCards({
@@ -186,43 +136,4 @@ describe('diskDetailPresentation', () => {
]),
);
});
-
- it('returns canonical disk detail chart contracts', () => {
- expect(DISK_DETAIL_HISTORY_RANGE_OPTIONS.map((option) => option.value)).toEqual([
- '1h',
- '6h',
- '12h',
- '24h',
- '7d',
- '14d',
- '30d',
- '90d',
- ]);
- expect(DISK_DETAIL_LIVE_CHARTS.map((chart) => chart.label)).toEqual(['Read', 'Write', 'Busy']);
- expect(getDiskDetailLiveBadgeLabel()).toBe('Real-time');
- expect(getDiskDetailHistoryFallbackMessage()).toContain('stable identity');
-
- expect(
- getDiskDetailHistoryCharts({
- node: 'tower',
- instance: 'cluster-main',
- devPath: '/dev/nvme0n1',
- model: 'NVMe',
- serial: 'SERIAL-2',
- wwn: '',
- size: 1,
- health: 'PASSED',
- wearout: -1,
- type: 'nvme',
- temperature: 55,
- rpm: 0,
- used: '',
- riskReasons: [],
- smartAttributes: {
- percentageUsed: 12,
- availableSpare: 97,
- },
- }).map((chart) => chart.metric),
- ).toEqual(['smart_temp', 'smart_percentage_used', 'smart_available_spare']);
- });
});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/diskDrawerPresentation.test.ts b/frontend-modern/src/features/storageBackups/__tests__/diskDrawerPresentation.test.ts
index 9dedf3fd93..4295637b2e 100644
--- a/frontend-modern/src/features/storageBackups/__tests__/diskDrawerPresentation.test.ts
+++ b/frontend-modern/src/features/storageBackups/__tests__/diskDrawerPresentation.test.ts
@@ -2,7 +2,11 @@ import { describe, expect, it } from 'vitest';
import {
buildDiskDrawerActivitySection,
buildDiskDrawerHealthSection,
+ buildDiskDrawerSmartSection,
+ getDiskDrawerCurrentMetrics,
+ getDiskDrawerDeferredMetrics,
getDiskDrawerHistoryGroups,
+ getDiskDrawerNotices,
isDiskDrawerIOAvailable,
} from '@/features/storageBackups/diskDrawerPresentation';
import {
@@ -70,6 +74,103 @@ describe('disk drawer presentation', () => {
);
});
+ it('picks the history catalog by disk family, not by the latest readings', () => {
+ const full = disk({ smartAttributes: { powerOnHours: 100, reallocatedSectors: 0 } });
+ const bare = disk({ temperature: 0, smartAttributes: undefined });
+ const hot = disk({ temperature: 65, smartAttributes: { reallocatedSectors: 0 } });
+ // The same panels, by reference, whatever the snapshot carries.
+ expect(getDiskDrawerHistoryGroups(bare, true)).toBe(getDiskDrawerHistoryGroups(full, true));
+ expect(getDiskDrawerHistoryGroups(hot, true)).toBe(getDiskDrawerHistoryGroups(full, true));
+ expect(metrics(getDiskDrawerHistoryGroups(bare, false))).toEqual([
+ 'smart_temp',
+ 'smart_reallocated_sectors',
+ ]);
+ const nvme = disk({ type: 'nvme', temperature: 0, smartAttributes: undefined });
+ expect(metrics(getDiskDrawerHistoryGroups(nvme, true))).toEqual([
+ 'smart_temp',
+ 'diskread',
+ 'diskwrite',
+ 'disk',
+ 'smart_percentage_used',
+ 'smart_available_spare',
+ ]);
+ expect(getDiskDrawerHistoryGroups(nvme, false)).toBe(
+ getDiskDrawerHistoryGroups(disk({ type: 'NVMe' }), false),
+ );
+ });
+
+ it('leaves I/O panels out only when the collector says per-disk I/O is not available', () => {
+ for (const state of ['unsupported', 'unavailable', 'missing'] as const) {
+ expect(isDiskDrawerIOAvailable(disk({ collection: { io: { state } } }))).toBe(false);
+ }
+ expect(isDiskDrawerIOAvailable(disk({ collection: { io: { state: 'available' } } }))).toBe(
+ true,
+ );
+ // Silence about I/O is not a report that it is missing.
+ expect(isDiskDrawerIOAvailable(disk({ collection: {} }))).toBe(true);
+ expect(
+ getDiskDrawerNotices(
+ disk({
+ smartAttributes: { reallocatedSectors: 0 },
+ collection: {
+ io: { state: 'unsupported', reason: 'per-member counters unavailable' },
+ },
+ }),
+ ),
+ ).toEqual(['Disk I/O is unsupported: per-member counters unavailable']);
+ });
+
+ it('gives the charts only readings the snapshot reports, and a retained one as last known', () => {
+ expect(getDiskDrawerCurrentMetrics(disk({ smartAttributes: undefined }))).toEqual({
+ smart_temp: 40,
+ smart_reallocated_sectors: undefined,
+ smart_percentage_used: undefined,
+ smart_available_spare: undefined,
+ });
+ // A stored zero counter is a reading; a missing or zero temperature is not.
+ expect(
+ getDiskDrawerCurrentMetrics(
+ disk({ temperature: 0, smartAttributes: { reallocatedSectors: 0 } }),
+ ),
+ ).toEqual({
+ smart_temp: undefined,
+ smart_reallocated_sectors: 0,
+ smart_percentage_used: undefined,
+ smart_available_spare: undefined,
+ });
+ expect(getDiskDrawerDeferredMetrics(disk())).toBeUndefined();
+ const retained = disk({
+ collection: { temperature: { state: 'unavailable', reason: 'collection deadline exceeded' } },
+ });
+ expect(getDiskDrawerCurrentMetrics(retained).smart_temp).toBeUndefined();
+ expect(getDiskDrawerDeferredMetrics(retained)).toEqual({
+ smart_temp: { lastKnownValue: 40, message: expect.stringMatching(/\.$/) },
+ });
+ });
+
+ it('shows a positive temperature without the extended SMART object, and invents no counters', () => {
+ const tempOnly = disk({ smartAttributes: undefined });
+ expect(buildDiskDrawerHealthSection(tempOnly).rows).toContainEqual(
+ expect.objectContaining({ label: 'Temperature', value: '40°C' }),
+ );
+ expect(buildDiskDrawerSmartSection(tempOnly).rows).toEqual([]);
+ expect(getDiskDrawerNotices(tempOnly)).toEqual([]);
+ const empty = disk({ smartAttributes: {} });
+ expect(buildDiskDrawerHealthSection(empty).rows).toContainEqual(
+ expect.objectContaining({ label: 'Temperature', value: '40°C' }),
+ );
+ expect(buildDiskDrawerSmartSection(empty).rows).toEqual([]);
+ for (const temperature of [0, -5, Number.NaN]) {
+ const unread = disk({ temperature, smartAttributes: undefined });
+ expect(buildDiskDrawerHealthSection(unread).rows.map((row) => row.label)).not.toContain(
+ 'Temperature',
+ );
+ expect(getDiskDrawerNotices(unread)).toEqual([
+ 'Detailed SMART attributes are not available for this disk.',
+ ]);
+ }
+ });
+
it('tones SSD life and a disk error count so the drawer lifts them', () => {
const health = buildDiskDrawerHealthSection(disk({ type: 'ssd', wearout: 30 }));
expect(health.rows.find((row) => row.label === 'Life remaining')).toMatchObject({
diff --git a/frontend-modern/src/features/storageBackups/detailPresentation.ts b/frontend-modern/src/features/storageBackups/detailPresentation.ts
deleted file mode 100644
index 5e6cc6cc45..0000000000
--- a/frontend-modern/src/features/storageBackups/detailPresentation.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { INFO_CARD_FRAME_CLASS } from '@/components/shared/InfoCardFrame';
-
-// Classes of the compact disk detail the guest drawer embeds for a guest's
-// physical disks (DiskDetail). The Storage page's pool and disk drawers are
-// built from the shared drawer primitives and use none of these.
-
-export const STORAGE_DETAIL_CARD_CLASS = 'rounded-md border border-border bg-surface p-3 shadow-xs';
-
-export const STORAGE_DETAIL_SECTION_TITLE_CLASS = 'text-xs font-semibold text-base-content';
-
-export const STORAGE_DETAIL_INLINE_LABEL_CLASS =
- 'text-[10px] font-medium text-muted uppercase tracking-wide';
-
-export const STORAGE_DETAIL_BADGE_CLASS =
- 'text-[10px] font-normal text-slate-400 bg-surface-alt px-1.5 py-0.5 rounded-sm';
-
-export const STORAGE_DETAIL_META_ROW_CLASS =
- 'flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]';
-
-export const STORAGE_DETAIL_MONO_CHIP_CLASS =
- 'text-muted font-mono bg-surface-alt px-1.5 py-0.5 rounded-sm border border-border';
-
-export const STORAGE_DETAIL_HEADER_ROW_CLASS = 'flex items-center justify-between mb-2';
-export const STORAGE_DETAIL_KEY_CLASS = 'text-muted';
-export const STORAGE_DETAIL_VALUE_CLASS = 'text-base-content font-medium';
-
-export const STORAGE_DETAIL_EMPTY_CLASS = `${INFO_CARD_FRAME_CLASS} text-center text-[11px] text-muted`;
-
-export const STORAGE_DISK_DETAIL_ROOT_CLASS = 'space-y-3';
-export const STORAGE_DISK_DETAIL_HEADER_CLASS =
- 'flex flex-wrap items-end justify-between gap-3 border-b border-border-subtle pb-3';
-export const STORAGE_DISK_DETAIL_MODEL_CLASS = 'font-semibold text-base-content text-sm';
-export const STORAGE_DISK_DETAIL_SERIAL_CLASS = 'font-mono';
-export const STORAGE_DISK_DETAIL_NODE_CLASS = 'text-muted';
-export const STORAGE_DISK_DETAIL_ATTRIBUTE_GRID_CLASS =
- 'flex flex-wrap gap-3 *:flex-1 *:basis-[calc(16.666%-0.5rem)] *:min-w-[120px]';
-export const STORAGE_DISK_DETAIL_SECTION_CLASS = 'space-y-2';
-export const STORAGE_DISK_DETAIL_LIVE_GRID_CLASS = 'grid grid-cols-1 sm:grid-cols-3 gap-3';
-export const STORAGE_DISK_DETAIL_HISTORY_GRID_CLASS =
- 'flex flex-wrap gap-3 *:flex-1 *:basis-[calc(33.333%-0.5rem)] *:min-w-[250px]';
-export const STORAGE_DISK_DETAIL_SECTION_HEADING_CLASS = 'flex items-center gap-2';
diff --git a/frontend-modern/src/features/storageBackups/diskDetailPresentation.ts b/frontend-modern/src/features/storageBackups/diskDetailPresentation.ts
index 96a8fbbbf6..607f03a919 100644
--- a/frontend-modern/src/features/storageBackups/diskDetailPresentation.ts
+++ b/frontend-modern/src/features/storageBackups/diskDetailPresentation.ts
@@ -1,22 +1,10 @@
import {
- getPhysicalDiskHealthStatus,
- getPhysicalDiskHealthSummary,
getPhysicalDiskTemperaturePresentation,
type PhysicalDiskPresentationData,
} from '@/features/storageBackups/diskPresentation';
-import type { HistoryTimeRange } from '@/api/charts';
import { formatPowerOnHours } from '@/utils/format';
import { getMetricSeverity, type MetricDisplayThresholds } from '@/utils/metricThresholds';
import type { StatusIndicatorVariant } from '@/utils/status';
-import { formatHistoryRangeOptionLabel } from '@/components/shared/historyChartModel';
-
-export function getDiskAttributeValueTextClass(ok: boolean): string {
- return ok ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400';
-}
-
-export function getDiskAttributeCardValueTextClass(card: DiskDetailAttributeCard): string {
- return card.lastKnown ? 'text-muted' : getDiskAttributeValueTextClass(card.ok);
-}
export function getLinkedDiskHealthDotVariant(hasIssue: boolean): StatusIndicatorVariant {
return hasIssue ? 'warning' : 'success';
@@ -57,67 +45,6 @@ export type DiskDetailAttributeCard = {
lastKnown?: boolean;
};
-export type DiskDetailChartOption = {
- value: HistoryTimeRange;
- label: string;
-};
-
-export type DiskDetailLiveChartConfig = {
- label: string;
- unit: string;
- metric: 'disk';
- series: 'read' | 'write' | 'io';
-};
-
-export type DiskDetailHistoryChartConfig = {
- metric:
- 'smart_temp' | 'smart_reallocated_sectors' | 'smart_percentage_used' | 'smart_available_spare';
- label: string;
- unit: string;
- color: string;
-};
-
-export const DISK_DETAIL_HISTORY_RANGE_OPTIONS: readonly DiskDetailChartOption[] = (
- ['1h', '6h', '12h', '24h', '7d', '14d', '30d', '90d'] as const
-).map((value) => ({ value, label: formatHistoryRangeOptionLabel(value) }));
-
-export const DISK_DETAIL_LIVE_CHARTS: readonly DiskDetailLiveChartConfig[] = [
- { label: 'Read', unit: 'B/s', metric: 'disk', series: 'read' },
- { label: 'Write', unit: 'B/s', metric: 'disk', series: 'write' },
- { label: 'Busy', unit: '%', metric: 'disk', series: 'io' },
-] as const;
-
-export const getDiskDetailLiveBadgeLabel = (): string => 'Real-time';
-
-export const getDiskDetailHistoryFallbackMessage = (): string =>
- 'Historical disk charts are unavailable until Pulse can resolve a stable identity for this disk.';
-
-export type DiskDetailHealthPresentation = {
- label: string;
- summary: string;
- tone: string;
-};
-
-// The drawer header carries the disk's verdict and its reason. The table row
-// shows only the verdict word, so this is where the reason is read in full.
-export const DISK_DETAIL_HEADER_STACK_CLASS = 'min-w-0 space-y-1';
-export const DISK_DETAIL_HEALTH_ROW_CLASS =
- 'flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-[11px]';
-export const DISK_DETAIL_HEALTH_LABEL_CLASS = 'font-semibold';
-export const DISK_DETAIL_HEALTH_SUMMARY_CLASS =
- 'min-w-0 max-w-full whitespace-normal wrap-break-word text-muted';
-
-export function getDiskDetailHealthPresentation(
- disk: PhysicalDiskPresentationData,
-): DiskDetailHealthPresentation {
- const status = getPhysicalDiskHealthStatus(disk);
- return {
- label: status.label,
- summary: getPhysicalDiskHealthSummary(status),
- tone: status.tone,
- };
-}
-
export function getDiskDetailAttributeCards(
disk: PhysicalDiskPresentationData,
diskTempThresholds?: MetricDisplayThresholds | null,
@@ -224,62 +151,3 @@ export function getDiskDetailAttributeCards(
return cards;
}
-
-const DISK_TEMPERATURE_HISTORY_CHART: DiskDetailHistoryChartConfig = {
- metric: 'smart_temp',
- label: 'Temperature',
- unit: 'C',
- color: '#ef4444',
-};
-
-const ATA_DISK_HISTORY_CHARTS: readonly DiskDetailHistoryChartConfig[] = [
- DISK_TEMPERATURE_HISTORY_CHART,
- {
- metric: 'smart_reallocated_sectors',
- label: 'Reallocated Sectors',
- unit: 'sectors',
- color: '#f59e0b',
- },
-];
-
-const NVME_DISK_HISTORY_CHARTS: readonly DiskDetailHistoryChartConfig[] = [
- DISK_TEMPERATURE_HISTORY_CHART,
- {
- metric: 'smart_percentage_used',
- label: 'Life Used',
- unit: '%',
- color: '#f59e0b',
- },
- {
- metric: 'smart_available_spare',
- label: 'Available Spare',
- unit: '%',
- color: '#10b981',
- },
-];
-
-/**
- * Charts a phone keeps on screen when the rest fold behind one button: the
- * first History chart, and any chart whose SMART card is out of bounds (the
- * cards and charts share labels). Live I/O never pins.
- */
-export function getDiskDetailPhonePinnedChartLabels(
- historyCharts: readonly DiskDetailHistoryChartConfig[],
- cards: readonly DiskDetailAttributeCard[],
-): string[] {
- const failing = new Set(cards.filter((card) => !card.ok && !card.lastKnown).map((c) => c.label));
- return historyCharts
- .filter((chart, index) => index === 0 || failing.has(chart.label))
- .map((chart) => chart.label);
-}
-
-export function getDiskDetailHistoryCharts(
- disk: PhysicalDiskPresentationData,
-): readonly DiskDetailHistoryChartConfig[] {
- // Missing current collection does not erase stored observations. Ask for the
- // existing disk-family catalog and let the store return samples or an honest
- // empty series; never synthesize a value from the current snapshot.
- // Stable entries also keep Solid's reference-keyed For from remounting charts
- // and restarting History reads on every ordinary disk snapshot replacement.
- return disk.type?.toLowerCase() === 'nvme' ? NVME_DISK_HISTORY_CHARTS : ATA_DISK_HISTORY_CHARTS;
-}
diff --git a/frontend-modern/src/routing/__tests__/resourceLinks.test.ts b/frontend-modern/src/routing/__tests__/resourceLinks.test.ts
index c6abbabb38..880d639444 100644
--- a/frontend-modern/src/routing/__tests__/resourceLinks.test.ts
+++ b/frontend-modern/src/routing/__tests__/resourceLinks.test.ts
@@ -53,6 +53,7 @@ import {
buildDockerPath,
buildDockerRouteSearch,
buildKubernetesPath,
+ buildKubernetesRouteSearch,
buildProxmoxPath,
buildProxmoxBackupsPath,
buildStandalonePath,
@@ -210,6 +211,11 @@ describe('resource link routing contract', () => {
expect(buildKubernetesPath('configuration')).toBe('/kubernetes/configuration');
expect(buildKubernetesPath('pods')).toBe('/kubernetes/pods');
expect(KUBERNETES_QUERY_PARAMS.cluster).toBe('cluster');
+ expect(buildKubernetesRouteSearch({ cluster: 'prod', namespace: 'kube-system' })).toBe(
+ '?cluster=prod&namespace=kube-system',
+ );
+ expect(buildKubernetesRouteSearch({ cluster: ' prod ', namespace: '' })).toBe('?cluster=prod');
+ expect(buildKubernetesRouteSearch({})).toBe('');
expect(TRUENAS_PATH).toBe('/truenas');
expect(buildTrueNASPath()).toBe('/truenas/overview');
diff --git a/frontend-modern/src/routing/resourceLinks.ts b/frontend-modern/src/routing/resourceLinks.ts
index e49dff407d..420b72c469 100644
--- a/frontend-modern/src/routing/resourceLinks.ts
+++ b/frontend-modern/src/routing/resourceLinks.ts
@@ -168,6 +168,11 @@ type DockerLinkOptions = {
host?: string | null;
};
+type KubernetesLinkOptions = {
+ cluster?: string | null;
+ namespace?: string | null;
+};
+
type StorageLinkOptions = {
tab?: string | null;
group?: string | null;
@@ -322,6 +327,18 @@ export const buildKubernetesPath = (tab: string = KUBERNETES_DEFAULT_TAB): strin
return normalized ? `${KUBERNETES_PATH}/${normalized}` : KUBERNETES_PATH;
};
+// The cluster and namespace scope the Kubernetes tabs read from the URL. The
+// cluster value is the one the page matches rows on: the cluster id, or its
+// name when no id is reported.
+export const buildKubernetesRouteSearch = (options: KubernetesLinkOptions = {}): string => {
+ const params = new URLSearchParams();
+ const cluster = normalizeQueryValue(options.cluster);
+ const namespace = normalizeQueryValue(options.namespace);
+ if (cluster) params.set(KUBERNETES_QUERY_PARAMS.cluster, cluster);
+ if (namespace) params.set(KUBERNETES_QUERY_PARAMS.namespace, namespace);
+ return serializedRouteSearch(params);
+};
+
export const buildTrueNASPath = (tab: string = TRUENAS_DEFAULT_TAB): string => {
const normalized = tab.trim().replace(/^\/+|\/+$/g, '');
return normalized ? `${TRUENAS_PATH}/${normalized}` : TRUENAS_PATH;
diff --git a/frontend-modern/src/utils/__tests__/alerts.test.ts b/frontend-modern/src/utils/__tests__/alerts.test.ts
index dd5994b993..52eb4fffca 100644
--- a/frontend-modern/src/utils/__tests__/alerts.test.ts
+++ b/frontend-modern/src/utils/__tests__/alerts.test.ts
@@ -418,6 +418,23 @@ describe('getAlertsForUnifiedResource', () => {
expect(ids(getAlertsForUnifiedResource(pmg, active, true))).toEqual(['pmg-queue']);
});
+ it('matches PBS and PMG alerts on their instance id without a metrics target', () => {
+ const pbs = resource({
+ id: 'pbs-unified-1',
+ type: 'pbs',
+ pbs: { instanceId: 'pbs-main' },
+ } as Partial<Resource>);
+ const pmg = resource({
+ id: 'pmg-unified-1',
+ type: 'pmg',
+ pmg: { instanceId: 'pmg-main' },
+ } as Partial<Resource>);
+ const active = byId(alert('pbs-offline', 'pbs-main'), alert('pmg-queue', 'pmg-main'));
+
+ expect(ids(getAlertsForUnifiedResource(pbs, active, true))).toEqual(['pbs-offline']);
+ expect(ids(getAlertsForUnifiedResource(pmg, active, true))).toEqual(['pmg-queue']);
+ });
+
it('matches provider incidents on the unified id without borrowing a parent agent key', () => {
const pod = resource({
id: 'pod-9bd9679901d26654',
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index cf5b769460..e997675063 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -193,9 +193,6 @@ import resourceIdentitySource from '@/utils/resourceIdentity.ts?raw';
import stringUtilsSource from '@/utils/stringUtils.ts?raw';
import diskListSource from '@/components/Storage/DiskList.tsx?raw';
import useDiskListModelSource from '@/components/Storage/useDiskListModel.ts?raw';
-import diskDetailSource from '@/components/Storage/DiskDetail.tsx?raw';
-import storageDetailKeyValueRowSource from '@/components/Storage/StorageDetailKeyValueRow.tsx?raw';
-import storageDetailMetricCardSource from '@/components/Storage/StorageDetailMetricCard.tsx?raw';
import storagePageControlsSource from '@/components/Storage/StoragePageControls.tsx?raw';
import storageContentCardSource from '@/components/Storage/StorageContentCard.tsx?raw';
import storagePageSource from '@/components/Storage/Storage.tsx?raw';
@@ -206,9 +203,10 @@ import useStoragePoolsTableModelSource from '@/components/Storage/useStoragePool
import storageGroupRowSource from '@/components/Storage/StorageGroupRow.tsx?raw';
import enhancedStorageBarSource from '@/components/Storage/EnhancedStorageBar.tsx?raw';
import useEnhancedStorageBarModelSource from '@/components/Storage/useEnhancedStorageBarModel.ts?raw';
+import diskDrawerOverviewSource from '@/components/Storage/DiskDrawerOverview.tsx?raw';
+import diskDrawerPresentationSource from '@/features/storageBackups/diskDrawerPresentation.ts?raw';
import storagePoolDetailSource from '@/components/Storage/StoragePoolDetail.tsx?raw';
import useStoragePoolDetailModelSource from '@/components/Storage/useStoragePoolDetailModel.ts?raw';
-import useDiskDetailModelSource from '@/components/Storage/useDiskDetailModel.ts?raw';
import storagePoolRowSource from '@/components/Storage/StoragePoolRow.tsx?raw';
import storageExpansionStateSource from '@/components/Storage/useStorageExpansionState.ts?raw';
import storageFilterStateSource from '@/components/Storage/useStorageFilterState.ts?raw';
@@ -228,10 +226,6 @@ import serviceHealthPresentationSource from '@/utils/serviceHealthPresentation.t
import alertIncidentEventFiltersSource from '@/components/Alerts/IncidentEventFilters.tsx?raw';
import alertIncidentTimelinePanelSource from '@/components/Alerts/IncidentTimelinePanel.tsx?raw';
import alertIncidentTimelineEventCardSource from '@/components/Alerts/IncidentTimelineEventCard.tsx?raw';
-import swarmServicesDrawerSource from '@/components/Docker/SwarmServicesDrawer.tsx?raw';
-import swarmPresentationSource from '@/utils/swarmPresentation.ts?raw';
-import k8sDeploymentsDrawerSource from '@/components/Kubernetes/K8sDeploymentsDrawer.tsx?raw';
-import k8sDeploymentPresentationSource from '@/utils/k8sDeploymentPresentation.ts?raw';
import k8sNamespacesDrawerSource from '@/components/Kubernetes/K8sNamespacesDrawer.tsx?raw';
import k8sNamespacePresentationSource from '@/utils/k8sNamespacePresentation.ts?raw';
import k8sStatusPresentationSource from '@/utils/k8sStatusPresentation.ts?raw';
@@ -275,7 +269,6 @@ import nodeModalStatusFooterSource from '@/components/Settings/NodeModalStatusFo
import nodeModalStateSource from '@/components/Settings/useNodeModalState.ts?raw';
import nodeModalPresentationSource from '@/utils/nodeModalPresentation.ts?raw';
import diskPresentationSource from '@/features/storageBackups/diskPresentation.ts?raw';
-import storageDetailPresentationSource from '@/features/storageBackups/detailPresentation.ts?raw';
import diskDetailPresentationSource from '@/features/storageBackups/diskDetailPresentation.ts?raw';
import storageRecordPresentationSource from '@/features/storageBackups/recordPresentation.ts?raw';
import storageModelCoreSource from '@/features/storageBackups/storageModelCore.ts?raw';
@@ -1282,9 +1275,9 @@ describe('frontend resource type boundaries', () => {
expect(diskListSource).toContain('getPhysicalDiskRoleLabel');
expect(diskListSource).toContain('getPhysicalDiskParentLabel');
expect(diskListSource).toContain('getPhysicalDiskLifeLabel');
- // The source badge renders in the expansion (DiskDetail), not the table.
+ // The source badge renders in the disk drawer, not the table.
expect(diskListSource).not.toContain('getPhysicalDiskSourceBadgePresentation');
- expect(diskDetailSource).toContain('getPhysicalDiskSourceBadgePresentation');
+ expect(diskDrawerPresentationSource).toContain('getPhysicalDiskSourceBadgePresentation');
expect(diskListSource).not.toContain('const titleize =');
expect(diskListSource).not.toContain('const platformLabel =');
expect(diskListSource).not.toContain('function hasSmartWarning(');
@@ -1325,30 +1318,13 @@ describe('frontend resource type boundaries', () => {
expect(storagePoolDetailSource).not.toContain("'text-yellow-500'");
expect(storagePoolDetailSource).not.toContain("'text-yellow-600 dark:text-yellow-400 italic'");
expect(storagePoolDetailSource).not.toContain("'text-red-600 dark:text-red-400 font-medium'");
- expect(diskDetailSource).toContain('getDiskAttributeCardValueTextClass');
- expect(diskDetailSource).toContain('attributeCards()');
- expect(diskDetailSource).toContain('historyCharts()');
- expect(diskDetailSource).toContain('getDiskDetailHistoryFallbackMessage');
- expect(diskDetailSource).toContain('getDiskDetailLiveBadgeLabel');
- expect(diskDetailSource).toContain('DISK_DETAIL_HISTORY_RANGE_OPTIONS');
- expect(diskDetailSource).toContain('DISK_DETAIL_LIVE_CHARTS');
- expect(diskDetailSource).toContain('StorageDetailMetricCard');
- expect(diskDetailSource).toContain('STORAGE_DETAIL_CARD_CLASS');
- expect(diskDetailSource).toContain('STORAGE_DISK_DETAIL_HEADER_CLASS');
- expect(diskDetailSource).toContain('useDiskDetailModel');
- expect(diskDetailSource).toContain('FormSelect');
- expect(diskDetailSource).toContain('label="Disk history range"');
- expect(diskDetailSource).not.toContain('<select');
- expect(diskDetailSource).not.toContain('const AttrCard: Component');
- expect(diskDetailSource).not.toContain('function extractDiskData(');
- expect(diskDetailSource).not.toContain('const getMetricResourceId = () => {');
- expect(diskDetailSource).not.toContain('function attrColor(');
- expect(diskDetailSource).not.toContain(
- 'flex flex-wrap items-end justify-between gap-3 border-b border-border-subtle pb-3',
- );
- expect(diskDetailSource).not.toContain('class="relative"');
- expect(useDiskDetailModelSource).toContain('extractPhysicalDiskPresentationData');
- expect(useDiskDetailModelSource).toContain('resolvePhysicalDiskHistoryResourceId');
+ // The disk drawer is built like the guest and node drawers: alerts,
+ // Worth checking, drawer charts, then one closed Details.
+ expect(diskDrawerOverviewSource).toContain('DrawerAttentionSection');
+ expect(diskDrawerOverviewSource).toContain('DrawerExceptionList');
+ expect(diskDrawerOverviewSource).toContain('GuestDrawerHistory');
+ expect(diskDrawerOverviewSource).toContain('TechnicalDetailsDisclosure');
+ expect(diskDrawerOverviewSource).not.toContain('<select');
expect(storagePoolRowSource).toContain('getStoragePoolProtectionTextClass');
expect(storagePoolRowSource).toContain('stateToneClass');
expect(storagePoolRowSource).toContain('buildStoragePoolRowModel');
@@ -1630,20 +1606,6 @@ describe('frontend resource type boundaries', () => {
);
expect(diskPresentationSource).toContain('export function filterAndSortPhysicalDisks');
expect(diskDetailPresentationSource).toContain('export function getDiskDetailAttributeCards');
- expect(diskDetailPresentationSource).toContain('export function getDiskDetailHistoryCharts');
- expect(diskDetailPresentationSource).toContain(
- 'export const DISK_DETAIL_HISTORY_RANGE_OPTIONS',
- );
- expect(diskDetailPresentationSource).toContain('export const DISK_DETAIL_LIVE_CHARTS');
- expect(storageDetailPresentationSource).toContain('export const STORAGE_DETAIL_CARD_CLASS');
- expect(storageDetailPresentationSource).not.toContain('STORAGE_DETAIL_SELECT_CLASS');
- expect(storageDetailPresentationSource).toContain('export const STORAGE_DETAIL_EMPTY_CLASS');
- expect(storageDetailPresentationSource).toContain(
- 'export const STORAGE_DISK_DETAIL_HEADER_CLASS',
- );
- expect(storageDetailKeyValueRowSource).toContain('InfoCardKeyValueRow');
- expect(storageDetailKeyValueRowSource).toContain('desktopAt="sm"');
- expect(storageDetailMetricCardSource).toContain('STORAGE_DETAIL_CARD_CLASS');
expect(storagePoolDetailSource).not.toContain('<tr class=');
expect(storagePoolDetailSource).not.toContain('col-span-2');
expect(storagePoolDetailSource).not.toContain('text-base-content truncate flex-1');
@@ -1761,9 +1723,6 @@ describe('frontend resource type boundaries', () => {
expect(useStorageAlertStateSource).not.toContain('const severityWeight =');
expect(useStorageAlertStateSource).not.toContain('const mergeAlertState =');
expect(useStorageAlertStateSource).not.toContain('const getRecordAlertResourceIds =');
- expect(diskDetailPresentationSource).toContain(
- 'export function getDiskAttributeValueTextClass',
- );
expect(diskDetailPresentationSource).toContain('export function getLinkedDiskHealthDotVariant');
expect(diskDetailPresentationSource).toContain(
'export function getLinkedDiskTemperatureTextClass',
@@ -1904,50 +1863,6 @@ describe('frontend resource type boundaries', () => {
expect(serviceHealthPresentationSource).toContain(
'export function getServiceHealthPresentation',
);
- expect(swarmServicesDrawerSource).toContain('getSimpleStatusIndicator');
- expect(swarmServicesDrawerSource).toContain('<StatusDot');
- expect(swarmServicesDrawerSource).toContain('getSwarmDrawerPresentation');
- expect(swarmServicesDrawerSource).toContain('getSwarmServicesEmptyState');
- expect(swarmServicesDrawerSource).toContain('getSwarmServicesLoadingState');
- expect(swarmServicesDrawerSource).toContain('<PlatformDetailTable');
- expect(swarmServicesDrawerSource).not.toContain('<div class="overflow-x-auto">');
- expect(swarmServicesDrawerSource).not.toContain('const statusTone =');
- expect(swarmServicesDrawerSource).not.toContain('No Swarm cluster detected');
- expect(swarmServicesDrawerSource).not.toContain('Search services...');
- expect(swarmServicesDrawerSource).not.toContain('Loading Swarm services...');
- expect(swarmServicesDrawerSource).not.toContain('No Swarm services found');
- expect(swarmServicesDrawerSource).not.toContain('No services match your filters');
- expect(swarmPresentationSource).toContain('export function getSwarmDrawerPresentation');
- expect(swarmPresentationSource).toContain('export function getSwarmServicesEmptyState');
- expect(swarmPresentationSource).toContain('export function getSwarmServicesLoadingState');
- expect(k8sDeploymentsDrawerSource).toContain('getSimpleStatusIndicator');
- expect(k8sDeploymentsDrawerSource).toContain('<StatusDot');
- expect(k8sDeploymentsDrawerSource).toContain('getK8sDeploymentsDrawerPresentation');
- expect(k8sDeploymentsDrawerSource).toContain('getK8sDeploymentsEmptyState');
- expect(k8sDeploymentsDrawerSource).toContain('getK8sDeploymentsLoadingState');
- expect(k8sDeploymentsDrawerSource).toContain('<PlatformDetailTable');
- expect(k8sDeploymentsDrawerSource).not.toContain('<div class="overflow-x-auto">');
- expect(k8sDeploymentPresentationSource).toContain('getAllFilterOptionLabel');
- expect(k8sDeploymentsDrawerSource).not.toContain('const statusTone =');
- expect(k8sDeploymentsDrawerSource).not.toContain('Desired state controllers (not Pods)');
- expect(k8sDeploymentsDrawerSource).not.toContain('Search deployments...');
- expect(k8sDeploymentsDrawerSource).not.toContain('label="Namespace"');
- expect(k8sDeploymentsDrawerSource).not.toContain('All namespaces');
- expect(k8sDeploymentsDrawerSource).not.toContain('Open Pods');
- expect(k8sDeploymentsDrawerSource).not.toContain('Loading deployments...');
- expect(k8sDeploymentsDrawerSource).not.toContain('No deployments match your filters');
- expect(k8sDeploymentsDrawerSource).not.toContain(
- 'Try clearing the search or namespace filter.',
- );
- expect(k8sDeploymentPresentationSource).toContain(
- 'export function getK8sDeploymentsDrawerPresentation',
- );
- expect(k8sDeploymentPresentationSource).toContain(
- 'export function getK8sDeploymentsEmptyState',
- );
- expect(k8sDeploymentPresentationSource).toContain(
- 'export function getK8sDeploymentsLoadingState',
- );
expect(k8sNamespacesDrawerSource).toContain('getNamespaceCountsIndicator');
expect(k8sNamespacesDrawerSource).toContain('getK8sNamespacesDrawerPresentation');
expect(k8sNamespacesDrawerSource).toContain('getK8sNamespacesEmptyState');
@@ -2205,10 +2120,6 @@ describe('frontend resource type boundaries', () => {
expect(textPresentationSource).toContain('humanizeToken');
expect(textPresentationSource).toContain('formatIdentifierLabel');
expect(resourceCorrelationPresentationSource).not.toContain('formatTrimmedLabel');
- expect(swarmServicesDrawerSource).toContain('asTrimmedString');
- expect(swarmServicesDrawerSource).not.toContain(
- "const normalize = (value?: string | null) => (value || '').trim();",
- );
expect(proxmoxMailGatewayDrawerSource).toContain('asTrimmedString');
expect(proxmoxMailGatewayDrawerSource).not.toContain(
"const normalize = (value?: string | null) => (value || '').trim();",
@@ -2217,10 +2128,6 @@ describe('frontend resource type boundaries', () => {
expect(k8sNamespacesDrawerSource).not.toContain(
"const normalize = (value?: string | null) => (value || '').trim();",
);
- expect(k8sDeploymentsDrawerSource).toContain('asTrimmedString');
- expect(k8sDeploymentsDrawerSource).not.toContain(
- "const normalize = (value?: string | null) => (value || '').trim();",
- );
expect(activeTurnStatusSource).toContain('formatIdentifierLabel');
expect(toolPresentationSource).toContain('formatIdentifierLabel');
expect(aiChatSource).toContain('formatIdentifierLabel');
diff --git a/frontend-modern/src/utils/__tests__/k8sDeploymentPresentation.test.ts b/frontend-modern/src/utils/__tests__/k8sDeploymentPresentation.test.ts
deleted file mode 100644
index 5f80eeb1e4..0000000000
--- a/frontend-modern/src/utils/__tests__/k8sDeploymentPresentation.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- getK8sDeploymentsDrawerPresentation,
- getK8sDeploymentsEmptyState,
- getK8sDeploymentsLoadingState,
-} from '../k8sDeploymentPresentation';
-
-describe('k8sDeploymentPresentation', () => {
- it('returns canonical drawer presentation', () => {
- expect(getK8sDeploymentsDrawerPresentation()).toEqual({
- title: 'Deployments',
- description: 'Desired state controllers (not Pods)',
- searchPlaceholder: 'Search deployments...',
- namespaceFilterLabel: 'Namespace',
- allNamespacesLabel: 'All namespaces',
- openPodsLabel: 'Open Pods',
- viewPodsLabel: 'View Pods',
- deploymentColumnLabel: 'Deployment',
- namespaceColumnLabel: 'Namespace',
- desiredColumnLabel: 'Desired',
- updatedColumnLabel: 'Updated',
- readyColumnLabel: 'Ready',
- availableColumnLabel: 'Available',
- actionsColumnLabel: 'Actions',
- });
- });
-
- it('returns canonical deployments empty-state copy', () => {
- expect(getK8sDeploymentsLoadingState()).toEqual({
- title: 'Loading deployments...',
- description: 'Fetching unified resources.',
- });
- expect(getK8sDeploymentsEmptyState(true)).toEqual({
- title: 'No deployments match your filters',
- description: 'Try clearing the search or namespace filter.',
- });
- expect(getK8sDeploymentsEmptyState(false)).toEqual({
- title: 'No deployments found',
- description:
- 'Enable the Kubernetes agent deployment collection, then wait for the next report.',
- });
- });
-});
diff --git a/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.branchcov0718.test.ts b/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.branchcov0718.test.ts
index e968c6cbbc..55cb02c6d7 100644
--- a/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.branchcov0718.test.ts
+++ b/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.branchcov0718.test.ts
@@ -6,10 +6,9 @@ import {
K8S_NAMESPACES_COLUMN_PODS_LABEL,
K8S_NAMESPACES_DRAWER_DESCRIPTION,
K8S_NAMESPACES_DRAWER_TITLE,
- K8S_NAMESPACES_OPEN_ALL_PODS_LABEL,
- K8S_NAMESPACES_OPEN_PODS_LABEL,
+ K8S_NAMESPACES_OPEN_ALL_WORKLOADS_LABEL,
+ K8S_NAMESPACES_OPEN_WORKLOADS_LABEL,
K8S_NAMESPACES_SEARCH_PLACEHOLDER,
- K8S_NAMESPACES_VIEW_DEPLOYMENTS_LABEL,
getK8sNamespacesFailureState,
} from '../k8sNamespacePresentation';
@@ -45,9 +44,8 @@ describe('k8sNamespacePresentation.branchcov0718 — residual uncovered exports'
});
it('exposes the canonical action button labels', () => {
- expect(K8S_NAMESPACES_OPEN_ALL_PODS_LABEL).toBe('Open All Pods');
- expect(K8S_NAMESPACES_OPEN_PODS_LABEL).toBe('Open Pods');
- expect(K8S_NAMESPACES_VIEW_DEPLOYMENTS_LABEL).toBe('View Deployments');
+ expect(K8S_NAMESPACES_OPEN_ALL_WORKLOADS_LABEL).toBe('Open all workloads');
+ expect(K8S_NAMESPACES_OPEN_WORKLOADS_LABEL).toBe('Open workloads');
});
it('exposes the canonical table column labels', () => {
diff --git a/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.test.ts b/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.test.ts
index fee9e6c33b..8c80a51a8a 100644
--- a/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/k8sNamespacePresentation.test.ts
@@ -12,9 +12,8 @@ describe('k8sNamespacePresentation', () => {
title: 'Namespaces',
description: 'Scope Pods and Deployments by namespace',
searchPlaceholder: 'Search namespaces...',
- openAllPodsLabel: 'Open All Pods',
- openPodsLabel: 'Open Pods',
- viewDeploymentsLabel: 'View Deployments',
+ openAllWorkloadsLabel: 'Open all workloads',
+ openWorkloadsLabel: 'Open workloads',
namespaceColumnLabel: 'Namespace',
podsColumnLabel: 'Pods',
deploymentsColumnLabel: 'Deployments',
diff --git a/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts b/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts
index 74ec7d8083..0c98e3618a 100644
--- a/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts
+++ b/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
+import canonicalPlatformAuditSource from '../../../scripts/canonical-platform-audit.mjs?raw';
import {
getSourcePlatformLabel,
getSourcePlatformPresentation,
@@ -286,4 +287,20 @@ describe('sourcePlatforms', () => {
expect(sourcePlatformScopeMatchesFilter('', 'proxmox-all')).toBe(false);
});
});
+
+ // The platform audit names the presentation modules that own canonical
+ // copy; a module deleted with its drawer must leave the audit too, or the
+ // audit keeps pointing contributors at code that no longer exists.
+ it('names only platform presentation modules that still exist', () => {
+ const sources = import.meta.glob('/src/**/*.{ts,tsx}');
+ const auditedPaths = [
+ ...new Set(
+ [...canonicalPlatformAuditSource.matchAll(/'(src\/[^'*]+\.(?:ts|tsx))'/g)].map(
+ (match) => match[1],
+ ),
+ ),
+ ];
+ expect(auditedPaths.length).toBeGreaterThan(0);
+ expect(auditedPaths.filter((path) => !(`/${path}` in sources))).toEqual([]);
+ });
});
diff --git a/frontend-modern/src/utils/__tests__/swarmPresentation.branchcov0718.test.ts b/frontend-modern/src/utils/__tests__/swarmPresentation.branchcov0718.test.ts
deleted file mode 100644
index ab0d3c8488..0000000000
--- a/frontend-modern/src/utils/__tests__/swarmPresentation.branchcov0718.test.ts
+++ /dev/null
@@ -1,256 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- // Vocabulary constants — the sibling test never imports these directly;
- // each `export const` is its own coverage statement, so pinning them
- // guards against silent renames and exercises the per-symbol getter
- // coverage reports flag as "get".
- SWARM_DRAWER_TITLE,
- SWARM_DRAWER_SEARCH_PLACEHOLDER,
- SWARM_DRAWER_NO_CLUSTER_LABEL,
- SWARM_DRAWER_CLUSTER_PREFIX,
- SWARM_DRAWER_CLUSTER_ID_PREFIX,
- SWARM_DRAWER_ROLE_PREFIX,
- SWARM_DRAWER_STATE_PREFIX,
- SWARM_DRAWER_CONTROL_PREFIX,
- SWARM_DRAWER_CONTROL_AVAILABLE_LABEL,
- SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL,
- SWARM_DRAWER_COLUMN_SERVICE_LABEL,
- SWARM_DRAWER_COLUMN_STACK_LABEL,
- SWARM_DRAWER_COLUMN_IMAGE_LABEL,
- SWARM_DRAWER_COLUMN_MODE_LABEL,
- SWARM_DRAWER_COLUMN_DESIRED_LABEL,
- SWARM_DRAWER_COLUMN_RUNNING_LABEL,
- SWARM_DRAWER_COLUMN_UPDATE_LABEL,
- SWARM_DRAWER_COLUMN_PORTS_LABEL,
- formatSwarmClusterId,
- formatSwarmClusterSummary,
- formatSwarmControlLabel,
- formatSwarmRoleLabel,
- formatSwarmStateLabel,
- getSwarmDrawerPresentation,
-} from '../swarmPresentation';
-
-// Residual branch-coverage probes for the swarm-presentation module.
-// The sibling test (swarmPresentation.test.ts) already exercises:
-// - getSwarmDrawerPresentation() via a single bulk toEqual,
-// - the happy trim-truthy arm + the empty-string falsy arm of every
-// formatSwarm* helper,
-// - the boolean true/false arms and the null arm of
-// formatSwarmControlLabel,
-// - both arms of getSwarmServicesEmptyState and the fixed return of
-// getSwarmServicesLoadingState.
-// This file targets the residual:
-// (a) every exported SWARM_DRAWER_* constant imported and pinned, so the
-// per-symbol getter the coverage tool reports is exercised for each,
-// (b) every field of getSwarmDrawerPresentation() read individually (the
-// bulk toEqual in the sibling test reads the object shape but does
-// not register a dedicated property-get coverage hit per field),
-// (c) the null / undefined / whitespace-only / surrounding-whitespace
-// input variants of every formatSwarm* helper — these all funnel
-// through the `|| ''` coalesce + `.trim()` pipeline but are never
-// exercised by the sibling test,
-// (d) the non-boolean primitive arm of formatSwarmControlLabel's
-// typeof guard (sibling test only passes null, which is one
-// specific non-boolean; the typeof check also rejects undefined,
-// strings, and numbers).
-
-describe('swarmPresentation.branchcov0718', () => {
- describe('exported vocabulary constants', () => {
- // Each constant below is its own coverage statement; importing and
- // asserting the literal pins the canonical UI copy and protects
- // against silent renames.
- it('exposes the drawer title and search placeholder', () => {
- expect(SWARM_DRAWER_TITLE).toBe('Swarm');
- expect(SWARM_DRAWER_SEARCH_PLACEHOLDER).toBe('Search services...');
- });
-
- it('exposes the no-cluster and cluster-prefix vocabulary', () => {
- expect(SWARM_DRAWER_NO_CLUSTER_LABEL).toBe('No Swarm cluster detected');
- expect(SWARM_DRAWER_CLUSTER_PREFIX).toBe('Cluster:');
- expect(SWARM_DRAWER_CLUSTER_ID_PREFIX).toBe('Cluster ID:');
- });
-
- it('exposes the role / state / control prefix vocabulary', () => {
- expect(SWARM_DRAWER_ROLE_PREFIX).toBe('Role:');
- expect(SWARM_DRAWER_STATE_PREFIX).toBe('State:');
- expect(SWARM_DRAWER_CONTROL_PREFIX).toBe('Control:');
- });
-
- it('exposes the control availability status vocabulary', () => {
- expect(SWARM_DRAWER_CONTROL_AVAILABLE_LABEL).toBe('available');
- expect(SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL).toBe('unavailable');
- });
-
- it('exposes every service-table column label', () => {
- expect(SWARM_DRAWER_COLUMN_SERVICE_LABEL).toBe('Service');
- expect(SWARM_DRAWER_COLUMN_STACK_LABEL).toBe('Stack');
- expect(SWARM_DRAWER_COLUMN_IMAGE_LABEL).toBe('Image');
- expect(SWARM_DRAWER_COLUMN_MODE_LABEL).toBe('Mode');
- expect(SWARM_DRAWER_COLUMN_DESIRED_LABEL).toBe('Desired');
- expect(SWARM_DRAWER_COLUMN_RUNNING_LABEL).toBe('Running');
- expect(SWARM_DRAWER_COLUMN_UPDATE_LABEL).toBe('Update');
- expect(SWARM_DRAWER_COLUMN_PORTS_LABEL).toBe('Ports');
- });
- });
-
- describe('getSwarmDrawerPresentation — per-field property gets', () => {
- // The sibling test asserts the whole shape via toEqual; reading each
- // field individually registers a dedicated property-get coverage hit
- // and guards against the wrapper drifting away from any single
- // underlying constant.
- const presentation = getSwarmDrawerPresentation();
-
- it('wires title and searchPlaceholder fields', () => {
- expect(presentation.title).toBe(SWARM_DRAWER_TITLE);
- expect(presentation.title).toBe('Swarm');
- expect(presentation.searchPlaceholder).toBe(SWARM_DRAWER_SEARCH_PLACEHOLDER);
- expect(presentation.searchPlaceholder).toBe('Search services...');
- });
-
- it('wires noClusterLabel and the cluster/cluster-id prefixes', () => {
- expect(presentation.noClusterLabel).toBe(SWARM_DRAWER_NO_CLUSTER_LABEL);
- expect(presentation.noClusterLabel).toBe('No Swarm cluster detected');
- expect(presentation.clusterPrefix).toBe(SWARM_DRAWER_CLUSTER_PREFIX);
- expect(presentation.clusterPrefix).toBe('Cluster:');
- expect(presentation.clusterIdPrefix).toBe(SWARM_DRAWER_CLUSTER_ID_PREFIX);
- expect(presentation.clusterIdPrefix).toBe('Cluster ID:');
- });
-
- it('wires the role / state / control prefixes', () => {
- expect(presentation.rolePrefix).toBe(SWARM_DRAWER_ROLE_PREFIX);
- expect(presentation.rolePrefix).toBe('Role:');
- expect(presentation.statePrefix).toBe(SWARM_DRAWER_STATE_PREFIX);
- expect(presentation.statePrefix).toBe('State:');
- expect(presentation.controlPrefix).toBe(SWARM_DRAWER_CONTROL_PREFIX);
- expect(presentation.controlPrefix).toBe('Control:');
- });
-
- it('wires the control availability status labels', () => {
- expect(presentation.controlAvailableLabel).toBe(SWARM_DRAWER_CONTROL_AVAILABLE_LABEL);
- expect(presentation.controlAvailableLabel).toBe('available');
- expect(presentation.controlUnavailableLabel).toBe(SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL);
- expect(presentation.controlUnavailableLabel).toBe('unavailable');
- });
-
- it('wires every service-table column label field', () => {
- expect(presentation.serviceColumnLabel).toBe(SWARM_DRAWER_COLUMN_SERVICE_LABEL);
- expect(presentation.serviceColumnLabel).toBe('Service');
- expect(presentation.stackColumnLabel).toBe(SWARM_DRAWER_COLUMN_STACK_LABEL);
- expect(presentation.stackColumnLabel).toBe('Stack');
- expect(presentation.imageColumnLabel).toBe(SWARM_DRAWER_COLUMN_IMAGE_LABEL);
- expect(presentation.imageColumnLabel).toBe('Image');
- expect(presentation.modeColumnLabel).toBe(SWARM_DRAWER_COLUMN_MODE_LABEL);
- expect(presentation.modeColumnLabel).toBe('Mode');
- expect(presentation.desiredColumnLabel).toBe(SWARM_DRAWER_COLUMN_DESIRED_LABEL);
- expect(presentation.desiredColumnLabel).toBe('Desired');
- expect(presentation.runningColumnLabel).toBe(SWARM_DRAWER_COLUMN_RUNNING_LABEL);
- expect(presentation.runningColumnLabel).toBe('Running');
- expect(presentation.updateColumnLabel).toBe(SWARM_DRAWER_COLUMN_UPDATE_LABEL);
- expect(presentation.updateColumnLabel).toBe('Update');
- expect(presentation.portsColumnLabel).toBe(SWARM_DRAWER_COLUMN_PORTS_LABEL);
- expect(presentation.portsColumnLabel).toBe('Ports');
- });
- });
-
- describe('formatSwarmClusterSummary — coalesce + trim edge variants', () => {
- // Sibling test passes 'Prod' (truthy post-trim) and '' (falsy post-trim).
- // Residual: the `clusterName || ''` coalesce arm (null/undefined inputs),
- // the whitespace-only post-trim falsy arm, and the surrounding-whitespace
- // post-trim truthy arm.
- it('returns the no-cluster label for null/undefined', () => {
- expect(formatSwarmClusterSummary(null)).toBe(SWARM_DRAWER_NO_CLUSTER_LABEL);
- expect(formatSwarmClusterSummary(undefined)).toBe(SWARM_DRAWER_NO_CLUSTER_LABEL);
- });
-
- it('returns the no-cluster label for whitespace-only input', () => {
- expect(formatSwarmClusterSummary(' ')).toBe(SWARM_DRAWER_NO_CLUSTER_LABEL);
- expect(formatSwarmClusterSummary('\t\n')).toBe(SWARM_DRAWER_NO_CLUSTER_LABEL);
- });
-
- it('trims surrounding whitespace before joining with the prefix', () => {
- expect(formatSwarmClusterSummary(' Prod ')).toBe('Cluster: Prod');
- expect(formatSwarmClusterSummary('\tStaging\n')).toBe('Cluster: Staging');
- });
- });
-
- describe('formatSwarmClusterId — coalesce + trim edge variants', () => {
- it('returns empty string for null/undefined', () => {
- expect(formatSwarmClusterId(null)).toBe('');
- expect(formatSwarmClusterId(undefined)).toBe('');
- });
-
- it('returns empty string for whitespace-only input', () => {
- expect(formatSwarmClusterId(' ')).toBe('');
- expect(formatSwarmClusterId('\t\n')).toBe('');
- });
-
- it('trims surrounding whitespace before joining with the prefix', () => {
- expect(formatSwarmClusterId(' abc123 ')).toBe('Cluster ID: abc123');
- expect(formatSwarmClusterId('\tdef456\n')).toBe('Cluster ID: def456');
- });
- });
-
- describe('formatSwarmRoleLabel — coalesce + trim edge variants', () => {
- it('returns empty string for null/undefined', () => {
- expect(formatSwarmRoleLabel(null)).toBe('');
- expect(formatSwarmRoleLabel(undefined)).toBe('');
- });
-
- it('returns empty string for whitespace-only input', () => {
- expect(formatSwarmRoleLabel(' ')).toBe('');
- expect(formatSwarmRoleLabel('\t\n')).toBe('');
- });
-
- it('trims surrounding whitespace before joining with the prefix', () => {
- expect(formatSwarmRoleLabel(' manager ')).toBe('Role: manager');
- expect(formatSwarmRoleLabel('\tworker\n')).toBe('Role: worker');
- });
- });
-
- describe('formatSwarmStateLabel — coalesce + trim edge variants', () => {
- it('returns empty string for null/undefined', () => {
- expect(formatSwarmStateLabel(null)).toBe('');
- expect(formatSwarmStateLabel(undefined)).toBe('');
- });
-
- it('returns empty string for whitespace-only input', () => {
- expect(formatSwarmStateLabel(' ')).toBe('');
- expect(formatSwarmStateLabel('\t\n')).toBe('');
- });
-
- it('trims surrounding whitespace before joining with the prefix', () => {
- expect(formatSwarmStateLabel(' active ')).toBe('State: active');
- expect(formatSwarmStateLabel('\tpaused\n')).toBe('State: paused');
- });
- });
-
- describe('formatSwarmControlLabel — typeof guard residual arms', () => {
- // Sibling test passes true/false (the boolean arms of the ternary) and
- // null (one specific non-boolean). The typeof guard also rejects
- // undefined, strings, and numbers — exercise each of those to take
- // every arm the guard offers.
- it('returns empty string for undefined', () => {
- expect(formatSwarmControlLabel(undefined)).toBe('');
- });
-
- it('returns empty string for non-boolean primitive inputs', () => {
- const stringInput = 'true' as unknown as Parameters<typeof formatSwarmControlLabel>[0];
- const numberInput = 1 as unknown as Parameters<typeof formatSwarmControlLabel>[0];
- const objectInput = {} as unknown as Parameters<typeof formatSwarmControlLabel>[0];
- expect(formatSwarmControlLabel(stringInput)).toBe('');
- expect(formatSwarmControlLabel(numberInput)).toBe('');
- expect(formatSwarmControlLabel(objectInput)).toBe('');
- });
-
- it('still returns the canonical copy for genuine boolean inputs', () => {
- // Guard against an over-eager typeof change: the boolean path must
- // still interpolate the canonical available/unavailable labels.
- expect(formatSwarmControlLabel(true)).toBe(
- `${SWARM_DRAWER_CONTROL_PREFIX} ${SWARM_DRAWER_CONTROL_AVAILABLE_LABEL}`,
- );
- expect(formatSwarmControlLabel(false)).toBe(
- `${SWARM_DRAWER_CONTROL_PREFIX} ${SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL}`,
- );
- });
- });
-});
diff --git a/frontend-modern/src/utils/__tests__/swarmPresentation.test.ts b/frontend-modern/src/utils/__tests__/swarmPresentation.test.ts
deleted file mode 100644
index e226209346..0000000000
--- a/frontend-modern/src/utils/__tests__/swarmPresentation.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- formatSwarmClusterId,
- formatSwarmClusterSummary,
- formatSwarmControlLabel,
- formatSwarmRoleLabel,
- formatSwarmStateLabel,
- getSwarmDrawerPresentation,
- getSwarmServicesEmptyState,
- getSwarmServicesLoadingState,
-} from '../swarmPresentation';
-
-describe('swarmPresentation', () => {
- it('returns canonical swarm drawer presentation', () => {
- expect(getSwarmDrawerPresentation()).toEqual({
- title: 'Swarm',
- searchPlaceholder: 'Search services...',
- noClusterLabel: 'No Swarm cluster detected',
- clusterPrefix: 'Cluster:',
- clusterIdPrefix: 'Cluster ID:',
- rolePrefix: 'Role:',
- statePrefix: 'State:',
- controlPrefix: 'Control:',
- controlAvailableLabel: 'available',
- controlUnavailableLabel: 'unavailable',
- serviceColumnLabel: 'Service',
- stackColumnLabel: 'Stack',
- imageColumnLabel: 'Image',
- modeColumnLabel: 'Mode',
- desiredColumnLabel: 'Desired',
- runningColumnLabel: 'Running',
- updateColumnLabel: 'Update',
- portsColumnLabel: 'Ports',
- });
- });
-
- it('formats canonical swarm drawer labels', () => {
- expect(formatSwarmClusterSummary('Prod')).toBe('Cluster: Prod');
- expect(formatSwarmClusterSummary('')).toBe('No Swarm cluster detected');
- expect(formatSwarmClusterId('abc123')).toBe('Cluster ID: abc123');
- expect(formatSwarmClusterId('')).toBe('');
- expect(formatSwarmRoleLabel('manager')).toBe('Role: manager');
- expect(formatSwarmRoleLabel('')).toBe('');
- expect(formatSwarmStateLabel('active')).toBe('State: active');
- expect(formatSwarmStateLabel('')).toBe('');
- expect(formatSwarmControlLabel(true)).toBe('Control: available');
- expect(formatSwarmControlLabel(false)).toBe('Control: unavailable');
- expect(formatSwarmControlLabel(null)).toBe('');
- });
-
- it('returns canonical swarm empty-state copy', () => {
- expect(getSwarmServicesEmptyState(true)).toEqual({
- title: 'No services match your filters',
- description: 'Try clearing the search.',
- });
- expect(getSwarmServicesEmptyState(false)).toEqual({
- title: 'No Swarm services found',
- description:
- 'Enable Swarm service collection in the container runtime agent (includeServices) and wait for the next report.',
- });
- expect(getSwarmServicesLoadingState()).toEqual({
- text: 'Loading Swarm services...',
- });
- });
-});
diff --git a/frontend-modern/src/utils/alerts.ts b/frontend-modern/src/utils/alerts.ts
index 0677a13fbf..f789f7514b 100644
--- a/frontend-modern/src/utils/alerts.ts
+++ b/frontend-modern/src/utils/alerts.ts
@@ -194,6 +194,11 @@ const getUnifiedResourceAlertKeys = (
resource.canonicalIdentity?.supersededIds?.forEach(add);
add(resource.proxmox?.sourceId);
add(resource.metricsTarget?.resourceId);
+ // PBS and PMG alerts are keyed on the instance id (internal/alerts pmg.go,
+ // pbs.go), which the platform tables match too; the drawer must not depend
+ // on a metrics target being set to find them.
+ add(resource.pbs?.instanceId);
+ add(resource.pmg?.instanceId);
// The alert engine keys a Docker container's alerts on its host and
// container ID ("docker:<host>/<container ID>"), or on its name when it has
// no ID (internal/alerts DockerContainerResourceID).
diff --git a/frontend-modern/src/utils/k8sDeploymentPresentation.ts b/frontend-modern/src/utils/k8sDeploymentPresentation.ts
deleted file mode 100644
index 06c5c7e05b..0000000000
--- a/frontend-modern/src/utils/k8sDeploymentPresentation.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { getAllFilterOptionLabel } from '@/components/shared/filterOptionPresentation';
-
-export const K8S_DEPLOYMENTS_DRAWER_TITLE = 'Deployments';
-export const K8S_DEPLOYMENTS_DRAWER_DESCRIPTION = 'Desired state controllers (not Pods)';
-export const K8S_DEPLOYMENTS_SEARCH_PLACEHOLDER = 'Search deployments...';
-export const K8S_DEPLOYMENTS_NAMESPACE_FILTER_LABEL = 'Namespace';
-export const K8S_DEPLOYMENTS_ALL_NAMESPACES_LABEL = getAllFilterOptionLabel('namespaces');
-export const K8S_DEPLOYMENTS_OPEN_PODS_LABEL = 'Open Pods';
-export const K8S_DEPLOYMENTS_VIEW_PODS_LABEL = 'View Pods';
-export const K8S_DEPLOYMENTS_COLUMN_DEPLOYMENT_LABEL = 'Deployment';
-export const K8S_DEPLOYMENTS_COLUMN_NAMESPACE_LABEL = 'Namespace';
-export const K8S_DEPLOYMENTS_COLUMN_DESIRED_LABEL = 'Desired';
-export const K8S_DEPLOYMENTS_COLUMN_UPDATED_LABEL = 'Updated';
-export const K8S_DEPLOYMENTS_COLUMN_READY_LABEL = 'Ready';
-export const K8S_DEPLOYMENTS_COLUMN_AVAILABLE_LABEL = 'Available';
-export const K8S_DEPLOYMENTS_COLUMN_ACTIONS_LABEL = 'Actions';
-
-export function getK8sDeploymentsDrawerPresentation() {
- return {
- title: K8S_DEPLOYMENTS_DRAWER_TITLE,
- description: K8S_DEPLOYMENTS_DRAWER_DESCRIPTION,
- searchPlaceholder: K8S_DEPLOYMENTS_SEARCH_PLACEHOLDER,
- namespaceFilterLabel: K8S_DEPLOYMENTS_NAMESPACE_FILTER_LABEL,
- allNamespacesLabel: K8S_DEPLOYMENTS_ALL_NAMESPACES_LABEL,
- openPodsLabel: K8S_DEPLOYMENTS_OPEN_PODS_LABEL,
- viewPodsLabel: K8S_DEPLOYMENTS_VIEW_PODS_LABEL,
- deploymentColumnLabel: K8S_DEPLOYMENTS_COLUMN_DEPLOYMENT_LABEL,
- namespaceColumnLabel: K8S_DEPLOYMENTS_COLUMN_NAMESPACE_LABEL,
- desiredColumnLabel: K8S_DEPLOYMENTS_COLUMN_DESIRED_LABEL,
- updatedColumnLabel: K8S_DEPLOYMENTS_COLUMN_UPDATED_LABEL,
- readyColumnLabel: K8S_DEPLOYMENTS_COLUMN_READY_LABEL,
- availableColumnLabel: K8S_DEPLOYMENTS_COLUMN_AVAILABLE_LABEL,
- actionsColumnLabel: K8S_DEPLOYMENTS_COLUMN_ACTIONS_LABEL,
- } as const;
-}
-
-export function getK8sDeploymentsLoadingState() {
- return {
- title: 'Loading deployments...',
- description: 'Fetching unified resources.',
- } as const;
-}
-
-export function getK8sDeploymentsEmptyState(hasDeployments: boolean) {
- return hasDeployments
- ? {
- title: 'No deployments match your filters',
- description: 'Try clearing the search or namespace filter.',
- }
- : {
- title: 'No deployments found',
- description:
- 'Enable the Kubernetes agent deployment collection, then wait for the next report.',
- };
-}
diff --git a/frontend-modern/src/utils/k8sNamespacePresentation.ts b/frontend-modern/src/utils/k8sNamespacePresentation.ts
index 71ba7cb048..0d68909956 100644
--- a/frontend-modern/src/utils/k8sNamespacePresentation.ts
+++ b/frontend-modern/src/utils/k8sNamespacePresentation.ts
@@ -1,9 +1,10 @@
export const K8S_NAMESPACES_DRAWER_TITLE = 'Namespaces';
export const K8S_NAMESPACES_DRAWER_DESCRIPTION = 'Scope Pods and Deployments by namespace';
export const K8S_NAMESPACES_SEARCH_PLACEHOLDER = 'Search namespaces...';
-export const K8S_NAMESPACES_OPEN_ALL_PODS_LABEL = 'Open All Pods';
-export const K8S_NAMESPACES_OPEN_PODS_LABEL = 'Open Pods';
-export const K8S_NAMESPACES_VIEW_DEPLOYMENTS_LABEL = 'View Deployments';
+// Pods and deployments share the Workloads tab, so one action opens both,
+// scoped to the namespace.
+export const K8S_NAMESPACES_OPEN_ALL_WORKLOADS_LABEL = 'Open all workloads';
+export const K8S_NAMESPACES_OPEN_WORKLOADS_LABEL = 'Open workloads';
export const K8S_NAMESPACES_COLUMN_NAMESPACE_LABEL = 'Namespace';
export const K8S_NAMESPACES_COLUMN_PODS_LABEL = 'Pods';
export const K8S_NAMESPACES_COLUMN_DEPLOYMENTS_LABEL = 'Deployments';
@@ -14,9 +15,8 @@ export function getK8sNamespacesDrawerPresentation() {
title: K8S_NAMESPACES_DRAWER_TITLE,
description: K8S_NAMESPACES_DRAWER_DESCRIPTION,
searchPlaceholder: K8S_NAMESPACES_SEARCH_PLACEHOLDER,
- openAllPodsLabel: K8S_NAMESPACES_OPEN_ALL_PODS_LABEL,
- openPodsLabel: K8S_NAMESPACES_OPEN_PODS_LABEL,
- viewDeploymentsLabel: K8S_NAMESPACES_VIEW_DEPLOYMENTS_LABEL,
+ openAllWorkloadsLabel: K8S_NAMESPACES_OPEN_ALL_WORKLOADS_LABEL,
+ openWorkloadsLabel: K8S_NAMESPACES_OPEN_WORKLOADS_LABEL,
namespaceColumnLabel: K8S_NAMESPACES_COLUMN_NAMESPACE_LABEL,
podsColumnLabel: K8S_NAMESPACES_COLUMN_PODS_LABEL,
deploymentsColumnLabel: K8S_NAMESPACES_COLUMN_DEPLOYMENTS_LABEL,
diff --git a/frontend-modern/src/utils/swarmPresentation.ts b/frontend-modern/src/utils/swarmPresentation.ts
deleted file mode 100644
index e4e2c2908f..0000000000
--- a/frontend-modern/src/utils/swarmPresentation.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-export const SWARM_DRAWER_TITLE = 'Swarm';
-export const SWARM_DRAWER_SEARCH_PLACEHOLDER = 'Search services...';
-export const SWARM_DRAWER_NO_CLUSTER_LABEL = 'No Swarm cluster detected';
-export const SWARM_DRAWER_CLUSTER_PREFIX = 'Cluster:';
-export const SWARM_DRAWER_CLUSTER_ID_PREFIX = 'Cluster ID:';
-export const SWARM_DRAWER_ROLE_PREFIX = 'Role:';
-export const SWARM_DRAWER_STATE_PREFIX = 'State:';
-export const SWARM_DRAWER_CONTROL_PREFIX = 'Control:';
-export const SWARM_DRAWER_CONTROL_AVAILABLE_LABEL = 'available';
-export const SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL = 'unavailable';
-export const SWARM_DRAWER_COLUMN_SERVICE_LABEL = 'Service';
-export const SWARM_DRAWER_COLUMN_STACK_LABEL = 'Stack';
-export const SWARM_DRAWER_COLUMN_IMAGE_LABEL = 'Image';
-export const SWARM_DRAWER_COLUMN_MODE_LABEL = 'Mode';
-export const SWARM_DRAWER_COLUMN_DESIRED_LABEL = 'Desired';
-export const SWARM_DRAWER_COLUMN_RUNNING_LABEL = 'Running';
-export const SWARM_DRAWER_COLUMN_UPDATE_LABEL = 'Update';
-export const SWARM_DRAWER_COLUMN_PORTS_LABEL = 'Ports';
-
-export function getSwarmDrawerPresentation() {
- return {
- title: SWARM_DRAWER_TITLE,
- searchPlaceholder: SWARM_DRAWER_SEARCH_PLACEHOLDER,
- noClusterLabel: SWARM_DRAWER_NO_CLUSTER_LABEL,
- clusterPrefix: SWARM_DRAWER_CLUSTER_PREFIX,
- clusterIdPrefix: SWARM_DRAWER_CLUSTER_ID_PREFIX,
- rolePrefix: SWARM_DRAWER_ROLE_PREFIX,
- statePrefix: SWARM_DRAWER_STATE_PREFIX,
- controlPrefix: SWARM_DRAWER_CONTROL_PREFIX,
- controlAvailableLabel: SWARM_DRAWER_CONTROL_AVAILABLE_LABEL,
- controlUnavailableLabel: SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL,
- serviceColumnLabel: SWARM_DRAWER_COLUMN_SERVICE_LABEL,
- stackColumnLabel: SWARM_DRAWER_COLUMN_STACK_LABEL,
- imageColumnLabel: SWARM_DRAWER_COLUMN_IMAGE_LABEL,
- modeColumnLabel: SWARM_DRAWER_COLUMN_MODE_LABEL,
- desiredColumnLabel: SWARM_DRAWER_COLUMN_DESIRED_LABEL,
- runningColumnLabel: SWARM_DRAWER_COLUMN_RUNNING_LABEL,
- updateColumnLabel: SWARM_DRAWER_COLUMN_UPDATE_LABEL,
- portsColumnLabel: SWARM_DRAWER_COLUMN_PORTS_LABEL,
- } as const;
-}
-
-export function formatSwarmClusterSummary(clusterName?: string | null) {
- const value = (clusterName || '').trim();
- return value ? `${SWARM_DRAWER_CLUSTER_PREFIX} ${value}` : SWARM_DRAWER_NO_CLUSTER_LABEL;
-}
-
-export function formatSwarmClusterId(clusterId?: string | null) {
- const value = (clusterId || '').trim();
- return value ? `${SWARM_DRAWER_CLUSTER_ID_PREFIX} ${value}` : '';
-}
-
-export function formatSwarmRoleLabel(role?: string | null) {
- const value = (role || '').trim();
- return value ? `${SWARM_DRAWER_ROLE_PREFIX} ${value}` : '';
-}
-
-export function formatSwarmStateLabel(state?: string | null) {
- const value = (state || '').trim();
- return value ? `${SWARM_DRAWER_STATE_PREFIX} ${value}` : '';
-}
-
-export function formatSwarmControlLabel(controlAvailable?: boolean | null) {
- if (typeof controlAvailable !== 'boolean') return '';
- return `${SWARM_DRAWER_CONTROL_PREFIX} ${controlAvailable ? SWARM_DRAWER_CONTROL_AVAILABLE_LABEL : SWARM_DRAWER_CONTROL_UNAVAILABLE_LABEL}`;
-}
-
-export function getSwarmServicesEmptyState(hasServices: boolean) {
- return hasServices
- ? {
- title: 'No services match your filters',
- description: 'Try clearing the search.',
- }
- : {
- title: 'No Swarm services found',
- description:
- 'Enable Swarm service collection in the container runtime agent (includeServices) and wait for the next report.',
- };
-}
-
-export function getSwarmServicesLoadingState() {
- return {
- text: 'Loading Swarm services...',
- } as const;
-}
diff --git a/scripts/release_control/registry_audit_test.py b/scripts/release_control/registry_audit_test.py
index 1d1029b0e6..3a760f1ab5 100644
--- a/scripts/release_control/registry_audit_test.py
+++ b/scripts/release_control/registry_audit_test.py
@@ -184,8 +184,9 @@ class RegistryAuditTest(unittest.TestCase):
"frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts",
},
("storage-recovery", "storage-product-surface"): {
- "frontend-modern/src/components/Storage/__tests__/DiskDetail.test.tsx",
- "frontend-modern/src/components/Storage/__tests__/useDiskDetailModel.test.ts",
+ "frontend-modern/src/components/Storage/__tests__/DiskDrawer.history-collection.test.tsx",
+ "frontend-modern/src/components/Storage/__tests__/DiskDrawer.test.tsx",
+ "frontend-modern/src/features/storageBackups/__tests__/diskDrawerPresentation.test.ts",
"frontend-modern/src/features/storageBackups/__tests__/diskPresentation.test.ts",
},
("unified-resources", "identity-canonicalization"): {