From 83262b359398049a6c1eb64ce498e59b76d24ecb Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Fri, 13 Mar 2026 11:08:58 -0400 Subject: [PATCH] feat: enhance debug logging and fix background notifications Debug logging: - Add logging to LeaveRoomPrompt, CreateRoom, Space, AccountSwitcherTab - Add build version to debug log exports - Add network/sync logging to initMatrix Background notifications: - Add explicit listener cleanup before stopping clients - Add exponential backoff retry for failed background clients (5 attempts) - Add 30s timeout to waitForSync to prevent indefinite hangs - Use useMemo for inactive sessions array - Track cleanup callbacks per client --- .../leave-room-prompt/LeaveRoomPrompt.tsx | 7 +- src/app/features/create-room/CreateRoom.tsx | 19 +++++ .../developer-tools/DebugLogViewer.tsx | 2 + .../pages/client/BackgroundNotifications.tsx | 73 +++++++++++++++++-- .../client/sidebar/AccountSwitcherTab.tsx | 5 ++ src/app/pages/client/space/Space.tsx | 4 + src/app/utils/debugLogger.ts | 1 + src/client/initMatrix.ts | 19 ++++- 8 files changed, 119 insertions(+), 11 deletions(-) diff --git a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx index 21b108e6..36cdd89d 100644 --- a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx +++ b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx @@ -20,6 +20,9 @@ import { MatrixError } from '$types/matrix-sdk'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { stopPropagation } from '$utils/keyboard'; +import { createDebugLogger } from '$utils/debugLogger'; + +const debugLog = createDebugLogger('LeaveRoomPrompt'); type LeaveRoomPromptProps = { roomId: string; @@ -31,6 +34,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro const [leaveState, leaveRoom] = useAsyncCallback( useCallback(async () => { + debugLog.info('ui', 'Leave room button clicked', { roomId }); mx.leave(roomId); }, [mx, roomId]) ); @@ -41,9 +45,10 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro useEffect(() => { if (leaveState.status === AsyncStatus.Success) { + debugLog.info('ui', 'Successfully left room', { roomId }); onDone(); } - }, [leaveState, onDone]); + }, [leaveState, onDone, roomId]); return ( }> diff --git a/src/app/features/create-room/CreateRoom.tsx b/src/app/features/create-room/CreateRoom.tsx index 38716c45..b4da5132 100644 --- a/src/app/features/create-room/CreateRoom.tsx +++ b/src/app/features/create-room/CreateRoom.tsx @@ -42,6 +42,9 @@ import { RoomType } from '$types/matrix/room'; import { CreateRoomTypeSelector } from '$components/create-room/CreateRoomTypeSelector'; import { getRoomIconSrc } from '$utils/room'; import { ErrorCode } from '../../cs-errorcode'; +import { createDebugLogger } from '$utils/debugLogger'; + +const debugLog = createDebugLogger('CreateRoom'); const getCreateRoomAccessToIcon = (access: CreateRoomAccess, type?: CreateRoomType) => { const isVoiceRoom = type === CreateRoomType.VoiceRoom; @@ -139,6 +142,16 @@ export function CreateRoomForm({ let roomType: RoomType | undefined; if (type === CreateRoomType.VoiceRoom) roomType = RoomType.Call; + debugLog.info('ui', 'Create room button clicked', { + roomName, + access, + type, + publicRoom, + encryption, + hasParent: !!space, + parentRoomId: space?.roomId, + }); + create({ version: selectedRoomVersion, type: roomType, @@ -152,6 +165,12 @@ export function CreateRoomForm({ allowFederation: federation, additionalCreators: allowAdditionalCreators ? additionalCreators : undefined, }).then((roomId) => { + debugLog.info('ui', 'Room created successfully', { + roomId, + roomName, + access, + type, + }); if (alive()) { onCreate?.(roomId); } diff --git a/src/app/features/settings/developer-tools/DebugLogViewer.tsx b/src/app/features/settings/developer-tools/DebugLogViewer.tsx index ae29edb2..6f3de2ae 100644 --- a/src/app/features/settings/developer-tools/DebugLogViewer.tsx +++ b/src/app/features/settings/developer-tools/DebugLogViewer.tsx @@ -202,6 +202,7 @@ export function DebugLogViewer() { jsonData = JSON.stringify( { exportedAt: new Date().toISOString(), + build: `v${APP_VERSION}${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`, filters: { level: filterLevel !== 'all' ? filterLevel : 'none', category: filterCategory !== 'all' ? filterCategory : 'none', @@ -249,6 +250,7 @@ export function DebugLogViewer() { jsonData = JSON.stringify( { exportedAt: new Date().toISOString(), + build: `v${APP_VERSION}${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`, filters: { level: filterLevel !== 'all' ? filterLevel : 'none', category: filterCategory !== 'all' ? filterCategory : 'none', diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index ffb7da76..c294aef7 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useMemo, useRef } from 'react'; import { ClientEvent, createClient, @@ -70,21 +70,29 @@ const startBackgroundClient = async ( /** * Wait for the background client to finish its initial sync so that * push rules and account data are available before processing events. + * Rejects after 30 seconds so callers can handle a stalled client instead + * of blocking indefinitely. */ const waitForSync = (mx: MatrixClient): Promise => - new Promise((resolve) => { + new Promise((resolve, reject) => { const state = mx.getSyncState(); if (isClientReadyForNotifications(state)) { resolve(); return; } + let syncTimer: ReturnType | undefined; const onSync = (newState: SyncState) => { if (isClientReadyForNotifications(newState)) { + if (syncTimer !== undefined) clearTimeout(syncTimer); mx.removeListener(ClientEvent.Sync, onSync); resolve(); } }; mx.on(ClientEvent.Sync, onSync); + syncTimer = setTimeout(() => { + mx.removeListener(ClientEvent.Sync, onSync); + reject(new Error('background client sync timed out')); + }, 30_000); }); export function BackgroundNotifications() { @@ -122,10 +130,18 @@ export function BackgroundNotifications() { setBackgroundUnreadsRef.current = setBackgroundUnreads; const setInAppBannerRef = useRef(setInAppBanner); setInAppBannerRef.current = setInAppBanner; + // Per-client listener teardown callbacks, so we can explicitly remove event + // listeners before stopping a background client. + const clientCleanupRef = useRef void>>(new Map()); - const inactiveSessions = sessions.filter( - (s) => s.userId !== (activeSessionId ?? sessions[0]?.userId) + const inactiveSessions = useMemo( + () => sessions.filter((s) => s.userId !== (activeSessionId ?? sessions[0]?.userId)), + [sessions, activeSessionId] ); + // Ref so retry setTimeout callbacks can access the current session list + // without stale closures. + const inactiveSessionsRef = useRef(inactiveSessions); + inactiveSessionsRef.current = inactiveSessions; interface NotifyOptions { /** Title shown in the notification banner. */ @@ -194,6 +210,8 @@ export function BackgroundNotifications() { current.forEach((mx, userId) => { if (!activeIds.has(userId)) { + clientCleanupRef.current.get(userId)?.(); + clientCleanupRef.current.delete(userId); stopClient(mx); current.delete(userId); // Clear the background unread badge when this session is no longer a background account. @@ -205,11 +223,14 @@ export function BackgroundNotifications() { } }); - inactiveSessions.forEach((session) => { - const alreadyRunning = current.has(session.userId); - if (alreadyRunning) return; + // startSession handles init, listener teardown tracking, and retry-on-failure. + // Using a named function (vs. inline .then) lets the .catch() schedule a + // fresh retry referencing the latest session from inactiveSessionsRef. + const startSession = (session: Session, attempt = 0): void => { + let sessionMx: MatrixClient | undefined; startBackgroundClient(session, clientConfig.slidingSync) .then(async (mx) => { + sessionMx = mx; current.set(session.userId, mx); await waitForSync(mx); @@ -471,6 +492,12 @@ export function BackgroundNotifications() { }; mx.on(RoomEvent.Timeline, handleTimeline as unknown as (...args: unknown[]) => void); + + // Register teardown so these listeners are removed when this client is stopped. + clientCleanupRef.current.set(session.userId, () => { + mx.off(ClientEvent.AccountData as any, handleAccountData); + mx.off(RoomEvent.Timeline, handleTimeline as unknown as (...args: unknown[]) => void); + }); }) .catch((err) => { log.error('failed to start background client for', session.userId, err); @@ -478,11 +505,41 @@ export function BackgroundNotifications() { userId: session.userId, error: err, }); + + // Remove the stuck/failed client from current so future runs (or the + // retry below) can attempt a fresh start. + if (sessionMx && current.get(session.userId) === sessionMx) { + clientCleanupRef.current.get(session.userId)?.(); + clientCleanupRef.current.delete(session.userId); + current.delete(session.userId); + stopClient(sessionMx); + } + + // Retry with exponential backoff, up to 5 attempts (5s, 10s, 20s, 40s, 60s cap). + if (attempt < 5) { + const retryDelay = Math.min(5_000 * 2 ** attempt, 60_000); + setTimeout(() => { + const latestSession = inactiveSessionsRef.current.find( + (s) => s.userId === session.userId + ); + if (latestSession && !current.has(session.userId)) { + startSession(latestSession, attempt + 1); + } + }, retryDelay); + } }); + }; + + inactiveSessions.forEach((session) => { + if (!current.has(session.userId)) startSession(session); }); return () => { - current.forEach((mx) => stopClient(mx)); + current.forEach((mx, userId) => { + clientCleanupRef.current.get(userId)?.(); + clientCleanupRef.current.delete(userId); + stopClient(mx); + }); current.clear(); }; }, [ diff --git a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx index 1b722d24..39438b11 100644 --- a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx +++ b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx @@ -42,10 +42,12 @@ import { useSessionProfiles } from '$hooks/useSessionProfiles'; import { Settings } from '$features/settings'; import { Modal500 } from '$components/Modal500'; import { createLogger } from '$utils/debug'; +import { createDebugLogger } from '$utils/debugLogger'; import { useClientConfig } from '$hooks/useClientConfig'; import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; const log = createLogger('AccountSwitcherTab'); +const debugLog = createDebugLogger('AccountSwitcherTab'); function AccountRow({ session, @@ -246,6 +248,9 @@ export function AccountSwitcherTab() { }; const handleOpenSettings = () => { + debugLog.info('ui', 'Settings button clicked', { + userId: activeSession?.userId, + }); setMenuAnchor(undefined); setSettingsOpen(true); }; diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index bc88b9af..aae2f2d7 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -72,6 +72,9 @@ import { mobileOrTablet } from '$utils/user-agent'; import { lastVisitedRoomIdAtom } from '$state/room/lastRoom'; import { SwipeableOverlayWrapper } from '$components/SwipeableOverlayWrapper'; import { useCallEmbed } from '$hooks/useCallEmbed'; +import { createDebugLogger } from '$utils/debugLogger'; + +const debugLog = createDebugLogger('Space'); type SpaceMenuProps = { room: Room; @@ -122,6 +125,7 @@ const SpaceMenu = forwardRef(({ room, requestClo }; const handleOpenTimeline = () => { + debugLog.info('ui', 'Space timeline opened', { roomId: room.roomId }); navigateRoom(room.roomId); requestClose(); }; diff --git a/src/app/utils/debugLogger.ts b/src/app/utils/debugLogger.ts index 3fe70eb5..18829d9f 100644 --- a/src/app/utils/debugLogger.ts +++ b/src/app/utils/debugLogger.ts @@ -140,6 +140,7 @@ class DebugLoggerService { return JSON.stringify( { exportedAt: new Date().toISOString(), + build: `v${APP_VERSION}${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`, logsCount: this.logs.length, logs: this.logs.map((log) => ({ ...log, diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 6b4adbc1..45c6fdd0 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -433,8 +433,12 @@ export const startClient = async ( if (await shouldBootstrapClassicOnColdCache()) { log.log('startClient cold-cache bootstrap: using classic sync for this run', mx.getUserId()); await startClassicSync(false, 'cold_cache_bootstrap'); - waitForClientReady(mx, COLD_CACHE_BOOTSTRAP_TIMEOUT_MS).catch(() => { - /* ignore */ + waitForClientReady(mx, COLD_CACHE_BOOTSTRAP_TIMEOUT_MS).catch((err) => { + debugLog.warn('network', 'Cold cache bootstrap timed out', { + userId: mx.getUserId(), + timeout: `${COLD_CACHE_BOOTSTRAP_TIMEOUT_MS}ms`, + error: err instanceof Error ? err.message : String(err), + }); }); return; } @@ -454,6 +458,11 @@ export const startClient = async ( }); if (!supported) { log.warn('Sliding Sync unavailable, falling back to classic sync for', mx.getUserId()); + debugLog.warn('network', 'Sliding Sync probe failed, falling back to classic sync', { + userId: mx.getUserId(), + proxyBaseUrl: resolvedProxyBaseUrl, + probeTimeout: `${probeTimeoutMs}ms`, + }); await startClassicSync(true, 'probe_failed_fallback'); return; } @@ -484,6 +493,12 @@ export const startClient = async ( slidingSync: manager.slidingSync, }); } catch (err) { + debugLog.error('network', 'Failed to start client with sliding sync', { + error: err instanceof Error ? err.message : String(err), + userId: mx.getUserId(), + proxyBaseUrl: resolvedProxyBaseUrl, + stack: err instanceof Error ? err.stack : undefined, + }); disposeSlidingSync(mx); throw err; }