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
This commit is contained in:
1 parent
9c017b85cf
commit
83262b3593
8 files changed
+119
-11
No files matched your search
@@ -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<undefined, MatrixError, []>(
|
||||
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 (
|
||||
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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<void> =>
|
||||
new Promise((resolve) => {
|
||||
new Promise((resolve, reject) => {
|
||||
const state = mx.getSyncState();
|
||||
if (isClientReadyForNotifications(state)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
let syncTimer: ReturnType<typeof setTimeout> | 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<Map<string, () => 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();
|
||||
};
|
||||
}, [
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -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<HTMLDivElement, SpaceMenuProps>(({ room, requestClo
|
||||
};
|
||||
|
||||
const handleOpenTimeline = () => {
|
||||
debugLog.info('ui', 'Space timeline opened', { roomId: room.roomId });
|
||||
navigateRoom(room.roomId);
|
||||
requestClose();
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user