Keep the selected organization when workspace choices cannot be read (#4630)

**Keep the selected organization when workspace choices cannot be read**

Distinguish an unavailable list from an empty one and offer a read-only
retry without replacing the current organization. Admit only identities
returned by a complete list. Rebind the live stream and retire its old
snapshot on a real organization change even when the socket URL stays
the same.

Contract-Neutral: Implements the existing authorized workspace-list and
scoped-switch behavior in the shell; no API schema, authentication,
access policy or cookie contract changes.

**Type the workspace admission test transport**

Give the scoped mock a callable signature while unrelated reads keep
their original fixture.

**Verify workspace list recovery and stream switching in browsers**

Record source-bound desktop Chromium and narrow WebKit proof of outage,
empty and malformed choices, Retry, and a real organization switch on
the existing Machines route.

**Load the destination alert policy on workspace switches**

A first successful socket in a different workspace is not a reconnect.
Refresh the policy after either selection path resets the old scope, and
retire slow reads so they cannot replace the destination or silently
retarget. Keep alert rows in the canonical socket/REST store.

Contract-Neutral: Restores the selected workspace's existing read-only
alert policy and canonical alert projection. Alert settings,
authorisation, socket protocol, delivery and mutation contracts are
unchanged.

**Verify workspace alert policy in desktop and narrow browsers**

Compare deliberate and list-driven switches at matching anchors, with
one destination handshake and the outgoing alert-policy read still
pending. Record only content that was compiled and examined.

**Keep alert delivery confirmations with their workspace**

Retire reads and writes independently when the workspace changes. Scope
explicit delivery mutations without replay, and report results only to
their originating Alerts page lifetime.

Contract-Neutral: Restores client-side ownership of existing alert
policy confirmations. The settings and API schemas, in-workspace policy
and server authorization and delivery contracts are unchanged.

**Verify alert confirmations across workspace switches**

Record the exact browser-verified files and matched desktop and
narrow-view results.

---
Fleet candidate `20261118T184632Z-web-product` from the `web-product`
lane. Reviewed tip `bdf902b20986ce81b6c8d47ffa382e62024a1175` on `main`.

[How Pulse handles
triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
pulse-triage[bot]
2026-11-18 19:49:55 +00:00
committed by GitHub
19 changed files with 1116 additions and 338 deletions

View File

@@ -0,0 +1,46 @@
{
"version": 1,
"base_sha": "b9f76d6e3dcfc578744037919039bc28cdf6a6e2",
"verified_at": "2026-11-18T17:07:53Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/App.tsx",
"frontend-modern/src/AppLayout.tsx",
"frontend-modern/src/components/OrgSwitcher.tsx",
"frontend-modern/src/stores/websocket.ts",
"frontend-modern/src/useAppRuntimeState.ts"
],
"content_sha256": {
"frontend-modern/src/App.tsx": "8b2622b955701174e45843a8f503651521f8ba5a17c94934e276ad6b9fc03a7f",
"frontend-modern/src/AppLayout.tsx": "f82c4319f219c3cda93bd9d65a420227975804cf3927331ff266d9d46b3cca67",
"frontend-modern/src/components/OrgSwitcher.tsx": "038755c05a1fb90a11db35f0aa2b2d35e3dfb33a8e4e02702cd2521f2de0426e",
"frontend-modern/src/stores/websocket.ts": "4374180fd286a0d0ccbba210b883c859949e64fffa9b7e8ad113c58dd10e4a5d",
"frontend-modern/src/useAppRuntimeState.ts": "ccd67865c70fda885f186f03ec33bd17bd67225aeb9d597a18c5df176f349968"
},
"routes": [
"/standalone/machines"
],
"viewports": [
{
"width": 1365,
"height": 900
},
{
"width": 390,
"height": 844
}
],
"states": [
"Compiled application shell and Machines route against synthetic loopback HTTP and WebSocket fixtures. Playwright 1.56.1: Chromium 141.0.7390.37 at 1365×900/light and WebKit 26.0 at 390×844/dark.",
"Saved west with a 503: parent invents Default and renders its host; candidate says list unavailable, identifies client-west, keeps its host and provides Retry.",
"No saved selection: a successful empty list reads No organizations listed; malformed 200 reads Organization list unavailable. Neither persists a fabricated organization; the fixture serves its unchanged default routing for unbound sessions.",
"Checking and returned states preserve the selected workspace, controls and monitoring. Healthy focused West chooser is unchanged at both viewports.",
"For a deliberate East switch, matched delayed-data pairs retain the existing confirmation and dismissal. At the matched post-release observation the candidate renders East-only host without the West row; the parent remains empty under the East label. The candidate can still show the existing empty placeholder while the fixture withholds data.",
"Twenty completed journeys; 32 original frames were inspected (14 before/after pairs plus four candidate-only Retry frames). The first East switch pair includes different toast timing; the two controlled pairs at each width supply matched confirmation and post-release comparisons."
],
"interactions": [
"Activated Retry with Enter, verified pending state prevents duplicate submits, and Tab reached the restored selector without a route reload or new West socket. A read after an unbound empty result uses the first authorized listed workspace returned by the fixture.",
"Selected client-east from the existing chooser with the same list. A new /ws handshake carries the East cookie and West telemetry is absent; the parent keeps only the original West connection. The supplemental run holds matching East REST/live data, captures the confirmation, dismisses it in both builds and releases data at the same checkpoint.",
"Both captures retain existing shell navigation and monitoring controls at their respective widths. No external requests or fixture writes, no assertion about real account grants, original estates or cross-tab behavior."
]
}

View File

@@ -0,0 +1,42 @@
{
"version": 1,
"base_sha": "ea12b6b817eb1d9fc5c928089114a133b98daa43",
"verified_at": "2026-11-18T18:29:39Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/api/alerts.ts",
"frontend-modern/src/features/alerts/useAlertDeliveryPausedReason.ts",
"frontend-modern/src/pages/Alerts.tsx",
"frontend-modern/src/stores/alertsActivation.ts"
],
"content_sha256": {
"frontend-modern/src/api/alerts.ts": "7f5315813f2f960ec0c3fdf39efafd8db150a1391590687b66dd1634b329f268",
"frontend-modern/src/features/alerts/useAlertDeliveryPausedReason.ts": "9d8de8e59a31cf31d094b1624274e7adc043a78453960d09f6c8f6cf75a06082",
"frontend-modern/src/pages/Alerts.tsx": "d8521818bd3063e3d17f619aca2081e01a24d2119e765acd86bb172dea43b188",
"frontend-modern/src/stores/alertsActivation.ts": "f3fa29ced652398a23b330f542ff50bcafa31c3b1a237c132da6e619895d0cd3"
},
"routes": [
"/alerts"
],
"viewports": [
{
"width": 1365,
"height": 900
},
{
"width": 390,
"height": 844
}
],
"states": [
"Compiled Alerts Overview and identical synthetic loopback API/WebSocket state on both sides. Playwright 1.56.1, desktop Chromium 141.0.7390.37 light and narrow WebKit 26.0 dark. Twenty native-inspected captures in ten matched pairs, with matching theme, width, scroll and chooser focus.",
"Retry replaces West with East while West's notification-off PUT is in flight. East detection is paused and the settled switch belongs to East. On the baseline the late West success changes paused alerting to a green No active alerts and shows a West success toast. The fix preserves East's paused state without stale feedback.",
"Deliberate selection loads East's on switch and East-only warning. A buffered West response then arrives after the replacement has settled, even though its signal was aborted. The fix keeps East's enabled switch, current warning and usable controls; the baseline turns delivery off in its presentation and posts a stale toast.",
"A buffered West activation from Turn on delivery cannot start an extra East policy GET or busy its switch. East's real paused banner, active warning and queue warning remain visible in both comparisons."
],
"interactions": [
"Switch Send notifications off by keyboard with West selected. Retry a 503 list with Enter, then Tab to the restored chooser, or deliberately choose East. Wait for the destination socket and policy. Release West's held success afterwards; exercise native interruption via Retry and queued response body via explicit selection.",
"Click Turn on delivery in West and hold the already received fixture response at the body delivery boundary. Choose East and load its policy. Release the old success; verify the candidate has no extra GET, toast, policy change or replay.",
"In an unbound session, the same switch still sends exactly one PUT without a fabricated organization header, and its own confirmation remains visible. All writes in this proof are synthetic; this is not server rollback or notification delivery verification."
]
}

View File

@@ -0,0 +1,40 @@
{
"version": 1,
"base_sha": "e5a1b33e83585caf0f27274060c6246acad24b7c",
"verified_at": "2026-11-18T17:49:33Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/pages/Alerts.tsx",
"frontend-modern/src/stores/alertsActivation.ts",
"frontend-modern/src/useAppRuntimeState.ts"
],
"content_sha256": {
"frontend-modern/src/pages/Alerts.tsx": "2a6d9d3d97cb03ae63f81bdb09743edd2421fd62e03b3b422a073a27d370319b",
"frontend-modern/src/stores/alertsActivation.ts": "4b6ed8f0b0462ddd07e225852a301838e3f6cfe95e6a0c3bef3a95ff428d78ea",
"frontend-modern/src/useAppRuntimeState.ts": "2f6420c6805fdb5a7d93ebfa0b423e64718b4e617317ecdc96b190e815d78cb6"
},
"routes": [
"/alerts"
],
"viewports": [
{
"width": 1365,
"height": 900
},
{
"width": 390,
"height": 844
}
],
"states": [
"Playwright 1.56.1; compiled Alerts Overview against identical, synthetic loopback API and WebSocket fixtures. Chromium 141.0.7390.37 desktop light; WebKit 26.0 narrow dark. 24 native-inspected captures in 12 pairs with matched viewport, theme, focus and scroll.",
"Explicitly select East with an already-open West session. East's first socket shows its existing alert in both builds; the repaired build also enables the Send notifications switch after East's policy read completes.",
"A 503 retains West, its alert and notification setting. A read-only retry returns East as the replacement. After the same policy release checkpoint the repaired build explains paused detection instead of the predecessor's green No active alerts state; the West alert is absent in both.",
"While East's policy is held, both keep live East alert rows when present. The repaired switch is disabled while reading; empty active-alert projection still uses the existing empty state until config returns. The fixture's separate unavailable delivery-queue status stays visible."
],
"interactions": [
"Force a genuine transient close in West; the successful West reconnect starts a delayed GET. Switch from the organization chooser or by Enter on Retry with a new valid membership list. Tab reaches the restored chooser. The destination uses one successful first handshake, not a reconnect.",
"Release East config, then complete the old West reply. Before: the editor reads East but cannot settle the global switch. After: a destination-bound shell read settles detection and notification configuration; West's fetch is aborted. No stale West rows, credential changes, or writes (fixture API observed only GET).",
"Empty and malformed list responses retain the unbound session without a Default header on the shell config read. Retrying restores the listed chooser and selected workspace. No real delivery, account grants, or cross-tab acceptance is claimed."
]
}

