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 uncertain System Logs buffers and reconnect explicitly
pulse-triage[bot]de0a4163c2f5
diff --git a/frontend-modern/browser-verification/bb864117b983b5cd.json b/frontend-modern/browser-verification/bb864117b983b5cd.jsonnew file mode 100644index 0000000000..e731f485a8--- /dev/null+++ b/frontend-modern/browser-verification/bb864117b983b5cd.json@@ -0,0 +1,44 @@+{+ "version": 1,+ "base_sha": "7bc1dd11583c4b393506d507f4e51af60c3204cf",+ "verified_at": "2026-11-02T14:30:38Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/components/Settings/SystemLogsPanel.tsx",+ "frontend-modern/src/components/Settings/settingsPanelRegistry.ts",+ "frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx",+ "frontend-modern/src/components/Settings/useSystemLogsPanelState.ts",+ "frontend-modern/src/utils/systemLogsPresentation.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/components/Settings/SystemLogsPanel.tsx": "37339282dcffbd4b86cbb030e8738b09e0ffe890cee8fabf450cc91e39ee0eec",+ "frontend-modern/src/components/Settings/useSystemLogsPanelState.ts": "3fb2a30b220273fbbf37d58ff4c6bc79c4bb12a606a3430f3c3570235ebc7f5a",+ "frontend-modern/src/components/Settings/settingsPanelRegistry.ts": "1fed9467c825e8339116197ebeb285d594affa42e522bd36097a1d0cdd2c3d37",+ "frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx": "11253aa870f3620558b8f74c97f4f18d3bda0d4c88b1d87665381256cac36579",+ "frontend-modern/src/utils/systemLogsPresentation.ts": "5107b27035670add2f422d9ee96b3fc9ef40fe6dce56b9f943c2936a77b87176"+ },+ "routes": [+ "/settings/support/logs"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 900+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "states": [+ "Actual App/Settings registry admits native SSE from synthetic local fixture through real apiClient. Playwright1.56.1 matches integration lock; desktop Chromium141.0.7390.37/light and narrow WebKit26.0/dark.",+ "Live buffer, transient EOF/reconnecting with pause retained, terminal denied reconnect, denied and malformed level checks, workspace withdrawal, obsolete level-read cancellation, explicit current-reader recovery and level-change feedback. Principal/credential/capability lifetimes also have registered tests, not an installed IdP claim."+ ],+ "interactions": [+ "61 checks; actual level read then SSE, synthetic support download without cancelling either engine's live stream, display-only pause/resume/clear. Native support streaming is kept; no browser memory buffering of large archives.",+ "Any connection error withdraws pending/visible private lines and disables server actions. Transient loss preserves native reconnect. Terminal failure offers explicit Reconnect logs and does not auto-reopen. Denied/malformed level reads open no stream and have no API retry.",+ "Existing workspace-change producer closes the previous stream and cancels obsolete level fetches. Released old completion cannot reopen logs; recovery requires a fresh explicit read. Current level changes submit once and feedback does not leak after page disposal.",+ "All eight captures opened with native view_image. Readable private warnings and local reconnect/error/status at desktop and390px; disabled controls and removed old private line observed; new current lines only after recovery. Captures are viewport crops, not full terminal/status coverage.",+ "Both contexts, browser engines, Vite and fixture HTTP server closed; zero uncaught page errors. Expected403 and cancelled-request evidence retained. Earlier browser failure from WebKit top-navigation stream cancellation is separately retained, not an overall pass."+ ]+}diff --git a/frontend-modern/src/components/Settings/SystemLogsPanel.tsx b/frontend-modern/src/components/Settings/SystemLogsPanel.tsxindex 079ce222f2..ff7a16470d 100644--- a/frontend-modern/src/components/Settings/SystemLogsPanel.tsx+++ b/frontend-modern/src/components/Settings/SystemLogsPanel.tsx@@ -1,4 +1,4 @@-import { Component, For, createUniqueId } from 'solid-js';+import { Component, For, Show, createUniqueId } from 'solid-js';import OperationsPanel from '@/components/Settings/OperationsPanel';import {getSystemLogBufferSummary,@@ -14,10 +14,10 @@ import Trash2 from 'lucide-solid/icons/trash-2';import Terminal from 'lucide-solid/icons/terminal';import { FormSelect } from '@/components/shared/FormSelect';import { Button } from '@/components/shared/Button';-import { useSystemLogsPanelState } from './useSystemLogsPanelState';+import { useSystemLogsPanelState, type SystemLogsPanelProps } from './useSystemLogsPanelState';-export const SystemLogsPanel: Component = () => {- const state = useSystemLogsPanelState();+export const SystemLogsPanel: Component<SystemLogsPanelProps> = (props) => {+ const state = useSystemLogsPanelState(props);const levelHelpId = createUniqueId();const displayHelpId = createUniqueId();const bundleHelpId = createUniqueId();@@ -35,6 +35,7 @@ export const SystemLogsPanel: Component = () => {id={`system-log-level-${levelHelpId}`}label={SYSTEM_LOGS_PANEL_COPY.levelLabel}aria-describedby={levelHelpId}+ disabled={!state.canUseControls() || state.changingLevel()}value={state.level()}onChange={(e) => void state.handleLevelChange(e.currentTarget.value)}fieldBaseClass="flex"@@ -78,6 +79,7 @@ export const SystemLogsPanel: Component = () => {<div class="h-6 w-px bg-surface-hover mx-2"></div><Buttontype="button"+ disabled={!state.canUseControls()}onClick={state.handleDownload}aria-describedby={bundleHelpId}variant="primaryFlat"@@ -96,6 +98,24 @@ export const SystemLogsPanel: Component = () => {</div></div>+ <div class="px-4 sm:px-6 space-y-3">+ <Show when={state.error()}>+ <p role="alert" class="text-sm text-red-600 dark:text-red-400">+ {state.error()}+ </p>+ </Show>+ <Show when={state.notice()}>+ <p role="status" class="text-sm text-muted">+ {state.notice()}+ </p>+ </Show>+ <Show when={state.canReconnect()}>+ <Button type="button" size="settingsAction" onClick={() => void state.reconnect()}>+ Reconnect logs+ </Button>+ </Show>+ </div>+{/* Terminal View */}<div class="p-4 sm:p-6"><div@@ -113,7 +133,11 @@ export const SystemLogsPanel: Component = () => {{state.logs().length === 0 && !state.isLoading() && (<div class="h-full flex flex-col items-center justify-center "><Terminal size={48} class="mb-4 opacity-50" />- <p>{SYSTEM_LOGS_PANEL_COPY.emptyState}</p>+ <p>+ {state.canUseControls()+ ? SYSTEM_LOGS_PANEL_COPY.emptyState+ : SYSTEM_LOGS_PANEL_COPY.unavailableState}+ </p></div>)}</div>diff --git a/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.safety.test.tsx b/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.safety.test.tsxindex 512bec62db..353285ac4e 100644--- a/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.safety.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.safety.test.tsx@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SystemLogsPanel } from '../SystemLogsPanel';const apiFetchJSON = vi.hoisted(() => vi.fn());-vi.mock('@/utils/apiClient', () => ({ apiFetchJSON }));+vi.mock('@/utils/apiClient', () => ({ apiFetchJSON, getOrgID: () => 'default' }));vi.mock('@/utils/logger', () => ({ logger: { debug: vi.fn(), error: vi.fn() } }));vi.mock('@/stores/notifications', () => ({notificationStore: { success: vi.fn(), error: vi.fn() },@@ -48,25 +48,56 @@ describe('SystemLogsPanel control safety', () => {it('does not call a disconnected or reconnecting native stream Streaming, even when the display is paused', async () => {const { stream } = await mountPanel();- expect(screen.getByRole('status')).toHaveTextContent('Connecting');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Connecting');stream.onopen?.();- expect(screen.getByRole('status')).toHaveTextContent('Streaming');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Streaming');stream.readyState = 0;stream.onerror?.();- expect(screen.getByRole('status')).toHaveTextContent('Reconnecting');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Reconnecting');fireEvent.click(screen.getByRole('button', { name: 'Pause Stream' }));- expect(screen.getByRole('status')).toHaveTextContent('Reconnecting · paused');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Reconnecting · paused');stream.readyState = 2;stream.onerror?.();- expect(screen.getByRole('status')).toHaveTextContent('Disconnected · paused');- expect(screen.getByRole('status')).not.toHaveTextContent('Streaming');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Disconnected · paused');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).not.toHaveTextContent('Streaming');fireEvent.click(screen.getByRole('button', { name: 'Clear Log Output' }));- expect(screen.getByRole('status')).toHaveTextContent('Disconnected · paused');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Disconnected · paused');stream.onopen?.();- expect(screen.getByRole('status')).toHaveTextContent('Paused');+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Disconnected');+ fireEvent.click(screen.getByRole('button', { name: 'Reconnect logs' }));+ await waitFor(() => expect(DisplayStream.instances).toHaveLength(2));+ DisplayStream.instances[1].onopen?.();+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Paused');fireEvent.click(screen.getByRole('button', { name: 'Resume Stream' }));- expect(screen.getByRole('status')).toHaveTextContent('Streaming');- expect(apiFetchJSON.mock.calls).toEqual([['/api/logs/level']]);+ expect(+ screen.getAllByRole('status').find((x) => x.querySelector('.rounded-full'))!,+ ).toHaveTextContent('Streaming');+ expect(+ apiFetchJSON.mock.calls.every(+ ([path, options]) =>+ path === '/api/logs/level' &&+ options.retry === false &&+ options.expectedOrgID === 'default',+ ),+ ).toBe(true);});it('describes the server-wide threshold at the level control without changing it on mount', async () => {@@ -77,7 +108,16 @@ describe('SystemLogsPanel control safety', () => {expect(select).toHaveAccessibleDescription(/Debug can include private guest names and paths/);const help = document.getElementById(select.getAttribute('aria-describedby')!);expect(help).toBeVisible();- expect(apiFetchJSON.mock.calls).toEqual([['/api/logs/level']]);+ expect(apiFetchJSON.mock.calls).toEqual([+ [+ '/api/logs/level',+ expect.objectContaining({+ retry: false,+ expectedOrgID: 'default',+ signal: expect.any(AbortSignal),+ }),+ ],+ ]);});it('describes display-only pause and still receives later messages on the same stream', async () => {@@ -101,7 +141,16 @@ describe('SystemLogsPanel control safety', () => {expect(screen.queryByText('INFO received while paused')).toBeNull();expect(DisplayStream.instances).toHaveLength(1);expect(stream.url).toBe('/api/logs/stream');- expect(apiFetchJSON.mock.calls).toEqual([['/api/logs/level']]);+ expect(apiFetchJSON.mock.calls).toEqual([+ [+ '/api/logs/level',+ expect.objectContaining({+ retry: false,+ expectedOrgID: 'default',+ signal: expect.any(AbortSignal),+ }),+ ],+ ]);});it('describes view-only clear without changing the level or closing the stream', async () => {@@ -117,7 +166,16 @@ describe('SystemLogsPanel control safety', () => {expect(screen.queryByText('INFO displayed before clear')).toBeNull();expect(stream.close).not.toHaveBeenCalled();expect(screen.getByRole('combobox', { name: 'Server Log Level:' })).toHaveValue('info');- expect(apiFetchJSON.mock.calls).toEqual([['/api/logs/level']]);+ expect(apiFetchJSON.mock.calls).toEqual([+ [+ '/api/logs/level',+ expect.objectContaining({+ retry: false,+ expectedOrgID: 'default',+ signal: expect.any(AbortSignal),+ }),+ ],+ ]);});it('keeps the full archive privacy warning visible and attached after pause and clear', async () => {@@ -139,7 +197,16 @@ describe('SystemLogsPanel control safety', () => {expect(warning).toBeVisible();expect(bundle).toHaveAccessibleDescription(/Keep the archive private/);expect(bundle).not.toHaveAccessibleDescription(/safe to (publish|share)/);- expect(apiFetchJSON.mock.calls).toEqual([['/api/logs/level']]);+ expect(apiFetchJSON.mock.calls).toEqual([+ [+ '/api/logs/level',+ expect.objectContaining({+ retry: false,+ expectedOrgID: 'default',+ signal: expect.any(AbortSignal),+ }),+ ],+ ]);});it('does not turn display actions into submission of a surrounding settings form', async () => {diff --git a/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.test.tsxindex 6d09dd8849..e78a1dd4b6 100644--- a/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.test.tsx@@ -12,6 +12,12 @@ vi.mock('../useSystemLogsPanelState', () => ({isPaused: () => false,connectionState: () => 'streaming',isLoading: () => false,+ canUseControls: () => true,+ changingLevel: () => false,+ canReconnect: () => false,+ reconnect: vi.fn(),+ error: () => '',+ notice: () => '',maxLogs: 1000,clearLogs: vi.fn(),togglePaused: vi.fn(),@@ -31,8 +37,11 @@ describe('SystemLogsPanel architecture', () => {expect(systemLogsPanelSource).not.toContain("apiFetchJSON('/api/logs/level'");expect(systemLogsPanelStateSource).toContain('new EventSource');expect(systemLogsPanelStateSource).toContain("apiFetchJSON('/api/logs/level'");- expect(systemLogsPanelStateSource).toContain("window.location.href = '/api/logs/download'");- expect(systemLogsPanelStateSource).toContain('notificationStore.success');+ expect(systemLogsPanelStateSource).toContain("anchor.href = '/api/logs/download'");+ expect(systemLogsPanelStateSource).toContain('eventSource === source');+ expect(systemLogsPanelStateSource).toContain('expectedOrgID: acceptedReader.org');+ expect(systemLogsPanelStateSource).toContain('retry: false');+ expect(systemLogsPanelStateSource).not.toContain('notificationStore');});it('keeps support-page controls touch-sized on phones', () => {diff --git a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.tsindex 800461a128..ceda21de48 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts@@ -351,4 +351,30 @@ describe('buildSettingsPanelRegistryContext', () => {canRead: false,});});+ it('binds System Logs to the current reader and explicit capability without treating scope order as a new reader', () => {+ const [status, setStatus] = createSignal<SecurityStatus | null>(null);+ const context = buildSettingsPanelRegistryContext({+ ...buildParams(null),+ securityStatus: status,+ });+ expect(context.getSystemLogsPanelProps()).toEqual({+ currentUser: undefined,+ accessKey: '[null,null]',+ canRead: false,+ });+ setStatus({+ currentUsername: 'reader',+ apiTokenHint: 'hint-a',+ tokenScopes: ['settings:read', 'settings:write'],+ settingsCapabilities: { systemLogsRead: true },+ } as SecurityStatus);+ const accepted = context.getSystemLogsPanelProps();+ expect(accepted).toMatchObject({ currentUser: 'reader', canRead: true });+ setStatus({ ...status(), tokenScopes: ['settings:write', 'settings:read'] } as SecurityStatus);+ expect(context.getSystemLogsPanelProps()).toEqual(accepted);+ setStatus({ ...status(), apiTokenHint: 'hint-b' } as SecurityStatus);+ expect(context.getSystemLogsPanelProps().accessKey).not.toBe(accepted.accessKey);+ setStatus({ ...status(), settingsCapabilities: { systemLogsRead: false } } as SecurityStatus);+ expect(context.getSystemLogsPanelProps().canRead).toBe(false);+ });});diff --git a/frontend-modern/src/components/Settings/__tests__/useSystemLogsPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useSystemLogsPanelState.test.tsxindex 39f830286a..ac51818f60 100644--- a/frontend-modern/src/components/Settings/__tests__/useSystemLogsPanelState.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/useSystemLogsPanelState.test.tsx@@ -1,14 +1,20 @@-import { For, createEffect } from 'solid-js';+import { For, createEffect, createSignal } from 'solid-js';import { cleanup, render } from '@solidjs/testing-library';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { useSystemLogsPanelState } from '../useSystemLogsPanelState';+import { useSystemLogsPanelState, type SystemLogsPanelProps } from '../useSystemLogsPanelState';+import { eventBus } from '@/stores/events';-const mocks = vi.hoisted(() => ({ api: vi.fn(), success: vi.fn(), error: vi.fn() }));-vi.mock('@/utils/apiClient', () => ({ apiFetchJSON: mocks.api }));+const mocks = vi.hoisted(() => ({+ api: vi.fn(),+ success: vi.fn(),+ error: vi.fn(),+ org: 'default',+}));+vi.mock('@/utils/apiClient', () => ({ apiFetchJSON: mocks.api, getOrgID: () => mocks.org }));vi.mock('@/stores/notifications', () => ({notificationStore: { success: mocks.success, error: mocks.error },}));-vi.mock('@/utils/logger', () => ({ logger: { debug: vi.fn(), error: vi.fn() } }));+vi.mock('@/utils/logger', () => ({ logger: { debug: vi.fn(), error: vi.fn(), org: 'default' } }));class FixtureEventSource {static instances: FixtureEventSource[] = [];@@ -39,11 +45,11 @@ const flushFrame = () => {callbacks.forEach((callback) => callback(0));};-async function mount() {+async function mount(props: SystemLogsPanelProps = {}) {let state!: ReturnType<typeof useSystemLogsPanelState>;const publish = vi.fn();const view = render(() => {- state = useSystemLogsPanelState();+ state = useSystemLogsPanelState(props);createEffect(() => {publish(state.logs());});@@ -73,6 +79,7 @@ async function mount() {beforeEach(() => {vi.clearAllMocks();+ mocks.org = 'default';FixtureEventSource.instances = [];frames = new Map();nextFrame = 0;@@ -99,35 +106,47 @@ afterEach(() => {});describe('live system log rendering', () => {- it('reports native connection state independently of display pause, and recovers without clearing accepted lines', async () => {+ it('withdraws private lines on transient loss and requires explicit recovery after terminal loss', async () => {const { state, stream, view } = await mount();expect(state.connectionState()).toBe('connecting');stream.onopen?.();- expect(state.connectionState()).toBe('streaming');stream.send('accepted before disconnect');flushFrame();+ stream.send('pending before disconnect');state.togglePaused();stream.readyState = 0;stream.onerror?.();expect(state.connectionState()).toBe('reconnecting');expect(state.isPaused()).toBe(true);- expect(state.logs()).toEqual(['accepted before disconnect']);- stream.readyState = 2;- stream.onerror?.();- expect(state.connectionState()).toBe('disconnected');+ expect(state.logs()).toEqual([]);+ expect(frames.size).toBe(0);+ expect(state.canUseControls()).toBe(false);expect(stream.close).not.toHaveBeenCalled();- stream.readyState = 1;stream.onopen?.();expect(state.connectionState()).toBe('streaming');stream.send('not collected while paused');flushFrame();- expect(state.logs()).toEqual(['accepted before disconnect']);- view.unmount();+ expect(state.logs()).toEqual([]);+ stream.readyState = 2;stream.onerror?.();- stream.onopen?.();- expect(state.connectionState()).toBe('streaming');+ expect(state.connectionState()).toBe('disconnected');expect(stream.close).toHaveBeenCalledTimes(1);- expect(mocks.api.mock.calls).toEqual([['/api/logs/level']]);+ stream.onopen?.();+ stream.send('obsolete queued callback');+ flushFrame();+ expect(state.connectionState()).toBe('disconnected');+ expect(state.logs()).toEqual([]);+ await state.reconnect();+ expect(FixtureEventSource.instances).toHaveLength(2);+ const next = FixtureEventSource.instances[1];+ next.onopen?.();+ state.togglePaused();+ next.send('fresh reader line');+ flushFrame();+ expect(state.logs()).toEqual(['fresh reader line']);+ view.unmount();+ expect(next.close).toHaveBeenCalledTimes(1);+ expect(state.logs()).toEqual([]);});it('publishes and scrolls once per frame, after the accepted rows render', async () => {@@ -239,15 +258,177 @@ describe('live system log rendering', () => {expect(stream.url).toBe('/api/logs/stream');expect(state.level()).toBe('info');expect(state.isLoading()).toBe(false);+ stream.onopen?.();await state.handleLevelChange('warn');expect(mocks.api).toHaveBeenLastCalledWith('/api/logs/level', {method: 'POST',body: JSON.stringify({ level: 'warn' }),+ signal: expect.any(AbortSignal),+ expectedOrgID: 'default',+ retry: false,});- expect(mocks.success).toHaveBeenCalledWith('Log level set to warn');+ expect(state.notice()).toBe('Log level set to warn');mocks.api.mockRejectedValueOnce(new Error('fixture unavailable'));await state.handleLevelChange('error');expect(state.level()).toBe('warn');- expect(mocks.error).toHaveBeenCalledWith('Failed to set log level');+ expect(state.error()).toMatch(/change could not be confirmed/);+ expect(state.logs()).toEqual([]);+ expect(state.canUseControls()).toBe(false);+ expect(mocks.success).not.toHaveBeenCalled();+ expect(mocks.error).not.toHaveBeenCalled();+ });+ it('binds initial reads to the workspace, disables actions until verified, and never starts a stream after a failed or malformed check', async () => {+ for (const value of [null, {}, { level: 'not-a-level' }]) {+ mocks.api.mockResolvedValueOnce(value);+ const { state, view } = await mount();+ expect(FixtureEventSource.instances).toHaveLength(0);+ expect(state.canUseControls()).toBe(false);+ expect(state.error()).toMatch(/Log access could not be confirmed/);+ await state.handleLevelChange('debug');+ view.unmount();+ }+ expect(mocks.api).toHaveBeenCalledTimes(3);+ for (const call of mocks.api.mock.calls)+ expect(call).toEqual([+ '/api/logs/level',+ {+ signal: expect.any(AbortSignal),+ expectedOrgID: 'default',+ retry: false,+ },+ ]);+ });++ it('withdraws visible and frame-starved buffers on workspace change, including a return to identical reader names', async () => {+ const { state, stream } = await mount();+ stream.send('visible-private');+ flushFrame();+ stream.send('pending-private');+ const oldFrame = [...frames.values()][0];+ mocks.org = 'tenant-b';+ eventBus.emit('org_switched', 'tenant-b');+ expect(state.logs()).toEqual([]);+ expect(state.canUseControls()).toBe(false);+ expect(stream.close).toHaveBeenCalledTimes(1);+ expect(FixtureEventSource.instances).toHaveLength(1);+ mocks.org = 'default';+ eventBus.emit('org_switched', 'default');+ await state.reconnect();+ const next = FixtureEventSource.instances[1];+ next.send('current-private');+ oldFrame(0);+ stream.send('late-private');+ stream.onopen?.();+ expect(state.logs()).toEqual([]);+ flushFrame();+ expect(state.logs()).toEqual(['current-private']);+ });++ it('ignores equal access facts but withdraws on principal, credential and capability changes', async () => {+ const [user, setUser] = createSignal('operator');+ const [key, setKey] = createSignal('credential-a');+ const [allowed, setAllowed] = createSignal(true);+ const { state, stream } = await mount({+ get currentUser() {+ return user();+ },+ get accessKey() {+ return key();+ },+ get canRead() {+ return allowed();+ },+ });+ stream.send('private');+ flushFrame();+ setUser('operator');+ setKey('credential-a');+ expect(state.logs()).toEqual(['private']);+ setUser('different-operator');+ expect(state.logs()).toEqual([]);+ expect(stream.close).toHaveBeenCalledTimes(1);+ expect(FixtureEventSource.instances).toHaveLength(1);+ await state.reconnect();+ FixtureEventSource.instances[1].send('current');+ flushFrame();+ setKey('credential-b');+ expect(state.logs()).toEqual([]);+ await state.reconnect();+ FixtureEventSource.instances[2].send('current');+ flushFrame();+ setAllowed(false);+ expect(state.logs()).toEqual([]);+ expect(state.canReconnect()).toBe(false);+ await state.reconnect();+ await state.handleLevelChange('debug');+ expect(FixtureEventSource.instances).toHaveLength(3);+ setAllowed(true);+ expect(state.canReconnect()).toBe(true);+ expect(FixtureEventSource.instances).toHaveLength(3);+ });++ it('cancels obsolete level reads and rejects their late completion even after returning to the same workspace', async () => {+ let finish!: (value: { level: string }) => void;+ mocks.api.mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { state } = await mount();+ const options = mocks.api.mock.calls[0][1];+ mocks.org = 'tenant-b';+ eventBus.emit('org_switched', 'tenant-b');+ mocks.org = 'default';+ eventBus.emit('org_switched', 'default');+ expect(options.signal.aborted).toBe(true);+ finish({ level: 'debug' });+ await flushAsync();+ expect(FixtureEventSource.instances).toHaveLength(0);+ expect(state.level()).toBe('info');+ await state.reconnect();+ expect(FixtureEventSource.instances).toHaveLength(1);+ });++ it('single-submits level changes and withholds late success after disposal', async () => {+ const { state, stream, view } = await mount();+ stream.onopen?.();+ let finish!: () => void;+ mocks.api.mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const changing = state.handleLevelChange('warn');+ await state.handleLevelChange('debug');+ expect(mocks.api).toHaveBeenCalledTimes(2);+ const options = mocks.api.mock.calls[1][1];+ view.unmount();+ expect(options.signal.aborted).toBe(true);+ finish();+ await changing;+ expect(state.notice()).toBe('');+ expect(state.error()).toBe('');+ expect(mocks.success).not.toHaveBeenCalled();+ });+ it('starts support downloads without navigating the live stream and disables them when access is unknown', async () => {+ const { state, stream } = await mount();+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (+ this: HTMLAnchorElement,+ ) {+ expect(this.isConnected).toBe(true);+ expect(this.getAttribute('href')).toBe('/api/logs/download');+ expect(this.hasAttribute('download')).toBe(true);+ });+ state.handleDownload();+ expect(click).not.toHaveBeenCalled();+ stream.onopen?.();+ state.handleDownload();+ expect(click).toHaveBeenCalledTimes(1);+ expect(document.querySelector('a[download]')).toBeNull();+ stream.readyState = 2;+ stream.onerror?.();+ state.handleDownload();+ expect(click).toHaveBeenCalledTimes(1);+ click.mockRestore();});});diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts b/frontend-modern/src/components/Settings/settingsPanelRegistry.tsindex 1c277c9630..abf3185ac0 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 { SystemLogsPanelProps } from './useSystemLogsPanelState';import type { DiagnosticsPanelProps } from './useDiagnosticsPanelState';import type { SettingsTab } from './settingsNavigationModel';import { SETTINGS_PANEL_REGISTRY_LOADERS } from './settingsPanelRegistryLoaders';@@ -50,6 +51,7 @@ export interface SettingsPanelRegistryContext {getRelayPanelProps: () => Parameters<typeof RelaySettingsPanelType>[0];getReportingPanelProps: () => Parameters<typeof ReportingPanelType>[0];getDiagnosticsPanelProps: () => DiagnosticsPanelProps;+ getSystemLogsPanelProps: () => SystemLogsPanelProps;getAuditWebhookPanelProps: () => Parameters<typeof AuditWebhookPanelType>[0];getAuditLogPanelProps: () => Parameters<typeof AuditLogPanelType>[0];getRolesPanelProps: () => Parameters<typeof RolesPanelType>[0];@@ -107,6 +109,7 @@ export const createSettingsPanelRegistry = (},'support-logs': {component: SETTINGS_PANEL_REGISTRY_LOADERS.SystemLogsPanel,+ getProps: context.getSystemLogsPanelProps,},'organization-overview': {component: SETTINGS_PANEL_REGISTRY_LOADERS.OrganizationOverviewPanel,diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsxindex 9f935cc052..23901e3171 100644--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx@@ -141,6 +141,14 @@ export function buildSettingsPanelRegistryContext(]),canRead: settingsCapabilities()?.diagnosticsRead === true,}),+ getSystemLogsPanelProps: () => ({+ currentUser: currentUser(),+ accessKey: JSON.stringify([+ params.securityStatus()?.apiTokenHint,+ params.securityStatus()?.tokenScopes?.slice().sort(),+ ]),+ canRead: settingsCapabilities()?.systemLogsRead === true,+ }),getAuditLogPanelProps: () => ({currentUser: currentUser(),accessKey: JSON.stringify([diff --git a/frontend-modern/src/components/Settings/useSystemLogsPanelState.ts b/frontend-modern/src/components/Settings/useSystemLogsPanelState.tsindex 2b24ffde3e..4f243f8944 100644--- a/frontend-modern/src/components/Settings/useSystemLogsPanelState.ts+++ b/frontend-modern/src/components/Settings/useSystemLogsPanelState.ts@@ -1,29 +1,64 @@-import { createSignal, onCleanup, onMount } from 'solid-js';-import { apiFetchJSON } from '@/utils/apiClient';-import { notificationStore } from '@/stores/notifications';-import { logger } from '@/utils/logger';-import type { SystemLogConnectionState } from '@/utils/systemLogsPresentation';+import { batch, createEffect, createSignal, onCleanup, onMount, untrack } from 'solid-js';+import { apiFetchJSON, getOrgID } from '@/utils/apiClient';+import { eventBus } from '@/stores/events';+import {+ SYSTEM_LOG_LEVEL_OPTIONS,+ SYSTEM_LOGS_PANEL_COPY,+ type SystemLogConnectionState,+} from '@/utils/systemLogsPresentation';const MAX_LOGS = 1000;-export function useSystemLogsPanelState() {- const [logs, setLogs] = createSignal<string[]>([]);+export interface SystemLogsPanelProps {+ currentUser?: string;+ accessKey?: string;+ canRead?: boolean;+}++export function useSystemLogsPanelState(props: SystemLogsPanelProps = {}) {+ const [buffer, setBuffer] = createSignal<string[]>([]);const [isPaused, setIsPaused] = createSignal(false);const [level, setLevel] = createSignal('info');- const [isLoading, setIsLoading] = createSignal(true);+ const [isLoading, setIsLoading] = createSignal(false);+ const [changingLevel, setChangingLevel] = createSignal(false);+ const [notice, setNotice] = createSignal('');+ const [error, setError] = createSignal('');const [connectionState, setConnectionState] =createSignal<SystemLogConnectionState>('connecting');+ const reader = () => ({+ org: getOrgID() || 'default',+ user: props.currentUser,+ access: props.accessKey,+ allowed: props.canRead !== false,+ });+ const [context, setContext] = createSignal(reader());let logContainer: HTMLDivElement | undefined;let eventSource: EventSource | null = null;+ let levelRequest: AbortController | undefined;+ let writeRequest: AbortController | undefined;let disposed = false;let renderFrame: number | null = null;// A bounded ring also caps pending work when a background tab stops frames.- // Receiving a line never clones the visible buffer or forces layout.let pendingLogs: string[] = [];let pendingCount = 0;let pendingNext = 0;+ const isCurrentReader = () => {+ const current = reader();+ const accepted = context();+ return (+ !disposed &&+ current.allowed &&+ accepted.allowed &&+ current.org === accepted.org &&+ current.user === accepted.user &&+ current.access === accepted.access+ );+ };+ const logs = () => (isCurrentReader() ? buffer() : []);+ const canUseControls = () => isCurrentReader() && connectionState() === 'streaming';+const resetPending = () => {pendingLogs = [];pendingCount = 0;@@ -33,128 +68,213 @@ export function useSystemLogsPanelState() {renderFrame = null;}};+ const clearLogs = () => {+ resetPending();+ setBuffer([]);+ };+ const disconnect = (message = '') => {+ eventSource?.close();+ eventSource = null;+ levelRequest?.abort();+ levelRequest = undefined;+ writeRequest?.abort();+ writeRequest = undefined;+ batch(() => {+ clearLogs();+ setIsLoading(false);+ setChangingLevel(false);+ setConnectionState('disconnected');+ setNotice('');+ setError(message);+ });+ };+ const resetReader = () => {+ disconnect();+ batch(() => {+ setContext(reader());+ setLevel('info');+ setNotice(SYSTEM_LOGS_PANEL_COPY.readerChanged);+ });+ // Reader/workspace changes never reopen a privileged stream automatically.+ };+ createEffect(() => {+ const next = reader();+ const previous = untrack(context);+ 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);const setLogContainer = (element: HTMLDivElement | undefined) => {logContainer = element;};-- const scrollToBottom = () => {- if (logContainer) {- logContainer.scrollTop = logContainer.scrollHeight;- }- };-const flushPendingLogs = () => {- if (disposed || pendingCount === 0) return;+ if (!canUseControls() || pendingCount === 0) return;const incoming = Array.from({ length: pendingCount },(_, index) => pendingLogs[(pendingNext - pendingCount + MAX_LOGS + index) % MAX_LOGS],);resetPending();- setLogs((prev) => [+ setBuffer((prev) => [...prev.slice(Math.max(0, prev.length + incoming.length - MAX_LOGS)),...incoming,]);- // Solid updates the rows synchronously; measure after the single publish.- scrollToBottom();- };-- const fetchLevel = async () => {- try {- const res = (await apiFetchJSON('/api/logs/level')) as { level?: string };- if (res.level && !disposed) setLevel(res.level);- } catch (error) {- logger.error('Failed to fetch log level', error);- }+ if (logContainer) logContainer.scrollTop = logContainer.scrollHeight;};- const connectStream = () => {- if (disposed) return;-- eventSource = new EventSource('/api/logs/stream');- const source = eventSource;-+ const connectStream = (acceptedReader: ReturnType<typeof reader>) => {+ const source = new EventSource('/api/logs/stream');+ eventSource = source;+ const isCurrent = () =>+ isCurrentReader() && context() === acceptedReader && eventSource === source;source.onopen = () => {- if (!disposed) setConnectionState('streaming');+ if (!isCurrent()) return;+ batch(() => {+ setConnectionState('streaming');+ setNotice('');+ setError('');+ });};-source.onmessage = (event) => {- if (disposed) return;+ if (!isCurrent()) return;setConnectionState('streaming');if (isPaused()) return;-pendingLogs[pendingNext] = event.data;pendingNext = (pendingNext + 1) % MAX_LOGS;pendingCount = Math.min(pendingCount + 1, MAX_LOGS);if (renderFrame === null) {- renderFrame = requestAnimationFrame(() => {+ const frame = requestAnimationFrame(() => {+ if (renderFrame !== frame || !isCurrent()) return;renderFrame = null;flushPendingLogs();});+ renderFrame = frame;}};-source.onerror = () => {- if (disposed) return;- // Native EventSource retries transient EOF, but stops after a denied- // reconnect. Neither state is evidence of a live stream or its cause.- setConnectionState(- source.readyState === EventSource.CLOSED ? 'disconnected' : 'reconnecting',- );- logger.debug('SSE log stream disconnected');+ if (!isCurrent()) return;+ // EventSource does not expose the HTTP error or its cause. Withdraw+ // private buffered lines even on transient EOF; keep native reconnects.+ clearLogs();+ if (source.readyState === EventSource.CLOSED) {+ disconnect(SYSTEM_LOGS_PANEL_COPY.connectionError);+ } else {+ batch(() => {+ setConnectionState('reconnecting');+ setNotice(SYSTEM_LOGS_PANEL_COPY.reconnecting);+ });+ }};};+ const reconnect = async () => {+ if (!isCurrentReader() || eventSource || levelRequest) return;+ const acceptedReader = context();+ const request = new AbortController();+ levelRequest = request;+ const isCurrent = () =>+ isCurrentReader() && context() === acceptedReader && levelRequest === request;+ batch(() => {+ clearLogs();+ setIsLoading(true);+ setConnectionState('connecting');+ setError('');+ setNotice('');+ });+ try {+ const res = await apiFetchJSON<{ level: string }>('/api/logs/level', {+ signal: request.signal,+ expectedOrgID: acceptedReader.org,+ retry: false,+ });+ if (!isCurrent()) return;+ if (!res || !SYSTEM_LOG_LEVEL_OPTIONS.some((option) => option.value === res.level))+ throw new Error('Invalid log level');+ setLevel(res.level);+ connectStream(acceptedReader);+ } catch {+ if (isCurrent()) disconnect(SYSTEM_LOGS_PANEL_COPY.connectionError);+ } finally {+ if (levelRequest === request) {+ levelRequest = undefined;+ setIsLoading(false);+ }+ }+ };+const handleLevelChange = async (newLevel: string) => {+ if (+ !canUseControls() ||+ writeRequest ||+ !SYSTEM_LOG_LEVEL_OPTIONS.some((option) => option.value === newLevel)+ )+ return;+ const acceptedReader = context();+ const request = new AbortController();+ writeRequest = request;+ const isCurrent = () =>+ canUseControls() && context() === acceptedReader && writeRequest === request;+ setChangingLevel(true);+ setNotice('');try {await apiFetchJSON('/api/logs/level', {method: 'POST',body: JSON.stringify({ level: newLevel }),+ signal: request.signal,+ expectedOrgID: acceptedReader.org,+ retry: false,});+ if (!isCurrent()) return;setLevel(newLevel);- notificationStore.success(`Log level set to ${newLevel}`);- } catch (error) {- logger.error('Error setting log level', error);- notificationStore.error('Failed to set log level');+ setNotice(`Log level set to ${newLevel}`);+ } catch {+ if (isCurrent()) disconnect(SYSTEM_LOGS_PANEL_COPY.levelError);+ } finally {+ if (writeRequest === request) {+ writeRequest = undefined;+ setChangingLevel(false);+ }}};const handleDownload = () => {- window.location.href = '/api/logs/download';+ if (!canUseControls()) return;+ // A top-level navigation cancels WebKit's live EventSource without an+ // error callback. Use a same-origin download, preserving native streaming+ // of large support archives rather than buffering them in JavaScript.+ const anchor = document.createElement('a');+ anchor.href = '/api/logs/download';+ anchor.download = '';+ document.body.appendChild(anchor);+ try {+ anchor.click();+ } finally {+ anchor.remove();+ }};-const togglePaused = () => {- // Lines accepted before Pause belong in the view; paused arrivals do not.if (!isPaused()) flushPendingLogs();setIsPaused((prev) => !prev);};-- const clearLogs = () => {- resetPending();- setLogs([]);- };-- onMount(() => {- void (async () => {- await fetchLevel();- if (disposed) return;- connectStream();- setIsLoading(false);- })();- });-+ onMount(() => void reconnect());onCleanup(() => {disposed = true;- resetPending();- if (eventSource) {- eventSource.close();- eventSource = null;- }+ unsubscribe();+ disconnect();});return {+ canUseControls,+ canReconnect: () => isCurrentReader() && connectionState() === 'disconnected',+ changingLevel,clearLogs,connectionState,+ error: () => (isCurrentReader() ? error() : ''),handleDownload,handleLevelChange,isLoading,@@ -162,6 +282,8 @@ export function useSystemLogsPanelState() {level,logs,maxLogs: MAX_LOGS,+ notice: () => (isCurrentReader() ? notice() : ''),+ reconnect,setLogContainer,togglePaused,};diff --git a/frontend-modern/src/utils/__tests__/systemLogsPresentation.test.ts b/frontend-modern/src/utils/__tests__/systemLogsPresentation.test.tsindex 199000d11e..2c91bba999 100644--- a/frontend-modern/src/utils/__tests__/systemLogsPresentation.test.ts+++ b/frontend-modern/src/utils/__tests__/systemLogsPresentation.test.ts@@ -22,6 +22,15 @@ describe('systemLogsPresentation', () => {clearTitle: 'Clear Log Output',downloadLabel: 'Support Bundle',emptyState: 'Waiting for log output.',+ unavailableState: 'No current log output.',+ connectionError:+ 'Log access could not be confirmed. Buffered lines were cleared. Reconnect to try again.',+ readerChanged:+ 'The reader or workspace changed. Buffered lines were cleared. Reconnect to read current logs.',+ reconnecting:+ 'The log connection was interrupted. Buffered lines were cleared while the stream reconnects.',+ levelError:+ 'The log level change could not be confirmed. Buffered lines were cleared. Reconnect to check the current level.',bufferHelp:'This view keeps only the latest 1,000 received lines. Paused lines are not collected. Clearing the view does not delete server logs.',});diff --git a/frontend-modern/src/utils/systemLogsPresentation.ts b/frontend-modern/src/utils/systemLogsPresentation.tsindex a545d66bcd..cf6913dfc3 100644--- a/frontend-modern/src/utils/systemLogsPresentation.ts+++ b/frontend-modern/src/utils/systemLogsPresentation.ts@@ -25,6 +25,15 @@ export const SYSTEM_LOGS_PANEL_COPY = {clearTitle: 'Clear Log Output',downloadLabel: 'Support Bundle',emptyState: 'Waiting for log output.',+ unavailableState: 'No current log output.',+ connectionError:+ 'Log access could not be confirmed. Buffered lines were cleared. Reconnect to try again.',+ readerChanged:+ 'The reader or workspace changed. Buffered lines were cleared. Reconnect to read current logs.',+ reconnecting:+ 'The log connection was interrupted. Buffered lines were cleared while the stream reconnects.',+ levelError:+ 'The log level change could not be confirmed. Buffered lines were cleared. Reconnect to check the current level.',bufferHelp:'This view keeps only the latest 1,000 received lines. Paused lines are not collected. Clearing the view does not delete server logs.',} as const;