feat: add internal debug logging system

- Add comprehensive debug logger utility with circular buffer (1000 entries max)
- Add debug log state management with Jotai atoms
- Create DebugLogViewer UI component with real-time updates and filtering
- Integrate debug logger into Developer Tools settings
- Add logging for sync state changes (initMatrix, slidingSync)
- Add logging for authentication (login, logout, session management)
- Add logging for push notifications (permissions, subscriptions)
- Add logging for app lifecycle (visibility changes, backgrounding)
- Add logging for network connectivity (online/offline)
- Add logging for notifications (filtering, routing, mute decisions)
- Add logging for messages (send success/failure, uploads, scheduled)
- Add logging for calls (widget lifecycle, join/hangup, events)
- Support filtering by category and level
- Support exporting logs as JSON (all or filtered)
- Support copying logs to clipboard
This commit is contained in:
Evie Gauthier committed 2026-03-13 21:25:34 -04:00
1 parent 8216d54a97
commit bcf5a84220
13 files changed
+968 -27

No files matched your search

+26 -9
View File
@@ -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<HTMLDivElement, RoomInputProps>(
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<HTMLDivElement, RoomInputProps>(
} 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,
@@ -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 (
<Box
direction="Column"
gap="100"
style={{
padding: config.space.S200,
backgroundColor: color.Surface.Container,
borderRadius: config.radii.R300,
fontSize: '11px',
fontFamily: 'monospace',
}}
>
<Box gap="200" alignItems="Center" justifyContent="SpaceBetween">
<Box gap="200" alignItems="Center">
<Text
size="T200"
style={{
color: getLevelColor(entry.level),
fontWeight: 'bold',
minWidth: '50px',
}}
>
{entry.level.toUpperCase()}
</Text>
<Badge variant={getCategoryBadgeVariant(entry.category)} fill="Soft" size="300">
<Text size="T200">{entry.category}</Text>
</Badge>
<Text size="T200" style={{ opacity: 0.6 }}>
{formatTimestamp(entry.timestamp)}
</Text>
<Text size="T200" style={{ opacity: 0.8 }}>
[{entry.namespace}]
</Text>
</Box>
{entry.data && (
<Button
variant="Secondary"
fill="None"
size="300"
radii="300"
onClick={() => setExpanded(!expanded)}
>
<Text size="T200">{expanded ? 'Hide' : 'Show'} Data</Text>
</Button>
)}
</Box>
<Text size="T200" style={{ wordBreak: 'break-word' }}>
{entry.message}
</Text>
{expanded && entry.data && (
<Box
direction="Column"
style={{
padding: config.space.S200,
backgroundColor: color.Surface.ContainerActive,
borderRadius: config.radii.R300,
maxHeight: '200px',
overflow: 'auto',
}}
>
<Text
as="pre"
size="T200"
style={{
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
margin: 0,
}}
>
{JSON.stringify(entry.data, null, 2)}
</Text>
</Box>
)}
</Box>
);
}
export function DebugLogViewer() {
const [enabled, setEnabled] = useAtom(debugLoggerEnabledAtom);
const logs = useAtomValue(debugLogsAtom);
const clearLogs = useSetAtom(clearDebugLogsAtom);
const [autoScroll, setAutoScroll] = useState(true);
const scrollRef = useState<HTMLDivElement | null>(null)[0];
const [filterLevel, setFilterLevel] = useState<LogLevel | 'all'>('all');
const [filterCategory, setFilterCategory] = useState<LogCategory | 'all'>('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 (
<Box direction="Column" gap="100">
<Box style={{ display: 'flex', flexDirection: 'column', gap: config.space.S400 }}>
<Box alignItems="Center" justifyContent="SpaceBetween">
<Text size="L400">Debug Log Status</Text>
<Badge variant={enabled ? 'Success' : 'Secondary'} fill="Solid">
<Text size="B300">{enabled ? 'Active' : 'Inactive'}</Text>
</Badge>
</Box>
<Text size="T300" style={{ opacity: 0.8 }}>
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.
</Text>
{/* Filter Controls */}
<Box gap="200" alignItems="Center" style={{ flexWrap: 'wrap' }}>
<Text size="T300" style={{ opacity: 0.8 }}>
Filters:
</Text>
<PopOut
offset={4}
alignOffset={-4}
position="Bottom"
align="Start"
content={
<Menu>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('all')}
disabled={filterCategory === 'all'}
>
<Text size="T300">All Categories</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('sync')}
disabled={filterCategory === 'sync'}
>
<Text size="T300">Sync</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('network')}
disabled={filterCategory === 'network'}
>
<Text size="T300">Network</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('notification')}
disabled={filterCategory === 'notification'}
>
<Text size="T300">Notification</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('message')}
disabled={filterCategory === 'message'}
>
<Text size="T300">Message</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('call')}
disabled={filterCategory === 'call'}
>
<Text size="T300">Call</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('general')}
disabled={filterCategory === 'general'}
>
<Text size="T300">General</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterCategory('error')}
disabled={filterCategory === 'error'}
>
<Text size="T300">Error</Text>
</MenuItem>
</Menu>
}
>
{(targetRef) => (
<Button
ref={targetRef}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
>
<Text size="B300">
Category: {filterCategory === 'all' ? 'All' : filterCategory}
</Text>
</Button>
)}
</PopOut>
<PopOut
offset={4}
alignOffset={-4}
position="Bottom"
align="Start"
content={
<Menu>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterLevel('all')}
disabled={filterLevel === 'all'}
>
<Text size="T300">All Levels</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterLevel('debug')}
disabled={filterLevel === 'debug'}
>
<Text size="T300">Debug</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterLevel('info')}
disabled={filterLevel === 'info'}
>
<Text size="T300">Info</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterLevel('warn')}
disabled={filterLevel === 'warn'}
>
<Text size="T300">Warning</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => setFilterLevel('error')}
disabled={filterLevel === 'error'}
>
<Text size="T300">Error</Text>
</MenuItem>
</Menu>
}
>
{(targetRef) => (
<Button
ref={targetRef}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
>
<Text size="B300">
Level: {filterLevel === 'all' ? 'All' : filterLevel}
</Text>
</Button>
)}
</PopOut>
{(filterLevel !== 'all' || filterCategory !== 'all') && (
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
onClick={() => {
setFilterLevel('all');
setFilterCategory('all');
}}
>
<Text size="B300">Clear Filters</Text>
</Button>
)}
</Box>
<Box gap="200" style={{ flexWrap: 'wrap' }}>
<Button
variant={enabled ? 'Critical' : 'Success'}
fill="Soft"
size="300"
radii="300"
onClick={() => setEnabled(!enabled)}
>
<Text size="B300">{enabled ? 'Disable Logging' : 'Enable Logging'}</Text>
</Button>
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
onClick={() => handleExportLogs(false)}
disabled={logs.length === 0}
>
<Text size="B300">Export All</Text>
</Button>
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
onClick={() => handleExportLogs(true)}
disabled={filteredLogs.length === 0}
>
<Text size="B300">
Export Filtered ({filteredLogs.length})
</Text>
</Button>
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
onClick={() => handleCopyToClipboard(true)}
disabled={filteredLogs.length === 0}
>
<Text size="B300">Copy Filtered</Text>
</Button>
<Button
variant="Critical"
fill="Soft"
size="300"
radii="300"
onClick={clearLogs}
disabled={logs.length === 0}
>
<Text size="B300">Clear Logs ({logs.length})</Text>
</Button>
</Box>
{enabled && (
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="200"
>
<Box alignItems="Center" justifyContent="SpaceBetween">
<Text size="L400">
Recent Logs (
{filterLevel !== 'all' || filterCategory !== 'all'
? `${filteredLogs.length}/${logs.length}`
: `${logs.length}/1000`}
)
</Text>
<Button
variant="Secondary"
fill="None"
size="300"
radii="300"
onClick={() => setAutoScroll(!autoScroll)}
>
<Text size="T200">Auto-scroll: {autoScroll ? 'On' : 'Off'}</Text>
</Button>
</Box>
<Box
direction="Column"
gap="200"
style={{
maxHeight: '500px',
overflow: 'auto',
padding: config.space.S200,
}}
>
{filteredLogs.length === 0 ? (
<Box
style={{
padding: config.space.S700,
textAlign: 'center',
opacity: 0.6,
}}
>
<Text size="T300">
{logs.length === 0
? 'No logs captured yet. Use the app to generate log entries.'
: 'No logs match the current filters.'}
</Text>
</Box>
) : (
filteredLogs.map((log) => (
<LogEntryItem key={`${log.timestamp}-${log.namespace}`} entry={log} />
))
)}
</Box>
</SequenceCard>
)}
</Box>
</Box>
);
}
@@ -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 && (
<Box direction="Column" gap="100">
<DebugLogViewer />
</Box>
)}
</Box>
</PageContent>
</Scroll>
@@ -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<NotificationPermission> {
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<void> {
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<void> {
debugLog.info('notification', 'Disabling push notifications');
const [pushSubAtom] = pushSubscriptionAtom;
const pusherData = {
+4
View File
@@ -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?.();
+9
View File
@@ -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<LoginResponse, MatrixError>(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,
@@ -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,
});
});
});
+9
View File
@@ -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();
+15 -2
View File
@@ -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<Capability>;
@@ -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 };
}
+50
View File
@@ -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();
});
+169
View File
@@ -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<LogListener> = 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),
});
+41 -15
View File
@@ -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<MatrixClient, SlidingSyncManager>();
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<void>
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<MatrixClient> => {
export const initClient = async (session: Session): Promise<MatrixClient> => {
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<MatrixClient> => {
};
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<MatrixClient> => {
};
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;
+17
View File
@@ -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(