View File

@@ -548,6 +548,8 @@ function App() {
organizations={runtime.organizations}
activeOrgID={runtime.activeOrgID}
orgsLoading={runtime.orgsLoading}
organizationListIssue={runtime.organizationListIssue}
onRetryOrganizationList={runtime.retryOrganizationList}
showOrgSwitcher={runtime.showOrgSwitcher}
onSwitchOrg={runtime.handleOrgSwitch}
>

View File

@@ -65,7 +65,7 @@ import { patrolAttentionStore } from '@/stores/patrolAttention';
import { isPro } from '@/stores/licenseCommercial';
import { runtimeBranding } from '@/stores/systemSettings';
import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentationPolicy';
import type { AppConnectionStatus } from '@/useAppRuntimeState';
import type { AppConnectionStatus, OrganizationListIssue } from '@/useAppRuntimeState';
import { buildInfrastructureWorkspacePath } from '@/components/Settings/infrastructureWorkspaceModel';
import {
InfrastructureMapEdgeTab,
@@ -156,6 +156,8 @@ export interface AppLayoutProps {
organizations: () => Organization[];
activeOrgID: () => string;
orgsLoading: () => boolean;
organizationListIssue: () => OrganizationListIssue | null;
onRetryOrganizationList: () => void;
showOrgSwitcher: () => boolean;
onSwitchOrg: (orgID: string) => void;
children?: JSX.Element;
@@ -787,6 +789,8 @@ export function AppLayout(props: AppLayoutProps) {
orgs={props.organizations()}
selectedOrgId={props.activeOrgID()}
loading={props.orgsLoading()}
listIssue={props.organizationListIssue()}
onRetry={props.onRetryOrganizationList}
onChange={props.onSwitchOrg}
/>
</Show>

View File

@@ -125,6 +125,8 @@ const renderLayout = (
organizations={() => []}
activeOrgID={() => 'default'}
orgsLoading={() => false}
organizationListIssue={() => null}
onRetryOrganizationList={() => {}}
showOrgSwitcher={() => false}
onSwitchOrg={() => {}}
>

View File

@@ -68,16 +68,18 @@ describe('useAppRuntimeState', () => {
let setOrgIDMock: ReturnType<typeof vi.fn>;
let clearAuthMock: ReturnType<typeof vi.fn>;
let shutdownGlobalWebSocketStoreMock: ReturnType<typeof vi.fn>;
let switchSocketMock: ReturnType<typeof vi.fn>;
let showToastMock: ReturnType<typeof vi.fn>;
let aiAvailabilitySetEnabledMock: ReturnType<typeof vi.fn>;
let aiAvailabilityRefreshMock: ReturnType<typeof vi.fn>;
let aiAvailabilityClearMock: ReturnType<typeof vi.fn>;
let refreshAlertConfigMock: ReturnType<typeof vi.fn>;
let getSystemSettingsMock: ReturnType<typeof vi.fn>;
let getRuntimeDisplayMock: ReturnType<typeof vi.fn>;
let applyServerModeMock: ReturnType<typeof vi.fn>;
let updateRuntimeDisplayFromResponseMock: ReturnType<typeof vi.fn>;
let markSystemSettingsLoadedWithDefaultsMock: ReturnType<typeof vi.fn>;
let apiFetchJSONMock: ReturnType<typeof vi.fn>;
let apiFetchJSONMock: ReturnType<typeof vi.fn<(url: string) => Promise<unknown>>>;
let websocketState: State;
let websocketConnected: boolean;
let websocketReconnecting: boolean;
@@ -151,10 +153,12 @@ describe('useAppRuntimeState', () => {
window.localStorage.removeItem('org_id');
});
shutdownGlobalWebSocketStoreMock = vi.fn();
switchSocketMock = vi.fn();
showToastMock = vi.fn();
aiAvailabilitySetEnabledMock = vi.fn();
aiAvailabilityRefreshMock = vi.fn().mockResolvedValue(undefined);
aiAvailabilityClearMock = vi.fn();
refreshAlertConfigMock = vi.fn().mockResolvedValue(undefined);
getSystemSettingsMock = vi.fn().mockResolvedValue({ theme: '' });
getRuntimeDisplayMock = vi.fn().mockResolvedValue({ theme: '', fullWidthMode: false });
applyServerModeMock = vi.fn();
@@ -176,7 +180,7 @@ describe('useAppRuntimeState', () => {
initialDataReceived: () => websocketInitialDataReceived,
resourceSnapshotReceived: () => websocketInitialDataReceived,
reconnect: vi.fn(),
switchUrl: vi.fn(),
switchUrl: switchSocketMock,
};
onStoreAcquired?.();
return store;
@@ -252,8 +256,7 @@ describe('useAppRuntimeState', () => {
vi.doMock('@/stores/alertsActivation', () => ({
useAlertsActivation: () => ({
refreshConfig: vi.fn().mockResolvedValue(undefined),
refreshActiveAlerts: vi.fn().mockResolvedValue(undefined),
refreshConfig: refreshAlertConfigMock,
}),
}));
@@ -621,9 +624,11 @@ describe('useAppRuntimeState', () => {
const { hookState, dispose } = mountHook();
await waitFor(() => {
expect(setOrgIDMock).toHaveBeenCalledWith('t-client');
expect(hookState.organizationListIssue()).toBe('unavailable');
});
expect(setOrgIDMock).not.toHaveBeenCalled();
expect(hookState.activeOrgID()).toBe('t-client');
expect(hookState.organizations()).toEqual([]);
expect(showToastMock).not.toHaveBeenCalledWith(
'error',
'Failed to load organizations. Using default.',
@@ -640,6 +645,7 @@ describe('useAppRuntimeState', () => {
await waitFor(() => expect(orgsListMock).toHaveBeenCalledOnce());
await waitFor(() => expect(first.hookState.orgsLoading()).toBe(false));
expect(setOrgIDMock).not.toHaveBeenCalled();
expect(first.hookState.activeOrgID()).toBe('');
first.dispose();
// The next load reads the list again and lands in the client workspace.
@@ -653,6 +659,194 @@ describe('useAppRuntimeState', () => {
second.dispose();
});
it.each([
{ list: [], issue: 'empty' },
{ list: null, issue: 'unavailable' },
{ list: [{ id: 'acme' }], issue: 'unavailable' },
{ list: [{ id: '..', displayName: 'Broken identity' }], issue: 'unavailable' },
{
list: [
{ id: 'acme', displayName: 'One' },
{ id: 'acme', displayName: 'Two' },
],
issue: 'unavailable',
},
])(
'keeps a selected workspace when choices settle as $issue ($list)',
async ({ list, issue }) => {
isMultiTenantEnabledMock.mockReturnValue(true);
getOrgIDMock.mockReturnValue('acme');
orgsListMock.mockResolvedValue(list);
const acquired = vi.fn(() => expect(setOrgIDMock).not.toHaveBeenCalled());
onStoreAcquired = acquired;
const { hookState, dispose } = mountHook();
await waitFor(() => expect(hookState.isLoading()).toBe(false));
expect(hookState.activeOrgID()).toBe('acme');
expect(hookState.organizationListIssue()).toBe(issue);
expect(hookState.organizations()).toEqual([]);
expect(acquired).toHaveBeenCalledOnce();
hookState.handleOrgSwitch('default');
expect(setOrgIDMock).not.toHaveBeenCalled();
expect(switchSocketMock).not.toHaveBeenCalled();
expect(clearAuthMock).not.toHaveBeenCalled();
dispose();
},
);
it('preserves the unbound bootstrap recovery if the next list read fails', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
orgsListMock.mockRejectedValue(new Error('503'));
const originalFetch = apiFetchMock.getMockImplementation()!;
apiFetchMock.mockImplementation((url, options) => {
if (url === '/api/state/summary') getOrgIDMock.mockReturnValue(null);
return originalFetch(url, options);
});
const { hookState, dispose } = mountHook();
await waitFor(() => expect(hookState.isLoading()).toBe(false));
expect(hookState.activeOrgID()).toBe('');
expect(hookState.organizationListIssue()).toBe('unavailable');
expect(setOrgIDMock).not.toHaveBeenCalled();
dispose();
});
it('refreshes unavailable choices without reopening the current monitoring stream', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
getOrgIDMock.mockReturnValue('acme');
orgsListMock.mockRejectedValueOnce(new Error('503'));
const { hookState, dispose } = mountHook();
await waitFor(() => expect(hookState.isLoading()).toBe(false));
const originalAdmission = hookState.platformAdmission();
expect(originalAdmission).not.toBeNull();
expect(hookState.organizationListIssue()).toBe('unavailable');
expect(setOrgIDMock).not.toHaveBeenCalled();
let finish!: (value: unknown) => void;
orgsListMock.mockImplementationOnce(() => new Promise((resolve) => (finish = resolve)));
hookState.retryOrganizationList();
hookState.retryOrganizationList();
expect(hookState.orgsLoading()).toBe(true);
expect(hookState.platformAdmission()).toBe(originalAdmission);
expect(hookState.organizationListIssue()).toBe('unavailable');
expect(orgsListMock).toHaveBeenCalledTimes(2);
finish([
{ id: 'default', displayName: 'Default' },
{ id: 'acme', displayName: 'Acme' },
]);
await waitFor(() => expect(hookState.organizationListIssue()).toBeNull());
expect(hookState.orgsLoading()).toBe(false);
expect(hookState.activeOrgID()).toBe('acme');
expect(setOrgIDMock).toHaveBeenCalledExactlyOnceWith('acme');
expect(switchSocketMock).not.toHaveBeenCalled();
expect(refreshAlertConfigMock).toHaveBeenCalledOnce();
expect(hookState.platformAdmission()).toBe(originalAdmission);
dispose();
});
it('withdraws old choices on a failed live refresh without changing the selected reader', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
getOrgIDMock.mockReturnValue('acme');
orgsListMock.mockResolvedValue([
{ id: 'acme', displayName: 'Acme' },
{ id: 'other', displayName: 'Other' },
]);
const { eventBus } = await import('@/stores/events');
const { hookState, dispose } = mountHook();
await waitFor(() => expect(hookState.isLoading()).toBe(false));
const originalAdmission = hookState.platformAdmission();
const changed = (eventBus.on as ReturnType<typeof vi.fn>).mock.calls.find(
([event]) => event === 'organizations_changed',
)![1] as () => void;
setOrgIDMock.mockClear();
orgsListMock.mockRejectedValueOnce(new Error('503'));
changed();
hookState.handleOrgSwitch('other');
await waitFor(() => expect(hookState.organizationListIssue()).toBe('unavailable'));
expect(hookState.organizations()).toEqual([]);
expect(hookState.activeOrgID()).toBe('acme');
expect(hookState.platformAdmission()).toBe(originalAdmission);
hookState.handleOrgSwitch('other');
expect(setOrgIDMock).not.toHaveBeenCalled();
expect(switchSocketMock).not.toHaveBeenCalled();
expect(eventBus.emit).not.toHaveBeenCalledWith('org_switched', expect.any(String));
dispose();
});
it('ignores an older organization refresh and rebinds only to the latest valid list', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
getOrgIDMock.mockReturnValue('acme');
const { eventBus } = await import('@/stores/events');
const { hookState, dispose } = mountHook();
await waitFor(() => expect(hookState.isLoading()).toBe(false));
const changed = (eventBus.on as ReturnType<typeof vi.fn>).mock.calls.find(
([event]) => event === 'organizations_changed',
)![1] as () => void;
let first!: (value: unknown) => void;
orgsListMock.mockImplementationOnce(() => new Promise((resolve) => (first = resolve)));
changed();
expect(hookState.orgsLoading()).toBe(true);
orgsListMock.mockResolvedValueOnce([{ id: 'north', displayName: 'North' }]);
changed();
await waitFor(() => expect(hookState.activeOrgID()).toBe('north'));
expect(setOrgIDMock).toHaveBeenLastCalledWith('north');
expect(switchSocketMock).toHaveBeenCalledExactlyOnceWith(expect.any(String), {
organizationChanged: true,
});
expect(eventBus.emit).toHaveBeenCalledWith('org_switched', 'north');
first([{ id: 'default', displayName: 'Default' }]);
await flushAsync();
expect(hookState.organizations()).toEqual([{ id: 'north', displayName: 'North' }]);
expect(hookState.activeOrgID()).toBe('north');
expect(hookState.organizationListIssue()).toBeNull();
expect(hookState.orgsLoading()).toBe(false);
expect(switchSocketMock).toHaveBeenCalledTimes(1);
expect(refreshAlertConfigMock).toHaveBeenCalledTimes(2);
dispose();
});
it.each(['choice', 'membership'] as const)(
'reloads the alert policy after a %s switch without waiting for a reconnect',
async (reason) => {
isMultiTenantEnabledMock.mockReturnValue(true);
let selected = 'acme';
getOrgIDMock.mockImplementation(() => selected);
setOrgIDMock.mockImplementation((org: string) => (selected = org));
const acme = { id: 'acme', displayName: 'Acme' };
const other = { id: 'other', displayName: 'Other' };
orgsListMock.mockResolvedValue([acme, other]);
const boundary: string[] = [];
const { eventBus } = await import('@/stores/events');
vi.mocked(eventBus.emit).mockImplementation((event) => {
if (event === 'org_switched') boundary.push(`retire:${selected}`);
});
refreshAlertConfigMock.mockImplementation(async () => {
boundary.push(`read:${selected}`);
});
const { hookState, dispose } = mountHook();
await waitFor(() => expect(hookState.isLoading()).toBe(false));
expect(boundary).toEqual(['read:acme']);
if (reason === 'choice') {
hookState.handleOrgSwitch(other.id);
} else {
orgsListMock.mockResolvedValueOnce([other]);
const changed = vi
.mocked(eventBus.on)
.mock.calls.find(([event]) => event === 'organizations_changed')![1] as () => void;
changed();
}
await waitFor(() => expect(hookState.activeOrgID()).toBe(other.id));
expect(boundary).toEqual(['read:acme', 'retire:other', 'read:other']);
expect(hookState.connected()).toBe(false);
const reconnect = vi
.mocked(eventBus.on)
.mock.calls.find(([event]) => event === 'websocket_reconnected')![1] as () => void;
reconnect();
expect(boundary).toEqual(['read:acme', 'retire:other', 'read:other', 'read:other']);
dispose();
},
);
it('opts into unbound default recovery then activates membership before acquiring the socket', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
const fallbackFetch = apiFetchMock.getMockImplementation()!;
@@ -1498,6 +1692,10 @@ describe('useAppRuntimeState', () => {
it('drops the previous tenant admission when the organization changes', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
orgsListMock.mockResolvedValue([
{ id: 'default', displayName: 'Default' },
{ id: 'acme', displayName: 'Acme' },
]);
const { dispose, hookState } = mountHook();
await waitFor(() => {
@@ -1572,6 +1770,10 @@ describe('useAppRuntimeState', () => {
it('does not retain outgoing tenant admission if the new tenant request fails', async () => {
isMultiTenantEnabledMock.mockReturnValue(true);
orgsListMock.mockResolvedValue([
{ id: 'default', displayName: 'Default' },
{ id: 'acme', displayName: 'Acme' },
]);
const { dispose, hookState } = mountHook();
await waitFor(() => {
expect(hookState.platformAdmission()).not.toBeNull();
@@ -1589,6 +1791,10 @@ describe('useAppRuntimeState', () => {
'ignores an outgoing tenant refresh after a %s tenant switch request',
async (completion) => {
isMultiTenantEnabledMock.mockReturnValue(true);
orgsListMock.mockResolvedValue([
{ id: 'default', displayName: 'Default' },
{ id: 'acme', displayName: 'Acme' },
]);
const eventsModule = await import('@/stores/events');
const { dispose, hookState } = mountHook();
await waitFor(() => {
@@ -1596,6 +1802,10 @@ describe('useAppRuntimeState', () => {
expect(hookState.organizations().some((org) => org.id === 'acme')).toBe(true);
});
const outgoing = hookState.platformAdmission();
const admissionPath = '/api/resources?page=1&limit=1';
const admissionReadCount = () =>
apiFetchJSONMock.mock.calls.filter(([path]) => path === admissionPath).length;
const initialReads = admissionReadCount();
let finishOutgoing!: (value: unknown) => void;
apiFetchJSONMock.mockImplementationOnce(
() =>
@@ -1607,21 +1817,21 @@ describe('useAppRuntimeState', () => {
([event]) => event === 'websocket_reconnected',
)![1] as () => void;
reconnect();
expect(admissionReadCount()).toBe(initialReads + 1);
const emptyAdmission = Object.fromEntries(Object.keys(outgoing!).map((key) => [key, false]));
let finishIncoming!: (value: unknown) => void;
if (completion === 'failed') {
apiFetchJSONMock.mockRejectedValue(new Error('503 admission unavailable'));
} else if (completion === 'successful') {
apiFetchJSONMock.mockResolvedValue({ aggregations: { platformAdmission: emptyAdmission } });
} else {
apiFetchJSONMock.mockImplementation(
() =>
new Promise((resolve) => {
finishIncoming = resolve;
}),
);
}
let finishIncoming: ((value: unknown) => void) | undefined;
const originalRead = apiFetchJSONMock.getMockImplementation()!;
apiFetchJSONMock.mockImplementation((url: string) => {
if (url !== admissionPath) return originalRead(url);
if (completion === 'failed') return Promise.reject(new Error('503 admission unavailable'));
if (completion === 'successful')
return Promise.resolve({ aggregations: { platformAdmission: emptyAdmission } });
return new Promise((resolve) => {
finishIncoming = resolve;
});
});
hookState.handleOrgSwitch(hookState.activeOrgID() === 'acme' ? 'default' : 'acme');
expect(admissionReadCount()).toBe(initialReads + 2);
await flushAsync();
expect(hookState.platformAdmission()).toEqual(
completion === 'successful' ? emptyAdmission : null,
@@ -1632,9 +1842,9 @@ describe('useAppRuntimeState', () => {
completion === 'successful' ? emptyAdmission : null,
);
if (completion === 'pending') {
finishIncoming({ aggregations: { platformAdmission: emptyAdmission } });
await flushAsync();
expect(hookState.platformAdmission()).toEqual(emptyAdmission);
expect(finishIncoming).toBeTypeOf('function');
finishIncoming?.({ aggregations: { platformAdmission: emptyAdmission } });
await waitFor(() => expect(hookState.platformAdmission()).toEqual(emptyAdmission));
}
dispose();
},

View File

@@ -172,8 +172,11 @@ export class AlertsAPI {
}) as Promise<{ success: boolean; configured: boolean }>;
}
static async activate(): Promise<{ success: boolean; state: string; activationTime?: string }> {
static async activate(
options?: APIContextOptions,
): Promise<{ success: boolean; state: string; activationTime?: string }> {
return apiFetchJSON(`${this.baseUrl}/activate`, {
...options,
method: 'POST',
});
}

View File

@@ -1,11 +1,15 @@
import { For, Show, createMemo } from 'solid-js';
import type { Organization } from '@/api/orgs';
import type { OrganizationListIssue } from '@/useAppRuntimeState';
import { FormSelect } from '@/components/shared/FormSelect';
import { Button } from '@/components/shared/Button';
interface OrgSwitcherProps {
orgs: Organization[];
selectedOrgId: string;
loading?: boolean;
listIssue?: OrganizationListIssue | null;
onRetry?: () => void;
onChange: (orgId: string) => void;
}
@@ -33,53 +37,96 @@ export function OrgSwitcher(props: OrgSwitcherProps) {
const selected = selectedOrg();
return selected?.displayName || props.selectedOrgId || 'Default';
});
let switcher: HTMLDivElement | undefined;
const retryList = () => {
// The retry control disappears when the real choices come back. Keep a
// local keyboard anchor without taking focus after an asynchronous read.
switcher?.focus({ preventScroll: true });
props.onRetry?.();
};
return (
<div class="flex items-center gap-2">
<div
ref={switcher}
role="group"
aria-label="Organization selection"
tabIndex={-1}
class="flex min-w-0 items-center gap-2 focus:outline-2 focus:-outline-offset-2 focus:outline-blue-500"
>
<span class="hidden lg:inline text-xs text-muted">Org</span>
<Show
when={props.orgs.length > 1}
when={props.listIssue}
fallback={
<span
class="inline-flex h-7 items-center rounded-md border border-border bg-surface px-2 text-xs font-medium text-base-content"
title={selectedOrgName()}
<Show
when={props.orgs.length > 1}
fallback={
<span
class="inline-flex h-7 items-center rounded-md border border-border bg-surface px-2 text-xs font-medium text-base-content"
title={selectedOrgName()}
>
{selectedOrgName()}
</span>
}
>
{selectedOrgName()}
</span>
<FormSelect
id="org-switcher-select"
label="Organization"
labelClass="sr-only"
fieldBaseClass={hasAmbiguousNames() ? 'min-w-0 max-w-44 overflow-clip' : 'contents'}
selectClass={hasAmbiguousNames() ? 'focus:ring-inset' : undefined}
selectBaseClass="h-7 max-w-44 rounded-md border border-border bg-surface px-2 text-xs text-base-content shadow-xs transition-colors focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-60"
help={
selectedNeedsIdentity() ? (
<>
Organization ID: <bdi>{props.selectedOrgId}</bdi>
</>
) : undefined
}
helpClass="mt-1 max-w-44 text-xs leading-4 [overflow-wrap:anywhere]"
aria-label="Organization"
value={props.selectedOrgId}
disabled={Boolean(props.loading)}
onChange={(event) => props.onChange(event.currentTarget.value)}
>
<For each={props.orgs}>
{(org) => (
<option value={org.id}>
{needsIdentity(org)
? `${organizationName(org)} (${org.id})`
: organizationName(org)}
</option>
)}
</For>
</FormSelect>
</Show>
}
>
<FormSelect
id="org-switcher-select"
label="Organization"
labelClass="sr-only"
fieldBaseClass={hasAmbiguousNames() ? 'min-w-0 max-w-44 overflow-clip' : 'contents'}
selectClass={hasAmbiguousNames() ? 'focus:ring-inset' : undefined}
selectBaseClass="h-7 max-w-44 rounded-md border border-border bg-surface px-2 text-xs text-base-content shadow-xs transition-colors focus:border-blue-500 focus:outline-hidden focus:ring-1 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-60"
help={
selectedNeedsIdentity() ? (
<>
Organization ID: <bdi>{props.selectedOrgId}</bdi>
</>
) : undefined
}
helpClass="mt-1 max-w-44 text-xs leading-4 [overflow-wrap:anywhere]"
aria-label="Organization"
value={props.selectedOrgId}
disabled={Boolean(props.loading)}
onChange={(event) => props.onChange(event.currentTarget.value)}
>
<For each={props.orgs}>
{(org) => (
<option value={org.id}>
{needsIdentity(org)
? `${organizationName(org)} (${org.id})`
: organizationName(org)}
</option>
)}
</For>
</FormSelect>
<div class="min-w-0 max-w-44 space-y-1 text-xs leading-4">
<div role="status" class="space-y-0.5">
<p class="font-medium text-amber-700 dark:text-amber-300">
{props.loading
? 'Checking organizations…'
: props.listIssue === 'empty'
? 'No organizations listed'
: 'Organization list unavailable'}
</p>
<Show when={props.selectedOrgId}>
<p class="text-muted [overflow-wrap:anywhere]">
Selected ID: <bdi>{props.selectedOrgId}</bdi>
</p>
</Show>
</div>
<Button
size="xs"
class="min-h-9 whitespace-normal"
onClick={retryList}
disabled={props.loading}
>
Retry organization list
</Button>
</div>
</Show>
<Show when={props.loading}>
<Show when={props.loading && !props.listIssue}>
<svg
class="h-3.5 w-3.5 animate-spin text-slate-400"
fill="none"

View File

@@ -140,4 +140,58 @@ describe('OrgSwitcher', () => {
expect(screen.getByText('east', { selector: 'bdi' })).toBeVisible();
expect(onChange).not.toHaveBeenCalled();
});
it('keeps a focus anchor across a read-only retry of unavailable choices', () => {
const [issue, setIssue] = createSignal<'unavailable' | null>('unavailable');
const [loading, setLoading] = createSignal(false);
const onChange = vi.fn();
const onRetry = vi.fn(() => setLoading(true));
render(() => (
<OrgSwitcher
orgs={[
{ id: 'west', displayName: 'Operations' },
{ id: 'east', displayName: 'Operations' },
]}
selectedOrgId="west"
loading={loading()}
listIssue={issue()}
onChange={onChange}
onRetry={onRetry}
/>
));
const status = screen.getByRole('status');
expect(status).toHaveTextContent('Organization list unavailable');
expect(status).toHaveTextContent('Selected ID: west');
expect(screen.queryByRole('combobox')).toBeNull();
const retry = screen.getByRole('button', { name: 'Retry organization list' });
retry.focus();
fireEvent.click(retry);
const group = screen.getByRole('group', { name: 'Organization selection' });
expect(group).toHaveFocus();
expect(onRetry).toHaveBeenCalledOnce();
expect(retry).toBeDisabled();
expect(status).toHaveTextContent('Checking organizations…');
setIssue(null);
setLoading(false);
expect(group).toHaveFocus();
expect(screen.getByRole('combobox', { name: 'Organization' })).toHaveValue('west');
expect(onChange).not.toHaveBeenCalled();
});
it('reports a verified empty list without claiming an unbound session selected Default', () => {
render(() => (
<OrgSwitcher
orgs={[]}
selectedOrgId=""
listIssue="empty"
onChange={() => {}}
onRetry={() => {}}
/>
));
expect(screen.getByRole('status')).toHaveTextContent('No organizations listed');
expect(screen.getByRole('status')).not.toHaveTextContent('Selected ID');
expect(screen.queryByText('Default')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Retry organization list' })).toBeEnabled();
});
});

View File

@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@solidjs/testing-library';
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { DEFAULT_LOCALE, setActiveLocale } from '@/i18n';
vi.mock('@solidjs/router', () => ({
@@ -8,9 +8,10 @@ vi.mock('@solidjs/router', () => ({
}));
const getConfigMock = vi.hoisted(() => vi.fn());
const activateMock = vi.hoisted(() => vi.fn());
vi.mock('@/api/alerts', () => ({
AlertsAPI: { getConfig: getConfigMock },
AlertsAPI: { getConfig: getConfigMock, activate: activateMock },
}));
vi.mock('@/stores/notifications', () => ({
@@ -28,6 +29,8 @@ vi.mock('@/components/Alerts/InvestigateAlertButton', () => ({
import { OverviewTab } from '../OverviewTab';
import { createAlertAcknowledgementRequests } from '@/stores/alertAcknowledgementRequests';
import { useAlertsActivation } from '@/stores/alertsActivation';
import { eventBus } from '@/stores/events';
import { setOrgID } from '@/utils/apiClient';
function defaultProps(overrides: Record<string, unknown> = {}) {
return {
@@ -101,6 +104,8 @@ describe('OverviewTab empty state', () => {
describe('OverviewTab delivery paused banner', () => {
afterEach(() => {
cleanup();
setOrgID(null);
eventBus.emit('org_switched');
});
it.each([
@@ -118,4 +123,32 @@ describe('OverviewTab delivery paused banner', () => {
expect(screen.getByText(/Notification delivery is turned off\./)).toBeInTheDocument();
expect(screen.queryByText(/for this install yet/)).not.toBeInTheDocument();
});
it('keeps the new workspace resume button usable while the old request is outstanding', async () => {
setOrgID('west');
getConfigMock.mockClear();
getConfigMock.mockResolvedValue({ enabled: true, activationState: 'pending_review' });
let finishOutgoing!: (result: { success: boolean }) => void;
activateMock.mockReturnValueOnce(
new Promise<{ success: boolean }>((resolve) => {
finishOutgoing = resolve;
}),
);
const store = useAlertsActivation();
await store.refreshConfig();
render(() => <OverviewTab {...defaultProps()} />);
const resume = () => screen.getByRole('button', { name: 'Turn on delivery' });
fireEvent.click(resume());
expect(resume()).toBeDisabled();
setOrgID('east');
eventBus.emit('org_switched', 'east');
await store.refreshConfig();
expect(resume()).toBeEnabled();
finishOutgoing({ success: true });
await Promise.resolve();
expect(getConfigMock).toHaveBeenCalledTimes(2);
expect(resume()).toBeEnabled();
});
});

View File

@@ -1,8 +1,7 @@
import { createMemo, createSignal, type Accessor } from 'solid-js';
import { createMemo, type Accessor } from 'solid-js';
import { useAlertsActivation } from '@/stores/alertsActivation';
import type { AlertDestinationsDeliveryPausedReason } from '@/utils/alertDestinationsPresentation';
import { logger } from '@/utils/logger';
export interface AlertDeliveryPausedState {
pausedReason: Accessor<AlertDestinationsDeliveryPausedReason | null>;
@@ -15,7 +14,6 @@ export interface AlertDeliveryPausedState {
// the same gate in the same words.
export function useAlertDeliveryPausedReason(): AlertDeliveryPausedState {
const alertsActivation = useAlertsActivation();
const [activating, setActivating] = createSignal(false);
const pausedReason = createMemo<AlertDestinationsDeliveryPausedReason | null>(() => {
// Until the alert config resolves, activation state is null and would read
@@ -36,18 +34,8 @@ export function useAlertDeliveryPausedReason(): AlertDeliveryPausedState {
});
const activate = async () => {
if (activating()) {
return;
}
setActivating(true);
try {
await alertsActivation.activate();
} catch (error) {
logger.error('Failed to activate notification delivery', error);
} finally {
setActivating(false);
}
await alertsActivation.activate();
};
return { pausedReason, activating, activate };
return { pausedReason, activating: alertsActivation.isWritingActivation, activate };
}

View File

@@ -64,13 +64,16 @@ export function Alerts(props: { securityStatus?: SecurityStatus | null }) {
const navigate = useNavigate();
const location = useLocation();
const alertsActivation = useAlertsActivation();
const [isSwitchingActivation, setIsSwitchingActivation] = createSignal(false);
const readOnlySession = createMemo(() => presentationPolicyIsReadOnly());
const [workspaceRevision, setWorkspaceRevision] = createSignal(0);
let disposed = false;
const unsubscribeWorkspace = eventBus.on('org_switched', () => {
setWorkspaceRevision((revision) => revision + 1);
});
onCleanup(unsubscribeWorkspace);
onCleanup(() => {
disposed = true;
unsubscribeWorkspace();
});
// A copied status with the same facts must preserve drafts and focus. A new
// reader must never inherit destination credentials or an in-flight editor.
const configurationReader = createMemo(() => {
@@ -99,54 +102,30 @@ export function Alerts(props: { securityStatus?: SecurityStatus | null }) {
const alertActivationPresentation = createMemo(() =>
getAlertActivationPresentation({
isActive: isNotificationDeliveryActive(),
isBusy: alertsActivation.isLoading() || isSwitchingActivation(),
isBusy: alertsActivation.isLoading(),
}),
);
const handleActivateAlerts = async () => {
if (alertsActivation.isLoading() || isSwitchingActivation()) {
return;
}
setIsSwitchingActivation(true);
const handleNotificationDeliveryChange = async (enable: boolean) => {
if (alertsActivation.isLoading() || readOnlySession()) return;
const revision = workspaceRevision();
const orgID = getOrgID();
const ownsFeedback = () =>
!disposed && workspaceRevision() === revision && getOrgID() === orgID && !readOnlySession();
const successMessage = enable ? getAlertActivationSuccess : getAlertDeactivationSuccess;
const failureMessage = enable ? getAlertActivationFailure : getAlertDeactivationFailure;
try {
const success = await alertsActivation.activate();
const success = await (enable ? alertsActivation.activate() : alertsActivation.deactivate());
if (!ownsFeedback()) return;
if (success) {
notificationStore.success(getAlertActivationSuccess());
try {
await alertsActivation.refreshActiveAlerts();
} catch (error) {
logger.error('Failed to refresh alerts after activation', error);
}
notificationStore.success(successMessage());
} else {
notificationStore.error(getAlertActivationFailure());
}
} finally {
setIsSwitchingActivation(false);
}
};
const handleDeactivateAlerts = async () => {
if (isSwitchingActivation()) {
return;
}
setIsSwitchingActivation(true);
try {
const success = await alertsActivation.deactivate();
if (success) {
notificationStore.success(getAlertDeactivationSuccess());
try {
await alertsActivation.refreshActiveAlerts();
} catch (error) {
logger.error('Failed to refresh alerts after deactivation', error);
}
} else {
notificationStore.error(getAlertDeactivationFailure());
notificationStore.error(failureMessage());
}
} catch (error) {
logger.error('Deactivate alerts failed', error);
notificationStore.error(getAlertDeactivationFailure());
} finally {
setIsSwitchingActivation(false);
if (!ownsFeedback()) return;
logger.error('Failed to change alert notification delivery', error);
notificationStore.error(failureMessage());
}
};
@@ -285,13 +264,9 @@ export function Alerts(props: { securityStatus?: SecurityStatus | null }) {
type="checkbox"
class="sr-only peer"
checked={isNotificationDeliveryActive()}
disabled={alertsActivation.isLoading() || isSwitchingActivation()}
disabled={alertsActivation.isLoading()}
onChange={(event) => {
if (event.currentTarget.checked) {
void handleActivateAlerts();
} else {
void handleDeactivateAlerts();
}
void handleNotificationDeliveryChange(event.currentTarget.checked);
}}
/>
<span class={alertActivationPresentation().trackClass}>

View File

@@ -1,4 +1,4 @@
import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';
import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Alerts } from '@/pages/Alerts';
@@ -6,6 +6,8 @@ import { createAlertAcknowledgementRequests } from '@/stores/alertAcknowledgemen
import { createSignal, onCleanup } from 'solid-js';
import type { SecurityStatus } from '@/types/config';
import { eventBus } from '@/stores/events';
import { notificationStore } from '@/stores/notifications';
import { getAlertDeactivationSuccess } from '@/utils/alertActivationPresentation';
import { setOrgID } from '@/utils/apiClient';
const navigateSpy = vi.hoisted(() => vi.fn());
@@ -16,6 +18,8 @@ const leaveGuards = vi.hoisted(() => ({
}));
const presentationPolicyIsReadOnlyMock = vi.hoisted(() => vi.fn(() => false));
const activationStateMock = vi.hoisted(() => vi.fn(() => 'active'));
const activateMock = vi.hoisted(() => vi.fn(async () => true));
const deactivateMock = vi.hoisted(() => vi.fn(async () => true));
const locationState = vi.hoisted(() => ({
pathname: '/alerts',
hash: '',
@@ -89,9 +93,8 @@ vi.mock('@/stores/alertsActivation', () => ({
detectionEnabled: () => true,
notificationDeliveryEnabled: () => activationStateMock() === 'active',
isLoading: () => false,
activate: vi.fn(async () => true),
deactivate: vi.fn(async () => true),
refreshActiveAlerts: vi.fn(async () => undefined),
activate: activateMock,
deactivate: deactivateMock,
refreshConfig: vi.fn(async () => undefined),
config: () => null,
}),
@@ -136,6 +139,10 @@ describe('Alerts read-only presentation', () => {
presentationPolicyIsReadOnlyMock.mockReturnValue(false);
activationStateMock.mockReset();
activationStateMock.mockReturnValue('active');
activateMock.mockReset().mockResolvedValue(true);
deactivateMock.mockReset().mockResolvedValue(true);
vi.mocked(notificationStore.success).mockClear();
vi.mocked(notificationStore.error).mockClear();
overviewTabSpy.mockClear();
historyTabSpy.mockClear();
configurationSurfaceSpy.mockClear();
@@ -393,4 +400,40 @@ describe('Alerts read-only presentation', () => {
expect(screen.getByRole('checkbox', { name: 'Send notifications' })).toBeChecked();
expect(screen.queryByText('Notifications enabled')).not.toBeInTheDocument();
});
it.each([true, false])(
'only gives delivery feedback to the initiating workspace (old save: %s)',
async (success) => {
let finishOutgoing!: (result: boolean) => void;
deactivateMock.mockReturnValueOnce(
new Promise<boolean>((resolve) => {
finishOutgoing = resolve;
}),
);
setOrgID('west');
render(() => <Alerts securityStatus={admittedStatus} />);
const toggle = screen.getByRole('checkbox', { name: 'Send notifications' });
fireEvent.click(toggle);
expect(deactivateMock).toHaveBeenCalledOnce();
// An equal-looking policy still belongs to a different editor. Do not
// turn a retired result into either a success or a failure here.
setOrgID('east');
eventBus.emit('org_switched', 'east');
finishOutgoing(success);
await Promise.resolve();
expect(notificationStore.success).not.toHaveBeenCalled();
expect(notificationStore.error).not.toHaveBeenCalled();
// The destination's own action still gives the existing feedback.
fireEvent.change(toggle, { target: { checked: false } });
await waitFor(() =>
expect(notificationStore.success).toHaveBeenCalledExactlyOnceWith(
getAlertDeactivationSuccess(),
),
);
expect(deactivateMock).toHaveBeenCalledTimes(2);
expect(notificationStore.error).not.toHaveBeenCalled();
},
);
});

View File

@@ -1,10 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AlertsAPI } from '@/api/alerts';
import { eventBus } from '@/stores/events';
import { useAlertsActivation } from '@/stores/alertsActivation';
import type { AlertConfig } from '@/types/alerts';
import { ALERTS_DETECTION_EVENT } from '@/utils/alertsActivation';
import { getOrgID, setOrgID } from '@/utils/apiClient';
const alertConfig = (
activationState: AlertConfig['activationState'],
@@ -15,6 +16,21 @@ const alertConfig = (
activationState,
}) as AlertConfig;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<T>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
function switchWorkspace(orgID: string) {
setOrgID(orgID);
eventBus.emit('org_switched', orgID);
}
describe('alerts activation ownership boundary', () => {
beforeEach(() => {
vi.restoreAllMocks();
@@ -22,6 +38,11 @@ describe('alerts activation ownership boundary', () => {
eventBus.emit('org_switched', 'test-org');
});
afterEach(() => {
vi.unstubAllGlobals();
setOrgID(null);
});
it('keeps detection enabled when external notifications are pending review', async () => {
vi.spyOn(AlertsAPI, 'getConfig').mockResolvedValue(alertConfig('pending_review'));
@@ -106,4 +127,211 @@ describe('alerts activation ownership boundary', () => {
expect(store.activationState()).toBe('snoozed');
expect(store.isLoading()).toBe(false);
});
it.each([
{ name: 'delayed config', response: () => Response.json(alertConfig('active')) },
{
name: 'retired workspace response',
response: () => Response.json({ error: 'invalid_org' }, { status: 400 }),
},
])('does not let a $name change the destination state or selection', async ({ response }) => {
let finishOutgoing!: (value: Response) => void;
const outgoing = new Promise<Response>((resolve) => (finishOutgoing = resolve));
const fetchMock = vi
.fn<typeof fetch>()
.mockReturnValueOnce(outgoing)
.mockResolvedValueOnce(Response.json(alertConfig('active', false)));
vi.stubGlobal('fetch', fetchMock);
setOrgID('outgoing');
const store = useAlertsActivation();
const previous = store.refreshConfig();
setOrgID('destination');
eventBus.emit('org_switched', 'destination');
expect(store.config()).toBeNull();
expect(fetchMock.mock.calls[0]?.[1]?.signal?.aborted).toBe(true);
await store.refreshConfig();
finishOutgoing(response());
await previous;
expect(
fetchMock.mock.calls.map(([url, init]) => [
url,
init?.method ?? 'GET',
new Headers(init?.headers).get('X-Pulse-Org-ID'),
init?.cache,
]),
).toEqual([
['/api/alerts/config', 'GET', 'outgoing', 'no-store'],
['/api/alerts/config', 'GET', 'destination', 'no-store'],
]);
expect(getOrgID()).toBe('destination');
expect(store.config()).toEqual(alertConfig('active', false));
expect(store.detectionEnabled()).toBe(false);
expect(store.notificationDeliveryEnabled()).toBe(false);
expect(window.__pulseAlertsDetectionEnabled).toBe(false);
expect(store.isLoading()).toBe(false);
expect(store.lastError()).toBeNull();
});
it('reads alert policy without creating a workspace binding on unbound startup', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json(alertConfig('active')));
vi.stubGlobal('fetch', fetchMock);
setOrgID(null);
await useAlertsActivation().refreshConfig();
expect(fetchMock).toHaveBeenCalledOnce();
expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).has('X-Pulse-Org-ID')).toBe(false);
expect(getOrgID()).toBeNull();
});
it('does not install a retired delivery save over the destination policy', async () => {
switchWorkspace('west');
const west = alertConfig('active');
const east = alertConfig('snoozed', false);
vi.spyOn(AlertsAPI, 'getConfig').mockResolvedValueOnce(west).mockResolvedValueOnce(east);
const pending = deferred<{ success: boolean }>();
const save = vi.spyOn(AlertsAPI, 'updateConfig').mockReturnValue(pending.promise);
const store = useAlertsActivation();
await store.refreshConfig();
const outgoing = store.deactivate();
expect(store.isLoading()).toBe(true);
expect(save).toHaveBeenCalledWith(
{ ...west, activationState: 'pending_review' },
{ expectedOrgID: 'west', retry: false, signal: expect.any(AbortSignal) },
);
const signal = save.mock.calls[0]?.[1]?.signal;
switchWorkspace('east');
expect(signal?.aborted).toBe(true);
expect(store.isLoading()).toBe(false);
await store.refreshConfig();
// Even a response which was already queued before abort must be ignored.
pending.resolve({ success: true });
expect(await outgoing).toBe(false);
expect(store.config()).toBe(east);
expect(store.detectionEnabled()).toBe(false);
expect(store.activationState()).toBe('snoozed');
expect(store.notificationDeliveryEnabled()).toBe(false);
expect(window.__pulseAlertsDetectionEnabled).toBe(false);
expect(store.lastError()).toBeNull();
expect(save).toHaveBeenCalledTimes(1);
});
it('does not report a retired write error or clear a destination read in progress', async () => {
switchWorkspace('west');
const east = deferred<AlertConfig>();
vi.spyOn(AlertsAPI, 'getConfig')
.mockResolvedValueOnce(alertConfig('active'))
.mockReturnValueOnce(east.promise);
const pending = deferred<{ success: boolean }>();
vi.spyOn(AlertsAPI, 'updateConfig').mockReturnValue(pending.promise);
const store = useAlertsActivation();
await store.refreshConfig();
const outgoing = store.snooze();
switchWorkspace('east');
const destination = store.refreshConfig();
pending.reject(new Error('outgoing save failed'));
expect(await outgoing).toBe(false);
expect(store.lastError()).toBeNull();
expect(store.isLoading()).toBe(true);
east.resolve(alertConfig('active'));
await destination;
expect(store.isLoading()).toBe(false);
expect(store.notificationDeliveryEnabled()).toBe(true);
});
it('does not issue an unsent confirmation with the new workspace config', async () => {
switchWorkspace('west');
const westRead = deferred<AlertConfig>();
const east = alertConfig('active', false);
vi.spyOn(AlertsAPI, 'getConfig')
.mockReturnValueOnce(westRead.promise)
.mockResolvedValueOnce(east);
const save = vi.spyOn(AlertsAPI, 'updateConfig');
const store = useAlertsActivation();
const confirmation = store.deactivate();
switchWorkspace('east');
await store.refreshConfig();
westRead.resolve(alertConfig('active'));
expect(await confirmation).toBe(false);
expect(store.config()).toBe(east);
expect(save).not.toHaveBeenCalled();
expect(store.lastError()).toBeNull();
});
it('does not refresh from an old activation or clear a newer write after switching back', async () => {
switchWorkspace('west');
const west = alertConfig('active');
const read = vi.spyOn(AlertsAPI, 'getConfig').mockResolvedValue(west);
const activation = deferred<Awaited<ReturnType<typeof AlertsAPI.activate>>>();
const activate = vi.spyOn(AlertsAPI, 'activate').mockReturnValue(activation.promise);
const nextSave = deferred<{ success: boolean }>();
const update = vi.spyOn(AlertsAPI, 'updateConfig').mockReturnValue(nextSave.promise);
const store = useAlertsActivation();
const outgoing = store.activate();
expect(activate).toHaveBeenCalledWith({
expectedOrgID: 'west',
retry: false,
signal: expect.any(AbortSignal),
});
switchWorkspace('east');
switchWorkspace('west');
await store.refreshConfig();
const current = store.deactivate();
// The header and resume card share the write owner.
expect(await store.activate()).toBe(false);
expect(activate).toHaveBeenCalledTimes(1);
activation.resolve({ success: true, state: 'active' });
expect(await outgoing).toBe(false);
expect(read).toHaveBeenCalledTimes(1);
expect(store.isWritingActivation()).toBe(true);
expect(store.isLoading()).toBe(true);
expect(store.config()).toBe(west);
nextSave.resolve({ success: true });
expect(await current).toBe(true);
expect(update).toHaveBeenCalledTimes(1);
expect(store.isLoading()).toBe(false);
expect(store.notificationDeliveryEnabled()).toBe(false);
});
it.each([
['west', 400, 'invalid_org'],
[null, 403, 'csrf_failure'],
] as const)(
'does not replay a rejected confirmation in workspace %s',
async (org, status, code) => {
setOrgID(org);
const transport = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json(alertConfig('active')))
.mockResolvedValueOnce(
Response.json(
{ error: code },
{ status, headers: { 'X-CSRF-Token': 'fixture-refresh' } },
),
);
vi.stubGlobal('fetch', transport);
const store = useAlertsActivation();
await store.refreshConfig();
expect(await store.deactivate()).toBe(false);
expect(getOrgID()).toBe(org);
expect(transport).toHaveBeenCalledTimes(2);
const [route, put] = transport.mock.calls[1]!;
expect(route).toBe('/api/alerts/config');
expect(put?.method).toBe('PUT');
expect(new Headers(put?.headers).get('X-Pulse-Org-ID')).toBe(org);
expect(store.lastError()).not.toBeNull();
expect(store.notificationDeliveryEnabled()).toBe(true);
expect(store.isLoading()).toBe(false);
},
);
});

View File

@@ -16,6 +16,7 @@ vi.mock('@/utils/logger', () => ({
}));
const endpoint = '/api/alerts/active';
const socketURL = 'ws://localhost/ws';
const token = 'synthetic-monitoring-reader';
const knownAlert: Alert = {
id: 'agent:same-name-cpu',
@@ -169,7 +170,7 @@ beforeEach(async () => {
const { createWebSocketStore } = await import('@/stores/websocket');
store = createRoot((cleanup) => {
dispose = cleanup;
return createWebSocketStore('ws://localhost/ws?org_id=north');
return createWebSocketStore(socketURL);
});
sockets[0].open();
});
@@ -335,6 +336,34 @@ describe('monitoring access across the real HTTP client and socket store', () =>
expectSavedAuthority();
});
it('retires outgoing snapshots and reads when a different organization uses the same socket URL', async () => {
const outgoing = sockets[0];
outgoing.snapshot([knownAlert]);
const reply = queuedResponse();
const read = refresh();
store.switchUrl(socketURL);
expect(sockets).toHaveLength(1);
expectAlerts([knownAlert], 'ready');
api.setOrgID('south');
store.switchUrl(socketURL, { organizationChanged: true });
expect(sockets).toHaveLength(2);
expect(sockets[1].url).toBe(outgoing.url);
expect(store.resourceSnapshotReceived()).toBe(false);
expectAlerts([], 'pending');
expect(outgoing.readyState).toBe(SyntheticSocket.CLOSED);
const incoming = { ...knownAlert, message: 'Current organization' };
sockets[1].open();
sockets[1].snapshot([incoming]);
outgoing.snapshot([knownAlert]);
reply.resolve(json([knownAlert]));
await expect(read).resolves.toBe(false);
expectRequests(['north']);
expectAlerts([incoming], 'ready');
expectSavedAuthority('south');
});
it('distinguishes an actual HTTP401 from membership403 and clears only saved authentication', async () => {
fetchMock.mockResolvedValueOnce(json({ error: 'Session expired' }, 401));
await expect(refresh()).resolves.toBe(false);

View File

@@ -1,8 +1,8 @@
import { createSignal } from 'solid-js';
import { batch, createSignal } from 'solid-js';
import { AlertsAPI } from '@/api/alerts';
import type { AlertConfig, ActivationState as ActivationStateType } from '@/types/alerts';
import type { Alert } from '@/types/api';
import type { Resource } from '@/types/resource';
import { getOrgID, type APIContextOptions } from '@/utils/apiClient';
import { setGlobalAlertsDetectionEnabled } from '@/utils/alertsActivation';
import { FACTORY_NODE_DEFAULTS } from '@/utils/alertThresholdDefaults';
import { logger } from '@/utils/logger';
@@ -18,9 +18,10 @@ import { eventBus } from './events';
// Create signals for activation state
const [config, setConfig] = createSignal<AlertConfig | null>(null);
const [activationState, setActivationStateSignal] = createSignal<ActivationStateType | null>(null);
const [isLoading, setIsLoading] = createSignal(false);
const [activeAlerts, setActiveAlerts] = createSignal<Alert[]>([]);
const [isReadingConfig, setIsReadingConfig] = createSignal(false);
const [isWritingActivation, setIsWritingActivation] = createSignal(false);
const [lastError, setLastError] = createSignal<string | null>(null);
const isLoading = () => isReadingConfig() || isWritingActivation();
const detectionEnabled = () => config()?.enabled ?? true;
const notificationDeliveryEnabled = () => detectionEnabled() && activationState() === 'active';
@@ -28,99 +29,108 @@ const applyActivationState = (state: ActivationStateType | null) => {
setActivationStateSignal(state);
};
const ensureConfigLoaded = async (): Promise<AlertConfig | null> => {
let current = config();
if (!current) {
await refreshConfig();
current = config();
}
return current;
};
// Each config read and each organisation switch takes a new generation. A
// read installs its answer only while it is still the latest, so a slow reply
// for the previous organisation, or an older read overtaken by a newer one,
// cannot overwrite what the page now shows.
let configGeneration = 0;
let configRead: AbortController | undefined;
let activationWrite: AbortController | undefined;
// Refresh config from API
const refreshConfig = async (): Promise<void> => {
const generation = ++configGeneration;
const isLatest = () => generation === configGeneration;
configRead?.abort();
const controller = new AbortController();
configRead = controller;
const { signal } = controller;
const orgID = getOrgID();
const ownsRead = () => !signal.aborted && getOrgID() === orgID;
try {
setIsLoading(true);
setIsReadingConfig(true);
setLastError(null);
const alertConfig = await AlertsAPI.getConfig();
if (!isLatest()) return;
setConfig(alertConfig);
setGlobalAlertsDetectionEnabled(alertConfig.enabled);
applyActivationState(alertConfig.activationState || 'active');
const alertConfig = await AlertsAPI.getConfig({
signal,
cache: 'no-store',
expectedOrgID: orgID ?? undefined,
// An unbound bootstrap must keep the header absent, while still using
// the API client's abort-aware response handling.
retry: orgID !== null,
});
if (!ownsRead()) return;
batch(() => {
setConfig(alertConfig);
applyActivationState(alertConfig.activationState || 'active');
setGlobalAlertsDetectionEnabled(alertConfig.enabled);
});
} catch (error) {
if (!isLatest()) return;
if (!ownsRead()) return;
logger.error('Failed to fetch alert config:', error);
setLastError(error instanceof Error ? error.message : 'Unknown error');
} finally {
if (isLatest()) setIsLoading(false);
if (configRead === controller) {
configRead = undefined;
setIsReadingConfig(false);
}
}
};
// Fetch active alerts (for violation count)
const refreshActiveAlerts = async (): Promise<void> => {
const runActivationWrite = async (
failureMessage: string,
write: (options: APIContextOptions, ownsWrite: () => boolean) => Promise<boolean>,
): Promise<boolean> => {
if (activationWrite) return false;
const controller = new AbortController();
activationWrite = controller;
const orgID = getOrgID();
const ownsWrite = () => activationWrite === controller && getOrgID() === orgID;
try {
const alerts = await AlertsAPI.getActive();
setActiveAlerts(alerts);
batch(() => {
setIsWritingActivation(true);
setLastError(null);
});
if (!ownsWrite()) return false;
// An unbound workspace still sends no org header. Never replay an explicit
// confirmation through the client's automatic org or CSRF recovery.
return await write(
{ expectedOrgID: orgID ?? undefined, retry: false, signal: controller.signal },
ownsWrite,
);
} catch (error) {
logger.error('Failed to fetch active alerts:', error);
// Don't set error state for this - it's not critical
}
};
// Activate alert notifications
const activate = async (): Promise<boolean> => {
try {
setIsLoading(true);
setLastError(null);
const result = await AlertsAPI.activate();
if (result.success) {
// Refresh config to get updated state
await refreshConfig();
return true;
if (ownsWrite()) {
logger.error(failureMessage, error);
setLastError(error instanceof Error ? error.message : 'Unknown error');
}
return false;
} catch (error) {
logger.error('Failed to activate alerts:', error);
setLastError(error instanceof Error ? error.message : 'Unknown error');
return false;
} finally {
setIsLoading(false);
if (activationWrite === controller) {
activationWrite = undefined;
setIsWritingActivation(false);
}
}
};
const updateActivationState = async (state: ActivationStateType): Promise<boolean> => {
try {
setIsLoading(true);
setLastError(null);
const current = await ensureConfigLoaded();
// A completed outgoing activation must not cause a follow-up read for its
// replacement workspace.
const activate = () =>
runActivationWrite('Failed to activate alerts:', async (options, ownsWrite) => {
const result = await AlertsAPI.activate(options);
if (!ownsWrite() || !result.success) return false;
await refreshConfig();
return ownsWrite();
});
const updateActivationState = (state: ActivationStateType) =>
runActivationWrite('Failed to update activation state:', async (options, ownsWrite) => {
if (!config()) await refreshConfig();
if (!ownsWrite()) return false;
const current = config();
if (!current) {
throw new Error('Alert configuration is unavailable');
}
const updated: AlertConfig = { ...current, activationState: state };
const result = await AlertsAPI.updateConfig(updated);
if (!result.success) {
return false;
}
setConfig(updated);
applyActivationState(state);
const result = await AlertsAPI.updateConfig(updated, options);
if (!ownsWrite() || !result.success) return false;
batch(() => {
setConfig(updated);
applyActivationState(state);
});
return true;
} catch (error) {
logger.error('Failed to update activation state:', error);
setLastError(error instanceof Error ? error.message : 'Unknown error');
return false;
} finally {
setIsLoading(false);
}
};
});
const deactivate = async (): Promise<boolean> => updateActivationState('pending_review');
@@ -183,13 +193,20 @@ const getTrueNASDiskTemperatureThresholds = (disk: Pick<Resource, 'id' | 'physic
};
eventBus.on('org_switched', () => {
configGeneration++;
setConfig(null);
setGlobalAlertsDetectionEnabled(null);
applyActivationState(null);
setActiveAlerts([]);
setLastError(null);
setIsLoading(false);
configRead?.abort();
configRead = undefined;
// Retire the outgoing browser operation, not the server-side write it may
// already have received. Even a response that outlives abort loses ownership.
activationWrite?.abort();
activationWrite = undefined;
batch(() => {
setConfig(null);
setGlobalAlertsDetectionEnabled(null);
applyActivationState(null);
setLastError(null);
setIsReadingConfig(false);
setIsWritingActivation(false);
});
});
// Export the store
@@ -200,7 +217,7 @@ export const useAlertsActivation = () => ({
detectionEnabled,
notificationDeliveryEnabled,
isLoading,
activeAlerts,
isWritingActivation,
lastError,
// Computed
@@ -213,7 +230,6 @@ export const useAlertsActivation = () => ({
// Actions
refreshConfig,
refreshActiveAlerts,
activate,
deactivate,
snooze,

View File

@@ -1959,8 +1959,10 @@ export function createWebSocketStore(url: string) {
setReconnecting(true);
connect();
},
switchUrl: (nextUrl: string) => {
if (!nextUrl || nextUrl === wsUrl) {
switchUrl: (nextUrl: string, options?: { organizationChanged: true }) => {
// The organization is selected by the handshake cookie, not the URL.
// A real workspace switch must clear the old state even at the same URL.
if (!nextUrl || isDisposed || (nextUrl === wsUrl && !options?.organizationChanged)) {
return;
}

View File

@@ -1,8 +1,10 @@
import {
batch,
createEffect,
createMemo,
createSignal,
getOwner,
on,
onCleanup,
onMount,
runWithOwner,
@@ -74,12 +76,34 @@ export type AppConnectionStatus = {
tone: 'healthy' | 'warning' | 'offline';
};
export type OrganizationListIssue = 'unavailable' | 'empty';
const isPreAuthLoginBootstrapPath = (pathname: string): boolean =>
pathname === '/' || pathname === '/login';
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null;
const isOrganizationList = (value: unknown): value is Organization[] => {
if (!Array.isArray(value)) return false;
const ids = new Set<string>();
return value.every((item: unknown) => {
if (
!isRecord(item) ||
typeof item.id !== 'string' ||
!/^[A-Za-z0-9._-]{1,64}$/.test(item.id) ||
item.id === '.' ||
item.id === '..' ||
ids.has(item.id) ||
typeof item.displayName !== 'string'
) {
return false;
}
ids.add(item.id);
return true;
});
};
export const useAppRuntimeState = () => {
initKioskMode();
syncKioskMode();
@@ -185,8 +209,14 @@ export const useAppRuntimeState = () => {
const [organizations, setOrganizations] = createSignal<Organization[]>([
{ id: 'default', displayName: 'Default Organization' },
]);
const [activeOrgID, setActiveOrgID] = createSignal(getSelectedOrgID() || 'default');
const [activeOrgID, setActiveOrgID] = createSignal(getSelectedOrgID() ?? '');
const [orgsLoading, setOrgsLoading] = createSignal(false);
const [organizationListIssue, setOrganizationListIssue] =
createSignal<OrganizationListIssue | null>(null);
let organizationListRead = 0;
onCleanup(() => {
organizationListRead += 1;
});
const [securityStatus, setSecurityStatus] = createSignal<SecurityStatus | null>(null);
const [proxyAuthInfo, setProxyAuthInfo] = createSignal<{
username?: string;
@@ -406,118 +436,25 @@ export const useAppRuntimeState = () => {
}
};
// The security status bootstrap read AI availability for the organization
// the page started with; when loading settles on another one, re-read it.
const activateLoadedOrg = (orgID: string) => {
const activateOrganization = (orgID: string) => {
const changed = orgID !== activeOrgID();
setSelectedOrgID(orgID);
setActiveOrgID(orgID);
if (changed) {
if (!changed) return;
const store = wsStore();
if (!store) {
// The bootstrap security status preceded the selected workspace.
void aiAvailabilityStore.refreshEnabledFromServer();
}
};
const loadOrganizations = async () => {
setOrgsLoading(true);
try {
if (!runtimeCapabilitiesLoaded()) {
await loadRuntimeCapabilities();
}
if (presentationPolicyHidesOrganizationSurfaces()) {
const storedOrgID = getSelectedOrgID();
const hiddenOrgID =
isHostedModeEnabled() && storedOrgID && storedOrgID !== 'default'
? storedOrgID
: 'default';
setOrganizations([
{
id: hiddenOrgID,
displayName: hiddenOrgID === 'default' ? 'Default Organization' : hiddenOrgID,
},
]);
setSelectedOrgID(hiddenOrgID);
setActiveOrgID(hiddenOrgID);
return;
}
// A hosted runtime serves its customer's workspace, not the default
// organization, whatever its licence: the server lists that workspace
// first, so a session with no stored selection lands there.
if (!isMultiTenantEnabled() && !isHostedModeEnabled()) {
setOrganizations([{ id: 'default', displayName: 'Default Organization' }]);
activateLoadedOrg('default');
return;
}
const fetched = await OrgsAPI.list();
const organizationList =
fetched.length > 0 ? fetched : [{ id: 'default', displayName: 'Default Organization' }];
setOrganizations(organizationList);
const storedOrgID = getSelectedOrgID();
const selectedOrg =
(storedOrgID && organizationList.some((org) => org.id === storedOrgID)
? storedOrgID
: null) ||
organizationList[0]?.id ||
'default';
activateLoadedOrg(selectedOrg);
} catch (error) {
// A hosted runtime keeps the workspace this browser already selected.
// With none, it stores no guess: requests that name no organization
// land in the client workspace, and the next load reads the list again.
if (isHostedModeEnabled()) {
const storedOrgID = getSelectedOrgID();
logger.warn('Failed to load organizations, keeping the hosted selection', error);
if (storedOrgID) {
setOrganizations([
{
id: storedOrgID,
displayName: storedOrgID === 'default' ? 'Default Organization' : storedOrgID,
},
]);
activateLoadedOrg(storedOrgID);
} else {
setOrganizations([{ id: 'default', displayName: 'Default Organization' }]);
setActiveOrgID('default');
}
return;
}
logger.warn('Failed to load organizations, falling back to default org', error);
showToast('error', 'Failed to load organizations. Using default.');
const fallback = [{ id: 'default', displayName: 'Default Organization' }];
setOrganizations(fallback);
activateLoadedOrg('default');
} finally {
setOrgsLoading(false);
}
};
const handleOrgSwitch = (nextOrgID: string) => {
const target = nextOrgID?.trim() || 'default';
if (target === activeOrgID()) {
return;
}
if (target !== 'default' && !organizations().some((org) => org.id === target)) {
showToast('error', 'Organization no longer exists');
return;
}
setSelectedOrgID(target);
setActiveOrgID(target);
// Drop the previous tenant's admission before anything can render from it:
// a stale facet here would show the other tenant's platform tabs until the
// new runtime state arrives.
// Both an explicit choice and a replacement from a valid list retire
// outgoing reads and snapshots. The cookie can change while /ws stays
// the same URL, so a URL equality check is not a scope check.
platformAdmissionRequest += 1;
setPlatformAdmission(null);
void loadPlatformAdmission();
// AI availability is organization-scoped: the new tenant may have a
// different provider setup, so Patrol entry points follow its answer.
aiAvailabilityStore.clear();
void aiAvailabilityStore.refreshEnabledFromServer();
eventBus.emit('org_switched', target);
try {
localStorage.removeItem(STORAGE_KEYS.GUEST_METADATA);
@@ -527,13 +464,91 @@ export const useAppRuntimeState = () => {
// Ignore storage errors.
}
store.switchUrl(getPulseWebSocketUrl(), { organizationChanged: true });
eventBus.emit('org_switched', orgID);
void loadPlatformAdmission();
void aiAvailabilityStore.refreshEnabledFromServer();
};
const loadOrganizations = async () => {
const read = ++organizationListRead;
const isCurrent = () => read === organizationListRead && !needsAuth();
const showListIssue = (issue: OrganizationListIssue) =>
batch(() => {
// Bootstrap may have recovered a stale default successfully by
// dropping the binding. Display that absence; do not persist a guess.
if (!wsStore()) setActiveOrgID(getSelectedOrgID() ?? '');
setOrganizations([]);
setOrganizationListIssue(issue);
});
const applyChoices = (choices: Organization[], orgID: string) =>
batch(() => {
setOrganizations(choices);
setOrganizationListIssue(null);
activateOrganization(orgID);
});
setOrgsLoading(true);
try {
const store = wsStore();
if (store && typeof store.switchUrl === 'function') {
store.switchUrl(getPulseWebSocketUrl());
} else {
store?.reconnect();
if (!runtimeCapabilitiesLoaded()) await loadRuntimeCapabilities();
if (!isCurrent()) return;
if (presentationPolicyHidesOrganizationSurfaces()) {
const storedOrgID = getSelectedOrgID();
const hiddenOrgID = isHostedModeEnabled() && storedOrgID ? storedOrgID : 'default';
applyChoices(
[
{
id: hiddenOrgID,
displayName: hiddenOrgID === 'default' ? 'Default Organization' : hiddenOrgID,
},
],
hiddenOrgID,
);
return;
}
if (!isMultiTenantEnabled() && !isHostedModeEnabled()) {
applyChoices([{ id: 'default', displayName: 'Default Organization' }], 'default');
return;
}
const fetched: unknown = await OrgsAPI.list();
if (!isCurrent() || presentationPolicyHidesOrganizationSurfaces()) return;
if (!isOrganizationList(fetched)) throw new Error('Invalid organization list');
if (!fetched.length) {
showListIssue('empty');
return;
}
// The server lists its landing workspace first, including for Community
// clients on hosted runtimes. Prefer the current selection if listed.
const selected = wsStore() ? activeOrgID() : getSelectedOrgID();
const target = fetched.find((org) => org.id === selected) ?? fetched[0];
applyChoices(fetched, target.id);
} catch (error) {
if (!isCurrent()) return;
logger.warn('Failed to load organization list', error);
showListIssue('unavailable');
} finally {
if (read === organizationListRead) setOrgsLoading(false);
}
};
const retryOrganizationList = () => {
if (!orgsLoading() && !needsAuth() && !isLoggingOut()) void loadOrganizations();
};
const handleOrgSwitch = (nextOrgID: string) => {
if (orgsLoading() || organizationListIssue() || nextOrgID === activeOrgID()) return;
if (!organizations().some((org) => org.id === nextOrgID)) {
showToast('error', 'Organization no longer exists');
return;
}
try {
batch(() => activateOrganization(nextOrgID));
showToast('success', 'Organization switched');
} catch (error) {
logger.error('Failed to switch organization', error);
@@ -583,18 +598,14 @@ export const useAppRuntimeState = () => {
void syncVersionInfoFromUpdateStore();
});
let alertsInitialized = false;
createEffect(() => {
const ready = !isLoading() && !needsAuth();
if (ready && !alertsInitialized) {
alertsInitialized = true;
void alertsActivation.refreshConfig();
void alertsActivation.refreshActiveAlerts();
}
if (!ready) {
alertsInitialized = false;
}
});
const alertReaderReady = () => !isLoading() && !needsAuth();
// The first successful socket in a new workspace isn't a reconnect. Read
// its alert policy after the selection batch has retired the previous one.
createEffect(
on([alertReaderReady, activeOrgID], ([ready]) => {
if (ready) void alertsActivation.refreshConfig();
}),
);
createEffect(() => {
activeOrgID();
@@ -677,13 +688,13 @@ export const useAppRuntimeState = () => {
const handleWebSocketReconnected = () => {
logger.info('WebSocket reconnected, refreshing alert configuration');
void alertsActivation.refreshConfig();
void alertsActivation.refreshActiveAlerts();
if (alertReaderReady()) void alertsActivation.refreshConfig();
// The estate can gain or lose a platform while the socket is down.
void loadPlatformAdmission();
};
const handleOrganizationsChanged = () => {
if (!wsStore() || needsAuth()) return;
logger.info('Organization membership changed, refreshing organization list');
void loadOrganizations();
};
@@ -874,6 +885,7 @@ export const useAppRuntimeState = () => {
}
controller.signal.throwIfAborted();
organizationListRead += 1;
// One blocked storage operation must not prevent the remaining cleanup.
let cleanupFailed = false;
const clean = (operation: () => void) => {
@@ -946,6 +958,8 @@ export const useAppRuntimeState = () => {
organizations,
activeOrgID,
orgsLoading,
organizationListIssue,
retryOrganizationList,
securityStatus,
proxyAuthInfo,
state,