diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 6cbf52de1..8627bb8e4 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -128,6 +128,7 @@ import { useImagePackRooms } from '$hooks/useImagePackRooms'; import { useComposingCheck } from '$hooks/useComposingCheck'; import { useSableCosmetics } from '$hooks/useSableCosmetics'; import { createLogger } from '$utils/debug'; +import { createDebugLogger } from '$utils/debugLogger'; import FocusTrap from 'focus-trap-react'; import { useQueryClient } from '@tanstack/react-query'; import { @@ -176,6 +177,7 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => }; const log = createLogger('RoomInput'); +const debugLog = createDebugLogger('RoomInput'); interface ReplyEventContent { 'm.relates_to'?: IEventRelation; } @@ -422,10 +424,16 @@ export const RoomInput = forwardRef( await Promise.all( contents.map((content) => - mx.sendMessage(roomId, content as any).catch((error: unknown) => { - log.error('failed to send uploaded message', { roomId }, error); - throw error; - }) + mx.sendMessage(roomId, content as any) + .then((res) => { + debugLog.info('message', 'Uploaded file message sent', { roomId, eventId: res.event_id, msgtype: content.msgtype }); + return res; + }) + .catch((error: unknown) => { + debugLog.error('message', 'Failed to send uploaded file message', { roomId, error: error instanceof Error ? error.message : String(error) }); + log.error('failed to send uploaded message', { roomId }, error); + throw error; + }) ) ); }; @@ -569,18 +577,27 @@ export const RoomInput = forwardRef( } else if (editingScheduledDelayId) { try { await cancelDelayedEvent(mx, editingScheduledDelayId); - mx.sendMessage(roomId, content as any); + debugLog.info('message', 'Sending message after cancelling scheduled event', { roomId, scheduledDelayId: editingScheduledDelayId }); + const res = await mx.sendMessage(roomId, content as any); + debugLog.info('message', 'Message sent successfully', { roomId, eventId: res.event_id }); invalidate(); setEditingScheduledDelayId(null); resetInput(); - } catch { + } catch (error) { + debugLog.error('message', 'Failed to send message after cancelling scheduled event', { roomId, error: error instanceof Error ? error.message : String(error) }); // Cancel failed — leave state intact for retry } } else { resetInput(); - mx.sendMessage(roomId, content as any).catch((error: unknown) => { - log.error('failed to send message', { roomId }, error); - }); + debugLog.info('message', 'Sending message', { roomId, msgtype: (content as any).msgtype }); + mx.sendMessage(roomId, content as any) + .then((res) => { + debugLog.info('message', 'Message sent successfully', { roomId, eventId: res.event_id }); + }) + .catch((error: unknown) => { + debugLog.error('message', 'Failed to send message', { roomId, error: error instanceof Error ? error.message : String(error) }); + log.error('failed to send message', { roomId }, error); + }); } }, [ editor, diff --git a/src/app/features/settings/developer-tools/DebugLogViewer.tsx b/src/app/features/settings/developer-tools/DebugLogViewer.tsx new file mode 100644 index 000000000..1c9ae8365 --- /dev/null +++ b/src/app/features/settings/developer-tools/DebugLogViewer.tsx @@ -0,0 +1,566 @@ +import { useEffect, useState, useCallback, useMemo } from 'react'; +import { useAtom, useAtomValue, useSetAtom } from 'jotai'; +import { Box, Text, Button, color, config, Badge, Menu, MenuItem, PopOut } from 'folds'; +import { SequenceCard } from '$components/sequence-card'; + +import { + debugLoggerEnabledAtom, + debugLogsAtom, + clearDebugLogsAtom, +} from '$state/debugLogger'; +import { LogEntry, getDebugLogger, LogLevel, LogCategory } from '$utils/debugLogger'; +import { SequenceCardStyle } from '$features/settings/styles.css'; + +const formatTimestamp = (timestamp: number): string => { + const date = new Date(timestamp); + return date.toLocaleTimeString('en-US', { + hour12: false, + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + fractionalSecondDigits: 3, + }); +}; + +const getLevelColor = (level: string): string => { + switch (level) { + case 'error': + return color.Critical.Main; + case 'warn': + return color.Warning.Main; + case 'info': + return color.Success.Main; + default: + return color.Secondary.Main; + } +}; + +const getCategoryBadgeVariant = ( + category: string +): 'Primary' | 'Secondary' | 'Success' | 'Warning' | 'Critical' => { + switch (category) { + case 'error': + return 'Critical'; + case 'sync': + return 'Primary'; + case 'notification': + return 'Success'; + case 'message': + return 'Secondary'; + case 'call': + return 'Warning'; + default: + return 'Secondary'; + } +}; + +function LogEntryItem({ entry }: { entry: LogEntry }) { + const [expanded, setExpanded] = useState(false); + + return ( + + + + + {entry.level.toUpperCase()} + + + {entry.category} + + + {formatTimestamp(entry.timestamp)} + + + [{entry.namespace}] + + + {entry.data && ( + + )} + + + {entry.message} + + {expanded && entry.data && ( + + + {JSON.stringify(entry.data, null, 2)} + + + )} + + ); +} + +export function DebugLogViewer() { + const [enabled, setEnabled] = useAtom(debugLoggerEnabledAtom); + const logs = useAtomValue(debugLogsAtom); + const clearLogs = useSetAtom(clearDebugLogsAtom); + const [autoScroll, setAutoScroll] = useState(true); + const scrollRef = useState(null)[0]; + const [filterLevel, setFilterLevel] = useState('all'); + const [filterCategory, setFilterCategory] = useState('all'); + + // Filter logs based on current filters + const filteredLogs = useMemo(() => { + if (filterLevel === 'all' && filterCategory === 'all') { + return logs; + } + + const debugLogger = getDebugLogger(); + return debugLogger.getFilteredLogs({ + level: filterLevel !== 'all' ? filterLevel : undefined, + category: filterCategory !== 'all' ? filterCategory : undefined, + }); + }, [logs, filterLevel, filterCategory]); + + // Auto-refresh logs when new entries arrive + useEffect(() => { + if (!enabled) return undefined; + + const debugLogger = getDebugLogger(); + const unsubscribe = debugLogger.addListener(() => { + // Trigger re-render by refreshing the atom + // This will be handled by the debugLogsAtom's refresh mechanism + }); + + return unsubscribe; + }, [enabled]); + + // Auto-scroll to bottom when new logs arrive + useEffect(() => { + if (autoScroll && scrollRef) { + scrollRef.scrollTop = scrollRef.scrollHeight; + } + }, [filteredLogs, autoScroll, scrollRef]); + + const handleExportLogs = useCallback( + (filtered: boolean) => { + const debugLogger = getDebugLogger(); + let jsonData: string; + + if (filtered && (filterLevel !== 'all' || filterCategory !== 'all')) { + // Export filtered logs + const logsToExport = debugLogger.getFilteredLogs({ + level: filterLevel !== 'all' ? filterLevel : undefined, + category: filterCategory !== 'all' ? filterCategory : undefined, + }); + jsonData = JSON.stringify( + { + exportedAt: new Date().toISOString(), + filters: { + level: filterLevel !== 'all' ? filterLevel : 'none', + category: filterCategory !== 'all' ? filterCategory : 'none', + }, + logsCount: logsToExport.length, + logs: logsToExport.map((log) => ({ + ...log, + timestamp: new Date(log.timestamp).toISOString(), + })), + }, + null, + 2 + ); + } else { + // Export all logs + jsonData = debugLogger.exportLogs(); + } + + const blob = new Blob([jsonData], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + const filterSuffix = filtered && (filterLevel !== 'all' || filterCategory !== 'all') + ? `-${filterCategory !== 'all' ? filterCategory : 'all'}-${filterLevel !== 'all' ? filterLevel : 'all'}` + : ''; + a.download = `sable-debug-logs${filterSuffix}-${new Date().toISOString()}.json`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }, + [filterLevel, filterCategory] + ); + + const handleCopyToClipboard = useCallback( + (filtered: boolean) => { + const debugLogger = getDebugLogger(); + let jsonData: string; + + if (filtered && (filterLevel !== 'all' || filterCategory !== 'all')) { + const logsToExport = debugLogger.getFilteredLogs({ + level: filterLevel !== 'all' ? filterLevel : undefined, + category: filterCategory !== 'all' ? filterCategory : undefined, + }); + jsonData = JSON.stringify( + { + exportedAt: new Date().toISOString(), + filters: { + level: filterLevel !== 'all' ? filterLevel : 'none', + category: filterCategory !== 'all' ? filterCategory : 'none', + }, + logsCount: logsToExport.length, + logs: logsToExport.map((log) => ({ + ...log, + timestamp: new Date(log.timestamp).toISOString(), + })), + }, + null, + 2 + ); + } else { + jsonData = debugLogger.exportLogs(); + } + + navigator.clipboard.writeText(jsonData); + }, + [filterLevel, filterCategory] + ); + + return ( + + + + Debug Log Status + + {enabled ? 'Active' : 'Inactive'} + + + + + Internal debug logging captures sync state, errors, notifications, messages, and call + events. Logs are stored in memory (max 1000 entries) and cleared when you close the app. + + + {/* Filter Controls */} + + + Filters: + + + setFilterCategory('all')} + disabled={filterCategory === 'all'} + > + All Categories + + setFilterCategory('sync')} + disabled={filterCategory === 'sync'} + > + Sync + + setFilterCategory('network')} + disabled={filterCategory === 'network'} + > + Network + + setFilterCategory('notification')} + disabled={filterCategory === 'notification'} + > + Notification + + setFilterCategory('message')} + disabled={filterCategory === 'message'} + > + Message + + setFilterCategory('call')} + disabled={filterCategory === 'call'} + > + Call + + setFilterCategory('general')} + disabled={filterCategory === 'general'} + > + General + + setFilterCategory('error')} + disabled={filterCategory === 'error'} + > + Error + + + } + > + {(targetRef) => ( + + )} + + + + setFilterLevel('all')} + disabled={filterLevel === 'all'} + > + All Levels + + setFilterLevel('debug')} + disabled={filterLevel === 'debug'} + > + Debug + + setFilterLevel('info')} + disabled={filterLevel === 'info'} + > + Info + + setFilterLevel('warn')} + disabled={filterLevel === 'warn'} + > + Warning + + setFilterLevel('error')} + disabled={filterLevel === 'error'} + > + Error + + + } + > + {(targetRef) => ( + + )} + + + {(filterLevel !== 'all' || filterCategory !== 'all') && ( + + )} + + + + + + + + + + + {enabled && ( + + + + Recent Logs ( + {filterLevel !== 'all' || filterCategory !== 'all' + ? `${filteredLogs.length}/${logs.length}` + : `${logs.length}/1000`} + ) + + + + + + {filteredLogs.length === 0 ? ( + + + {logs.length === 0 + ? 'No logs captured yet. Use the app to generate log entries.' + : 'No logs match the current filters.'} + + + ) : ( + filteredLogs.map((log) => ( + + )) + )} + + + )} + + + ); +} diff --git a/src/app/features/settings/developer-tools/DevelopTools.tsx b/src/app/features/settings/developer-tools/DevelopTools.tsx index d65c97db0..d230620ae 100644 --- a/src/app/features/settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/settings/developer-tools/DevelopTools.tsx @@ -11,6 +11,7 @@ import { copyToClipboard } from '$utils/dom'; import { SequenceCardStyle } from '$features/settings/styles.css'; import { AccountData } from './AccountData'; import { SyncDiagnostics } from './SyncDiagnostics'; +import { DebugLogViewer } from './DebugLogViewer'; type DeveloperToolsProps = { requestClose: () => void; @@ -120,6 +121,11 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { onSelect={setAccountDataType} /> )} + {developerTools && ( + + + + )} diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx index 08310d28d..c01cba410 100644 --- a/src/app/features/settings/notifications/PushNotifications.tsx +++ b/src/app/features/settings/notifications/PushNotifications.tsx @@ -1,5 +1,8 @@ import { MatrixClient } from '$types/matrix-sdk'; import { ClientConfig } from '../../../hooks/useClientConfig'; +import { createDebugLogger } from '$utils/debugLogger'; + +const debugLog = createDebugLogger('PushNotifications'); type PushSubscriptionState = [ PushSubscriptionJSON | null, @@ -8,12 +11,16 @@ type PushSubscriptionState = [ export async function requestBrowserNotificationPermission(): Promise { if (!('Notification' in window)) { + debugLog.warn('notification', 'Notification API not available in this browser'); return 'denied'; } try { + debugLog.info('notification', 'Requesting browser notification permission'); const permission: NotificationPermission = await Notification.requestPermission(); + debugLog.info('notification', 'Notification permission result', { permission }); return permission; - } catch { + } catch (error) { + debugLog.error('notification', 'Failed to request notification permission', { error: error instanceof Error ? error.message : String(error) }); return 'denied'; } } @@ -24,8 +31,10 @@ export async function enablePushNotifications( pushSubscriptionAtom: PushSubscriptionState ): Promise { if (!('serviceWorker' in navigator) || !('PushManager' in window)) { + debugLog.error('notification', 'Push messaging not supported - missing serviceWorker or PushManager'); throw new Error('Push messaging is not supported in this browser.'); } + debugLog.info('notification', 'Enabling push notifications'); const [pushSubAtom, setPushSubscription] = pushSubscriptionAtom; const registration = await navigator.serviceWorker.ready; const currentBrowserSub = await registration.pushManager.getSubscription(); @@ -34,6 +43,7 @@ export async function enablePushNotifications( only when necessary. This prevents us from needing an external call to get back the web push info. */ if (currentBrowserSub && pushSubAtom && currentBrowserSub.endpoint === pushSubAtom.endpoint) { + debugLog.info('notification', 'Push subscription already exists and is valid - reusing', { endpoint: pushSubAtom.endpoint }); const { keys } = pushSubAtom; if (!keys?.p256dh || !keys.auth) return; const pusherData = { @@ -63,19 +73,23 @@ export async function enablePushNotifications( } if (currentBrowserSub) { + debugLog.info('notification', 'Unsubscribing old push subscription'); await currentBrowserSub.unsubscribe(); } + debugLog.info('notification', 'Creating new push subscription'); const newSubscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: clientConfig.pushNotificationDetails?.vapidPublicKey, }); + debugLog.info('notification', 'Push subscription created successfully', { endpoint: newSubscription.endpoint }); setPushSubscription(newSubscription); const subJson = newSubscription.toJSON(); const { keys } = subJson; if (!keys?.p256dh || !keys.auth) { + debugLog.error('notification', 'Push subscription missing required keys'); throw new Error('Push subscription keys missing.'); } const pusherData = { @@ -113,6 +127,7 @@ export async function disablePushNotifications( clientConfig: ClientConfig, pushSubscriptionAtom: PushSubscriptionState ): Promise { + debugLog.info('notification', 'Disabling push notifications'); const [pushSubAtom] = pushSubscriptionAtom; const pusherData = { diff --git a/src/app/hooks/useAppVisibility.ts b/src/app/hooks/useAppVisibility.ts index 0688f2637..2d60d2f03 100644 --- a/src/app/hooks/useAppVisibility.ts +++ b/src/app/hooks/useAppVisibility.ts @@ -8,6 +8,9 @@ import { useSetting } from '../state/hooks/settings'; import { settingsAtom } from '../state/settings'; import { pushSubscriptionAtom } from '../state/pushSubscription'; import { mobileOrTablet } from '../utils/user-agent'; +import { createDebugLogger } from '../utils/debugLogger'; + +const debugLog = createDebugLogger('AppVisibility'); export function useAppVisibility(mx: MatrixClient | undefined) { const clientConfig = useClientConfig(); @@ -18,6 +21,7 @@ export function useAppVisibility(mx: MatrixClient | undefined) { useEffect(() => { const handleVisibilityChange = () => { const isVisible = document.visibilityState === 'visible'; + debugLog.info('general', `App visibility changed: ${isVisible ? 'visible (foreground)' : 'hidden (background)'}`, { visibilityState: document.visibilityState }); appEvents.onVisibilityChange?.(isVisible); if (!isVisible) { appEvents.onVisibilityHidden?.(); diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts index 1659e5474..f9f4ec465 100644 --- a/src/app/pages/auth/login/loginUtil.ts +++ b/src/app/pages/auth/login/loginUtil.ts @@ -11,10 +11,12 @@ import { import { getHomePath } from '$pages/pathUtils'; import { activeSessionIdAtom, sessionsAtom } from '$state/sessions'; import { createLogger } from '$utils/debug'; +import { createDebugLogger } from '$utils/debugLogger'; import { ErrorCode } from '../../../cs-errorcode'; import { autoDiscovery, specVersions } from '../../../cs-api'; const log = createLogger('loginUtil'); +const debugLog = createDebugLogger('loginUtil'); export enum GetBaseUrlError { NotAllow = 'NotAllow', @@ -75,35 +77,42 @@ export const login = async ( } const mx = createClient({ baseUrl: url }); + debugLog.info('general', 'Attempting login', { baseUrl: url, loginType: data.type }); const [err, res] = await to(mx.loginRequest(data)); if (err) { if (err.httpStatus === 400) { + debugLog.error('general', 'Login failed - invalid request', { httpStatus: 400 }); throw new MatrixError({ errcode: LoginError.InvalidRequest, }); } if (err.httpStatus === 429) { + debugLog.error('general', 'Login failed - rate limited', { httpStatus: 429 }); throw new MatrixError({ errcode: LoginError.RateLimited, }); } if (err.errcode === ErrorCode.M_USER_DEACTIVATED) { + debugLog.error('general', 'Login failed - user deactivated', { errcode: err.errcode }); throw new MatrixError({ errcode: LoginError.UserDeactivated, }); } if (err.httpStatus === 403) { + debugLog.error('general', 'Login failed - forbidden', { httpStatus: 403 }); throw new MatrixError({ errcode: LoginError.Forbidden, }); } + debugLog.error('general', 'Login failed - unknown error', { error: err.message, httpStatus: err.httpStatus }); throw new MatrixError({ errcode: LoginError.Unknown, }); } + debugLog.info('general', 'Login successful', { userId: res.user_id, deviceId: res.device_id }); return { baseUrl: url, response: res, diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index 9ca53b5cb..ffb7da763 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -32,6 +32,7 @@ import { } from '$utils/room'; import { NotificationType, StateEvent } from '$types/matrix/room'; import { createLogger } from '$utils/debug'; +import { createDebugLogger } from '$utils/debugLogger'; import LogoSVG from '$public/res/svg/cinny.svg'; import { nicknamesAtom } from '$state/nicknames'; import { @@ -43,6 +44,7 @@ import { useClientConfig } from '$hooks/useClientConfig'; import { mobileOrTablet } from '$utils/user-agent'; const log = createLogger('BackgroundNotifications'); +const debugLog = createDebugLogger('BackgroundNotifications'); const isClientReadyForNotifications = (state: SyncState | string | null): boolean => state === SyncState.Prepared || state === SyncState.Syncing || state === SyncState.Catchup; @@ -303,6 +305,10 @@ export function BackgroundNotifications() { const notificationType = getNotificationType(mx, room.roomId); if (notificationType === NotificationType.Mute) { + debugLog.debug('notification', 'Room is muted - skipping notification', { + roomId: room.roomId, + eventId, + }); return; } @@ -329,9 +335,24 @@ export function BackgroundNotifications() { const shouldNotify = pushActions?.notify || shouldForceDMNotification; if (!shouldNotify) { + debugLog.debug('notification', 'Event filtered - no push action match', { + eventId, + roomId: room.roomId, + eventType, + isDM, + }); return; } + debugLog.info('notification', 'Processing notification event', { + eventId, + roomId: room.roomId, + eventType, + isDM, + isHighlight, + loud: loudByRule, + }); + const senderName = getMemberDisplayName(room, sender, nicknamesRef.current) ?? getMxIdLocalPart(sender) ?? @@ -360,6 +381,10 @@ export function BackgroundNotifications() { // Silent-rule events: unread badge updated above; no OS notification or sound. if (!loudByRule && !isHighlight) { + debugLog.debug('notification', 'Silent notification - badge updated only', { + eventId, + roomId: room.roomId, + }); return; } @@ -410,6 +435,11 @@ export function BackgroundNotifications() { if (canShowInAppBanner) { // App is in the foreground on a different account — show the themed in-app banner. + debugLog.info('notification', 'Showing in-app banner', { + eventId, + roomId: room.roomId, + title: notificationPayload.title, + }); setInAppBannerRef.current({ id: dedupeId, title: notificationPayload.title, @@ -422,6 +452,12 @@ export function BackgroundNotifications() { } else if (loudByRule) { // App is backgrounded or in-app notifications disabled — fire an OS notification. // Only send for loud (sound-tweak) rules; highlight-only events are silently counted. + debugLog.info('notification', 'Sending OS notification', { + eventId, + roomId: room.roomId, + title: notificationPayload.title, + hasSound: !notificationPayload.options.silent, + }); sendNotification({ title: notificationPayload.title, icon: notificationPayload.options.icon, @@ -438,6 +474,10 @@ export function BackgroundNotifications() { }) .catch((err) => { log.error('failed to start background client for', session.userId, err); + debugLog.error('notification', 'Failed to start background client', { + userId: session.userId, + error: err, + }); }); }); diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index c370bfac5..8aaf6acd1 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -25,6 +25,9 @@ import { } from './types'; import { CallControl } from './CallControl'; import { CallControlState } from './CallControlState'; +import { createDebugLogger } from '../../utils/debugLogger'; + +const debugLog = createDebugLogger('CallEmbed'); export class CallEmbed { private mx: MatrixClient; @@ -127,6 +130,8 @@ export class CallEmbed { container: HTMLElement, initialControlState?: CallControlState ) { + debugLog.info('call', 'Initializing call embed', { roomId: room.roomId }); + const iframe = CallEmbed.getIframe( widget.getCompleteUrl({ currentUserId: mx.getSafeUserId() }) ); @@ -174,6 +179,7 @@ export class CallEmbed { } public hangup() { + debugLog.info('call', 'Hanging up call', { roomId: this.roomId }); return this.call.transport.send(ElementWidgetActions.HangupCall, {}); } @@ -194,6 +200,7 @@ export class CallEmbed { } private start() { + debugLog.info('call', 'Starting call widget', { roomId: this.roomId }); // Room widgets get locked to the room they were added in this.call.setViewedRoomId(this.roomId); this.disposables.push( @@ -224,6 +231,7 @@ export class CallEmbed { * @param opts */ public dispose(): void { + debugLog.info('call', 'Disposing call widget', { roomId: this.roomId }); this.disposables.forEach((disposable) => { disposable(); }); @@ -242,6 +250,7 @@ export class CallEmbed { } private onCallJoined(): void { + debugLog.info('call', 'Call joined', { roomId: this.roomId }); this.joined = true; this.applyStyles(); this.control.startObserving(); diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index a2cbc8ddc..27a2c4e02 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -26,6 +26,9 @@ import { } from 'matrix-js-sdk'; import { getCallCapabilities } from './utils'; import { downloadMedia, mxcUrlToHttp } from '../../utils/matrix'; +import { createDebugLogger } from '../../utils/debugLogger'; + +const debugLog = createDebugLogger('CallWidgetDriver'); export class CallWidgetDriver extends WidgetDriver { private allowedCapabilities: Set; @@ -40,8 +43,12 @@ export class CallWidgetDriver extends WidgetDriver { this.mx = mx; const deviceId = mx.getDeviceId(); - if (!deviceId) throw new Error('Failed to initialize CallWidgetDriver! Device ID not found.'); + if (!deviceId) { + debugLog.error('call', 'Failed to initialize CallWidgetDriver - no device ID'); + throw new Error('Failed to initialize CallWidgetDriver! Device ID not found.'); + } + debugLog.info('call', 'Initializing CallWidgetDriver', { roomId: inRoomId, deviceId }); this.allowedCapabilities = getCallCapabilities(inRoomId, mx.getSafeUserId(), deviceId); } @@ -59,7 +66,12 @@ export class CallWidgetDriver extends WidgetDriver { const client = this.mx; const roomId = targetRoomId || this.inRoomId; - if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + if (!client || !roomId) { + debugLog.error('call', 'Cannot send event - no client or room', { eventType, roomId }); + throw new Error('Not in a room or not attached to a client'); + } + + debugLog.info('call', 'Sending call event', { eventType, roomId, hasStateKey: stateKey !== null }); let r: { event_id: string } | null; if (typeof stateKey === 'string') { @@ -80,6 +92,7 @@ export class CallWidgetDriver extends WidgetDriver { ); } + debugLog.info('call', 'Call event sent successfully', { eventId: r.event_id, eventType }); return { roomId, eventId: r.event_id }; } diff --git a/src/app/state/debugLogger.ts b/src/app/state/debugLogger.ts new file mode 100644 index 000000000..9c155fdd7 --- /dev/null +++ b/src/app/state/debugLogger.ts @@ -0,0 +1,50 @@ +/** + * Jotai atoms for debug logger state management + */ +import { atom } from 'jotai'; +import { atomWithRefresh } from 'jotai/utils'; +import { getDebugLogger, LogEntry } from '$utils/debugLogger'; + +const debugLogger = getDebugLogger(); + +/** + * Atom for enabling/disabling debug logging + */ +export const debugLoggerEnabledAtom = atom( + () => debugLogger.isEnabled(), + (_, set, enabled: boolean) => { + debugLogger.setEnabled(enabled); + set(debugLogsAtom); + } +); + +/** + * Atom for retrieving debug logs with refresh capability + */ +export const debugLogsAtom = atomWithRefresh(() => debugLogger.getLogs()); + +/** + * Atom for filtered logs + */ +export const filteredDebugLogsAtom = atom( + (get) => get(debugLogsAtom), + (get, set, filters?: { level?: string; category?: string; since?: number }) => { + const allLogs = get(debugLogsAtom); + return allLogs; // Can be extended with filtering logic + } +); + +/** + * Action to clear all debug logs + */ +export const clearDebugLogsAtom = atom(null, (_, set) => { + debugLogger.clear(); + set(debugLogsAtom); +}); + +/** + * Action to export debug logs + */ +export const exportDebugLogsAtom = atom(null, () => { + return debugLogger.exportLogs(); +}); diff --git a/src/app/utils/debugLogger.ts b/src/app/utils/debugLogger.ts new file mode 100644 index 000000000..bef5fd416 --- /dev/null +++ b/src/app/utils/debugLogger.ts @@ -0,0 +1,169 @@ +/** + * Enhanced debug logger for Sable with circular buffer storage and categorization. + * + * Enable via Developer Tools UI or with: + * localStorage.setItem('sable_internal_debug', '1'); location.reload(); + */ + +export type LogLevel = 'debug' | 'info' | 'warn' | 'error'; + +export type LogCategory = + | 'sync' + | 'network' + | 'notification' + | 'message' + | 'call' + | 'error' + | 'general'; + +export interface LogEntry { + timestamp: number; + level: LogLevel; + category: LogCategory; + namespace: string; + message: string; + data?: unknown; +} + +type LogListener = (entry: LogEntry) => void; + +class DebugLoggerService { + private logs: LogEntry[] = []; + private maxLogs = 1000; // Circular buffer size + private enabled = false; + private listeners: Set = new Set(); + + constructor() { + // Check if debug logging is enabled from localStorage + this.enabled = localStorage.getItem('sable_internal_debug') === '1'; + } + + public isEnabled(): boolean { + return this.enabled; + } + + public setEnabled(enabled: boolean): void { + this.enabled = enabled; + if (enabled) { + localStorage.setItem('sable_internal_debug', '1'); + } else { + localStorage.removeItem('sable_internal_debug'); + } + } + + public addListener(listener: LogListener): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + private notifyListeners(entry: LogEntry): void { + this.listeners.forEach((listener) => { + try { + listener(entry); + } catch (error) { + // Silently catch listener errors to prevent debug logging from breaking the app + console.error('[DebugLogger] Listener error:', error); + } + }); + } + + public log( + level: LogLevel, + category: LogCategory, + namespace: string, + message: string, + data?: unknown + ): void { + if (!this.enabled && level !== 'error') return; + + const entry: LogEntry = { + timestamp: Date.now(), + level, + category, + namespace, + message, + data, + }; + + // Add to circular buffer + if (this.logs.length >= this.maxLogs) { + this.logs.shift(); // Remove oldest entry + } + this.logs.push(entry); + + // Notify listeners + this.notifyListeners(entry); + + // Also log to console for developer convenience + const prefix = `[sable:${category}:${namespace}]`; + const consoleLevel = level === 'debug' ? 'log' : level; + // eslint-disable-next-line no-console + console[consoleLevel](prefix, message, data !== undefined ? data : ''); + } + + public getLogs(): LogEntry[] { + return [...this.logs]; + } + + public getFilteredLogs( + filters?: { + level?: LogLevel; + category?: LogCategory; + since?: number; + } + ): LogEntry[] { + let filtered = [...this.logs]; + + if (filters?.level) { + filtered = filtered.filter((log) => log.level === filters.level); + } + + if (filters?.category) { + filtered = filtered.filter((log) => log.category === filters.category); + } + + if (filters?.since) { + filtered = filtered.filter((log) => log.timestamp >= filters.since); + } + + return filtered; + } + + public clear(): void { + this.logs = []; + } + + public exportLogs(): string { + return JSON.stringify( + { + exportedAt: new Date().toISOString(), + logsCount: this.logs.length, + logs: this.logs.map((log) => ({ + ...log, + timestamp: new Date(log.timestamp).toISOString(), + })), + }, + null, + 2 + ); + } +} + +// Singleton instance +const debugLoggerService = new DebugLoggerService(); + +export const getDebugLogger = (): DebugLoggerService => debugLoggerService; + +/** + * Creates a logger for a specific namespace + */ +export const createDebugLogger = (namespace: string) => ({ + debug: (category: LogCategory, message: string, data?: unknown) => + debugLoggerService.log('debug', category, namespace, message, data), + info: (category: LogCategory, message: string, data?: unknown) => + debugLoggerService.log('info', category, namespace, message, data), + warn: (category: LogCategory, message: string, data?: unknown) => + debugLoggerService.log('warn', category, namespace, message, data), + error: (category: LogCategory, message: string, data?: unknown) => + debugLoggerService.log('error', category, namespace, message, data), +}); diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 47c8ba29d..76d6a6d96 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -16,11 +16,13 @@ import { } from '$state/sessions'; import { getLocalStorageItem } from '$state/utils/atomWithLocalStorage'; import { createLogger } from '$utils/debug'; +import { createDebugLogger } from '$utils/debugLogger'; import { pushSessionToSW } from '../sw-session'; import { cryptoCallbacks } from './secretStorageKeys'; import { SlidingSyncConfig, SlidingSyncDiagnostics, SlidingSyncManager } from './slidingSync'; const log = createLogger('initMatrix'); +const debugLog = createDebugLogger('initMatrix'); const slidingSyncByClient = new WeakMap(); const FAST_SYNC_POLL_TIMEOUT_MS = 10000; const SLIDING_SYNC_POLL_TIMEOUT_MS = 20000; @@ -150,6 +152,7 @@ const waitForClientReady = (mx: MatrixClient, timeoutMs: number): Promise let timer = 0; let finish = () => {}; const onSync = (state: string) => { + debugLog.info('sync', `Sync state changed: ${state}`, { state, ready: isClientReadyForUi(state) }); if (isClientReadyForUi(state)) finish(); }; @@ -263,7 +266,7 @@ const buildClient = async (session: Session): Promise => { export const initClient = async (session: Session): Promise => { const storeName = getSessionStoreName(session); - log.log('initClient', { userId: session.userId, baseUrl: session.baseUrl, storeName }); + debugLog.info('sync', 'Initializing Matrix client', { userId: session.userId, baseUrl: session.baseUrl }); const isMismatch = (err: unknown): boolean => { const msg = err instanceof Error ? err.message : String(err); @@ -276,6 +279,8 @@ export const initClient = async (session: Session): Promise => { }; const wipeAllStores = async () => { + log.warn('initClient: wiping all stores for', session.userId); + debugLog.warn('sync', 'Wiping all stores due to mismatch', { userId: session.userId } log.warn('initClient: wiping all stores for', session.userId); await deleteSessionStores(storeName); try { @@ -294,17 +299,25 @@ export const initClient = async (session: Session): Promise => { }; let mx: MatrixClient; - try { - mx = await buildClient(session); - } catch (err) { - if (!isMismatch(err)) throw err; + try {{ + debugLog.error('sync', 'Failed to build client', { error: err }); + throw err; + } log.warn('initClient: mismatch on buildClient — wiping and retrying:', err); + debugLog.warn('sync', 'Client build mismatch - wiping stores and retrying', { error: err }); await wipeAllStores(); mx = await buildClient(session); } try { await mx.initRustCrypto({ cryptoDatabasePrefix: storeName.rustCryptoPrefix }); + } catch (err) { + if (!isMismatch(err)) { + debugLog.error('sync', 'Failed to initialize crypto', { error: err }); + throw err; + } + log.warn('initClient: mismatch on initRustCrypto — wiping and retrying:', err); + debugLog.warn('sync', 'Crypto init mismatch - wiping stores and retrying', { error: err }; } catch (err) { if (!isMismatch(err)) throw err; log.warn('initClient: mismatch on initRustCrypto — wiping and retrying:', err); @@ -336,16 +349,7 @@ const disposeSlidingSync = (mx: MatrixClient): void => { slidingSyncByClient.delete(mx); }; -export const stopClient = (mx: MatrixClient): void => { - disposeSlidingSync(mx); - mx.stopClient(); -}; - -export const getSlidingSyncManager = (mx: MatrixClient): SlidingSyncManager | undefined => - slidingSyncByClient.get(mx); - -export const startClient = async (mx: MatrixClient, config?: StartClientConfig) => { - log.log('startClient', mx.getUserId()); +expebugLog.info('sync', 'Starting Matrix client', { userId: mx.getUserId() }); disposeSlidingSync(mx); const slidingConfig = config?.slidingSync; const slidingEnabledOnServer = resolveSlidingEnabled(slidingConfig?.enabled); @@ -361,6 +365,25 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig) proxyBaseUrl, hasSlidingProxy, }); + debugLog.info('sync', 'Sliding sync configuration', { + enabledOnServer: slidingEnabledOnServer, + requested: slidingRequested, + hasProxy: hasSlidingProxy, + }); + + const startClassicSync = async (fallbackFromSliding: boolean, reason: SyncTransportReason) => { + debugLog.info('sync', `Starting classic sync (reason: ${reason})`, { + fallback: fallbackFromSliding, + reason, + }); + userId: mx.getUserId(), + enabled: slidingConfig?.enabled, + enabledOnServer: slidingEnabledOnServer, + sessionOptIn: config?.sessionSlidingSyncOptIn === true, + requestedEnabled: slidingRequested, + proxyBaseUrl, + hasSlidingProxy, + }); const startClassicSync = async (fallbackFromSliding: boolean, reason: SyncTransportReason) => { syncTransportByClient.set(mx, { @@ -504,10 +527,12 @@ export const getClientSyncDiagnostics = (mx: MatrixClient): ClientSyncDiagnostic */ export const logoutClient = async (mx: MatrixClient, session?: Session) => { log.log('logoutClient', { userId: mx.getUserId(), sessionUserId: session?.userId }); + debugLog.info('general', 'Logging out client', { userId: mx.getUserId() }); pushSessionToSW(); stopClient(mx); try { await mx.logout(); + debugLog.info('general', 'Logout successful', { userId: mx.getUserId() }); } catch { // ignore } @@ -525,6 +550,7 @@ export const logoutClient = async (mx: MatrixClient, session?: Session) => { }; export const clearLoginData = async () => { + debugLog.info('general', 'Clearing all login data and reloading'); const dbs = await window.indexedDB.databases(); dbs.forEach((idbInfo) => { const { name } = idbInfo; diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index eacb7a472..613c0bbd7 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -14,10 +14,18 @@ import { MSC3575_STATE_KEY_ME, EventType, User, +import { + MatrixClient, + SlidingSync, + SlidingSyncEvent, + SlidingSyncEventHandlerMap, + SlidingSyncState, } from '$types/matrix-sdk'; import { createLogger } from '$utils/debug'; +import { createDebugLogger } from '$utils/debugLogger'; const log = createLogger('slidingSync'); +const debugLog = createDebugLogger('slidingSync'); export const LIST_JOINED = 'joined'; export const LIST_INVITES = 'invites'; @@ -359,17 +367,26 @@ export class SlidingSyncManager { ); this.onLifecycle = (state, resp, err) => { + debugLog.info('sync', `Sliding sync lifecycle: ${state}`, { state, hasError: !!err }); + if (err) { + debugLog.error('sync', 'Sliding sync error', { error: err }); + } if (this.disposed || err || !resp || state !== SlidingSyncState.Complete) return; this.expandListsToKnownCount(); }; this.onConnectionChange = () => { + const isOnline = navigator.onLine; + debugLog.info('network', `Network connectivity changed: ${isOnline ? 'online' : 'offline'}`, { online: isOnline }); if (this.disposed || !this.adaptiveTimeline) return; const nextLimit = resolveAdaptiveRoomTimelineLimit( this.configuredTimelineLimit, readAdaptiveSignals() ); if (nextLimit === this.roomTimelineLimit) return; + debugLog.info('sync', `Adaptive timeline limit updated to ${nextLimit}`, { + limit: nextLimit, + }); this.roomTimelineLimit = nextLimit; this.applyRoomTimelineLimit(nextLimit); log.log(