Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

31.4 KB
Raw Blame
import {
  createEffect,
  createMemo,
  createSignal,
  getOwner,
  onCleanup,
  onMount,
  runWithOwner,
} from 'solid-js';
import { getGlobalWebSocketStore, shutdownGlobalWebSocketStore } from '@/stores/websocket-global';
import { logger } from '@/utils/logger';
import { apiFetchJSON } from '@/utils/apiClient';
import {
  PRIMARY_PLATFORM_NAV_IDS,
  type PlatformNavigationVisibility,
} from '@/features/platformNavigation/platformNavigationModel';
import { SESSION_STORAGE_KEYS, STORAGE_KEYS } from '@/utils/localStorage';
import type { VersionInfo } from '@/api/updates';
import type { Organization } from '@/api/orgs';
import { OrgsAPI } from '@/api/orgs';
import type { SecurityStatus } from '@/types/config';
import type { State } from '@/types/api';
import { SettingsAPI } from '@/api/settings';
import {
  apiFetch,
  getOrgID as getSelectedOrgID,
  hasAuth as hasStoredAuthSession,
  setOrgID as setSelectedOrgID,
} from '@/utils/apiClient';
import { eventBus } from '@/stores/events';
import { showToast } from '@/utils/toast';
import { updateStore } from '@/stores/updates';
import { useAlertsActivation } from '@/stores/alertsActivation';
import { actionInboxStore } from '@/stores/actionInbox';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import { patrolAttentionStore } from '@/stores/patrolAttention';
import {
  applyThemeClass,
  computeIsDark,
  getStoredThemePreference,
  hasStoredThemePreference,
  normalizeThemePreference,
  persistThemePreference,
  type ThemePreference,
} from '@/utils/theme';
import { initKioskMode, getPulseWebSocketUrl } from '@/utils/url';
import { syncKioskMode } from '@/hooks/useKioskMode';
import {
  isHostedModeEnabled,
  isMultiTenantEnabled,
  runtimeCapabilitiesLoaded,
  loadRuntimeCapabilities,
} from '@/stores/license';
import { aiAvailabilityStore } from '@/stores/aiAvailability';
import { loadCommercialPosture } from '@/stores/licenseCommercial';
import {
  presentationPolicyHidesOrganizationSurfaces,
  presentationPolicyHidesUpgradePrompts,
  syncSessionPresentationPolicy,
} from '@/stores/sessionPresentationPolicy';
import { layoutStore } from '@/utils/layout';
import {
  loadRuntimeBranding,
  markSystemSettingsLoadedWithDefaults,
  updateRuntimeDisplayFromResponse,
} from '@/stores/systemSettings';

type EnhancedStore = ReturnType<typeof getGlobalWebSocketStore>;

export type AppConnectionStatus = {
  kind: 'connected' | 'sync-reconnecting' | 'backend-healthy' | 'reconnecting' | 'disconnected';
  label: string;
  detail: string;
  tone: 'healthy' | 'warning' | 'offline';
};

const isPreAuthLoginBootstrapPath = (pathname: string): boolean =>
  pathname === '/' || pathname === '/login';

const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null;

