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
Keep Diagnostics results with their current reader
pulse-triage[bot]19b59b5497c6
diff --git a/frontend-modern/browser-verification/2d8c876035c01621.json b/frontend-modern/browser-verification/2d8c876035c01621.jsonnew file mode 100644index 0000000000..7d97359df8--- /dev/null+++ b/frontend-modern/browser-verification/2d8c876035c01621.json@@ -0,0 +1,44 @@+{+ "version": 1,+ "base_sha": "b8a4ecc8eeed6ee899a8bac68e166d0b11ceb9d7",+ "verified_at": "2026-11-02T13:20:44Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/components/Settings/DiagnosticsPanel.tsx",+ "frontend-modern/src/components/Settings/settingsPanelRegistry.ts",+ "frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx",+ "frontend-modern/src/components/Settings/useDiagnosticsPanelState.ts",+ "frontend-modern/src/utils/diagnosticsPresentation.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/components/Settings/DiagnosticsPanel.tsx": "2a77027e35af5416a4461017c25944eac36095d64cfc8041635588970862f541",+ "frontend-modern/src/components/Settings/useDiagnosticsPanelState.ts": "4dc6ba6950c137edfe1ce3956e499ab9466961f8ea04984647b919ded3d4b8a7",+ "frontend-modern/src/components/Settings/settingsPanelRegistry.ts": "1051f011698c00c5f9f726dcf237744737203db8d234ff612cab10b402f7b142",+ "frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx": "0930d3feceb30bab150d7cfa5d3d7c58afd0bb439f070b35de36ec505d683810",+ "frontend-modern/src/utils/diagnosticsPresentation.ts": "af4ad8052d0b21b2d4764bd6abea65fa785ad78c09fbfe98990379c3d2a87b9a"+ },+ "routes": [+ "/settings/support/diagnostics"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 900+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "states": [+ "Actual App and Settings registry using synthetic supported diagnostics/security responses, exact runtime content hashes checked before execution; Chromium 141.0.7390.37/light and WebKit 26.0/dark, Playwright 1.56.1 matching integration lock.",+ "Accepted current-reader results, held refresh with prior data withdrawn, disposed page, workspace change and return to same identifiers, denied refresh, malformed response, explicit recovery. Principal/token/capability prop lifetimes also have registered unit/component coverage, not an installed IdP claim."+ ],+ "interactions": [+ "79 checks: no diagnostics on mount/workspace switch/remount; single explicit bound GET; full and sanitised downloads use accepted data and never probe again.",+ "Real browser fetch cancellation after panel disposal and synthetic existing workspace-change event; old response release does not restore prior results or create a global toast. Disposal navigation used an unmatched synthetic route, not a verified General-page journey.",+ "Denied response performs one GET without automatic retry, clears previous cards and both downloads, and displays local safe error without the response body. Malformed envelope is unknown rather than a successful empty inventory. Explicit Run restores only current workspace results.",+ "All eight retained captures opened through native view_image: readable inline success/error, responsive touch controls and withdrawn old cards/downloads at desktop and narrow widths; no toast overlay or document-width overflow. Phone captures are viewport crops and do not display every result card.",+ "Both browser contexts/engines, Vite and fixture HTTP server closed. Two expected synthetic 403 console entries and four expected browser-cancelled requests retained; zero uncaught page errors."+ ]+}diff --git a/frontend-modern/src/components/Settings/DiagnosticsPanel.tsx b/frontend-modern/src/components/Settings/DiagnosticsPanel.tsxindex 5a64dcb9ec..ec93649f75 100644--- a/frontend-modern/src/components/Settings/DiagnosticsPanel.tsx+++ b/frontend-modern/src/components/Settings/DiagnosticsPanel.tsx@@ -3,106 +3,133 @@ import OperationsPanel from '@/components/Settings/OperationsPanel';import RefreshCw from 'lucide-solid/icons/refresh-cw';import Download from 'lucide-solid/icons/download';import { DiagnosticsResultsPanel } from '@/components/Settings/DiagnosticsResultsPanel';-import { useDiagnosticsPanelState } from '@/components/Settings/useDiagnosticsPanelState';+import {+ useDiagnosticsPanelState,+ type DiagnosticsPanelProps,+} from '@/components/Settings/useDiagnosticsPanelState';import { formatUptime } from '@/components/Settings/diagnosticsModel';import { DIAGNOSTICS_PANEL_COPY } from '@/utils/diagnosticsPresentation';import { TROUBLESHOOTING_DOC_URL } from '@/utils/docsLinks';-export const DiagnosticsPanel: Component = () => {- const { diagnosticsData, exportDiagnostics, exportLoading, loading, runDiagnostics } =- useDiagnosticsPanelState();+export const DiagnosticsPanel: Component<DiagnosticsPanelProps> = (props) => {+ const {+ diagnosticsData,+ error,+ exportDiagnostics,+ exportLoading,+ loading,+ notice,+ runDiagnostics,+ } = useDiagnosticsPanelState(props);const runSafetyId = createUniqueId();const exportSafetyId = createUniqueId();return (- <div class="space-y-6">- <OperationsPanel- title={DIAGNOSTICS_PANEL_COPY.title}- action={- <div class="flex items-center justify-between sm:justify-end gap-3 flex-wrap">- <Show when={diagnosticsData()}>- <div class="text-left sm:text-right text-xs text-muted">- <div>- {DIAGNOSTICS_PANEL_COPY.versionLabel} {diagnosticsData()?.version}- </div>- <div>- {DIAGNOSTICS_PANEL_COPY.uptimeLabel}:{' '}- {formatUptime(diagnosticsData()?.uptime || 0)}+ <Show+ when={props.canRead !== false}+ fallback={+ <OperationsPanel title={DIAGNOSTICS_PANEL_COPY.title}>+ <p class="p-4 text-sm text-muted">{DIAGNOSTICS_PANEL_COPY.accessUnavailable}</p>+ </OperationsPanel>+ }+ >+ <div class="space-y-6">+ <OperationsPanel+ title={DIAGNOSTICS_PANEL_COPY.title}+ action={+ <div class="flex items-center justify-between sm:justify-end gap-3 flex-wrap">+ <Show when={diagnosticsData()}>+ <div class="text-left sm:text-right text-xs text-muted">+ <div>+ {DIAGNOSTICS_PANEL_COPY.versionLabel} {diagnosticsData()?.version}+ </div>+ <div>+ {DIAGNOSTICS_PANEL_COPY.uptimeLabel}:{' '}+ {formatUptime(diagnosticsData()?.uptime || 0)}+ </div></div>- </div>- </Show>- <button- type="button"- onClick={runDiagnostics}- disabled={loading()}- aria-label={- loading()- ? DIAGNOSTICS_PANEL_COPY.runningActionLabel- : DIAGNOSTICS_PANEL_COPY.runActionLabel- }- aria-describedby={runSafetyId}- class="flex min-h-11 sm:min-h-9 min-w-11 sm:min-w-10 items-center gap-2 px-3 sm:px-4 py-2.5 rounded-md font-medium text-sm transition-colors whitespace-nowrap bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50 disabled:bg-surface disabled:text-muted"- >- <RefreshCw class={`w-4 h-4 ${loading() ? 'animate-spin' : ''}`} />- <span class="sm:hidden">- {loading()- ? DIAGNOSTICS_PANEL_COPY.runningActionLabel- : DIAGNOSTICS_PANEL_COPY.runShortLabel}- </span>- <span class="hidden sm:inline">- {loading()- ? DIAGNOSTICS_PANEL_COPY.runningActionLabel- : DIAGNOSTICS_PANEL_COPY.runActionLabel}- </span>- </button>- </div>- }- >- <div class="px-4 sm:px-6 py-3 sm:py-4 space-y-2 text-sm text-muted">- <p id={runSafetyId}>{DIAGNOSTICS_PANEL_COPY.runSafety}</p>- <p id={exportSafetyId}>{DIAGNOSTICS_PANEL_COPY.exportSafety}</p>- <a- href={`${TROUBLESHOOTING_DOC_URL}#collect-diagnostics-safely`}- class="inline-flex min-h-11 items-center text-link hover:underline"- >- Safe diagnostics and sharing- </a>- </div>- <div class="px-4 sm:px-6 py-3 sm:py-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">- <p class="text-xs text-muted">{DIAGNOSTICS_PANEL_COPY.summary}</p>- <Show when={diagnosticsData()}>- <div class="flex items-center gap-2 flex-wrap">- <button- type="button"- onClick={() => exportDiagnostics(false)}- disabled={exportLoading() || loading()}- aria-describedby={exportSafetyId}- class="flex min-h-11 sm:min-h-9 items-center gap-1.5 px-3 py-2 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover transition-colors"- >- <Download class="w-3.5 h-3.5" />- {DIAGNOSTICS_PANEL_COPY.exportFullLabel}- </button>+ </Show><buttontype="button"- onClick={() => exportDiagnostics(true)}- disabled={exportLoading() || loading()}- aria-describedby={exportSafetyId}- class="flex min-h-11 sm:min-h-9 items-center gap-1.5 px-3 py-2 text-sm font-medium text-green-700 dark:text-green-300 bg-green-50 dark:bg-green-900/25 border border-green-200 dark:border-green-800 rounded-md hover:bg-green-100 dark:hover:bg-green-900/25 transition-colors"+ onClick={runDiagnostics}+ disabled={loading()}+ aria-label={+ loading()+ ? DIAGNOSTICS_PANEL_COPY.runningActionLabel+ : DIAGNOSTICS_PANEL_COPY.runActionLabel+ }+ aria-describedby={runSafetyId}+ class="flex min-h-11 sm:min-h-9 min-w-11 sm:min-w-10 items-center gap-2 px-3 sm:px-4 py-2.5 rounded-md font-medium text-sm transition-colors whitespace-nowrap bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50 disabled:bg-surface disabled:text-muted">- <Download class="w-3.5 h-3.5" />- {DIAGNOSTICS_PANEL_COPY.exportGithubLabel}+ <RefreshCw class={`w-4 h-4 ${loading() ? 'animate-spin' : ''}`} />+ <span class="sm:hidden">+ {loading()+ ? DIAGNOSTICS_PANEL_COPY.runningActionLabel+ : DIAGNOSTICS_PANEL_COPY.runShortLabel}+ </span>+ <span class="hidden sm:inline">+ {loading()+ ? DIAGNOSTICS_PANEL_COPY.runningActionLabel+ : DIAGNOSTICS_PANEL_COPY.runActionLabel}+ </span></button></div>- </Show>- </div>- </OperationsPanel>- <DiagnosticsResultsPanel- diagnosticsData={diagnosticsData()}- loading={loading()}- onRunDiagnostics={runDiagnostics}- runDescriptionId={runSafetyId}- />- </div>+ }+ >+ <div class="px-4 sm:px-6 py-3 sm:py-4 space-y-2 text-sm text-muted">+ <Show when={error()}>+ <p role="alert" class="text-red-700 dark:text-red-300">+ {error()}+ </p>+ </Show>+ <Show when={notice()}>+ <p role="status">{notice()}</p>+ </Show>+ <p id={runSafetyId}>{DIAGNOSTICS_PANEL_COPY.runSafety}</p>+ <p id={exportSafetyId}>{DIAGNOSTICS_PANEL_COPY.exportSafety}</p>+ <a+ href={`${TROUBLESHOOTING_DOC_URL}#collect-diagnostics-safely`}+ class="inline-flex min-h-11 items-center text-link hover:underline"+ >+ Safe diagnostics and sharing+ </a>+ </div>+ <div class="px-4 sm:px-6 py-3 sm:py-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">+ <p class="text-xs text-muted">{DIAGNOSTICS_PANEL_COPY.summary}</p>+ <Show when={diagnosticsData()}>+ <div class="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={() => exportDiagnostics(false)}+ disabled={exportLoading() || loading()}+ aria-describedby={exportSafetyId}+ class="flex min-h-11 sm:min-h-9 items-center gap-1.5 px-3 py-2 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover transition-colors"+ >+ <Download class="w-3.5 h-3.5" />+ {DIAGNOSTICS_PANEL_COPY.exportFullLabel}+ </button>+ <button+ type="button"+ onClick={() => exportDiagnostics(true)}+ disabled={exportLoading() || loading()}+ aria-describedby={exportSafetyId}+ class="flex min-h-11 sm:min-h-9 items-center gap-1.5 px-3 py-2 text-sm font-medium text-green-700 dark:text-green-300 bg-green-50 dark:bg-green-900/25 border border-green-200 dark:border-green-800 rounded-md hover:bg-green-100 dark:hover:bg-green-900/25 transition-colors"+ >+ <Download class="w-3.5 h-3.5" />+ {DIAGNOSTICS_PANEL_COPY.exportGithubLabel}+ </button>+ </div>+ </Show>+ </div>+ </OperationsPanel>+ <DiagnosticsResultsPanel+ diagnosticsData={diagnosticsData()}+ loading={loading()}+ onRunDiagnostics={runDiagnostics}+ runDescriptionId={runSafetyId}+ />+ </div>+ </Show>);};diff --git a/frontend-modern/src/components/Settings/__tests__/DiagnosticsReaderLifetime.test.tsx b/frontend-modern/src/components/Settings/__tests__/DiagnosticsReaderLifetime.test.tsxnew file mode 100644index 0000000000..ca71463dd1--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/DiagnosticsReaderLifetime.test.tsx@@ -0,0 +1,140 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { Route, Router } from '@solidjs/router';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { DiagnosticsPanel } from '../DiagnosticsPanel';+import { DIAGNOSTICS_PANEL_COPY } from '@/utils/diagnosticsPresentation';++const api = vi.hoisted(() => ({ read: vi.fn(), org: 'diagnostics-a' }));+vi.mock('@/utils/apiClient', () => ({ apiFetchJSON: api.read, getOrgID: () => api.org }));+vi.mock('@/utils/toast', () => ({+ showError: () => {+ throw new Error('Diagnostics feedback must stay local');+ },+ showSuccess: () => {+ throw new Error('Diagnostics feedback must stay local');+ },+}));+const data = {+ version: '6.7.0',+ runtime: 'go',+ uptime: 3600,+ nodes: [+ {+ id: 'node-a',+ name: 'private-reader-a',+ host: 'private-a.fixture.test',+ type: 'pve',+ authMethod: 'token',+ connected: true,+ },+ ],+ pbs: [],+ errors: [],+ system: {+ os: 'linux',+ arch: 'amd64',+ goVersion: 'go1.26',+ numCPU: 4,+ numGoroutine: 32,+ memoryMB: 128,+ },+};+const run = () => fireEvent.click(screen.getAllByRole('button', { name: 'Run Diagnostics' })[0]);++beforeEach(() => {+ api.read.mockReset();+ api.org = 'diagnostics-a';+});+afterEach(cleanup);++describe('Diagnostics reader lifetime', () => {+ it('withdraws stale cards and export controls during a denied refresh with local safe feedback', async () => {+ api.read.mockResolvedValueOnce(data).mockRejectedValueOnce(new Error('private-error-payload'));+ render(() => (+ <Router>+ <Route path="/" component={() => <DiagnosticsPanel canRead={true} />} />+ </Router>+ ));+ expect(api.read).not.toHaveBeenCalled();+ run();+ await screen.findByText('private-reader-a');+ expect(screen.getByRole('status')).toHaveTextContent('Diagnostics completed');+ expect(screen.getByRole('button', { name: 'Full (private)' })).toBeEnabled();+ run();+ await screen.findByRole('alert');+ expect(screen.getByRole('alert')).toHaveTextContent(DIAGNOSTICS_PANEL_COPY.runError);+ expect(screen.queryByText('private-reader-a')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Full (private)' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'GitHub (review first)' })).not.toBeInTheDocument();+ expect(screen.queryByText('private-error-payload')).not.toBeInTheDocument();+ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ expect(api.read).toHaveBeenCalledTimes(2);+ });++ it('keeps live checks off on reader or permission changes and only recovers after an explicit run', async () => {+ const [reader, setReader] = createSignal('reader-a');+ const [allowed, setAllowed] = createSignal(true);+ api.read.mockResolvedValue(data);+ render(() => (+ <Router>+ <Route+ path="/"+ component={() => <DiagnosticsPanel currentUser={reader()} canRead={allowed()} />}+ />+ </Router>+ ));+ run();+ await screen.findByText('private-reader-a');+ setReader('reader-b');+ await waitFor(() => expect(screen.queryByText('private-reader-a')).not.toBeInTheDocument());+ expect(api.read).toHaveBeenCalledOnce();+ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ setAllowed(false);+ await screen.findByText(DIAGNOSTICS_PANEL_COPY.accessUnavailable);+ expect(screen.queryByRole('button', { name: 'Run Diagnostics' })).not.toBeInTheDocument();+ setAllowed(true);+ await waitFor(() =>+ expect(screen.getAllByRole('button', { name: 'Run Diagnostics' })).toHaveLength(2),+ );+ expect(api.read).toHaveBeenCalledOnce();+ run();+ await screen.findByText('private-reader-a');+ expect(api.read).toHaveBeenCalledTimes(2);+ });++ it('aborts a disposed panel without showing its eventual completion in a new panel', async () => {+ let resolve!: (value: typeof data) => void;+ api.read.mockReturnValue(+ new Promise<typeof data>((done) => {+ resolve = done;+ }),+ );+ const [visible, setVisible] = createSignal(true);+ const { Show } = await import('solid-js');+ render(() => (+ <Router>+ <Route+ path="/"+ component={() => (+ <Show when={visible()}>+ <DiagnosticsPanel canRead={true} />+ </Show>+ )}+ />+ </Router>+ ));+ run();+ const signal = api.read.mock.calls[0][1].signal as AbortSignal;+ setVisible(false);+ await waitFor(() => expect(signal.aborted).toBe(true));+ setVisible(true);+ resolve(data);+ await waitFor(() =>+ expect(screen.getAllByRole('button', { name: 'Run Diagnostics' })).toHaveLength(2),+ );+ expect(screen.queryByText('private-reader-a')).not.toBeInTheDocument();+ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ expect(api.read).toHaveBeenCalledOnce();+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.tsindex 82ce0f8fed..800461a128 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts@@ -316,4 +316,39 @@ describe('buildSettingsPanelRegistryContext', () => {} as SecurityStatus);expect(context.getAuditLogPanelProps()).toMatchObject({ currentUser: '', canRead: false });});+ it('binds Diagnostics to the live principal, explicit capability and stable credential scope facts', () => {+ const [status, setStatus] = createSignal<SecurityStatus | null>(null);+ const context = buildSettingsPanelRegistryContext({+ ...buildParams(null),+ securityStatus: status,+ });+ expect(context.getDiagnosticsPanelProps()).toEqual({+ currentUser: undefined,+ accessKey: '[null,null]',+ canRead: false,+ });+ setStatus({+ currentUsername: 'diagnostics-reader',+ apiTokenHint: 'fixture-hint',+ tokenScopes: ['settings:read', 'monitoring:read'],+ settingsCapabilities: { diagnosticsRead: true },+ } as SecurityStatus);+ expect(context.getDiagnosticsPanelProps()).toMatchObject({+ currentUser: 'diagnostics-reader',+ canRead: true,+ });+ const key = context.getDiagnosticsPanelProps().accessKey;+ setStatus({ ...status(), tokenScopes: ['monitoring:read', 'settings:read'] } as SecurityStatus);+ expect(context.getDiagnosticsPanelProps().accessKey).toBe(key);+ setStatus({ ...status(), tokenScopes: ['settings:read'] } as SecurityStatus);+ expect(context.getDiagnosticsPanelProps().accessKey).not.toBe(key);+ setStatus({+ currentUsername: 'other-reader',+ settingsCapabilities: { diagnosticsRead: false },+ } as SecurityStatus);+ expect(context.getDiagnosticsPanelProps()).toMatchObject({+ currentUser: 'other-reader',+ canRead: false,+ });+ });});diff --git a/frontend-modern/src/components/Settings/__tests__/useDiagnosticsPanelState.test.ts b/frontend-modern/src/components/Settings/__tests__/useDiagnosticsPanelState.test.tsindex d1e4975771..3f674b114a 100644--- a/frontend-modern/src/components/Settings/__tests__/useDiagnosticsPanelState.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/useDiagnosticsPanelState.test.ts@@ -1,5 +1,7 @@-import { renderHook, waitFor } from '@solidjs/testing-library';+import { cleanup, renderHook, waitFor } from '@solidjs/testing-library';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createSignal } from 'solid-js';+import { DIAGNOSTICS_PANEL_COPY } from '@/utils/diagnosticsPresentation';import type { DiagnosticsData } from '@/components/Settings/diagnosticsModel';type UseDiagnosticsPanelStateModule = typeof import('../useDiagnosticsPanelState');@@ -66,8 +68,8 @@ const currentExportDate = (): string => new Date().toISOString().split('T')[0];describe('useDiagnosticsPanelState', () => {let useDiagnosticsPanelState: UseDiagnosticsPanelStateModule['useDiagnosticsPanelState'];let apiFetchJSONMock: ReturnType<typeof vi.fn<(...args: any[]) => any>>;- let showErrorMock: ReturnType<typeof vi.fn<(...args: any[]) => any>>;- let showSuccessMock: ReturnType<typeof vi.fn<(...args: any[]) => any>>;+ let currentOrg: string;+ let eventBus: (typeof import('@/stores/events'))['eventBus'];let createObjectURLMock: ReturnType<typeof vi.fn<(...args: any[]) => any>>;let revokeObjectURLMock: ReturnType<typeof vi.fn<(...args: any[]) => any>>;let anchorClickMock: ReturnType<typeof vi.fn<(...args: any[]) => any>>;@@ -79,8 +81,7 @@ describe('useDiagnosticsPanelState', () => {vi.resetModules();apiFetchJSONMock = vi.fn();- showErrorMock = vi.fn();- showSuccessMock = vi.fn();+ currentOrg = 'diagnostics-a';createObjectURLMock = vi.fn(() => 'blob:diagnostics-export');revokeObjectURLMock = vi.fn();anchorClickMock = vi.fn();@@ -90,11 +91,7 @@ describe('useDiagnosticsPanelState', () => {vi.doMock('@/utils/apiClient', () => ({apiFetchJSON: apiFetchJSONMock,- }));-- vi.doMock('@/utils/toast', () => ({- showError: showErrorMock,- showSuccess: showSuccessMock,+ getOrgID: () => currentOrg,}));Object.defineProperty(URL, 'createObjectURL', {@@ -117,9 +114,11 @@ describe('useDiagnosticsPanelState', () => {}) as typeof document.createElement);({ useDiagnosticsPanelState } = await import('../useDiagnosticsPanelState'));+ ({ eventBus } = await import('@/stores/events'));});afterEach(() => {+ cleanup();if (originalCreateObjectURL) {Object.defineProperty(URL, 'createObjectURL', {configurable: true,@@ -149,8 +148,12 @@ describe('useDiagnosticsPanelState', () => {await result.runDiagnostics();await waitFor(() => expect(result.diagnosticsData()).not.toBeNull());- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/diagnostics');- expect(showSuccessMock).toHaveBeenCalledWith('Diagnostics completed');+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/diagnostics', {+ signal: expect.any(AbortSignal),+ expectedOrgID: 'diagnostics-a',+ retry: false,+ });+ expect(result.notice()).toBe('Diagnostics completed');expect(result.diagnosticsData()).not.toHaveProperty('commercialFunnel');expect(result.diagnosticsData()).not.toHaveProperty('infrastructureOnboarding');@@ -160,9 +163,7 @@ describe('useDiagnosticsPanelState', () => {expect(anchorClickMock).toHaveBeenCalledOnce();expect(createdAnchor?.download).toBe(`pulse-diagnostics-full-${currentExportDate()}.json`);expect(revokeObjectURLMock).toHaveBeenCalledWith('blob:diagnostics-export');- expect(showSuccessMock).toHaveBeenCalledWith(- 'Full diagnostics downloaded — keep this file private',- );+ expect(result.notice()).toBe('Full diagnostics downloaded — keep this file private');const payload = JSON.parse(await readBlobText(createObjectURLMock.mock.calls[0][0] as Blob),@@ -185,9 +186,7 @@ describe('useDiagnosticsPanelState', () => {expect(anchorClickMock).toHaveBeenCalledOnce();expect(createdAnchor?.download).toBe(`pulse-diagnostics-sanitized-${currentExportDate()}.json`);- expect(showSuccessMock).toHaveBeenCalledWith(- 'Sanitised diagnostics downloaded — review before sharing',- );+ expect(result.notice()).toBe('Sanitised diagnostics downloaded — review before sharing');const payload = JSON.parse(await readBlobText(createObjectURLMock.mock.calls[0][0] as Blob),@@ -220,8 +219,245 @@ describe('useDiagnosticsPanelState', () => {await result.exportDiagnostics(true);- expect(showErrorMock).toHaveBeenCalledWith('Run diagnostics first');+ expect(result.error()).toBe(DIAGNOSTICS_PANEL_COPY.exportRequiresResult);+ expect(createObjectURLMock).not.toHaveBeenCalled();+ expect(apiFetchJSONMock).not.toHaveBeenCalled();+ });++ const pendingResult = () => {+ let resolve!: (value: DiagnosticsData) => void;+ let reject!: (reason: Error) => void;+ const promise = new Promise<DiagnosticsData>((done, fail) => {+ resolve = done;+ reject = fail;+ });+ return { promise, resolve, reject };+ };++ it('withdraws the prior result at refresh start and keeps a denied refresh unknown', async () => {+ apiFetchJSONMock.mockResolvedValueOnce(createDiagnosticsData());+ const { result } = renderHook(() => useDiagnosticsPanelState());+ await result.runDiagnostics();+ const pending = pendingResult();+ apiFetchJSONMock.mockReturnValueOnce(pending.promise);+ const request = result.runDiagnostics();+ expect(result.diagnosticsData()).toBeNull();+ expect(result.loading()).toBe(true);+ await result.exportDiagnostics(false);+ await result.runDiagnostics();+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);+ expect(createObjectURLMock).not.toHaveBeenCalled();+ pending.reject(new Error('Denied for private.example.test?token=private-fixture'));+ await request;+ expect(result.loading()).toBe(false);+ expect(result.diagnosticsData()).toBeNull();+ expect(result.error()).toBe(DIAGNOSTICS_PANEL_COPY.runError);+ expect(result.notice()).toBe('');+ await result.exportDiagnostics(true);+ expect(createObjectURLMock).not.toHaveBeenCalled();+ expect(apiFetchJSONMock.mock.calls.every(([, options]) => options.retry === false)).toBe(true);+ });++ it.each(['user', 'access', 'permission', 'organization', 'same organization event'])(+ 'erases accepted data and local feedback on %s change without live probes',+ async (change) => {+ const [user, setUser] = createSignal('reader-a');+ const [access, setAccess] = createSignal('token-a');+ const [allowed, setAllowed] = createSignal(true);+ apiFetchJSONMock.mockResolvedValue(createDiagnosticsData());+ const { result } = renderHook(() =>+ useDiagnosticsPanelState({+ get currentUser() {+ return user();+ },+ get accessKey() {+ return access();+ },+ get canRead() {+ return allowed();+ },+ }),+ );+ await result.runDiagnostics();+ expect(result.diagnosticsData()).not.toBeNull();+ expect(result.notice()).toBeTruthy();+ if (change === 'user') setUser('reader-b');+ if (change === 'access') setAccess('token-b');+ if (change === 'permission') setAllowed(false);+ if (change === 'organization') currentOrg = 'diagnostics-b';+ if (change.includes('organization')) eventBus.emit('org_switched', currentOrg);+ await waitFor(() => expect(result.diagnosticsData()).toBeNull());+ expect(result.notice()).toBe('');+ expect(result.error()).toBe('');+ expect(apiFetchJSONMock).toHaveBeenCalledOnce();+ await result.exportDiagnostics(false);+ expect(createObjectURLMock).not.toHaveBeenCalled();+ // Returning to the old identifiers never restores the old result.+ setUser('reader-a');+ setAccess('token-a');+ setAllowed(true);+ currentOrg = 'diagnostics-a';+ eventBus.emit('org_switched', currentOrg);+ expect(result.diagnosticsData()).toBeNull();+ expect(apiFetchJSONMock).toHaveBeenCalledOnce();+ await result.runDiagnostics();+ expect(result.diagnosticsData()).not.toBeNull();+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);+ },+ );++ it('cancels obsolete work, ignores a late success and lets only an explicit new run recover', async () => {+ const obsolete = pendingResult();+ const fresh = pendingResult();+ apiFetchJSONMock.mockReturnValueOnce(obsolete.promise).mockReturnValueOnce(fresh.promise);+ const { result } = renderHook(() => useDiagnosticsPanelState());+ const oldRequest = result.runDiagnostics();+ const oldSignal = apiFetchJSONMock.mock.calls[0][1].signal as AbortSignal;+ currentOrg = 'diagnostics-b';+ eventBus.emit('org_switched', currentOrg);+ expect(oldSignal.aborted).toBe(true);+ expect(result.loading()).toBe(false);+ const newRequest = result.runDiagnostics();+ expect(apiFetchJSONMock.mock.calls[1][1].expectedOrgID).toBe('diagnostics-b');+ obsolete.resolve(createDiagnosticsData());+ await oldRequest;+ expect(result.diagnosticsData()).toBeNull();+ expect(result.loading()).toBe(true);+ expect(result.notice()).toBe('');+ fresh.resolve({ ...createDiagnosticsData(), version: 'current-reader' });+ await newRequest;+ expect(result.diagnosticsData()?.version).toBe('current-reader');+ expect(result.loading()).toBe(false);+ });++ it('ignores a late failure when the original reader returns during a new run', async () => {+ const old = pendingResult();+ const fresh = pendingResult();+ apiFetchJSONMock.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise);+ const { result } = renderHook(() => useDiagnosticsPanelState());+ const oldRequest = result.runDiagnostics();+ currentOrg = 'diagnostics-b';+ eventBus.emit('org_switched', currentOrg);+ currentOrg = 'diagnostics-a';+ eventBus.emit('org_switched', currentOrg);+ const newRequest = result.runDiagnostics();+ old.reject(new Error('old private failure'));+ await oldRequest;+ expect(result.error()).toBe('');+ expect(result.loading()).toBe(true);+ fresh.resolve(createDiagnosticsData());+ await newRequest;+ expect(result.notice()).toBe(DIAGNOSTICS_PANEL_COPY.runSuccess);+ });++ it.each(['resolve', 'reject'] as const)(+ 'cancels disposal and ignores late %s',+ async (completion) => {+ const pending = pendingResult();+ apiFetchJSONMock.mockReturnValueOnce(pending.promise);+ const { result, cleanup: dispose } = renderHook(() => useDiagnosticsPanelState());+ const request = result.runDiagnostics();+ const signal = apiFetchJSONMock.mock.calls[0][1].signal as AbortSignal;+ dispose();+ expect(signal.aborted).toBe(true);+ if (completion === 'resolve') pending.resolve(createDiagnosticsData());+ else pending.reject(new Error('obsolete private failure'));+ await request;+ expect(result.diagnosticsData()).toBeNull();+ expect(result.error()).toBe('');+ expect(result.notice()).toBe('');+ await result.exportDiagnostics(false);+ await result.runDiagnostics();+ expect(createObjectURLMock).not.toHaveBeenCalled();+ expect(apiFetchJSONMock).toHaveBeenCalledOnce();+ },+ );++ it('makes no request while read permission is absent or after restoration until Run', async () => {+ const [allowed, setAllowed] = createSignal(false);+ const { result } = renderHook(() =>+ useDiagnosticsPanelState({+ get canRead() {+ return allowed();+ },+ }),+ );+ await result.runDiagnostics();+ await result.exportDiagnostics(false);+ expect(apiFetchJSONMock).not.toHaveBeenCalled();expect(createObjectURLMock).not.toHaveBeenCalled();+ setAllowed(true);+ await waitFor(() => expect(result.loading()).toBe(false));expect(apiFetchJSONMock).not.toHaveBeenCalled();+ apiFetchJSONMock.mockResolvedValue(createDiagnosticsData());+ await result.runDiagnostics();+ expect(result.diagnosticsData()).not.toBeNull();+ });++ it('preserves a successful result on an unchanged reader refresh', async () => {+ const [props, setProps] = createSignal({+ currentUser: 'same-reader',+ accessKey: 'same-key',+ canRead: true,+ });+ const { result } = renderHook(() =>+ useDiagnosticsPanelState({+ get currentUser() {+ return props().currentUser;+ },+ get accessKey() {+ return props().accessKey;+ },+ get canRead() {+ return props().canRead;+ },+ }),+ );+ apiFetchJSONMock.mockResolvedValue(createDiagnosticsData());+ await result.runDiagnostics();+ const accepted = result.diagnosticsData();+ setProps({ ...props() });+ expect(result.diagnosticsData()).toBe(accepted);+ expect(apiFetchJSONMock).toHaveBeenCalledOnce();+ });++ it.each([+ null,+ {},+ { nodes: [] },+ { ...createDiagnosticsData(), nodes: null },+ { ...createDiagnosticsData(), system: null },+ { ...createDiagnosticsData(), errors: null },+ ])(+ 'keeps a malformed response unknown instead of displaying a successful empty inventory: %s',+ async (data) => {+ apiFetchJSONMock.mockResolvedValue(data);+ const { result } = renderHook(() => useDiagnosticsPanelState());+ await result.runDiagnostics();+ expect(result.diagnosticsData()).toBeNull();+ expect(result.notice()).toBe('');+ expect(result.error()).toBe(DIAGNOSTICS_PANEL_COPY.runError);+ await result.exportDiagnostics(false);+ expect(createObjectURLMock).not.toHaveBeenCalled();+ },+ );++ it('cleans up a failed local download and permits a download retry without probing', async () => {+ apiFetchJSONMock.mockResolvedValue(createDiagnosticsData());+ const { result } = renderHook(() => useDiagnosticsPanelState());+ await result.runDiagnostics();+ anchorClickMock.mockImplementationOnce(() => {+ throw new Error('Download blocked');+ });+ await result.exportDiagnostics(false);+ expect(revokeObjectURLMock).toHaveBeenCalledWith('blob:diagnostics-export');+ expect(document.querySelector('a[download]')).toBeNull();+ expect(result.error()).toBe(DIAGNOSTICS_PANEL_COPY.exportError);+ expect(result.notice()).toBe('');+ expect(result.exportLoading()).toBe(false);+ await result.exportDiagnostics(false);+ expect(result.error()).toBe('');+ expect(result.notice()).toBe(DIAGNOSTICS_PANEL_COPY.exportFullSuccess);+ expect(apiFetchJSONMock).toHaveBeenCalledOnce();});});diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts b/frontend-modern/src/components/Settings/settingsPanelRegistry.tsindex a94889d769..1c277c9630 100644--- a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts+++ b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts@@ -16,6 +16,7 @@ import type AuditLogPanelType from './AuditLogPanel';import type { RolesPanel as RolesPanelType } from './RolesPanel';import type { UserAssignmentsPanel as UserAssignmentsPanelType } from './UserAssignmentsPanel';import type { InfrastructureWorkspace as InfrastructureWorkspaceType } from './InfrastructureWorkspace';+import type { DiagnosticsPanelProps } from './useDiagnosticsPanelState';import type { SettingsTab } from './settingsNavigationModel';import { SETTINGS_PANEL_REGISTRY_LOADERS } from './settingsPanelRegistryLoaders';@@ -48,6 +49,7 @@ export interface SettingsPanelRegistryContext {getSecurityAuthPanelProps: () => Parameters<typeof SecurityAuthPanelType>[0];getRelayPanelProps: () => Parameters<typeof RelaySettingsPanelType>[0];getReportingPanelProps: () => Parameters<typeof ReportingPanelType>[0];+ getDiagnosticsPanelProps: () => DiagnosticsPanelProps;getAuditWebhookPanelProps: () => Parameters<typeof AuditWebhookPanelType>[0];getAuditLogPanelProps: () => Parameters<typeof AuditLogPanelType>[0];getRolesPanelProps: () => Parameters<typeof RolesPanelType>[0];@@ -97,6 +99,7 @@ export const createSettingsPanelRegistry = (},'support-diagnostics': {component: SETTINGS_PANEL_REGISTRY_LOADERS.DiagnosticsPanel,+ getProps: context.getDiagnosticsPanelProps,},'support-reporting': {component: SETTINGS_PANEL_REGISTRY_LOADERS.ReportingPanel,diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsxindex 443308940c..9f935cc052 100644--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx@@ -133,6 +133,14 @@ export function buildSettingsPanelRegistryContext(]),canRead: settingsCapabilities()?.reportingRead === true,}),+ getDiagnosticsPanelProps: () => ({+ currentUser: currentUser(),+ accessKey: JSON.stringify([+ params.securityStatus()?.apiTokenHint,+ params.securityStatus()?.tokenScopes?.slice().sort(),+ ]),+ canRead: settingsCapabilities()?.diagnosticsRead === true,+ }),getAuditLogPanelProps: () => ({currentUser: currentUser(),accessKey: JSON.stringify([diff --git a/frontend-modern/src/components/Settings/useDiagnosticsPanelState.ts b/frontend-modern/src/components/Settings/useDiagnosticsPanelState.tsindex d60642c8f0..d0ed23fc93 100644--- a/frontend-modern/src/components/Settings/useDiagnosticsPanelState.ts+++ b/frontend-modern/src/components/Settings/useDiagnosticsPanelState.ts@@ -1,6 +1,6 @@-import { createSignal } from 'solid-js';-import { apiFetchJSON } from '@/utils/apiClient';-import { showError, showSuccess } from '@/utils/toast';+import { batch, createEffect, createSignal, onCleanup, untrack } from 'solid-js';+import { apiFetchJSON, getOrgID } from '@/utils/apiClient';+import { eventBus } from '@/stores/events';import { DIAGNOSTICS_PANEL_COPY } from '@/utils/diagnosticsPresentation';import {buildDiagnosticsExportFilename,@@ -9,30 +9,135 @@ import {type DiagnosticsData,} from '@/components/Settings/diagnosticsModel';-export const useDiagnosticsPanelState = () => {+export interface DiagnosticsPanelProps {+ currentUser?: string;+ accessKey?: string;+ canRead?: boolean;+}++export const useDiagnosticsPanelState = (props: DiagnosticsPanelProps = {}) => {const [loading, setLoading] = createSignal(false);- const [diagnosticsData, setDiagnosticsData] = createSignal<DiagnosticsData | null>(null);+ const [result, setResult] = createSignal<DiagnosticsData | null>(null);const [exportLoading, setExportLoading] = createSignal(false);+ const [error, setError] = createSignal('');+ const [notice, setNotice] = createSignal('');+ const currentOrg = () => getOrgID() || 'default';+ const reader = () => ({+ org: currentOrg(),+ user: props.currentUser,+ access: props.accessKey,+ allowed: props.canRead !== false,+ });+ const [context, setContext] = createSignal(reader());+ let disposed = false;+ let controller: AbortController | undefined;+ const isCurrentReader = () =>+ !disposed &&+ context().allowed &&+ props.canRead !== false &&+ context().org === currentOrg() &&+ context().user === props.currentUser &&+ context().access === props.accessKey;+ // Withhold immediately, even before the effect handles a changed prop.+ const diagnosticsData = () => (isCurrentReader() ? result() : null);++ const resetReader = () => {+ controller?.abort();+ controller = undefined;+ batch(() => {+ setContext(reader());+ setResult(null);+ setLoading(false);+ setExportLoading(false);+ setError('');+ setNotice('');+ });+ // Diagnostics can probe live hosts. A new reader must explicitly Run;+ // neither switching workspace nor recovering access starts those probes.+ };+ createEffect(() => {+ const next = reader();+ const previous = untrack(context);+ // A copied status with unchanged reader facts must not discard a result.+ if (+ previous.org !== next.org ||+ previous.user !== next.user ||+ previous.access !== next.access ||+ previous.allowed !== next.allowed+ )+ resetReader();+ });+ const unsubscribe = eventBus.on('org_switched', resetReader);+ onCleanup(() => {+ disposed = true;+ unsubscribe();+ resetReader();+ });const runDiagnostics = async () => {- setLoading(true);+ if (!isCurrentReader() || controller) return;+ const acceptedReader = context();+ const request = new AbortController();+ controller = request;+ const isCurrent = () =>+ isCurrentReader() && context() === acceptedReader && controller === request;+ batch(() => {+ // An earlier successful check is not evidence of current access or health.+ setResult(null);+ setError('');+ setNotice('');+ setLoading(true);+ });try {- const data = (await apiFetchJSON('/api/diagnostics')) as DiagnosticsData;- setDiagnosticsData(stripInternalAnalyticsDiagnosticsFields(data));- showSuccess('Diagnostics completed');- } catch (error) {- showError(error instanceof Error ? error.message : 'Failed to run diagnostics');+ const data = (await apiFetchJSON('/api/diagnostics', {+ expectedOrgID: acceptedReader.org,+ signal: request.signal,+ retry: false,+ })) as DiagnosticsData;+ if (!isCurrent()) return;+ if (+ !data ||+ typeof data.version !== 'string' ||+ !Array.isArray(data.nodes) ||+ !Array.isArray(data.pbs) ||+ [...data.nodes, ...data.pbs].some(+ (node) =>+ !node ||+ typeof node.name !== 'string' ||+ typeof node.host !== 'string' ||+ typeof node.connected !== 'boolean',+ ) ||+ !data.system ||+ typeof data.system !== 'object' ||+ Array.isArray(data.system) ||+ !Array.isArray(data.errors) ||+ data.errors.some((entry) => typeof entry !== 'string')+ ) {+ throw new Error('Invalid diagnostics result');+ }+ setResult(stripInternalAnalyticsDiagnosticsFields(data));+ setNotice(DIAGNOSTICS_PANEL_COPY.runSuccess);+ } catch {+ if (isCurrent()) setError(DIAGNOSTICS_PANEL_COPY.runError);} finally {- setLoading(false);+ if (controller === request) {+ controller = undefined;+ setLoading(false);+ }}};const exportDiagnostics = async (sanitize: boolean) => {+ if (!isCurrentReader() || loading() || exportLoading()) return;setExportLoading(true);+ setError('');+ setNotice('');+ let url: string | undefined;+ let anchor: HTMLAnchorElement | undefined;try {const data = diagnosticsData();if (!data) {- showError('Run diagnostics first');+ setError(DIAGNOSTICS_PANEL_COPY.exportRequiresResult);return;}@@ -40,29 +145,35 @@ export const useDiagnosticsPanelState = () => {? sanitizeDiagnosticsData(data): stripInternalAnalyticsDiagnosticsFields(data);const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });- const url = URL.createObjectURL(blob);- const anchor = document.createElement('a');+ url = URL.createObjectURL(blob);+ anchor = document.createElement('a');anchor.href = url;anchor.download = buildDiagnosticsExportFilename(sanitize);document.body.appendChild(anchor);anchor.click();- document.body.removeChild(anchor);- URL.revokeObjectURL(url);- showSuccess(- sanitize- ? DIAGNOSTICS_PANEL_COPY.exportGithubSuccess- : DIAGNOSTICS_PANEL_COPY.exportFullSuccess,- );+ if (isCurrentReader()) {+ setNotice(+ sanitize+ ? DIAGNOSTICS_PANEL_COPY.exportGithubSuccess+ : DIAGNOSTICS_PANEL_COPY.exportFullSuccess,+ );+ }+ } catch {+ if (isCurrentReader()) setError(DIAGNOSTICS_PANEL_COPY.exportError);} finally {+ anchor?.remove();+ if (url) URL.revokeObjectURL(url);setExportLoading(false);}};return {diagnosticsData,+ error: () => (isCurrentReader() ? error() : ''),exportDiagnostics,exportLoading,loading,+ notice: () => (isCurrentReader() ? notice() : ''),runDiagnostics,};};diff --git a/frontend-modern/src/utils/diagnosticsPresentation.ts b/frontend-modern/src/utils/diagnosticsPresentation.tsindex 1488a64e8e..2d688924c5 100644--- a/frontend-modern/src/utils/diagnosticsPresentation.ts+++ b/frontend-modern/src/utils/diagnosticsPresentation.ts@@ -9,6 +9,12 @@ export const DIAGNOSTICS_PANEL_COPY = {runActionLabel: 'Run Diagnostics',runShortLabel: 'Run',runningActionLabel: 'Running...',+ runSuccess: 'Diagnostics completed',+ runError:+ 'Diagnostics could not be loaded. Previous results have been cleared. Check your access and try again only when live checks are safe.',+ accessUnavailable: 'Diagnostics is not available to this session.',+ exportRequiresResult: 'Run diagnostics first, only when live checks are safe.',+ exportError: 'Diagnostics could not be downloaded. Nothing was uploaded. Try downloading again.',exportFullLabel: 'Full (private)',exportGithubLabel: 'GitHub (review first)',exportFullSuccess: 'Full diagnostics downloaded — keep this file private',