Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Withdraw History readings when access is denied
pulse-triage[bot]6f5bf963704b
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 6255d4a7d0..f99fcd1271 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -353,7 +353,30 @@ PBS browser runner verifies delayed range and withdrawn-target reads at desktopand phone widths; neither proof establishes installed collection or #1723 relief.Failed same-source history refreshes keep valid previously loaded observations-visible with an explicit warning, rather than hiding the entire chart. Initial+visible with an explicit warning, rather than hiding the entire chart. That+retention applies to transient transport/server failures, never a final HTTP+`401` or `403`. Both the batch drawer and shared canvas reader withdraw stored+samples and inspection on access failure; denied history is not an empty,+collecting, or stale-but-still-readable result. Their guidance is bounded by+numeric status, not transport bodies or guessed diagnostic text. The shared+canvas announces its error, and the drawer keeps its scoped, focusable retry.+Only a successful replacement read restores observations.++The retained-value query helper also withdraws its active value on a final+`401`/`403` and clears its shared remount cache. Other resource/range entries+were read under the same access context, so they cannot be resurrected after+that context is denied. Advancing the cache generation rejects cache writes+from already-running pre-denial reads. A superseded denied completion cannot+clear the current target or its cache. This does not broadcast a session reset+or claim revocation of independently mounted consumers; their current response+still owns their presentation. Transient failures keep the existing retained+value, and a newly successful read may populate the cache normally. Verification+uses runtime assertions in `createNonSuspendingQuery.test.tsx`,+`GuestDrawerHistory.refresh.test.tsx`, `useHistoryChartState.test.tsx`,+`HistoryChart.test.tsx`, and `browser-tests/history-access.cjs` (both production+readers/client, real same-origin 403/503 responses, cache/range/remount and+fresh-read recovery on desktop Chromium and touch WebKit). These controls do+not establish appliance authorisation, collection or released acceptance. Initialor uncached replacement failures show unavailable history, never borrowed pointsor a collecting claim. The existing target/range owns every manual refresh;locked or absent targets expose no refresh control. The control remains mounted@@ -674,6 +697,9 @@ that manual-channel consequence must stay visible at desktop and narrow widths.108. `frontend-modern/src/components/shared/summaryInteractionA11y.ts`109. `frontend-modern/src/components/shared/SummaryRowActionButton.tsx`110. `frontend-modern/src/hooks/createNonSuspendingQuery.ts`+ Shared API read-access classification is owned by+ `frontend-modern/src/utils/apiAccessError.ts`; it recognises only final+ numeric 401/403 statuses and never renders transport diagnostics.111a. `frontend-modern/src/utils/storageSummaryCache.ts`111. `frontend-modern/src/components/shared/TableCardHeader.tsx`112. `frontend-modern/src/components/shared/UpgradeLink.tsx`diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 8df6300caa..80cd898e5a 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -921,7 +921,17 @@ change may globally weaken the Task 03 lifecycle-state idempotency invariant.single-observation caption rather than a collecting claim or invented trend.Successful empty reads say `No stored history in this range`. Onlymetrics-store samples may contribute chart geometry, bounds, or hover- inspection, including valid measured zero. This presentation adds no fetch,+ inspection, including valid measured zero. Same-source transient failures+ retain those observations with a warning, but final HTTP 401/403 responses+ withdraw the batch charts, inspection and its retained remount entries.+ The shared query cache advances its generation so a pre-denial read cannot+ restore a former cached range. Access guidance comes from numeric status,+ never raw transport text; the existing target/range-scoped retry remains+ focusable while pending, and only a successful read restores history.+ Runtime denial/cache/recovery controls are in+ `GuestDrawerHistory.refresh.test.tsx` and `createNonSuspendingQuery.test.tsx`,+ with real client 403/503 browser controls in `browser-tests/history-access.cjs`.+ These are client presentation proofs, not native authorisation or collection. This presentation adds no fetch,point expansion, polling or retention budget. Verify sparse and mixed-seriesgeometry and failed-refresh/source-change behaviour in`GuestDrawerHistory.sparse.test.tsx`, with rendered phone/desktop coverage indiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 5b59559345..e7361f0193 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -5812,6 +5812,7 @@"match_prefixes": [],"match_files": ["frontend-modern/src/hooks/createNonSuspendingQuery.ts",+ "frontend-modern/src/utils/apiAccessError.ts","frontend-modern/src/utils/storageSummaryCache.ts"],"allow_same_subsystem_tests": false,@@ -5819,6 +5820,7 @@"exact_files": ["frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx","frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx",+ "frontend-modern/src/utils/__tests__/apiAccessError.test.ts","frontend-modern/src/utils/__tests__/storageSummaryCache.test.ts"]},diff --git a/frontend-modern/browser-tests/history-access.cjs b/frontend-modern/browser-tests/history-access.cjsnew file mode 100644index 0000000000..0a2c6261e2--- /dev/null+++ b/frontend-modern/browser-tests/history-access.cjs@@ -0,0 +1,325 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { chromium, webkit } = require('playwright');+const parent = false;+(async () => {+ const root = parent+ ? '/workspace/tmp/history-access-parent/frontend-modern'+ : '/workspace/frontend-modern';+ process.chdir(root);+ const artifacts = `/workspace/tmp/history-access-${parent ? 'parent' : 'final'}-proof`;+ fs.mkdirSync(artifacts, { recursive: true });+ const { createServer } = await import(path.join(root, 'node_modules/vite/dist/node/index.js'));+ 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: 5261, strictPort: true },+ });+ const playwright = require('playwright/package.json').version;+ const expected = JSON.parse(+ fs.readFileSync('/workspace/tests/integration/package-lock.json', 'utf8'),+ ).packages['node_modules/@playwright/test'].version;+ assert.equal(playwright, expected);+ const observations = [];+ let browser;+ try {+ await server.listen();+ for (const [name, engine, phone] of [+ ['chromium-desktop', chromium, false],+ ['webkit-phone', webkit, true],+ ]) {+ browser = await engine.launch(+ engine === chromium+ ? { headless: true, channel: 'chromium', args: ['--no-sandbox'] }+ : { headless: true },+ );+ const page = await browser.newPage({+ viewport: phone ? { width: 390, height: 844 } : { width: 1365, height: 900 },+ hasTouch: phone,+ isMobile: phone,+ });+ page.setDefaultTimeout(15000);+ await page.clock.install({ time: new Date('2026-10-03T12:00:00Z') });+ let mode = 'success',+ value = 42;+ const requests = [],+ errors = [],+ offOrigin = [],+ held = [],+ checks = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (url.origin !== 'http://127.0.0.1:5261') {+ offOrigin.push(url.origin);+ return route.abort();+ }+ if (!url.pathname.startsWith('/api/')) return route.continue();+ if (url.pathname === '/api/metrics-store/history') {+ const query = Object.fromEntries(url.searchParams);+ requests.push({ ...query, responseMode: mode });+ if (mode === 'hold') await new Promise((resolve) => held.push(resolve));+ try {+ if (mode === '503' || mode === '403')+ return await route.fulfill({+ status: Number(mode),+ json: { error: 'fixture-only diagnostic body' },+ });+ const points = [0, 1].map((index) => ({+ timestamp: 1791028740000 + index * 60000,+ value: value - 1 + index,+ min: value - 1 + index,+ max: value - 1 + index,+ }));+ return await route.fulfill({+ json: {+ resourceType: query.resourceType,+ resourceId: query.resourceId,+ range: query.range,+ metric: query.metric,+ start: 1791028740000,+ end: 1791028800000,+ source: 'store',+ ...(query.metric ? { points } : { metrics: { cpu: points, temperature: points } }),+ },+ });+ } catch {+ /* An explicitly superseded browser read may already be aborted. */+ }+ return;+ }+ return route.fulfill({+ json:+ url.pathname === '/api/license/runtime-capabilities'+ ? {+ capabilities: [],+ limits: [],+ max_history_days: 7,+ hosted_mode: false,+ runtime: { build: 'community' },+ blocked_capabilities: [],+ }+ : { enabled: false, data: [] },+ });+ });+ const check = async (label, predicate) => {+ try {+ await predicate();+ checks.push({ label, passed: true });+ } catch (error) {+ checks.push({ label, passed: false, error: error.message });+ }+ };+ const screenshot = async (state) => {+ const file = `${name}-${state}.png`;+ await page.screenshot({+ path: path.join(artifacts, file),+ fullPage: true,+ animations: 'disabled',+ });+ observations.push({+ browser: name,+ state,+ screenshot: file,+ body: await page.locator('main').innerText(),+ overflow: await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),+ });+ };+ const disk = page.getByTestId('disk'),+ service = page.getByTestId('service');+ const thermal = disk.getByRole('img', { name: 'Temperature chart' });+ const description = () =>+ thermal.evaluate(+ (el) => document.getElementById(el.getAttribute('aria-describedby')).textContent,+ );+ const storedPaths = () => service.locator('[data-testid="guest-history-plot"] path').count();+ await page.goto('http://127.0.0.1:5261/browser-tests/history-access.html');+ if (phone) await page.evaluate(() => document.documentElement.classList.add('dark'));+ await service.getByRole('slider', { name: 'Inspect Utilization history' }).waitFor();+ await page.waitForFunction(+ () =>+ document.querySelector('[data-testid="disk"] canvas')?.getAttribute('aria-describedby') &&+ document+ .getElementById(+ document+ .querySelector('[data-testid="disk"] canvas')+ .getAttribute('aria-describedby'),+ )+ .textContent.includes('42°C'),+ );+ await service.getByRole('combobox', { name: 'History range' }).selectOption('24h');+ await service.getByRole('slider', { name: 'Inspect Utilization history' }).waitFor();+ if (phone) await thermal.tap({ position: { x: 100, y: 80 } });+ else {+ await thermal.focus();+ await thermal.press('End');+ }+ await check('Both readers show only their successful stored samples', async () => {+ assert.match(await description(), /42°C/);+ assert.equal(await storedPaths(), 2);+ assert.equal(await disk.locator('[data-history-chart-tooltip]').count(), 1);+ });+ await screenshot('loaded');+ mode = '503';+ await page.clock.fastForward(30_000);+ await service+ .getByRole('status', { name: 'History refresh status' })+ .getByText(/previously loaded/)+ .waitFor();+ await check('503 retains observations with a warning, not a collection claim', async () => {+ assert.match(await description(), /42°C/);+ assert.equal(await storedPaths(), 2);+ assert.match(+ await disk.getByRole('status', { name: 'History refresh status' }).innerText(),+ /last successful result/,+ );+ });+ await screenshot('transient');+ // Re-establish active inspection immediately before access changes.+ if (phone) await thermal.tap({ position: { x: 100, y: 80 } });+ else {+ await thermal.focus();+ await thermal.press('End');+ }+ mode = '403';+ const beforeDenied = requests.length;+ await page.clock.fastForward(30_000);+ await page.waitForTimeout(250);+ await check('The real API client receives a final 403 for both exact targets', async () => {+ const denied = requests.slice(beforeDenied).filter((r) => r.responseMode === '403');+ assert(denied.some((r) => r.resourceId === 'disk:nas-a:sda'));+ assert(denied.some((r) => r.resourceId === 'pbs-service-a' && !r.metric));+ });+ await check('403 withdraws canvas values, tooltip and announced inspection', async () => {+ assert.doesNotMatch(await description(), /42°C/);+ assert.equal(await disk.locator('[data-history-chart-tooltip]').count(), 0);+ assert.match(await disk.getByRole('alert').innerText(), /Access denied/);+ assert.equal(+ await disk.getByRole('status', { name: 'History refresh status' }).innerText(),+ '',+ );+ });+ await check('403 withdraws batch charts, sliders and current-only legends', async () => {+ assert.equal(await storedPaths(), 0);+ assert.equal(await service.getByRole('slider').count(), 0);+ assert.equal(await service.locator('[data-history-current]').count(), 0);+ assert.match(+ await service.getByRole('status', { name: 'History refresh status' }).innerText(),+ /Access denied/,+ );+ });+ await screenshot('denied');+ mode = 'hold';+ const retry = service.getByRole('button', { name: 'Retry history' });+ const beforeRetry = requests.length;+ await retry.focus();+ await retry.click();+ await retry.press('Enter');+ await page.waitForTimeout(150);+ await check(+ 'One busy keyboard-safe retry remains scoped and shows no denied samples',+ async () => {+ assert.equal(+ requests.slice(beforeRetry).filter((r) => r.resourceId === 'pbs-service-a').length,+ 1,+ );+ assert.equal(await retry.getAttribute('aria-disabled'), 'true');+ assert.equal(await retry.evaluate((el) => el === document.activeElement), true);+ assert.equal(await storedPaths(), 0);+ },+ );+ await screenshot('retry-pending');+ await service.getByRole('combobox', { name: 'History range' }).selectOption('1h');+ await page.waitForTimeout(150);+ await check('An earlier cached range cannot resurrect denied observations', async () =>+ assert.equal(await storedPaths(), 0),+ );+ await service.getByRole('button', { name: 'Hide service History' }).click();+ await service.getByRole('button', { name: 'Show service History' }).click();+ await page.waitForTimeout(150);+ await check('A remount cannot resurrect the earlier cached range', async () =>+ assert.equal(await storedPaths(), 0),+ );+ await screenshot('remount-pending');+ mode = 'success';+ value = 12;+ held.splice(0).forEach((resolve) => resolve());+ await page.clock.fastForward(30_000);+ await page.waitForFunction(() =>+ document+ .getElementById(+ document.querySelector('[data-testid="disk"] canvas').getAttribute('aria-describedby'),+ )+ .textContent.includes('12°C'),+ );+ await service.getByRole('slider', { name: 'Inspect Utilization history' }).waitFor();+ await check(+ 'Only a new successful response restores readings and clears access errors',+ async () => {+ assert.equal(await storedPaths(), 2);+ assert.equal(await disk.getByRole('alert').count(), 0);+ assert.equal(+ await service.getByRole('status', { name: 'History refresh status' }).innerText(),+ '',+ );+ assert.doesNotMatch(await description(), /42°C/);+ assert(+ requests.some(+ (r) =>+ r.resourceId === 'pbs-service-a' &&+ r.range === '1h' &&+ r.responseMode === 'success',+ ),+ );+ },+ );+ await screenshot('recovered');+ await check(+ 'No diagnostic body, page error, off-origin request or horizontal overflow',+ async () => {+ assert.doesNotMatch(+ await page.locator('main').innerText(),+ /fixture-only diagnostic body/,+ );+ assert.deepEqual(errors, []);+ assert.deepEqual(offOrigin, []);+ assert.equal(+ await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),+ false,+ );+ },+ );+ observations.push({+ browser: name,+ version: browser.version(),+ checks,+ requests,+ errors,+ offOrigin,+ });+ await browser.close();+ browser = undefined;+ }+ } finally {+ if (browser) await browser.close();+ await server.close();+ fs.writeFileSync(+ path.join(artifacts, 'result.json'),+ JSON.stringify({ parent, playwright, expected, observations }, null, 2),+ );+ }+ const failed = observations.flatMap((o) => o.checks ?? []).filter((c) => !c.passed);+ console.log(+ JSON.stringify({+ parent,+ checks: observations.flatMap((o) => o.checks ?? []).length,+ failed: failed.map((c) => c.label),+ }),+ );+ if (!parent) assert.equal(failed.length, 0);+})().catch((error) => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/frontend-modern/browser-tests/history-access.html b/frontend-modern/browser-tests/history-access.htmlnew file mode 100644index 0000000000..c41d942a61--- /dev/null+++ b/frontend-modern/browser-tests/history-access.html@@ -0,0 +1,12 @@+<!doctype html>+<html>+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>History access failure verification</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/browser-tests/history-access.tsx"></script>+ </body>+</html>diff --git a/frontend-modern/browser-tests/history-access.tsx b/frontend-modern/browser-tests/history-access.tsxnew file mode 100644index 0000000000..a1450ea206--- /dev/null+++ b/frontend-modern/browser-tests/history-access.tsx@@ -0,0 +1,57 @@+// Production readers/client/styles with synthetic same-origin HTTP responses.+// This fixture proves presentation, not appliance authorisation or collection.+import { Show, createSignal } from 'solid-js';+import { render } from 'solid-js/web';+import type { HistoryTimeRange } from '../src/api/charts';+import {+ GuestDrawerHistory,+ GuestDrawerHistoryRangeSelect,+} from '../src/components/Workloads/GuestDrawerHistory';+import { HistoryChart } from '../src/components/shared/HistoryChart';+import { HOST_METRICS_HISTORY_GROUPS } from '../src/components/shared/hostMetricsHistoryModel';+import '../src/index.css';++function Fixture() {+ const [range, setRange] = createSignal<HistoryTimeRange>('1h');+ const [visible, setVisible] = createSignal(true);+ return (+ <main class="mx-auto min-h-screen max-w-5xl space-y-5 bg-surface p-4 text-base-content">+ <h1 class="text-lg font-semibold">History access failure verification</h1>+ <section data-testid="disk" class="rounded border border-border p-3">+ <h2 class="mb-3 font-semibold">Disk History</h2>+ <HistoryChart+ resourceType="disk"+ resourceId="disk:nas-a:sda"+ metric="smart_temp"+ label="Temperature"+ unit="C"+ range="1h"+ height={160}+ hideSelector+ compact+ />+ </section>+ <section data-testid="service" class="space-y-3">+ <h2 class="font-semibold">PBS service History</h2>+ <div class="flex flex-wrap items-center justify-between gap-3">+ <button+ class="min-h-11 rounded border border-border px-3"+ onClick={() => setVisible(!visible())}+ >+ {visible() ? 'Hide service History' : 'Show service History'}+ </button>+ <GuestDrawerHistoryRangeSelect range={range()} onRangeChange={setRange} />+ </div>+ <Show when={visible()}>+ <GuestDrawerHistory+ target={{ resourceType: 'agent', resourceId: 'pbs-service-a' }}+ range={range()}+ groups={HOST_METRICS_HISTORY_GROUPS}+ currentMetrics={{ cpu: 99, memory: 98 }}+ />+ </Show>+ </section>+ </main>+ );+}+render(() => <Fixture />, document.getElementById('root')!);diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.jsonindex 7555748f01..353d9f0ce2 100644--- a/frontend-modern/browser-verification.json+++ b/frontend-modern/browser-verification.json@@ -1,16 +1,25 @@{"version": 1,"result": "passed",- "base_sha": "b6a42d8a4f329a1f3d7359d8d64b17c385006ed7",- "verified_at": "2026-10-03T00:38:42Z",+ "base_sha": "a9533eb82a29700ede2d4ad609812ddd01e5f287",+ "verified_at": "2026-10-03T01:44:27.336168Z","changed_paths": [- "frontend-modern/src/features/storageBackups/diskDetailPresentation.ts"+ "frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx",+ "frontend-modern/src/components/shared/HistoryChartOverlay.tsx",+ "frontend-modern/src/components/shared/useHistoryChartState.ts",+ "frontend-modern/src/hooks/createNonSuspendingQuery.ts",+ "frontend-modern/src/utils/apiAccessError.ts"],"content_sha256": {- "frontend-modern/src/features/storageBackups/diskDetailPresentation.ts": "31c71a2d696f1b74d55b855220885619bbeebc0b75a1f34354cc5b794ba49375"+ "frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx": "c4370a69495c8ccea01a0d92076e4a051e4d06abec0e675e2fb3547d46e87bcb",+ "frontend-modern/src/components/shared/HistoryChartOverlay.tsx": "14c0699b827ec6eb4d85cf9d8fc76d61a0af3dd6565d2396a3f22a03429af104",+ "frontend-modern/src/components/shared/useHistoryChartState.ts": "5a9b022656ac7316710675a0742e9b2908c9114ffbed67d6f6962d361bb65bbf",+ "frontend-modern/src/hooks/createNonSuspendingQuery.ts": "df293d0484612a6d31dd9f3fa6af2a1160e1e98d66965730a45829b7048a4ba7",+ "frontend-modern/src/utils/apiAccessError.ts": "3b34a498959a77014af3c842677fc6646b5e7e6a8b9b332ca8acf91254c01730"},"routes": [- "Existing Storage physical disk detail History"+ "Existing PBS/Machine/resource drawer History batch reader",+ "Existing Storage physical disk shared History reader"],"viewports": [{@@ -23,23 +32,25 @@}],"states": [- "Stored ATA temperature and measured-zero reallocated sectors render when current temperature and SMART are absent",- "Matching current snapshot updates keep the same chart owners and add zero History reads",- "Current field loss keeps stored samples and selected 7-day range; no unavailable live I/O is shown",- "Overview reports present collection unavailability instead of the earlier stored temperature",- "Empty temperature history is an explicit no-samples state, not a zero, while stored reallocated zero remains visible",- "NVMe uses its own explicit disk target and stored temperature/endurance/spare series without current SMART fields",- "No resolvable identity withdraws History and issues no guessed-target request",- "Keyboard desktop and touch phone inspection show real stored readings",- "All screenshots inspected with animations disabled; selected tab, light/dark layouts and page width agree with content",- "Playwright 1.56.1 matches the integration lock; no page errors or off-origin data reads"+ "Real same-origin 503 responses retain stored samples with explicit warnings in both production readers",+ "Real final HTTP 403 responses withdraw samples, tooltip, keyboard announcement, sliders and formerly displayed current-only legends",+ "Access-denied guidance fits light desktop Chromium and dark touch WebKit without horizontal overflow",+ "The existing focusable scoped retry remains mounted and ignores duplicate activation while busy",+ "Earlier cached ranges and remounts cannot resurrect denied stored readings while a replacement is pending",+ "Only a new successful read restores History and clears denial; old values do not return",+ "Every final screenshot inspected; fixed Playwright 1.56.1 equals integration lock, no page errors or off-origin data requests"],"interactions": [- "Open History from unavailable current Overview",- "Restore, update and remove current fields",- "Change 24h/7d/1h ranges",- "Inspect by keyboard or phone tap",- "Select NVMe B",- "Clear disk identity"+ "Inspect by desktop keyboard and phone tap",+ "Poll through 503 then 403",+ "Retry twice while busy",+ "Change 24h/1h range",+ "Unmount and remount batch History",+ "Resume with newly successful observations"+ ],+ "limitations": [+ "Direct production readers/client with synthetic HTTP responses, not a complete native PBS/NAS drawer, session revocation, appliance collection or release acceptance.",+ "401 is covered by runtime regressions; the real API client redirects on 401, not bypassed for browser proof.",+ "Independently supplied current readings remain distinctly current during a new pending query; they are not stored History."]}diff --git a/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx b/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsxindex 427b7ec2f6..4eed3c6ba5 100644--- a/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx+++ b/frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx@@ -30,6 +30,7 @@ import {} from '@/components/shared/historyChartModel';import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';import { isRangeLocked, loadRuntimeCapabilities, maxHistoryDays } from '@/stores/license';+import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';import {GUEST_DRAWER_HISTORY_DEFAULT_RANGE,@@ -686,9 +687,10 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>><Show when={historyQuery.error()}><InlineNotice tone={hasHistoryPoints() ? 'warning' : 'danger'}>- {hasHistoryPoints()- ? 'History refresh failed. Showing previously loaded history.'- : 'Failed to load history data'}+ {getAPIReadAccessErrorMessage(historyQuery.error()) ||+ (hasHistoryPoints()+ ? 'History refresh failed. Showing previously loaded history.'+ : 'Failed to load history data')}</InlineNotice></Show></div>diff --git a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsxindex e0dfcc7972..db854a9504 100644--- a/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx+++ b/frontend-modern/src/components/Workloads/__tests__/GuestDrawerHistory.refresh.test.tsx@@ -220,3 +220,105 @@ describe('GuestDrawerHistory refresh recovery', () => {expect(fetch).not.toHaveBeenCalled();});});++const accessTarget = { resourceType: 'agent', resourceId: 'pbs-host' } as const;+const accessResponse = (range: HistoryTimeRange): AllMetricsHistoryResponse => ({+ ...accessTarget,+ range,+ start: 1000,+ end: 2000,+ source: 'store',+ metrics: {+ cpu: [+ { timestamp: 1000, value: 41, min: 41, max: 41 },+ { timestamp: 2000, value: 42, min: 42, max: 42 },+ ],+ },+});+const accessPaths = (container: HTMLElement) =>+ container.querySelectorAll('[data-testid="guest-history-plot"] path');+const settleAccess = () => vi.advanceTimersByTimeAsync(0);++describe('drawer History access failures', () => {+ it.each([+ [401, 'Sign in again or check your API token.'],+ [403, 'Access denied. Check your permissions and license plan.'],+ ])(+ 'removes samples, inspection and current legends after %s; retry stays scoped',+ async (status, message) => {+ vi.useFakeTimers();+ let deny = false;+ let complete!: (value: AllMetricsHistoryResponse) => void;+ const fetch = vi.spyOn(ChartsAPI, 'getMetricsHistory').mockImplementation(async (request) => {+ if (deny) throw Object.assign(new Error('private transport detail'), { status });+ return accessResponse(request.range!);+ });+ const [range, setRange] = createSignal<HistoryTimeRange>('1h');+ const view = render(() => (+ <GuestDrawerHistory target={accessTarget} range={range()} currentMetrics={{ cpu: 99 }} />+ ));+ await settleAccess();+ setRange('24h');+ await settleAccess();+ expect(accessPaths(view.container)).toHaveLength(1);+ const inspection = screen.getByRole('slider', { name: 'Inspect Utilization history' });+ fireEvent.focus(inspection);+ expect(view.container).toHaveTextContent('42.0%');+ const region = screen.getByRole('status', { name: 'History refresh status' });+ deny = true;+ await vi.advanceTimersByTimeAsync(30_000);+ expect(accessPaths(view.container)).toHaveLength(0);+ expect(screen.queryByRole('slider')).not.toBeInTheDocument();+ expect(view.container).not.toHaveTextContent('42.0%');+ expect(view.container).not.toHaveTextContent('99.0%');+ expect(view.container).not.toHaveTextContent('private transport detail');+ expect(region).toHaveTextContent(message);+ expect(region).not.toHaveTextContent('previously loaded');+ const retry = screen.getByRole('button', { name: 'Retry history' });+ retry.focus();+ fetch.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ complete = resolve;+ }),+ );+ fireEvent.click(retry);+ fireEvent.click(retry);+ expect(retry).toHaveFocus();+ expect(retry).toHaveAttribute('aria-disabled', 'true');+ expect(accessPaths(view.container)).toHaveLength(0);+ expect(region).toHaveTextContent(message);+ expect(fetch.mock.calls.at(-1)![0]).toMatchObject({+ ...accessTarget,+ range: '24h',+ maxPoints: 240,+ });+ complete(accessResponse('24h'));+ await settleAccess();+ expect(accessPaths(view.container)).toHaveLength(1);+ expect(region).toBeEmptyDOMElement();+ expect(retry).toHaveFocus();+ },+ );++ it('does not resurrect another cached range or remount after denial', async () => {+ vi.useFakeTimers();+ const fetch = vi+ .spyOn(ChartsAPI, 'getMetricsHistory')+ .mockImplementation(async (request) => accessResponse(request.range!));+ const [range, setRange] = createSignal<HistoryTimeRange>('1h');+ const view = render(() => <GuestDrawerHistory target={accessTarget} range={range()} />);+ await settleAccess();+ setRange('24h');+ await settleAccess();+ expect(accessPaths(view.container)).toHaveLength(1);+ fetch.mockRejectedValueOnce(Object.assign(new Error('denied'), { status: 403 }));+ await vi.advanceTimersByTimeAsync(30_000);+ fetch.mockImplementation(() => new Promise(() => {}));+ setRange('1h');+ expect(accessPaths(view.container)).toHaveLength(0);+ view.unmount();+ const next = render(() => <GuestDrawerHistory target={accessTarget} range="24h" />);+ expect(accessPaths(next.container)).toHaveLength(0);+ });+});diff --git a/frontend-modern/src/components/shared/HistoryChartOverlay.tsx b/frontend-modern/src/components/shared/HistoryChartOverlay.tsxindex 2244e8d0db..3cad4322ec 100644--- a/frontend-modern/src/components/shared/HistoryChartOverlay.tsx+++ b/frontend-modern/src/components/shared/HistoryChartOverlay.tsx@@ -48,7 +48,9 @@ export const HistoryChartOverlay: Component<HistoryChartOverlayProps> = (props)<Show when={props.chart.error()}><div class="absolute inset-0 flex items-center justify-center">- <p class="text-sm text-red-500">{props.chart.error()}</p>+ <p role="alert" class="px-3 text-center text-sm text-red-500">+ {props.chart.error()}+ </p></div></Show>diff --git a/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx b/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsxindex 8729c8a2ba..ab9ba9d221 100644--- a/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx@@ -1,7 +1,7 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { createSignal } from 'solid-js';import { ChartsAPI } from '@/api/charts';-import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';import historyChartHeaderSource from '@/components/shared/HistoryChartHeader.tsx?raw';import historyChartHoverGroupSource from '@/components/shared/HistoryChartHoverGroup.tsx?raw';import historyChartOverlaySource from '@/components/shared/HistoryChartOverlay.tsx?raw';@@ -571,3 +571,51 @@ describe('HistoryChart', () => {expect(layout.x).toBe(212);});});++describe('History access boundary rendering', () => {+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.useRealTimers();+ });+ it.each([401, 403])(+ 'withdraws painted readings, tooltips and keyboard announcements on %s',+ async (status) => {+ vi.useFakeTimers();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const request = vi.mocked(ChartsAPI.getMetricsHistory);+ request.mockReset();+ request.mockResolvedValueOnce({+ points: [{ timestamp: 1000, value: 42, min: 42, max: 42 }],+ source: 'store',+ } as never);+ const { container } = render(() => (+ <HistoryChart+ resourceType="disk"+ resourceId="disk:nas:sda"+ metric="smart_temp"+ label="Temperature"+ unit="C"+ range="1h"+ />+ ));+ await vi.advanceTimersByTimeAsync(0);+ const canvas = screen.getByRole('img', { name: 'Temperature chart' });+ fireEvent.focus(canvas);+ expect(container.querySelector('[data-history-chart-tooltip]')).toHaveTextContent('42°C');+ request.mockRejectedValueOnce(Object.assign(new Error('private detail'), { status }));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(container.querySelector('[data-history-chart-tooltip]')).toBeNull();+ expect(container.querySelector('[aria-live="polite"]')).toHaveTextContent('');+ expect(container).not.toHaveTextContent('42°C');+ expect(container).not.toHaveTextContent('last successful');+ expect(container).not.toHaveTextContent('private detail');+ expect(screen.getByRole('alert')).toHaveTextContent(+ status === 401 ? 'Sign in again' : 'Access denied',+ );+ expect(screen.queryByText('No history samples in this time range.')).not.toBeInTheDocument();+ fireEvent.keyDown(canvas, { key: 'End' });+ expect(container.querySelector('[data-history-chart-tooltip]')).toBeNull();+ },+ );+});diff --git a/frontend-modern/src/components/shared/__tests__/useHistoryChartState.test.tsx b/frontend-modern/src/components/shared/__tests__/useHistoryChartState.test.tsxindex 872920316b..571dcd49ac 100644--- a/frontend-modern/src/components/shared/__tests__/useHistoryChartState.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/useHistoryChartState.test.tsx@@ -217,3 +217,45 @@ describe('History request ownership', () => {expect(state.data()).toEqual([]);});});++describe('History access errors', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ request.mockReset();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.restoreAllMocks();+ });+ it.each([+ [401, 'Sign in again or check your API token.'],+ [403, 'Access denied. Check your permissions and license plan.'],+ ])(+ 'withdraws stored samples and source on status %s until a successful read',+ async (status, message) => {+ request.mockResolvedValueOnce({ points: points(42), source: 'store' } as never);+ const { state } = mount();+ await settle();+ request.mockRejectedValueOnce(+ Object.assign(new Error('private transport detail'), { status }),+ );+ await vi.advanceTimersByTimeAsync(10_000);+ expect(state.data()).toEqual([]);+ expect(state.source()).toBeNull();+ expect(state.refreshFailed()).toBe(false);+ expect(state.error()).toBe(message);+ const retry = deferred();+ request.mockReturnValueOnce(retry.promise);+ vi.advanceTimersByTime(10_000);+ expect(state.data()).toEqual([]);+ expect(state.error()).toBe(message);+ retry.resolve({ points: points(12), source: 'store' } as never);+ await settle();+ expect(state.data()).toEqual(points(12));+ expect(state.error()).toBeNull();+ expect(state.source()).toBe('store');+ },+ );+});diff --git a/frontend-modern/src/components/shared/useHistoryChartState.ts b/frontend-modern/src/components/shared/useHistoryChartState.tsindex 2ccfa69c54..fb02e328d9 100644--- a/frontend-modern/src/components/shared/useHistoryChartState.ts+++ b/frontend-modern/src/components/shared/useHistoryChartState.ts@@ -1,5 +1,6 @@-import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';+import { batch, createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';import { ChartsAPI, type HistoryTimeRange } from '@/api/charts';+import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';import { isRangeLocked, loadRuntimeCapabilities, maxHistoryDays } from '@/stores/license';import { calculateOptimalPoints } from '@/utils/downsample';import { setupCanvasDPR } from '@/utils/canvasRenderQueue';@@ -148,7 +149,6 @@ export function useHistoryChartState(pending = true;controller = new AbortController();if (!hasLoaded) setLoading(true);- setError(null);try {const result = await ChartsAPI.getMetricsHistory({resourceType,@@ -161,12 +161,27 @@ export function useHistoryChartState(if (!active) return;setData('points' in result ? (result.points ?? []) : []);setSource(result.source ?? 'store');+ setError(null);setRefreshFailed(false);hasLoaded = true;} catch (err) {if (!active) return;console.error('Failed to fetch metrics history:', err);- if (hasLoaded) setRefreshFailed(true);+ const accessError = getAPIReadAccessErrorMessage(err);+ if (accessError) {+ hasLoaded = false;+ pendingTouch = undefined;+ touchTimestamp = null;+ batch(() => {+ setData([]);+ setSource(null);+ setHoveredPoint(null);+ setHoveredTimestamp(null);+ setKeyboardInspecting(false);+ setRefreshFailed(false);+ setError(accessError);+ });+ } else if (hasLoaded) setRefreshFailed(true);else setError('Failed to load history data');} finally {if (active) {diff --git a/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx b/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsxindex 488876a2c2..ce8b4af4b4 100644--- a/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx+++ b/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx@@ -311,3 +311,131 @@ it.each(['success', 'failure'] as const)(expect(screen.getByTestId('query')).toHaveTextContent(expected);},);++const settle = async () => {+ await Promise.resolve();+ await Promise.resolve();+};+const denied = (status: number) => Object.assign(new Error('private transport detail'), { status });+function mount(key: string, fetcher: () => Promise<string>) {+ let query!: ReturnType<typeof createNonSuspendingQuery<string, string>>;+ const view = render(() => {+ query = createNonSuspendingQuery({+ source: () => key,+ cacheKey: (key) => key,+ fetcher,+ initialValue: '',+ });+ return <output>{query.value()}</output>;+ });+ return { query, ...view };+}++describe('retained query access boundary', () => {+ it.each([401, 403])(+ 'withdraws the denied value and all remount entries after %s',+ async (status) => {+ const oldRange = mount('pbs:1h', async () => 'former reading');+ await settle();+ oldRange.unmount();+ let rejectRead = false;+ const active = mount('pbs:24h', async () => {+ if (rejectRead) throw denied(status);+ return 'current reading';+ });+ await settle();+ expect(getCreateNonSuspendingQueryCacheDiagnosticsForTest().size).toBe(2);+ rejectRead = true;+ await active.query.refetch({ background: true });+ expect(active.query.value()).toBe('');+ expect(active.query.error()).toMatchObject({ status });+ expect(active.query.loading()).toBe(false);+ expect(getCreateNonSuspendingQueryCacheDiagnosticsForTest().size).toBe(0);+ active.unmount();+ const remount = mount('pbs:1h', () => new Promise(() => {}));+ expect(remount.query.value()).toBe('');+ expect(remount.query.resolvedOnce()).toBe(false);+ },+ );++ it('does not repopulate the remount cache from a pre-denial read', async () => {+ let complete!: (value: string) => void;+ const pending = mount(+ 'pbs:1h',+ () =>+ new Promise((resolve) => {+ complete = resolve;+ }),+ );+ const active = mount('pbs:24h', async () => {+ throw denied(403);+ });+ await settle();+ expect(active.query.value()).toBe('');+ complete('before-access-change');+ await settle();+ expect(getCreateNonSuspendingQueryCacheDiagnosticsForTest().size).toBe(0);+ pending.unmount();+ const remount = mount('pbs:1h', () => new Promise(() => {}));+ expect(remount.query.value()).toBe('');+ });++ it.each([500, 503, 429, undefined])(+ 'retains useful readings on transient status %s',+ async (status) => {+ let rejectRead = false;+ const active = mount('pbs:24h', async () => {+ if (rejectRead) throw denied(status as number);+ return 'stored reading';+ });+ await settle();+ rejectRead = true;+ await active.query.refetch();+ expect(active.query.value()).toBe('stored reading');+ expect(getCreateNonSuspendingQueryCacheDiagnosticsForTest().size).toBe(1);+ },+ );++ it('restores only freshly authorised data after denial', async () => {+ let result: string | Error = 'before denial';+ const active = mount('pbs:24h', async () => {+ if (result instanceof Error) throw result;+ return result;+ });+ await settle();+ result = denied(403);+ await active.query.refetch();+ expect(active.query.value()).toBe('');+ result = 'newly authorised reading';+ await active.query.refetch();+ expect(active.query.value()).toBe(result);+ expect(active.query.error()).toBeNull();+ expect(getCreateNonSuspendingQueryCacheDiagnosticsForTest().size).toBe(1);+ });+ it('ignores a superseded denial rather than clearing the new target and its cache', async () => {+ let rejectOld!: (error: Error) => void;+ let query!: ReturnType<typeof createNonSuspendingQuery<string, string>>;+ const [source, setSource] = createSignal('old');+ render(() => {+ query = createNonSuspendingQuery({+ source,+ cacheKey: (key) => key,+ initialValue: '',+ fetcher: (key) =>+ key === 'old'+ ? new Promise((_, reject) => {+ rejectOld = reject;+ })+ : Promise.resolve('new reading'),+ });+ return <output>{query.value()}</output>;+ });+ setSource('new');+ await settle();+ rejectOld(denied(403));+ await settle();+ expect(query.value()).toBe('new reading');+ expect(query.error()).toBeNull();+ expect(getCreateNonSuspendingQueryCacheDiagnosticsForTest().keys).toEqual(['new']);+ });+});diff --git a/frontend-modern/src/hooks/createNonSuspendingQuery.ts b/frontend-modern/src/hooks/createNonSuspendingQuery.tsindex 39c88f8a79..920e0de316 100644--- a/frontend-modern/src/hooks/createNonSuspendingQuery.ts+++ b/frontend-modern/src/hooks/createNonSuspendingQuery.ts@@ -1,5 +1,6 @@-import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';+import { type Accessor, batch, createEffect, createSignal, onCleanup } from 'solid-js';import { eventBus } from '@/stores/events';+import { getAPIReadAccessErrorMessage } from '@/utils/apiAccessError';interface CreateNonSuspendingQueryOptions<T, K> {source: Accessor<K | null>;@@ -229,7 +230,17 @@ export function createNonSuspendingQuery<T, K>(options: CreateNonSuspendingQueryreturn nextValue;} catch (nextError) {if (requestId === latestRequestId) {- setError(nextError);+ batch(() => {+ if (getAPIReadAccessErrorMessage(nextError)) {+ // A permission/session/plan failure is not a transient outage.+ // Withdraw this value and all remount entries: the same access+ // context may own other resource/range keys. The generation also+ // prevents pre-denial reads from repopulating the shared cache.+ clearRetainedQueryCache();+ setValue(() => options.initialValue);+ }+ setError(nextError);+ });}return value();} finally {diff --git a/frontend-modern/src/utils/__tests__/apiAccessError.test.ts b/frontend-modern/src/utils/__tests__/apiAccessError.test.tsnew file mode 100644index 0000000000..40eb4e1882--- /dev/null+++ b/frontend-modern/src/utils/__tests__/apiAccessError.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';+import { getAPIReadAccessErrorMessage } from '../apiAccessError';++describe('bounded API read access messages', () => {+ it.each([+ [401, 'Sign in again or check your API token.'],+ [403, 'Access denied. Check your permissions and license plan.'],+ ])('recognises final HTTP status %s without exposing diagnostics', (status, message) => {+ expect(+ getAPIReadAccessErrorMessage(Object.assign(new Error('private detail'), { status })),+ ).toBe(message);+ expect(+ getAPIReadAccessErrorMessage({+ status,+ message: '<script>unsafe</script>',+ code: 'arbitrary',+ }),+ ).toBe(message);+ });+ it.each([+ null,+ undefined,+ '403 Forbidden',+ new Error('401 unauthorised'),+ {},+ { status: '403' },+ { status: 400 },+ { status: 402 },+ { status: 404 },+ { status: 429 },+ { status: 500 },+ ])('does not infer permission failure from %j', (error) => {+ expect(getAPIReadAccessErrorMessage(error)).toBeNull();+ });+});diff --git a/frontend-modern/src/utils/apiAccessError.ts b/frontend-modern/src/utils/apiAccessError.tsnew file mode 100644index 0000000000..a414a00118--- /dev/null+++ b/frontend-modern/src/utils/apiAccessError.ts@@ -0,0 +1,12 @@+/** Only final HTTP status establishes an access failure, never transport text. */+export function getAPIReadAccessErrorMessage(error: unknown): string | null {+ if (!error || typeof error !== 'object' || !('status' in error)) return null;+ switch (error.status) {+ case 401:+ return 'Sign in again or check your API token.';+ case 403:+ return 'Access denied. Check your permissions and license plan.';+ default:+ return null;+ }+}