export const useAppRuntimeState = () => {
  initKioskMode();
  syncKioskMode();

  const owner = getOwner();
  const acquireWsStore = (): EnhancedStore => {
    const store = owner
      ? runWithOwner(owner, () => getGlobalWebSocketStore())
      : getGlobalWebSocketStore();
    return store || getGlobalWebSocketStore();
  };

  const alertsActivation = useAlertsActivation();
  let hasFetchedVersionInfo = false;

  const hasLocalAuthBootstrapHint = (): boolean => {
    if (hasStoredAuthSession()) {
      return true;
    }

    if (typeof window === 'undefined') {
      return false;
    }

    try {
      if (window.sessionStorage.getItem(STORAGE_KEYS.AUTH_USER)) {
        return true;
      }
    } catch {
      // Fall through to the remember-me hint below.
    }

    // A remembered login username means this browser signed in with
    // "remember me", so an HttpOnly session cookie may still be valid even
    // though every per-tab artifact died with the tab. Without this hint the
    // pre-auth short-circuit pins the user back to the login page and the
    // 30-day session never gets a chance to authenticate (issue #1531).
    try {
      return Boolean(window.localStorage.getItem(STORAGE_KEYS.REMEMBERED_LOGIN_USERNAME));
    } catch {
      return false;
    }
  };

  // A completed SSO redirect (?oidc=success / ?saml=success) means a session
  // cookie may exist even though no local-auth artifacts do, so the pre-auth
  // bootstrap short-circuit below must not pin the user to the login page
  // before the /api/state probe runs (issue #1574).
  const hasSSOCallbackSuccessHint = (): boolean => {
    if (typeof window === 'undefined') {
      return false;
    }
    try {
      const params = new URLSearchParams(window.location.search);
      return params.get('oidc') === 'success' || params.get('saml') === 'success';
    } catch {
      return false;
    }
  };

  const fallbackState: State = {
    connectedInfrastructure: [],
    metrics: [],
    performance: {
      apiCallDuration: {},
      lastPollDuration: 0,
      pollingStartTime: '',
      totalApiCalls: 0,
      failedApiCalls: 0,
      cacheHits: 0,
      cacheMisses: 0,
    },
    connectionHealth: {},
    stats: {
      startTime: new Date().toISOString(),
      uptime: 0,
      pollingCycles: 0,
      webSocketClients: 0,
      version: '0.0.0',
    },
    activeAlerts: [],
    recentlyResolved: [],
    pveTagColors: {},
    lastUpdate: 0,
    resources: [],
  };
  const hasRuntimeStatePayload = (candidate: State | undefined): boolean => {
    if (!candidate) return false;
    return (
      candidate.lastUpdate > 0 ||
      candidate.resources.length > 0 ||
      candidate.connectedInfrastructure.length > 0 ||
      candidate.activeAlerts.length > 0 ||
      candidate.recentlyResolved.length > 0 ||
      candidate.metrics.length > 0
    );
  };

  const [isLoading, setIsLoading] = createSignal(true);
  const [bootstrapFailed, setBootstrapFailed] = createSignal(false);
  const [needsAuth, setNeedsAuth] = createSignal(false);
  const [hasAuth, setHasAuth] = createSignal(false);
  const [organizations, setOrganizations] = createSignal<Organization[]>([
    { id: 'default', displayName: 'Default Organization' },
  ]);
  const [activeOrgID, setActiveOrgID] = createSignal(getSelectedOrgID() || 'default');
  const [orgsLoading, setOrgsLoading] = createSignal(false);
  const [securityStatus, setSecurityStatus] = createSignal<SecurityStatus | null>(null);
  const [proxyAuthInfo, setProxyAuthInfo] = createSignal<{
    username?: string;
    logoutURL?: string;
  } | null>(null);
  const [wsStore, setWsStore] = createSignal<EnhancedStore | null>(null);
  // Which primary platform pages this estate admits, as reported by the
  // canonical resource contract. Null means the server did not report it, in
  // which case navigation falls back to classifying the runtime state payload.
  const [platformAdmission, setPlatformAdmission] =
    createSignal<PlatformNavigationVisibility | null>(null);
  const [backendHealthy, setBackendHealthy] = createSignal(false);
  const runtimeStateResolved = (): boolean => {
    const store = wsStore();
    // Alert REST recovery can populate state before the first resource frame.
    // It must not replace valid admission with an invented empty estate.
    return Boolean(store?.resourceSnapshotReceived()) || (store?.state.resources.length ?? 0) > 0;
  };
  const state = (): State => {
    const store = wsStore();
    const liveState = store?.state;
    if (liveState && (store.initialDataReceived() || hasRuntimeStatePayload(liveState))) {
      return liveState;
    }
    return liveState || fallbackState;
  };
  const connected = () => wsStore()?.connected() || false;
  const reconnecting = () => wsStore()?.reconnecting() || false;
  const [lastUpdateText, setLastUpdateText] = createSignal('');
  const [versionInfo, setVersionInfo] = createSignal<VersionInfo | null>(null);
  const connectionStatus = createMemo<AppConnectionStatus>(() => {
    if (connected()) {
      return {
        kind: 'connected',
        label: 'Connected',
        detail: 'Backend and live data stream are connected.',
        tone: 'healthy',
      };
    }

    if (backendHealthy() && reconnecting()) {
      return {
        kind: 'sync-reconnecting',
        label: 'Sync reconnecting',
        detail: 'Backend is healthy. Live updates are reconnecting.',
        tone: 'warning',
      };
    }

    if (backendHealthy()) {
      return {
        kind: 'backend-healthy',
        label: 'Backend healthy',
        detail: 'Backend is healthy, but the live data stream is not connected.',
        tone: 'warning',
      };
    }

    if (reconnecting()) {
      return {
        kind: 'reconnecting',
        label: 'Reconnecting...',
        detail: 'Attempting to reconnect to the backend and live data stream.',
        tone: 'offline',
      };
    }

    return {
      kind: 'disconnected',
      label: 'Disconnected',
      detail: 'Backend and live data stream are unavailable.',
      tone: 'offline',
    };
  });
  const showOrgSwitcher = createMemo(() => {
    if (!isMultiTenantEnabled()) {
      return false;
    }
    return !presentationPolicyHidesOrganizationSurfaces();
  });

  const initialThemePreference = getStoredThemePreference();
  const [themePreference, setThemePreference] =
    createSignal<ThemePreference>(initialThemePreference);
  const [, setHasLoadedServerTheme] = createSignal(false);
  const [darkMode, setDarkMode] = createSignal(computeIsDark(initialThemePreference));
  applyThemeClass(darkMode());

  const applyThemePreferenceLocally = (preference: ThemePreference) => {
    setThemePreference(preference);
    persistThemePreference(preference);
    const isDark = computeIsDark(preference);
    setDarkMode(isDark);
    applyThemeClass(isDark);
  };

  const applyServerThemeIfAllowed = (theme?: string) => {
    if (!hasStoredThemePreference() && theme && theme !== '') {
      applyThemePreferenceLocally(normalizeThemePreference(theme));
    }
  };

  const normalizePlatformAdmission = (value: unknown): PlatformNavigationVisibility | null => {
    if (!isRecord(value)) return null;
    const flags = PRIMARY_PLATFORM_NAV_IDS.map((navId) => [navId, value[navId]] as const);
    // Partial payloads are rejected outright: a missing flag would read as a
    // hidden platform, which is indistinguishable from a real absence.
    if (flags.some(([, flag]) => typeof flag !== 'boolean')) return null;
    return Object.fromEntries(flags) as PlatformNavigationVisibility;
  };

  let platformAdmissionRequest = 0;
  const loadPlatformAdmission = async () => {
    const request = ++platformAdmissionRequest;
    try {
      // One resource is enough: the aggregations describe the whole set, so
      // this resolves navigation without reading an estate-sized payload.
      const payload = await apiFetchJSON<{ aggregations?: { platformAdmission?: unknown } }>(
        '/api/resources?page=1&limit=1',
      );
      // A tenant switch or newer refresh supersedes this response, even if
      // that newer request failed. Never restore an outgoing tenant facet.
      if (request !== platformAdmissionRequest) return;
      setPlatformAdmission(normalizePlatformAdmission(payload?.aggregations?.platformAdmission));
    } catch (error) {
      // A failed refresh says nothing about which platforms still exist.
      // Keep the last valid facet until a successful response replaces it.
      // First-load failures remain unresolved; org switches clear it before
      // requesting the new tenant, so this cannot retain outgoing admission.
      logger.debug('[useAppRuntimeState] platform admission unavailable', error);
    }
  };

  const loadRuntimeDisplayAndLayout = async () => {
    try {
      // Bootstrap runs for every authenticated role. Read only the explicit
      // session-tier display projection; /api/system/settings remains admin-only.
      const display = await SettingsAPI.getRuntimeDisplay();
      updateRuntimeDisplayFromResponse(display);
      applyServerThemeIfAllowed(display.theme);
      setHasLoadedServerTheme(true);
      // Apply the server's canonical full-width mode using the settings we just
      // fetched, so it is honored after auth even if a stale localStorage
      // preference exists (#1130).
      layoutStore.applyServerMode(display.fullWidthMode);
    } catch (error) {
      logger.error('Failed to load runtime display settings from server', error);
      markSystemSettingsLoadedWithDefaults();
    }
  };

  const applySecurityStatus = (securityData: SecurityStatus | null) => {
    if (securityData) {
      syncSessionPresentationPolicy(securityData);
    }
    setSecurityStatus(securityData);
    aiAvailabilityStore.setEnabled(securityData?.sessionCapabilities?.assistantEnabled === true);
  };

  // Probes the session against the same auth and scope checks as `/api/state`
  // without pulling an estate-sized payload through them. The shell used to
  // read the full state here purely to find out whether it was authenticated
  // and to have something to render before the socket connected; navigation now
  // resolves from the platform admission facet, and everything else the shell
  // shows comes from the socket. `/api/state` itself is untouched: it is the
  // recovery path for a snapshot too large for a websocket frame.
  const loadAuthenticatedBootstrapState = async (): Promise<boolean> => {
    const summaryResponse = await apiFetch('/api/state/summary', {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        Accept: 'application/json',
      },
    });

    if (summaryResponse.status === 401) {
      setNeedsAuth(true);
      return false;
    }

    if (!summaryResponse.ok) {
      throw new Error(`Session check failed with status ${summaryResponse.status}`);
    }

    return true;
  };

  const beginAuthenticatedRuntime = async (): Promise<boolean> => {
    if (!(await loadAuthenticatedBootstrapState())) {
      return false;
    }

    setNeedsAuth(false);
    await loadOrganizations();
    setWsStore(acquireWsStore());
    setBackendHealthy(true);
    await Promise.all([
      loadRuntimeDisplayAndLayout(),
      loadRuntimeBranding(),
      loadPlatformAdmission(),
    ]);
    // Shared commercial posture stays off ordinary self-hosted app shells.
    if (!presentationPolicyHidesUpgradePrompts()) {
      void loadCommercialPosture();
    }
    return true;
  };

  const checkBackendHealth = async () => {
    try {
      const response = await apiFetch('/api/health', { cache: 'no-store' });
      setBackendHealthy(response.ok);
      return response.ok;
    } catch {
      setBackendHealthy(false);
      return false;
    }
  };

  // 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 changed = orgID !== activeOrgID();
    setSelectedOrgID(orgID);
    setActiveOrgID(orgID);
    if (changed) {
      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;
      }

      if (!isMultiTenantEnabled()) {
        const storedOrgID = getSelectedOrgID();
        const hostedOrgID =
          isHostedModeEnabled() && storedOrgID && storedOrgID !== 'default'
            ? storedOrgID
            : 'default';
        setOrganizations([
          {
            id: hostedOrgID,
            displayName: hostedOrgID === 'default' ? 'Default Organization' : hostedOrgID,
          },
        ]);
        activateLoadedOrg(hostedOrgID);
        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) {
      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.
    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);
      localStorage.removeItem(STORAGE_KEYS.DOCKER_METADATA);
      localStorage.removeItem(STORAGE_KEYS.DOCKER_METADATA + '_hosts');
    } catch {
      // Ignore storage errors.
    }

    try {
      const store = wsStore();
      if (store && typeof store.switchUrl === 'function') {
        store.switchUrl(getPulseWebSocketUrl());
      } else {
        store?.reconnect();
      }
      showToast('success', 'Organization switched');
    } catch (error) {
      logger.error('Failed to switch organization', error);
      showToast('error', 'Failed to switch organization');
    }
  };

  const formatLastUpdate = (timestamp: number) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    // Passing undefined lets the runtime pick the viewer's locale, including
    // whether it wants a 12 or 24 hour clock. #1279 made this change once; the
    // v6 rewrite of this state hook reinstated the hardcoded form (#1685).
    return date.toLocaleTimeString(undefined, {
      hour: 'numeric',
      minute: '2-digit',
      second: '2-digit',
    });
  };

  createEffect(() => {
    const updateTime = state().lastUpdate;
    if (updateTime > 0) {
      setLastUpdateText(formatLastUpdate(updateTime));
    }
  });

  const syncVersionInfoFromUpdateStore = async () => {
    const cachedVersion = updateStore.versionInfo();
    if (cachedVersion) {
      setVersionInfo(cachedVersion);
    }

    await updateStore.checkForUpdates();

    const resolvedVersion = updateStore.versionInfo();
    if (resolvedVersion) {
      setVersionInfo(resolvedVersion);
    }
  };

  createEffect(() => {
    if (isLoading() || needsAuth() || hasFetchedVersionInfo) {
      return;
    }
    hasFetchedVersionInfo = true;
    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;
    }
  });

  createEffect(() => {
    activeOrgID();
    const ready = !isLoading() && !needsAuth();
    if (!ready) return;

    const refreshOpenWorkBadges = () => {
      void Promise.allSettled([
        aiIntelligenceStore.loadPatrolFindings(),
        aiIntelligenceStore.loadPendingApprovals(),
        patrolAttentionStore.loadSummary(),
        actionInboxStore.loadPendingActionCount(),
      ]);
    };

    refreshOpenWorkBadges();
    const interval = window.setInterval(refreshOpenWorkBadges, 30000);
    onCleanup(() => {
      window.clearInterval(interval);
    });
  });

  createEffect(() => {
    if (isLoading() || needsAuth() || bootstrapFailed() || !hasAuth()) {
      setBackendHealthy(false);
      return;
    }

    if (connected()) {
      setBackendHealthy(true);
      return;
    }

    void checkBackendHealth();
    const interval = window.setInterval(
      () => {
        void checkBackendHealth();
      },
      reconnecting() ? 5000 : 15000,
    );

    onCleanup(() => {
      window.clearInterval(interval);
    });
  });

  const handleThemeChange = async (newPreference: ThemePreference) => {
    applyThemePreferenceLocally(newPreference);
    logger.info('Theme changed', {
      pref: newPreference,
      active: computeIsDark(newPreference) ? 'dark' : 'light',
    });

    if (!needsAuth()) {
      try {
        await SettingsAPI.updateSystemSettings({ theme: newPreference });
        logger.info('Theme preference saved to server');
      } catch (error) {
        logger.error('Failed to save theme preference to server', error);
      }
    }
  };

  onMount(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const systemThemeListener = (event: MediaQueryListEvent) => {
      if (themePreference() === 'system') {
        const isDark = event.matches;
        setDarkMode(isDark);
        applyThemeClass(isDark);
      }
    };
    mediaQuery.addEventListener('change', systemThemeListener);

    const handleRemoteThemeChange = (theme?: string) => {
      if (!theme) return;
      logger.info('Received theme change from another browser instance', { theme });
      applyThemePreferenceLocally(normalizeThemePreference(theme));
    };

    const handleWebSocketReconnected = () => {
      logger.info('WebSocket reconnected, refreshing alert configuration');
      void alertsActivation.refreshConfig();
      void alertsActivation.refreshActiveAlerts();
      // The estate can gain or lose a platform while the socket is down.
      void loadPlatformAdmission();
    };

    const handleOrganizationsChanged = () => {
      logger.info('Organization membership changed, refreshing organization list');
      void loadOrganizations();
    };

    eventBus.on('theme_changed', handleRemoteThemeChange);
    eventBus.on('websocket_reconnected', handleWebSocketReconnected);
    eventBus.on('organizations_changed', handleOrganizationsChanged);

    onCleanup(() => {
      mediaQuery.removeEventListener('change', systemThemeListener);
      eventBus.off('theme_changed', handleRemoteThemeChange);
      eventBus.off('websocket_reconnected', handleWebSocketReconnected);
      eventBus.off('organizations_changed', handleOrganizationsChanged);
    });
  });

  onMount(async () => {
    logger.debug('[App] Starting auth check...');
    const justLoggedOut = localStorage.getItem('just_logged_out');

    try {
      const securityResponse = await apiFetch('/api/security/status');

      if (securityResponse.status === 401) {
        logger.warn(
          '[App] Security status request returned 401. Clearing stored credentials and showing login.',
        );
        try {
          const { clearAuth } = await import('@/utils/apiClient');
          clearAuth();
        } catch (clearError) {
          logger.warn('[App] Failed to clear stored auth after 401', clearError);
        }
        aiAvailabilityStore.setEnabled(false);
        setHasAuth(false);
        setNeedsAuth(true);
        setIsLoading(false);
        return;
      }

      if (!securityResponse.ok) {
        throw new Error(`Security status request failed with status ${securityResponse.status}`);
      }

      const securityData = (await securityResponse.json()) as SecurityStatus & {
        hasAuthentication?: boolean;
        hasProxyAuth?: boolean;
        proxyAuthUsername?: string;
        proxyAuthLogoutURL?: string;
        ssoEnabled?: boolean;
        ssoSessionUsername?: string;
        ssoSessionDisplayName?: string;
        ssoLogoutURL?: string;
      };
      if (!isRecord(securityData) || typeof securityData.hasAuthentication !== 'boolean') {
        throw new Error('Authentication discovery is incomplete');
      }
      logger.debug('[App] Security status fetched', securityData);
      applySecurityStatus(securityData);

      if (justLoggedOut) {
        localStorage.removeItem('just_logged_out');
        logger.debug('[App] User logged out, showing login page');
        setHasAuth(true);
        setNeedsAuth(true);
        return;
      }

      const authConfigured = securityData.hasAuthentication;
      setHasAuth(authConfigured);

      if (securityData.hasProxyAuth && securityData.proxyAuthUsername) {
        logger.info('[App] Proxy auth detected', { user: securityData.proxyAuthUsername });
        setProxyAuthInfo({
          username: securityData.proxyAuthUsername,
          logoutURL: securityData.proxyAuthLogoutURL,
        });
        if (!(await beginAuthenticatedRuntime())) {
          setIsLoading(false);
          return;
        }
        void syncVersionInfoFromUpdateStore();
        setIsLoading(false);
        return;
      }

      if (securityData.ssoEnabled && securityData.ssoSessionUsername) {
        const ssoDisplayName =
          securityData.ssoSessionDisplayName || securityData.ssoSessionUsername;
        logger.info('[App] SSO session detected', { user: ssoDisplayName });
        setHasAuth(true);
        setProxyAuthInfo({
          username: ssoDisplayName,
          logoutURL: securityData.ssoLogoutURL,
        });
        if (!(await beginAuthenticatedRuntime())) {
          setIsLoading(false);
          return;
        }
        void syncVersionInfoFromUpdateStore();
        setIsLoading(false);
        return;
      }

      if (!authConfigured) {
        logger.info('[App] No auth configured, showing Login/FirstRunSetup');
        setNeedsAuth(true);
        setIsLoading(false);
        return;
      }

      if (
        isPreAuthLoginBootstrapPath(window.location.pathname) &&
        !hasLocalAuthBootstrapHint() &&
        !hasSSOCallbackSuccessHint()
      ) {
        logger.debug('[App] Public login bootstrap has no local auth hint yet', {
          pathname: window.location.pathname,
        });
        setNeedsAuth(true);
        return;
      }

      await beginAuthenticatedRuntime();
    } catch (error) {
      logger.error('Auth check error', error);
      // A transport, discovery or permission failure is not an expired session.
      // Keep the saved credentials and tenant for an explicit connection retry,
      // but admit neither the authenticated shell nor first-run setup.
      setBootstrapFailed(true);
      aiAvailabilityStore.setEnabled(false);
      setHasAuth(false);
      setNeedsAuth(true);
    } finally {
      setIsLoading(false);
    }
  });

  const handleLogin = () => {
    window.location.reload();
  };

  const [isLoggingOut, setIsLoggingOut] = createSignal(false);
  let logoutController: AbortController | undefined;
  let logoutDisposed = false;
  onCleanup(() => {
    logoutDisposed = true;
    logoutController?.abort();
  });

  const handleLogout = async () => {
    if (logoutDisposed || isLoggingOut()) return;
    setIsLoggingOut(true);
    const destination = proxyAuthInfo()?.logoutURL || '/';
    const controller = new AbortController();
    logoutController = controller;
    const aborted = new Promise<never>((_resolve, reject) => {
      controller.signal.addEventListener('abort', () => reject(new Error('Sign-out aborted')), {
        once: true,
      });
    });
    const timeout = window.setTimeout(() => controller.abort(), 15_000);

    try {
      const { apiFetch: runtimeApiFetch, clearAuth } = await Promise.race([
        import('@/utils/apiClient'),
        aborted,
      ]);
      const response = await Promise.race([
        runtimeApiFetch('/api/logout', {
          method: 'POST',
          // Keep normal credentials and CSRF, including token-only browsers.
          // The endpoint ends only the cookie session; it does not revoke tokens.
          skipOrgContext: true,
          // Also stops a late CSRF preparation from dispatching after abort.
          retry: false,
          redirect: 'error',
          signal: controller.signal,
        }),
        aborted,
      ]);
      const acknowledgement = response.ok ? await Promise.race([response.json(), aborted]) : null;
      if (acknowledgement?.success !== true) {
        throw new Error('Pulse did not acknowledge sign-out');
      }
      controller.signal.throwIfAborted();

      // One blocked storage operation must not prevent the remaining cleanup.
      let cleanupFailed = false;
      const clean = (operation: () => void) => {
        try {
          operation();
        } catch {
          cleanupFailed = true;
        }
      };
      clean(clearAuth);
      // Older Workloads versions persisted an org-only copy of server
      // metadata. New owners never read/write it; remove every legacy scope
      // only after withdrawal is acknowledged. Snapshot keys before removal.
      const guestMetadataKeys = new Set<string>([STORAGE_KEYS.GUEST_METADATA]);
      clean(() => {
        for (let index = 0; index < localStorage.length; index += 1) {
          const key = localStorage.key(index);
          if (key?.startsWith(`${STORAGE_KEYS.GUEST_METADATA}.`)) guestMetadataKeys.add(key);
        }
      });
      for (const key of [
        STORAGE_KEYS.AUTH,
        ...guestMetadataKeys,
        STORAGE_KEYS.DOCKER_METADATA,
        STORAGE_KEYS.DOCKER_METADATA + '_hosts',
      ]) {
        clean(() => localStorage.removeItem(key));
      }
      clean(() => sessionStorage.clear());
      clean(() => sessionStorage.setItem(SESSION_STORAGE_KEYS.DEMO_AUTO_LOGIN, 'suppressed'));
      clean(() => localStorage.setItem('just_logged_out', 'true'));
      aiAvailabilityStore.setEnabled(false);
      clean(shutdownGlobalWebSocketStore);
      setWsStore(null);
      setNeedsAuth(true);

      if (cleanupFailed) {
        showToast(
          'error',
          'Browser cleanup incomplete',
          'Pulse ended this session, but could not finish browser cleanup. Close this tab. Your proxy or identity-provider session may still be active.',
        );
        return;
      }
      // Provider logout is still required for upstream sessions. Navigate only
      // after Pulse has acknowledged local withdrawal and browser cleanup.
      window.location.href = destination;
    } catch {
      if (!logoutDisposed) {
        showToast(
          'error',
          'Sign-out not confirmed',
          'Your session may still be active. Check your connection and try Sign out again.',
        );
      }
    } finally {
      window.clearTimeout(timeout);
      logoutController = undefined;
      if (!logoutDisposed) setIsLoggingOut(false);
    }
  };

  const enhancedStore = () => wsStore();

  return {
    isLoading,
    bootstrapFailed,
    needsAuth,
    hasAuth,
    organizations,
    activeOrgID,
    orgsLoading,
    securityStatus,
    proxyAuthInfo,
    state,
    runtimeStateResolved,
    platformAdmission,
    connected,
    backendHealthy,
    connectionStatus,
    reconnecting,
    lastUpdateText,
    versionInfo,
    showOrgSwitcher,
    themePreference,
    darkMode,
    handleThemeChange,
    handleOrgSwitch,
    handleLogin,
    handleLogout,
    isLoggingOut,
    enhancedStore,
  };
};