import { Box, Button, config, Dialog, IconButton, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; import { Icon, Icons } from '../../components/icons'; import { ClientEvent, HttpApiEvent, HttpApiEventHandlerMap, MatrixClient, SyncState, } from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; import { clearCacheAndReload, clearLoginData, initClient, logoutClient, startClient, } from '../../../client/initMatrix'; import { SplashScreen } from '../../components/splash-screen'; import { ClientLoading } from './ClientLoading'; import { ServerConfigsLoader } from '../../components/ServerConfigsLoader'; import { CapabilitiesProvider } from '../../hooks/useCapabilities'; import { MediaConfigProvider } from '../../hooks/useMediaConfig'; import { MatrixClientProvider } from '../../hooks/useMatrixClient'; import { PluginLoader } from '../../features/settings/plugins'; import { SpecVersions } from './SpecVersions'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { useSyncState } from '../../hooks/useSyncState'; import { stopPropagation } from '../../utils/keyboard'; import { useAtomValue } from 'jotai'; import { allRoomsAtom, useBindAllRoomsAtom } from '../../state/room-list/roomList'; import { mDirectAtom, useBindMDirectAtom } from '../../state/mDirectList'; import { roomToParentsAtom, useBindRoomToParentsAtom } from '../../state/room/roomToParents'; import { AuthMetadataProvider } from '../../hooks/useAuthMetadata'; import { getCurrentSession } from '../../state/sessions'; import { CallProviderWrapper } from '../../features/call/CallProviderWrapper'; import { isTauriMobile, startBackgroundSync, stopBackgroundSync } from '../../utils/tauri'; import { TitleBar } from '../../components/title-bar'; import { AccountSwitcher } from '../../components/account-switcher'; import { getLoginPath, withSearchParam } from '../pathUtils'; import { useViewTransitions } from '../../hooks/useViewTransitions'; const useLogoutListener = (mx?: MatrixClient) => { useEffect(() => { const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { mx?.stopClient(); await mx?.clearStores(); window.localStorage.clear(); window.location.reload(); }; mx?.on(HttpApiEvent.SessionLoggedOut, handleLogout); return () => { mx?.removeListener(HttpApiEvent.SessionLoggedOut, handleLogout); }; }, [mx]); }; /** * Hook to handle visibility changes and restart sync on mobile * When the app goes to background and comes back, sync may be stale/stopped */ const useVisibilitySync = (mx?: MatrixClient) => { useEffect(() => { if (!mx || !isTauriMobile()) return; const handleVisibilityChange = () => { if (document.visibilityState === 'visible') { console.log('[useVisibilitySync] App became visible, checking sync state'); const syncState = mx.getSyncState(); console.log('[useVisibilitySync] Current sync state:', syncState); // If sync is not running or errored, restart it if (!mx.clientRunning || syncState === SyncState.Error || syncState === SyncState.Stopped || syncState === null) { console.log('[useVisibilitySync] Restarting sync...'); startClient(mx).catch((err) => { console.error('[useVisibilitySync] Failed to restart sync:', err); }); } else { // Force a sync even if client is running (to catch up quickly) console.log('[useVisibilitySync] Triggering immediate sync'); mx.retryImmediately(); } } }; document.addEventListener('visibilitychange', handleVisibilityChange); // Also handle resume event for mobile (if available) window.addEventListener('resume', handleVisibilityChange); return () => { document.removeEventListener('visibilitychange', handleVisibilityChange); window.removeEventListener('resume', handleVisibilityChange); }; }, [mx]); }; /** * Hook to start/stop native Rust background sync on mobile * This allows notifications to work even when the app is backgrounded */ const useBackgroundSync = (mx?: MatrixClient) => { useEffect(() => { if (!mx || !isTauriMobile()) return; // Start background sync with credentials from the Matrix client const startSync = async () => { try { const homeserverUrl = mx.getHomeserverUrl(); const userId = mx.getUserId(); const accessToken = mx.getAccessToken(); const deviceId = mx.getDeviceId(); if (!homeserverUrl || !userId || !accessToken || !deviceId) { console.warn('[useBackgroundSync] Missing credentials, cannot start background sync'); return; } await startBackgroundSync({ homeserverUrl, userId, accessToken, deviceId, }); console.log('[useBackgroundSync] Background sync started'); } catch (err) { console.error('[useBackgroundSync] Failed to start background sync:', err); } }; startSync(); // Stop background sync on cleanup return () => { stopBackgroundSync().catch((err) => { console.error('[useBackgroundSync] Failed to stop background sync:', err); }); }; }, [mx]); }; /** * Binds the atoms the chat UI reads while the splash is still up. Without this, * they are only bound after the splash hides, so the first paint shows the empty * state ("No Direct Messages") for a moment. * * Only the context-free bindings go here: the rest (unread, typing, auto-join) * needs the RoomsNotificationPreferences provider, which lives inside children. */ function ClientAtomBinder({ mx }: { mx: MatrixClient }) { useBindMDirectAtom(mx, mDirectAtom); useBindAllRoomsAtom(mx, allRoomsAtom); useBindRoomToParentsAtom(mx, roomToParentsAtom); return null; } type ClientRootProps = { children: ReactNode; }; export function ClientRoot({ children }: ClientRootProps) { const [loading, setLoading] = useState(true); const mxRef = useRef(undefined); const recoverInFlight = useRef(false); // Hold the splash briefly after chats are loaded so the space particles // finish animating before the UI swaps in. const splashHoldTimer = useRef(undefined); // Grace window for the first network sync to land after the cache is ready; // hide anyway if we are offline so the UI is never blocked. const firstNetworkSyncGrace = useRef(undefined); // Hard deadline so a sync that never lands (offline, empty store, errored // first sync) can not leave the splash up forever. const splashDeadline = useRef(undefined); const scheduleHide = useCallback((reason?: string) => { if (splashHoldTimer.current !== undefined) return; if (reason) console.log(`[ClientRoot] Hiding splash: ${reason}`); splashHoldTimer.current = window.setTimeout(() => { splashHoldTimer.current = undefined; setLoading(false); }, 1500); }, []); // The UI renders chats from the room-list atoms, which are filled by // ClientAtomBinder while the splash is still up. Gate the hide on those atoms // so the first paint after the splash already contains the chats. const roomsAtom = useAtomValue(allRoomsAtom); const directsAtom = useAtomValue(mDirectAtom); const chatsReady = roomsAtom.length > 0 && directsAtom.size > 0 && roomsAtom.some((roomId) => directsAtom.has(roomId)); const tryHide = useCallback( (reason: string): boolean => { if (chatsReady) { scheduleHide(reason); return true; } return false; }, [chatsReady, scheduleHide] ); // The atoms fill in as the store restores the cache; hide as soon as they do. useEffect(() => { if (loading && chatsReady) scheduleHide('chats populated'); }, [loading, chatsReady, scheduleHide]); const { baseUrl } = getCurrentSession() ?? {}; // Enable view transitions for smooth navigation useViewTransitions(); const [loadState, loadMatrix] = useAsyncCallback( useCallback(() => { const session = getCurrentSession(); if (!session) { throw new Error('No session Found!'); } return initClient(session); }, []) ); const mx = loadState.status === AsyncStatus.Success ? loadState.data : undefined; useEffect(() => { mxRef.current = mx; }, [mx]); useEffect(() => { return () => { if (splashHoldTimer.current !== undefined) { window.clearTimeout(splashHoldTimer.current); } if (firstNetworkSyncGrace.current !== undefined) { window.clearTimeout(firstNetworkSyncGrace.current); } if (splashDeadline.current !== undefined) { window.clearTimeout(splashDeadline.current); } }; }, []); const [startState, startMatrix] = useAsyncCallback( useCallback((m) => startClient(m), []) ); useLogoutListener(mx); useVisibilitySync(mx); useBackgroundSync(mx); useEffect(() => { if (loadState.status === AsyncStatus.Idle) { loadMatrix(); } }, [loadState, loadMatrix]); useEffect(() => { if (mx && !mx.clientRunning) { startMatrix(mx); } }, [mx, startMatrix]); // Cached rooms and m.direct land asynchronously from the IndexedDB store, so // watch for them while loading and hide as soon as the chats are populated. useEffect(() => { if (!mx || !loading) return undefined; const check = () => tryHide('chats populated'); check(); console.log( '[ClientRoot] Splash gate:', mx.getSyncState(), `${roomsAtom.length} rooms in atom`, `${directsAtom.size} m.direct` ); // Prepared can fire before this listener attaches, so look at the current // state too, and never let the splash outlive the deadline. const syncState = mx.getSyncState(); if (syncState === SyncState.Prepared || syncState === SyncState.Syncing) check(); if (splashDeadline.current === undefined) { splashDeadline.current = window.setTimeout(() => { splashDeadline.current = undefined; scheduleHide('deadline reached, showing whatever the cache has'); }, 10000); } const poll = window.setInterval(check, 400); mx.on(ClientEvent.Room, check); mx.on(ClientEvent.AccountData, check); return () => { window.clearInterval(poll); mx.removeListener(ClientEvent.Room, check); mx.removeListener(ClientEvent.AccountData, check); }; }, [mx, loading, chatsReady, tryHide, scheduleHide, roomsAtom, directsAtom]); // Timeout if sync takes too long - nudge the client rather than immediately erroring useEffect(() => { if (!mx || !loading) return; const timeout = setTimeout(() => { console.warn('[ClientRoot] Sync taking too long, nudging client...'); mx.retryImmediately(); }, 30000); return () => clearTimeout(timeout); }, [mx, loading]); // Hold the splash until the chats are actually populated, then keep it a // moment longer so the space particles finish animating. // Soft-recover from sync ERROR (e.g. sleep/wake with no network); the grace // window ensures we never block the UI when offline. useSyncState( mx, useCallback((state, prevState, data) => { const client = mxRef.current; if (state === SyncState.Prepared || state === SyncState.Syncing) { if (state === SyncState.Prepared) { console.log( '[ClientRoot] Prepared from', prevState ?? 'nothing', data?.fromCache ? '(cache)' : '(network)' ); } if (tryHide(data?.fromCache ? 'cache populated' : 'first network sync')) { return; } if (data?.fromCache) { // Cache-only prepared: the room list is still being restored, so wait // for it, but hide anyway once the grace expires so we never block the // UI when offline. if (firstNetworkSyncGrace.current === undefined) { firstNetworkSyncGrace.current = window.setTimeout(() => { firstNetworkSyncGrace.current = undefined; scheduleHide('cache grace expired'); }, 5000); } } else { // First network sync completed: whatever we have is what the UI shows. scheduleHide('first network sync completed'); } recoverInFlight.current = false; return; } if (state !== SyncState.Error || !client) { return; } // Sync failed (no network, first sync never landed). Show whatever the // cache restored instead of leaving the splash up. if (client.getRooms().length > 0) scheduleHide('sync error with cached chats'); if (recoverInFlight.current) { return; } recoverInFlight.current = true; console.warn('[ClientRoot] Sync error after sleep/network blip, soft-recovering...'); const recover = () => { if (!mxRef.current) { recoverInFlight.current = false; return; } const c = mxRef.current; if (!c.clientRunning) { startClient(c) .catch((err) => console.warn('[ClientRoot] Soft recover startClient failed:', err)) .finally(() => { recoverInFlight.current = false; }); return; } try { c.retryImmediately(); } catch (err) { console.warn('[ClientRoot] Soft recover retryImmediately failed:', err); } recoverInFlight.current = false; }; // Give Wi‑Fi a moment to come back after lid open / resume window.setTimeout(recover, 1500); }, [tryHide, scheduleHide]) ); // Also nudge sync when the laptop wakes / network returns useEffect(() => { if (!mx) return; const nudge = () => { if (document.visibilityState !== 'visible') return; const syncState = mx.getSyncState(); if (syncState === SyncState.Error || syncState === SyncState.Reconnecting || !mx.clientRunning) { console.log('[ClientRoot] Online/visible again, nudging sync', syncState); if (!mx.clientRunning) { startClient(mx).catch(() => {}); } else { mx.retryImmediately(); } } }; window.addEventListener('online', nudge); document.addEventListener('visibilitychange', nudge); return () => { window.removeEventListener('online', nudge); document.removeEventListener('visibilitychange', nudge); }; }, [mx]); return ( {mx && } {(loadState.status === AsyncStatus.Error || startState.status === AsyncStatus.Error) && ( {loadState.status === AsyncStatus.Error && ( {`Failed to load. ${loadState.error.message}`} )} {startState.status === AsyncStatus.Error && ( {`Failed to start. ${startState.error.message}`} )} )} {loading || !mx ? ( ) : ( {(serverConfigs) => ( {children} )} )} ); }