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 TrueNAS settings requests with their admitted reader
pulse-triage[bot]f886613300bc
diff --git a/frontend-modern/browser-verification/0d950174733ea020.json b/frontend-modern/browser-verification/0d950174733ea020.jsonnew file mode 100644index 0000000000..488c6933f4--- /dev/null+++ b/frontend-modern/browser-verification/0d950174733ea020.json@@ -0,0 +1,43 @@+{+ "version": 1,+ "base_sha": "0e82e9b2a19081ba6c2b7c72d728ab45af05dbba",+ "verified_at": "2026-11-02T19:58:57.735826Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/api/truenas.ts",+ "frontend-modern/src/components/Settings/Settings.tsx",+ "frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts",+ "frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/api/truenas.ts": "8375d3219eacf215ffcc73d9ceee37cc70965c5931ebc21de8e635d66c4a90a8",+ "frontend-modern/src/components/Settings/Settings.tsx": "cc0e83ce82510a1fddd3cef8e84d8856a94c1d0ad1101cefcd077b5f4c92ff81",+ "frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts": "4735207796b3c1bf2bfca992b003c7f5f19b4cb7b97ca00ec12761d556294ea8",+ "frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts": "d647d153f3d6b9f0b4b7dabe8b1dc68b3f4046244f33de982ef6ebd4f9a2f6c7"+ },+ "routes": [+ "/settings/infrastructure",+ "/settings/security-auth",+ "/settings/general"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 900+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "states": [+ "Actual App/Settings/Infrastructure/TrueNAS credential slot with synthetic HTTP producers and the real API client. Desktop Chromium/light and narrow WebKit/dark; Playwright 1.56.1 matches integration lock.",+ "Saved connection with masked credential, unsaved key draft and pending Test; organisation change through production client/event bus; fresh same-ID editor and successful Test/explicit Update; denied preview; full-page reload recovery; real password-modal Cancel triggers a fresh status that withdraws infrastructure access."+ ],+ "interactions": [+ "35 assertions. Organisation withdrawal closes the draft and late Test cannot publish a success. Fresh Test and explicit PUT bind team-b and preserve host, owner, masked stored key, HTTPS, verification and certificate pin. Denied preview removes the draft without provider detail or automatic replay.",+ "Real access refresh removes Infrastructure/Manage and issues no further TrueNAS request. One explicit save, no automatic create or removal; native unit regressions separately cover hook delete confirmations (the unchanged generic row-action pause/remove controller is not qualified by this proof).",+ "Eight final captures opened using native view_image: desktop full credential form, narrow vertically scrolling form, closed draft with focus returned to Manage, fresh empty key field with saved-key retention hint, and denied access falling back to General. No body overflow. Narrow captures do not show every lower field; actual buttons were scrolled to and exercised.",+ "Both context/browser trees and websocket/Vite/HTTP servers close. No uncaught page errors. Two expected synthetic HTTP403 console entries and two Vite ECONNRESET observations retained; no clean-console claim. Fixture-contract and exact-label preparation failures retained separately, with unchanged product source."+ ]+}diff --git a/frontend-modern/src/api/__tests__/truenas.test.ts b/frontend-modern/src/api/__tests__/truenas.test.tsindex 0e1ee4d1d2..391bc34c1d 100644--- a/frontend-modern/src/api/__tests__/truenas.test.ts+++ b/frontend-modern/src/api/__tests__/truenas.test.ts@@ -281,3 +281,53 @@ describe('TrueNASAPI', () => {expect(isRedactedTrueNASSecret(undefined)).toBe(false);});});++describe('TrueNAS request context', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });+ it('carries reader scope, cancellation and retry policy through every canonical connection operation', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValue({ success: true });+ const options = { expectedOrgID: 'team-a', signal: new AbortController().signal, retry: false };+ const input = {+ host: 'nas.example.invalid',+ username: 'monitor',+ useHttps: true,+ insecureSkipVerify: false,+ fingerprint: 'SHA256:synthetic',+ };+ await TrueNASAPI.listConnections(options);+ await TrueNASAPI.createConnection(input, options);+ await TrueNASAPI.updateConnection('id/with slash', input, options);+ await TrueNASAPI.deleteConnection('id/with slash', options);+ await TrueNASAPI.testConnection(input, options);+ await TrueNASAPI.testSavedConnection('id/with slash', input, options);+ await TrueNASAPI.previewConnection(input, options);+ await TrueNASAPI.previewSavedConnection('id/with slash', input, options);+ const calls = vi.mocked(apiFetchJSON).mock.calls;+ expect(calls).toHaveLength(8);+ expect(calls.map(([url]) => url)).toEqual([+ '/api/truenas/connections',+ '/api/truenas/connections',+ '/api/truenas/connections/id%2Fwith%20slash',+ '/api/truenas/connections/id%2Fwith%20slash',+ '/api/truenas/connections/test',+ '/api/truenas/connections/id%2Fwith%20slash/test',+ '/api/truenas/connections/preview',+ '/api/truenas/connections/id%2Fwith%20slash/preview',+ ]);+ expect(calls.map(([, request]) => request?.method ?? 'GET')).toEqual([+ 'GET',+ 'POST',+ 'PUT',+ 'DELETE',+ 'POST',+ 'POST',+ 'POST',+ 'POST',+ ]);+ for (const [, request] of calls) expect(request).toMatchObject(options);+ for (const [, request] of calls.filter(([, request]) => request?.body))+ expect(JSON.parse(request!.body as string)).toEqual(input);+ });+});diff --git a/frontend-modern/src/api/truenas.ts b/frontend-modern/src/api/truenas.tsindex d08e07978c..bdd53c7973 100644--- a/frontend-modern/src/api/truenas.ts+++ b/frontend-modern/src/api/truenas.ts@@ -1,4 +1,4 @@-import { apiFetchJSON } from '@/utils/apiClient';+import { apiFetchJSON, type APIContextOptions } from '@/utils/apiClient';import {normalizeMonitoredSystemLedgerPreviewResponse,type MonitoredSystemLedgerPreviewResponse,@@ -218,14 +218,20 @@ export const isRedactedTrueNASSecret = (value: string | null | undefined) =>(value || '').trim() === REDACTED_SECRET;export class TrueNASAPI {- static async listConnections(): Promise<TrueNASConnection[]> {- const response = await apiFetchJSON<RawTrueNASConnection[]>(TRUE_NAS_CONNECTIONS_PATH);+ static async listConnections(options?: APIContextOptions): Promise<TrueNASConnection[]> {+ const response = await (options === undefined+ ? apiFetchJSON<RawTrueNASConnection[]>(TRUE_NAS_CONNECTIONS_PATH)+ : apiFetchJSON<RawTrueNASConnection[]>(TRUE_NAS_CONNECTIONS_PATH, options));const list = arrayOrUndefined<RawTrueNASConnection>(response) ?? [];return list.map(normalizeTrueNASConnection);}- static async createConnection(input: TrueNASConnectionInput): Promise<TrueNASConnection> {+ static async createConnection(+ input: TrueNASConnectionInput,+ options?: APIContextOptions,+ ): Promise<TrueNASConnection> {const response = await apiFetchJSON<RawTrueNASConnection>(TRUE_NAS_CONNECTIONS_PATH, {+ ...options,method: 'POST',body: JSON.stringify(serializeTrueNASConnectionInput(input)),});@@ -235,10 +241,12 @@ export class TrueNASAPI {static async updateConnection(id: string,input: TrueNASConnectionInput,+ options?: APIContextOptions,): Promise<TrueNASConnection> {const response = await apiFetchJSON<RawTrueNASConnection>(`${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}`,{+ ...options,method: 'PUT',body: JSON.stringify(serializeTrueNASConnectionInput(input)),},@@ -246,16 +254,24 @@ export class TrueNASAPI {return normalizeTrueNASConnection(response);}- static async deleteConnection(id: string): Promise<{ success: boolean; id: string }> {+ static async deleteConnection(+ id: string,+ options?: APIContextOptions,+ ): Promise<{ success: boolean; id: string }> {return apiFetchJSON(`${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}`, {+ ...options,method: 'DELETE',});}- static async testConnection(input: TrueNASConnectionInput): Promise<TrueNASConnectionTestResult> {+ static async testConnection(+ input: TrueNASConnectionInput,+ options?: APIContextOptions,+ ): Promise<TrueNASConnectionTestResult> {const response = await apiFetchJSON<Partial<TrueNASConnectionTestResult>>(`${TRUE_NAS_CONNECTIONS_PATH}/test`,{+ ...options,method: 'POST',body: JSON.stringify(serializeTrueNASConnectionInput(input)),},@@ -268,10 +284,12 @@ export class TrueNASAPI {static async testSavedConnection(id: string,input?: TrueNASConnectionInput,+ options?: APIContextOptions,): Promise<TrueNASConnectionTestResult> {const response = await apiFetchJSON<Partial<TrueNASConnectionTestResult>>(`${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}/test`,{+ ...options,method: 'POST',...(input !== undefined? { body: JSON.stringify(serializeTrueNASConnectionInput(input)) }@@ -285,10 +303,12 @@ export class TrueNASAPI {static async previewConnection(input: TrueNASConnectionInput,+ options?: APIContextOptions,): Promise<MonitoredSystemLedgerPreviewResponse> {const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(`${TRUE_NAS_CONNECTIONS_PATH}/preview`,{+ ...options,method: 'POST',body: JSON.stringify(serializeTrueNASConnectionInput(input)),},@@ -299,10 +319,12 @@ export class TrueNASAPI {static async previewSavedConnection(id: string,input?: TrueNASConnectionInput,+ options?: APIContextOptions,): Promise<MonitoredSystemLedgerPreviewResponse> {const response = await apiFetchJSON<MonitoredSystemLedgerRawPreviewResponse>(`${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}/preview`,{+ ...options,method: 'POST',...(input !== undefined? { body: JSON.stringify(serializeTrueNASConnectionInput(input)) }diff --git a/frontend-modern/src/components/Settings/Settings.tsx b/frontend-modern/src/components/Settings/Settings.tsxindex d48ef6cd5b..61baef9dcd 100644--- a/frontend-modern/src/components/Settings/Settings.tsx+++ b/frontend-modern/src/components/Settings/Settings.tsx@@ -98,6 +98,7 @@ const SettingsWorkspace: Component<SettingsProps> = (props) => {const infrastructureSettings = useInfrastructureSettingsState({eventBus,canReadInfrastructure,+ currentUser: () => securityStatus()?.currentUsername,discoveryEnabled: discoverySettings.discoveryEnabled,setDiscoveryEnabled: discoverySettings.setDiscoveryEnabled,discoverySubnet: discoverySettings.discoverySubnet,diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsxindex c2a08448cb..2aa8bff9f5 100644--- a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.branchcov0722am.test.tsx@@ -123,13 +123,15 @@ describe('useTrueNASSettingsPanelState — error-message + dialog branch coverag});it('extracts and trims a plain-object message through testSavedConnection failure', async () => {- vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([+ makeConnection({ id: 'conn-saved', name: 'tower' }),+ ]);vi.mocked(TrueNASAPI.testSavedConnection).mockRejectedValueOnce({ message: ' saved boom ' });const { result } = renderHook(() => useTrueNASSettingsPanelState());await waitFor(() => expect(result.loading()).toBe(false));- await result.testSavedConnection(makeConnection({ id: 'conn-saved', name: 'tower' }));+ await result.testSavedConnection(result.connections()[0]);expect(notificationStore.error).toHaveBeenCalledWith('saved boom');expect(logger.error).toHaveBeenCalledWith(@@ -280,7 +282,9 @@ describe('useTrueNASSettingsPanelState — error-message + dialog branch coveragit('opens the delete confirmation dialog with the pending connection and closes it while idle', async () => {vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);+const target = makeConnection({ id: 'conn-del', name: 'tower' });+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([target]);const { result } = renderHook(() => useTrueNASSettingsPanelState());await waitFor(() => expect(result.loading()).toBe(false));@@ -302,7 +306,9 @@ describe('useTrueNASSettingsPanelState — error-message + dialog branch coveragresolveDelete = resolve;}),);+const target = makeConnection({ id: 'conn-del', name: 'tower' });+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([target]);const { result } = renderHook(() => useTrueNASSettingsPanelState());await waitFor(() => expect(result.loading()).toBe(false));@@ -329,13 +335,23 @@ describe('useTrueNASSettingsPanelState — error-message + dialog branch coveragvi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);vi.mocked(TrueNASAPI.deleteConnection).mockResolvedValueOnce({ success: true, id: 'conn-1' });+ const target = makeConnection({ id: 'conn-1', name: 'tower', host: 'truenas.local' });+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([target]);+const { result } = renderHook(() => useTrueNASSettingsPanelState());await waitFor(() => expect(result.loading()).toBe(false));- result.openDeleteDialog(makeConnection({ id: 'conn-1', name: 'tower', host: 'truenas.local' }));+ result.openDeleteDialog(target);await result.deletePendingConnection();- expect(TrueNASAPI.deleteConnection).toHaveBeenCalledWith('conn-1');+ expect(TrueNASAPI.deleteConnection).toHaveBeenCalledWith(+ 'conn-1',+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),+ );expect(notificationStore.success).toHaveBeenCalledWith('Removed tower');expect(result.deleteDialogOpen()).toBe(false);expect(result.pendingDeleteConnection()).toBeNull();@@ -348,10 +364,13 @@ describe('useTrueNASSettingsPanelState — error-message + dialog branch coveragvi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);vi.mocked(TrueNASAPI.deleteConnection).mockResolvedValueOnce({ success: true, id: 'conn-2' });+ const target = makeConnection({ id: 'conn-2', name: '', host: 'box.local' });+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([target]);+const { result } = renderHook(() => useTrueNASSettingsPanelState());await waitFor(() => expect(result.loading()).toBe(false));- result.openDeleteDialog(makeConnection({ id: 'conn-2', name: '', host: 'box.local' }));+ result.openDeleteDialog(target);await result.deletePendingConnection();expect(notificationStore.success).toHaveBeenCalledWith('Removed box.local');@@ -361,10 +380,12 @@ describe('useTrueNASSettingsPanelState — error-message + dialog branch coveragvi.mocked(TrueNASAPI.listConnections).mockResolvedValue([] as never);vi.mocked(TrueNASAPI.deleteConnection).mockRejectedValueOnce(new Error('server is down'));+ const target = makeConnection({ id: 'conn-3', name: 'tower' });+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValue([target]);+const { result } = renderHook(() => useTrueNASSettingsPanelState());await waitFor(() => expect(result.loading()).toBe(false));- const target = makeConnection({ id: 'conn-3', name: 'tower' });result.openDeleteDialog(target);await result.deletePendingConnection();diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.reader.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.reader.test.tsxnew file mode 100644index 0000000000..eb0a0c0782--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.reader.test.tsx@@ -0,0 +1,341 @@+import { renderHook, waitFor } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { TrueNASAPI, type TrueNASConnection } from '@/api/truenas';+import { eventBus } from '@/stores/events';+import { notificationStore } from '@/stores/notifications';+import { logger } from '@/utils/logger';+import { useTrueNASSettingsPanelState } from '../useTrueNASSettingsPanelState';++const scope = vi.hoisted(() => ({ org: 'team-a' }));+vi.mock('@/utils/apiClient', () => ({ getOrgID: () => scope.org }));+vi.mock('@/api/truenas', () => ({+ TrueNASAPI: {+ listConnections: vi.fn(),+ createConnection: vi.fn(),+ updateConnection: vi.fn(),+ deleteConnection: vi.fn(),+ previewConnection: vi.fn(),+ previewSavedConnection: vi.fn(),+ testConnection: vi.fn(),+ testSavedConnection: vi.fn(),+ },+ isRedactedTrueNASSecret: (value?: string) => value?.trim() === '********',+}));+vi.mock('@/stores/notifications', () => ({+ notificationStore: { success: vi.fn(), error: vi.fn() },+}));+vi.mock('@/utils/logger', () => ({ logger: { error: vi.fn() } }));++const connection = (): TrueNASConnection => ({+ id: 'same-id',+ name: 'Synthetic NAS',+ host: 'nas.example.invalid',+ username: 'monitor',+ apiKey: '********',+ useHttps: true,+ insecureSkipVerify: false,+ fingerprint: 'SHA256:synthetic-pin',+ enabled: true,+ monitorDatasets: true,+ monitorPools: true,+ monitorReplication: true,+});+const deferred = <T,>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+};+const ready = async (state: ReturnType<typeof useTrueNASSettingsPanelState>) =>+ waitFor(() => {+ expect(state.loading()).toBe(false);+ expect(state.connections()).toHaveLength(1);+ });+const openDraft = (state: ReturnType<typeof useTrueNASSettingsPanelState>) => {+ state.openEditDialog(state.connections()[0]);+ state.updateForm({ apiKey: 'synthetic-draft', name: 'Unconfirmed draft' });+};++describe('TrueNAS reader lifetime', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ scope.org = 'team-a';+ vi.mocked(TrueNASAPI.listConnections).mockImplementation(async () => [connection()]);+ });++ it('withdraws accepted inventory, draft secrets and confirmations when access is revoked', async () => {+ const [canLoad, setAllowed] = createSignal(true);+ const { result } = renderHook(() => useTrueNASSettingsPanelState({ canLoad }));+ await ready(result);+ openDraft(result);+ const old = result.connections()[0];+ setAllowed(false);+ await waitFor(() => expect(result.connections()).toEqual([]));+ expect(result.form().apiKey).toBe('');+ expect(result.dialogOpen()).toBe(false);+ expect(result.editingConnection()).toBeNull();+ expect(result.pendingDeleteConnection()).toBeNull();+ result.openEditDialog(old);+ result.openDeleteDialog(old);+ result.openCreateDialog();+ result.updateForm({ apiKey: 'must-not-stick' });+ await result.testCurrentForm();+ await result.testSavedConnection(old);+ await result.previewCurrentForm();+ await result.saveCurrentForm();+ await result.deletePendingConnection();+ expect(result.dialogOpen()).toBe(false);+ expect(result.deleteDialogOpen()).toBe(false);+ expect(result.form().apiKey).toBe('');+ for (const [method, mock] of Object.entries(TrueNASAPI))+ if (method !== 'listConnections') expect(mock).not.toHaveBeenCalled();+ await result.loadConnections();+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(1);+ setAllowed(true);+ await ready(result);+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(2);+ });++ it('aborts a pending inventory read and rejects its late result after revocation', async () => {+ const pending = deferred<TrueNASConnection[]>();+ vi.mocked(TrueNASAPI.listConnections).mockReturnValueOnce(pending.promise);+ const [canLoad, setAllowed] = createSignal(true);+ const { result } = renderHook(() => useTrueNASSettingsPanelState({ canLoad }));+ const options = vi.mocked(TrueNASAPI.listConnections).mock.calls[0][0]!;+ expect(options).toMatchObject({ expectedOrgID: 'team-a', retry: false });+ setAllowed(false);+ expect(options.signal?.aborted).toBe(true);+ pending.resolve([connection()]);+ await pending.promise;+ await Promise.resolve();+ expect(result.connections()).toEqual([]);+ expect(result.loading()).toBe(false);+ expect(result.loadingError()).toBeNull();+ });++ it('preserves a same-reader draft across copied status and duplicate org events', async () => {+ const [status, setStatus] = createSignal({ user: 'reader-a', allowed: true });+ const { result } = renderHook(() =>+ useTrueNASSettingsPanelState({+ canLoad: () => status().allowed,+ currentUser: () => status().user,+ }),+ );+ await ready(result);+ openDraft(result);+ setStatus({ user: 'reader-a', allowed: true });+ eventBus.emit('org_switched', 'team-a');+ expect(result.form().apiKey).toBe('synthetic-draft');+ expect(result.dialogOpen()).toBe(true);+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(1);+ });++ it('does not accept an A-to-B-to-A read or let its finally clear a later loading state', async () => {+ const a = deferred<TrueNASConnection[]>(),+ b = deferred<TrueNASConnection[]>(),+ next = deferred<TrueNASConnection[]>();+ vi.mocked(TrueNASAPI.listConnections)+ .mockReturnValueOnce(a.promise)+ .mockReturnValueOnce(b.promise)+ .mockReturnValueOnce(next.promise);+ const [currentUser, setUser] = createSignal('a');+ const { result } = renderHook(() => useTrueNASSettingsPanelState({ currentUser }));+ setUser('b');+ setUser('a');+ a.resolve([connection()]);+ b.reject(new Error('obsolete-private-detail'));+ await Promise.allSettled([a.promise, b.promise]);+ await Promise.resolve();+ expect(result.loading()).toBe(true);+ expect(result.connections()).toEqual([]);+ expect(result.loadingError()).toBeNull();+ expect(logger.error).not.toHaveBeenCalled();+ next.resolve([connection()]);+ await ready(result);+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(3);+ });++ const actions = [+ 'test',+ 'saved-test',+ 'preview',+ 'saved-preview',+ 'create',+ 'update',+ 'delete',+ ] as const;+ for (const action of actions)+ for (const outcome of ['success', 'error'] as const) {+ it(`ignores ${action} ${outcome} after an org switch, including notifications and follow-up reads`, async () => {+ const pending = deferred<never>();+ const method = {+ test: 'testConnection',+ 'saved-test': 'testSavedConnection',+ preview: 'previewConnection',+ 'saved-preview': 'previewSavedConnection',+ create: 'createConnection',+ update: 'updateConnection',+ delete: 'deleteConnection',+ }[action] as Exclude<keyof typeof TrueNASAPI, 'prototype' | 'listConnections'>;+ vi.mocked(TrueNASAPI[method]).mockReturnValueOnce(pending.promise);+ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await ready(result);+ const old = result.connections()[0];+ if (['test', 'preview', 'create'].includes(action)) {+ result.openCreateDialog();+ result.updateForm({+ host: 'nas.example.invalid',+ username: 'monitor',+ apiKey: 'synthetic-draft',+ });+ } else if (action === 'delete') result.openDeleteDialog(old);+ else if (action !== 'saved-test') openDraft(result);+ const task =+ action === 'test'+ ? result.testCurrentForm()+ : action === 'saved-test'+ ? result.testSavedConnection(old)+ : ['preview', 'saved-preview'].includes(action)+ ? result.previewCurrentForm()+ : action === 'delete'+ ? result.deletePendingConnection()+ : result.saveCurrentForm();+ expect(TrueNASAPI[method]).toHaveBeenCalledTimes(1);+ const call = vi.mocked(TrueNASAPI[method]).mock.calls[0];+ const options = call[call.length - 1] as {+ signal: AbortSignal;+ expectedOrgID: string;+ retry: boolean;+ };+ expect(options).toMatchObject({ expectedOrgID: 'team-a', retry: false });+ scope.org = 'team-b';+ eventBus.emit('org_switched', 'team-b');+ await ready(result);+ expect(options.signal.aborted).toBe(true);+ expect(result.form().apiKey).toBe('');+ expect(result.dialogOpen()).toBe(false);+ openDraft(result); // The late completion must not close/clear this new draft.+ if (outcome === 'success') pending.resolve({ success: true } as never);+ else pending.reject(new Error('obsolete-private-detail'));+ await task;+ expect(result.form().apiKey).toBe('synthetic-draft');+ expect(result.dialogOpen()).toBe(true);+ expect(result.monitoredSystemPreview()).toBeNull();+ expect(result.monitoredSystemPreviewError()).toBeNull();+ expect(notificationStore.success).not.toHaveBeenCalled();+ expect(notificationStore.error).not.toHaveBeenCalled();+ expect(logger.error).not.toHaveBeenCalled();+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(2);+ expect(+ result.saving() || result.testing() || result.previewing() || result.deleting(),+ ).toBe(false);+ await result.testSavedConnection(old);+ result.openDeleteDialog(old);+ expect(result.deleteDialogOpen()).toBe(false); // Same ID is not the newly admitted object.+ });+ }++ for (const outcome of ['success', 'error'] as const)+ it(`aborts on disposal and ignores late ${outcome}`, async () => {+ const pending = deferred<never>();+ vi.mocked(TrueNASAPI.testSavedConnection).mockReturnValueOnce(pending.promise);+ const { result, cleanup } = renderHook(() => useTrueNASSettingsPanelState());+ await ready(result);+ const task = result.testSavedConnection(result.connections()[0]);+ const options = vi.mocked(TrueNASAPI.testSavedConnection).mock.calls[0][2]!;+ cleanup();+ expect(options.signal?.aborted).toBe(true);+ if (outcome === 'success') pending.resolve({ success: true } as never);+ else pending.reject(new Error('late'));+ await task;+ eventBus.emit('org_switched', 'team-b');+ expect(notificationStore.success).not.toHaveBeenCalled();+ expect(notificationStore.error).not.toHaveBeenCalled();+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(1);+ });++ it('withdraws before a stale action when org storage changed without an event', async () => {+ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await ready(result);+ openDraft(result);+ scope.org = 'team-b';+ await result.saveCurrentForm();+ await ready(result);+ expect(TrueNASAPI.updateConnection).not.toHaveBeenCalled();+ expect(result.form().apiKey).toBe('');+ expect(vi.mocked(TrueNASAPI.listConnections).mock.calls[1][0]?.expectedOrgID).toBe('team-b');+ });++ it('ignores a preview and Test result for an edited draft, without leaving controls busy', async () => {+ const preview = deferred<never>(),+ test = deferred<never>();+ vi.mocked(TrueNASAPI.previewSavedConnection).mockReturnValueOnce(preview.promise);+ vi.mocked(TrueNASAPI.testSavedConnection).mockReturnValueOnce(test.promise);+ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await ready(result);+ openDraft(result);+ const a = result.previewCurrentForm();+ result.updateForm({ host: 'changed.example.invalid' });+ preview.resolve({ additional_count: 5 } as never);+ expect(await a).toBeNull();+ expect(result.monitoredSystemPreview()).toBeNull();+ expect(result.previewing()).toBe(false);+ const b = result.testCurrentForm();+ result.updateForm({ host: 'newer.example.invalid' });+ test.resolve({ success: true } as never);+ expect(await b).toBe(false);+ expect(result.testing()).toBe(false);+ expect(notificationStore.success).not.toHaveBeenCalled();+ });++ it('starts a single mutation and does not retarget it while busy', async () => {+ const pending = deferred<never>();+ vi.mocked(TrueNASAPI.updateConnection).mockReturnValueOnce(pending.promise);+ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await ready(result);+ openDraft(result);+ const task = result.saveCurrentForm();+ await result.saveCurrentForm();+ await result.previewCurrentForm();+ result.openCreateDialog();+ result.openDeleteDialog(result.connections()[0]);+ expect(result.dialogOpen()).toBe(true);+ expect(result.deleteDialogOpen()).toBe(false);+ expect(TrueNASAPI.updateConnection).toHaveBeenCalledTimes(1);+ expect(TrueNASAPI.previewSavedConnection).not.toHaveBeenCalled();+ pending.resolve(connection() as never);+ await task;+ expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection updated');+ expect(TrueNASAPI.listConnections).toHaveBeenCalledTimes(2);+ });++ for (const status of [401, 403])+ it(`withdraws on HTTP ${status} and requires a fresh read, not a stale confirmation`, async () => {+ vi.mocked(TrueNASAPI.updateConnection).mockRejectedValueOnce({+ status,+ message: 'private-provider-detail',+ });+ const { result } = renderHook(() => useTrueNASSettingsPanelState());+ await ready(result);+ openDraft(result);+ const old = result.connections()[0];+ await result.saveCurrentForm();+ expect(result.connections()).toEqual([]);+ expect(result.form().apiKey).toBe('');+ expect(result.loadingError()).toContain('access could not be verified');+ expect(notificationStore.error).not.toHaveBeenCalledWith('private-provider-detail');+ await result.testSavedConnection(old);+ result.openCreateDialog();+ expect(result.dialogOpen()).toBe(false);+ expect(TrueNASAPI.testSavedConnection).not.toHaveBeenCalled();+ await result.loadConnections();+ await ready(result);+ result.openCreateDialog();+ expect(result.dialogOpen()).toBe(true);+ expect(result.loadingError()).toBeNull();+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsxindex c79119377b..ad81385aa6 100644--- a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx@@ -160,6 +160,11 @@ describe('useTrueNASSettingsPanelState', () => {pollIntervalSeconds: 90,username: 'pulse-readonly',}),+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),);expect(TrueNASAPI.updateConnection).toHaveBeenCalledWith('conn-1',@@ -171,6 +176,11 @@ describe('useTrueNASSettingsPanelState', () => {password: '',fingerprint: '',}),+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),);expect(result.dialogOpen()).toBe(false);expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection updated');@@ -215,7 +225,15 @@ describe('useTrueNASSettingsPanelState', () => {await result.testSavedConnection(result.connections()[0]);- expect(TrueNASAPI.testSavedConnection).toHaveBeenCalledWith('conn-1');+ expect(TrueNASAPI.testSavedConnection).toHaveBeenCalledWith(+ 'conn-1',+ undefined,+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),+ );expect(TrueNASAPI.testConnection).not.toHaveBeenCalled();expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection successful for tower',@@ -255,6 +273,11 @@ describe('useTrueNASSettingsPanelState', () => {apiKey: '********',pollIntervalSeconds: 120,}),+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),);expect(TrueNASAPI.testConnection).not.toHaveBeenCalled();expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection successful');@@ -283,6 +306,11 @@ describe('useTrueNASSettingsPanelState', () => {host: 'tower.local',apiKey: 'secret',}),+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),);expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection added');});@@ -352,6 +380,11 @@ describe('useTrueNASSettingsPanelState', () => {host: 'tower.local',apiKey: 'secret',}),+ expect.objectContaining({+ expectedOrgID: 'default',+ retry: false,+ signal: expect.any(AbortSignal),+ }),);expect(preview?.additional_count).toBe(0);expect(result.monitoredSystemPreview()?.effect).toBe('attaches_existing');diff --git a/frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts b/frontend-modern/src/components/Settings/useInfrastructureSettingsState.tsindex d346605f0c..d0e5c21b50 100644--- a/frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts+++ b/frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts@@ -17,6 +17,7 @@ interface UseInfrastructureSettingsStateParams {// whole bootstrap (nodes, discovery, system settings, TrueNAS, VMware) on any// settings page and then keeps polling discovery.canReadInfrastructure: Accessor<boolean>;+ currentUser?: Accessor<string | undefined>;discoveryEnabled: Accessor<boolean>;setDiscoveryEnabled: Setter<boolean>;discoverySubnet: Accessor<string>;@@ -44,6 +45,7 @@ interface UseInfrastructureSettingsStateParams {export function useInfrastructureSettingsState({eventBus,canReadInfrastructure,+ currentUser,discoveryEnabled,setDiscoveryEnabled,discoverySubnet,@@ -75,7 +77,10 @@ export function useInfrastructureSettingsState({savingTemperatureSetting,setSavingTemperatureSetting,});- const trueNASSettings = useTrueNASSettingsPanelState({ canLoad: canReadInfrastructure });+ const trueNASSettings = useTrueNASSettingsPanelState({+ canLoad: canReadInfrastructure,+ currentUser,+ });const vmwareSettings = useVMwareSettingsPanelState({ canLoad: canReadInfrastructure });const discoveryRuntime = useInfrastructureDiscoveryRuntimeState({diff --git a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.tsindex 2c3cdf843a..ed6393418c 100644--- a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts+++ b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts@@ -1,4 +1,7 @@-import { createEffect, createMemo, createSignal } from 'solid-js';+import { batch, createEffect, createMemo, createSignal, on, onCleanup } from 'solid-js';+import { unwrap } from 'solid-js/store';+import { getOrgID } from '@/utils/apiClient';+import { eventBus } from '@/stores/events';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import type { MonitoredSystemLedgerPreviewResponse } from '@/api/monitoredSystemLedger';@@ -182,11 +185,17 @@ const buildConnectionInput = (form: TrueNASConnectionFormState): TrueNASConnectireturn input;};-// `canLoad` gates the mount fetch: /api/truenas/connections is RequireAdmin and+// `canLoad` gates the reader lifetime: /api/truenas/connections is RequireAdmin and// this hook is constructed for every settings tab, so a non-admin session would// otherwise 403 on any settings page. Defaults to enabled for callers (tests,// stories) that have no capability to hand it.-export function useTrueNASSettingsPanelState({ canLoad }: { canLoad?: () => boolean } = {}) {+export function useTrueNASSettingsPanelState({+ canLoad,+ currentUser,+}: {+ canLoad?: () => boolean;+ currentUser?: () => string | undefined;+} = {}) {const [connections, setConnections] = createSignal<TrueNASConnection[]>([]);const [loading, setLoading] = createSignal(true);const [loadingError, setLoadingError] = createSignal<string | null>(null);@@ -219,207 +228,349 @@ export function useTrueNASSettingsPanelState({ canLoad }: { canLoad?: () => bool() => connections().find((connection) => connection.id === editingConnectionId()) ?? null,);- const loadConnections = async () => {- setLoading(true);- setLoadingError(null);- try {- const nextConnections = await TrueNASAPI.listConnections();- setConnections(nextConnections);+ const accessAllowed = () => canLoad?.() ?? true;+ const currentOrg = () => getOrgID() || 'default';+ const snapshot = () => ({+ org: currentOrg(),+ user: currentUser?.(),+ allowed: accessAllowed(),+ controller: new AbortController(),+ });+ const [reader, setReader] = createSignal(snapshot());+ const [accessRejected, setAccessRejected] = createSignal(false);+ let disposed = false;+ let readController: AbortController | undefined;+ let dialogVersion = 0;+ const isCurrentReader = (accepted = reader()) =>+ !disposed &&+ accepted === reader() &&+ !accepted.controller.signal.aborted &&+ accepted.org === currentOrg() &&+ accepted.user === currentUser?.() &&+ accepted.allowed === accessAllowed();+ const requestOptions = (accepted = reader(), signal = accepted.controller.signal) => ({+ expectedOrgID: accepted.org,+ signal,+ retry: false,+ });+ const busy = () => saving() || testing() || deleting() || previewing();+ const isCurrentConnection = (connection: TrueNASConnection) =>+ connections().some((current) => unwrap(current) === unwrap(connection));++ const clearPreview = () => {+ setMonitoredSystemPreview(null);+ setMonitoredSystemPreviewUnavailableState(null);+ setMonitoredSystemPreviewGenericError(null);+ };+ const resetDialogState = () => {+ dialogVersion += 1;+ setDialogOpen(false);+ setEditingConnectionId(null);+ setForm(createEmptyFormState());+ clearPreview();+ };+ const resetDeleteDialogState = () => {+ setDeleteDialogOpen(false);+ setPendingDeleteConnection(null);+ };+ const resetReader = (reload = true) => {+ reader().controller.abort();+ readController?.abort();+ readController = undefined;+ batch(() => {+ // Object identity prevents a late completion being accepted on A -> B -> A.+ setReader(snapshot());+ resetDialogState();+ resetDeleteDialogState();+ setConnections([]);+ setLoadingError(null);setFeatureDisabled(false);setFeatureDisabledMessage('');+ setAccessRejected(false);+ setSaving(false);+ setTesting(false);+ setDeleting(false);+ setPreviewing(false);+ setLoading(false);+ });+ if (!disposed && reload) void loadConnections();+ };+ const ensureReader = () => {+ if (isCurrentReader()) return true;+ // A storage change without an org event also withdraws before any action.+ if (!disposed) resetReader();+ return false;+ };+ const canAct = () =>+ ensureReader() && accessAllowed() && !accessRejected() && !featureDisabled() && !busy();+ const withdrawOnDenial = (error: unknown) => {+ if (![401, 403].includes(apiErrorStatus(error) ?? 0)) return false;+ resetReader(false);+ setAccessRejected(true);+ setLoadingError('TrueNAS settings access could not be verified. Reload before making changes.');+ return true;+ };++ const loadConnections = async () => {+ if (!ensureReader() || !accessAllowed() || readController || busy()) return;+ const accepted = reader();+ const controller = new AbortController();+ readController = controller;+ const isCurrent = () => isCurrentReader(accepted) && readController === controller;+ batch(() => {+ setLoading(true);+ setLoadingError(null);+ });+ try {+ const nextConnections = await TrueNASAPI.listConnections(+ requestOptions(accepted, controller.signal),+ );+ if (!isCurrent()) return;+ batch(() => {+ setConnections(nextConnections);+ setAccessRejected(false);+ setFeatureDisabled(false);+ setFeatureDisabledMessage('');+ });} catch (error) {+ if (!isCurrent()) return;+ if (withdrawOnDenial(error)) return;+ setConnections([]);if (apiErrorStatus(error) === 404) {setFeatureDisabled(true);setFeatureDisabledMessage(getErrorMessage(error, 'TrueNAS integration has been explicitly disabled'),);- setConnections([]);return;}- const message = getErrorMessage(error, 'Failed to load TrueNAS connections');- setLoadingError(message);+ setLoadingError(getErrorMessage(error, 'Failed to load TrueNAS connections'));logger.error('[TrueNAS Settings] Failed to load connections', error);} finally {- setLoading(false);+ if (isCurrent()) {+ readController = undefined;+ setLoading(false);+ }}};- // The capability resolves asynchronously (Settings awaits /api/security/status- // after mount), so this waits for it rather than reading it once at mount —- // an onMount check would see `false` for admins too and never load.- let connectionsRequested = false;- createEffect(() => {- if (connectionsRequested) return;- if (canLoad && !canLoad()) {- setLoading(false);- return;- }- connectionsRequested = true;- void loadConnections();+ createEffect(+ on([accessAllowed, () => currentUser?.()], (current, previous) => {+ // Copied security status objects must not erase a same-reader draft.+ if (!previous || current.some((value, index) => value !== previous[index])) resetReader();+ }),+ );+ const unsubscribeOrg = eventBus.on('org_switched', () => {+ if (!isCurrentReader()) resetReader();+ });+ onCleanup(() => {+ disposed = true;+ unsubscribeOrg();+ resetReader(false);});const openCreateDialog = () => {- setEditingConnectionId(null);- setForm(createEmptyFormState());- setMonitoredSystemPreview(null);- setMonitoredSystemPreviewUnavailableState(null);- setMonitoredSystemPreviewGenericError(null);- setDialogOpen(true);+ if (!canAct()) return;+ batch(() => {+ resetDialogState();+ resetDeleteDialogState();+ setDialogOpen(true);+ });};-const openEditDialog = (connection: TrueNASConnection) => {- setEditingConnectionId(connection.id);- setForm(buildFormStateFromConnection(connection));- setMonitoredSystemPreview(null);- setMonitoredSystemPreviewUnavailableState(null);- setMonitoredSystemPreviewGenericError(null);- setDialogOpen(true);- };-- const resetDialogState = () => {- setDialogOpen(false);- setEditingConnectionId(null);- setForm(createEmptyFormState());- setMonitoredSystemPreview(null);- setMonitoredSystemPreviewUnavailableState(null);- setMonitoredSystemPreviewGenericError(null);+ if (!canAct() || !isCurrentConnection(connection)) return;+ batch(() => {+ resetDialogState();+ resetDeleteDialogState();+ setEditingConnectionId(connection.id);+ setForm(buildFormStateFromConnection(connection));+ setDialogOpen(true);+ });};-const closeDialog = () => {if (saving() || testing()) return;- resetDialogState();+ batch(resetDialogState);};-const openDeleteDialog = (connection: TrueNASConnection) => {- setPendingDeleteConnection(connection);- setDeleteDialogOpen(true);- };-- const resetDeleteDialogState = () => {- setDeleteDialogOpen(false);- setPendingDeleteConnection(null);+ if (!canAct() || !isCurrentConnection(connection)) return;+ batch(() => {+ resetDialogState();+ setPendingDeleteConnection(connection);+ setDeleteDialogOpen(true);+ });};-const closeDeleteDialog = () => {- if (deleting()) return;- resetDeleteDialogState();+ if (!deleting()) resetDeleteDialogState();};-const updateForm = (patch: Partial<TrueNASConnectionFormState>) => {- setMonitoredSystemPreview(null);- setMonitoredSystemPreviewUnavailableState(null);- setMonitoredSystemPreviewGenericError(null);- setForm((current) => ({ ...current, ...patch }));+ if (!ensureReader() || !accessAllowed() || accessRejected() || !dialogOpen() || saving())+ return;+ dialogVersion += 1;+ batch(() => {+ clearPreview();+ setForm((current) => ({ ...current, ...patch }));+ });+ };+ const handleActionError = (error: unknown, fallback: string, log: string) => {+ if (withdrawOnDenial(error)) {+ notificationStore.error(loadingError()!);+ return;+ }+ notificationStore.error(getTrueNASErrorMessage(error, fallback));+ logger.error(log, error);};const testCurrentForm = async () => {+ if (!canAct() || !dialogOpen()) return false;+ const accepted = reader();+ const version = dialogVersion;+ const isCurrent = () => isCurrentReader(accepted) && version === dialogVersion;setTesting(true);try {const payload = buildConnectionInput(form());if (editingConnectionId()) {- await TrueNASAPI.testSavedConnection(editingConnectionId()!, payload);+ await TrueNASAPI.testSavedConnection(+ editingConnectionId()!,+ payload,+ requestOptions(accepted),+ );} else {- await TrueNASAPI.testConnection(payload);+ await TrueNASAPI.testConnection(payload, requestOptions(accepted));}+ if (!isCurrent()) return false;notificationStore.success('TrueNAS connection successful');return true;} catch (error) {- const message = getTrueNASErrorMessage(error, 'TrueNAS connection failed');- notificationStore.error(message);- logger.error('[TrueNAS Settings] Connection test failed', error);+ if (isCurrent())+ handleActionError(+ error,+ 'TrueNAS connection failed',+ '[TrueNAS Settings] Connection test failed',+ );return false;} finally {- setTesting(false);+ if (isCurrentReader(accepted)) setTesting(false);}};const testSavedConnection = async (connection: TrueNASConnection) => {+ if (!canAct() || !isCurrentConnection(connection)) return;+ const accepted = reader();setTesting(true);try {- await TrueNASAPI.testSavedConnection(connection.id);+ await TrueNASAPI.testSavedConnection(connection.id, undefined, requestOptions(accepted));+ if (!isCurrentReader(accepted)) return;notificationStore.success(`TrueNAS connection successful for ${connection.name || connection.host}`,);} catch (error) {- const message = getTrueNASErrorMessage(error, 'TrueNAS connection failed');- notificationStore.error(message);- logger.error('[TrueNAS Settings] Saved connection test failed', error);+ if (isCurrentReader(accepted))+ handleActionError(+ error,+ 'TrueNAS connection failed',+ '[TrueNAS Settings] Saved connection test failed',+ );} finally {- setTesting(false);- await loadConnections();+ if (isCurrentReader(accepted)) {+ setTesting(false);+ await loadConnections();+ }}};const previewCurrentForm = async () => {- setPreviewing(true);- setMonitoredSystemPreviewUnavailableState(null);- setMonitoredSystemPreviewGenericError(null);+ if (!canAct() || !dialogOpen()) return null;+ const accepted = reader();+ const version = dialogVersion;+ const isCurrent = () => isCurrentReader(accepted) && version === dialogVersion;+ batch(() => {+ setPreviewing(true);+ clearPreview();+ });try {const payload = buildConnectionInput(form());const preview = editingConnectionId()- ? await TrueNASAPI.previewSavedConnection(editingConnectionId()!, payload)- : await TrueNASAPI.previewConnection(payload);+ ? await TrueNASAPI.previewSavedConnection(+ editingConnectionId()!,+ payload,+ requestOptions(accepted),+ )+ : await TrueNASAPI.previewConnection(payload, requestOptions(accepted));+ if (!isCurrent()) return null;setMonitoredSystemPreview(preview);- setMonitoredSystemPreviewUnavailableState(null);- setMonitoredSystemPreviewGenericError(null);return preview;} catch (error) {+ if (!isCurrent()) return null;+ if (withdrawOnDenial(error)) return null;const unavailableState = monitoredSystemImpactPreviewUnavailableStateFromError(error);- setMonitoredSystemPreview(null);- if (unavailableState) {- setMonitoredSystemPreviewUnavailableState(unavailableState);- setMonitoredSystemPreviewGenericError(null);- } else {- setMonitoredSystemPreviewUnavailableState(null);+ if (unavailableState) setMonitoredSystemPreviewUnavailableState(unavailableState);+ elsesetMonitoredSystemPreviewGenericError(getTrueNASErrorMessage(error, 'Could not preview monitored-system impact'),);- }logger.error('[TrueNAS Settings] Preview failed', error);return null;} finally {- setPreviewing(false);+ if (isCurrentReader(accepted)) setPreviewing(false);}};const saveCurrentForm = async () => {+ if (!canAct() || !dialogOpen()) return;+ const accepted = reader();setSaving(true);try {const payload = buildConnectionInput(form());if (editingConnectionId()) {- await TrueNASAPI.updateConnection(editingConnectionId()!, payload);- notificationStore.success('TrueNAS connection updated');+ await TrueNASAPI.updateConnection(+ editingConnectionId()!,+ payload,+ requestOptions(accepted),+ );} else {- await TrueNASAPI.createConnection(payload);- notificationStore.success('TrueNAS connection added');+ await TrueNASAPI.createConnection(payload, requestOptions(accepted));}- resetDialogState();+ if (!isCurrentReader(accepted)) return;+ notificationStore.success(+ editingConnectionId() ? 'TrueNAS connection updated' : 'TrueNAS connection added',+ );+ batch(resetDialogState);+ setSaving(false);await loadConnections();} catch (error) {+ if (!isCurrentReader(accepted)) return;setMonitoredSystemPreviewUnavailableState(null);- const message = getErrorMessage(error, 'Failed to save TrueNAS connection');- notificationStore.error(message);- logger.error('[TrueNAS Settings] Save failed', error);+ handleActionError(+ error,+ 'Failed to save TrueNAS connection',+ '[TrueNAS Settings] Save failed',+ );} finally {- setSaving(false);+ if (isCurrentReader(accepted)) setSaving(false);}};const deletePendingConnection = async () => {+ if (!canAct()) return;const connection = pendingDeleteConnection();- if (!connection) return;+ if (!connection || !isCurrentConnection(connection)) return;+ const accepted = reader();setDeleting(true);try {- await TrueNASAPI.deleteConnection(connection.id);+ await TrueNASAPI.deleteConnection(connection.id, requestOptions(accepted));+ if (!isCurrentReader(accepted)) return;notificationStore.success(`Removed ${connection.name || connection.host}`);resetDeleteDialogState();+ setDeleting(false);await loadConnections();} catch (error) {- const message = getErrorMessage(error, 'Failed to remove TrueNAS connection');- notificationStore.error(message);- logger.error('[TrueNAS Settings] Delete failed', error);+ if (isCurrentReader(accepted))+ handleActionError(+ error,+ 'Failed to remove TrueNAS connection',+ '[TrueNAS Settings] Delete failed',+ );} finally {- setDeleting(false);+ if (isCurrentReader(accepted)) setDeleting(false);}};