diff --git a/src/app/features/settings/developer-tools/DevelopTools.tsx b/src/app/features/settings/developer-tools/DevelopTools.tsx index 4559c938..eeef738e 100644 --- a/src/app/features/settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/settings/developer-tools/DevelopTools.tsx @@ -37,6 +37,7 @@ type DeveloperToolsProps = { export function DeveloperTools({ requestClose }: DeveloperToolsProps) { const mx = useMatrixClient(); const [developerTools, setDeveloperTools] = useSetting(settingsAtom, 'developerTools'); + const [debugPackets, setDebugPackets] = useSetting(settingsAtom, 'debugPackets'); const [expand, setExpend] = useState(false); const [accountDataType, setAccountDataType] = useState(); const [profileExpand, setProfileExpand] = useState(false); @@ -162,6 +163,30 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { /> } /> + + } + /> + {window.electron?.debug && ( + window.electron?.debug?.openWindow()} + variant="Secondary" + fill="Soft" + size="300" + radii="300" + outlined + > + Open packet window + + } + /> + )} {developerTools && ( ) { + const full: DebugPacket = { id: nextId, ...packet }; + nextId += 1; + + // Web and mobile builds have no electron bridge, so nothing is recorded there + window.electron?.debug?.send(full); +} diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index cccbcc24..630a79b6 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -63,6 +63,7 @@ export interface Settings { dateFormatString: string; developerTools: boolean; + debugPackets: boolean; autoJoinSpaceRooms: boolean; @@ -109,6 +110,7 @@ const defaultSettings: Settings = { dateFormatString: 'D MMM YYYY', developerTools: false, + debugPackets: false, autoJoinSpaceRooms: true, diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 55eb40f9..2035e751 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -3,6 +3,87 @@ import { createClient, MatrixClient, IndexedDBStore, IndexedDBCryptoStore } from import { cryptoCallbacks } from './secretStorageKeys'; import { clearNavToActivePathStore } from '../app/state/navToActivePath'; import { Session, getSessionStoreName } from '../app/state/sessions'; +import { getSettings } from '../app/state/settings'; +import { recordPacket } from '../app/state/debugPackets'; + +const MAX_BODY = 8192; + +const jsonField = (text: string | undefined, key: string) => { + if (!text) return undefined; + try { + const parsed = JSON.parse(text); + return typeof parsed?.[key] === 'string' ? parsed[key] : undefined; + } catch { + return undefined; + } +}; + +// Bodies are only read from a clone, so the SDK still gets the response it asked for +const readBody = async (res: Response) => { + const type = res.headers.get('content-type') ?? ''; + if (!type.includes('json') && !type.includes('text')) return undefined; + try { + return (await res.clone().text()).slice(0, MAX_BODY); + } catch { + return undefined; + } +}; + +const debugFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise => { + if (!getSettings().debugPackets) return globalThis.fetch(input, init); + + // The SDK passes `URL | string`, and a URL instance has href, not url + const url = input instanceof URL ? input : new URL(typeof input === 'string' ? input : input.url); + const method = init?.method ?? (input instanceof Request ? input.method : 'GET'); + const req = typeof init?.body === 'string' ? init.body.slice(0, MAX_BODY) : undefined; + const txnId = jsonField(req, 'transaction_id'); + const start = Date.now(); + + recordPacket({ + ts: start, + phase: 'start', + method, + url: url.toString(), + path: url.pathname, + txnId, + req, + }); + + let res: Response; + try { + res = await globalThis.fetch(input, init); + } catch (error) { + recordPacket({ + ts: Date.now(), + phase: 'end', + method, + url: url.toString(), + path: url.pathname, + ms: Date.now() - start, + txnId, + req, + error: String(error), + }); + throw error; + } + + const body = await readBody(res); + recordPacket({ + ts: Date.now(), + phase: 'end', + method, + url: url.toString(), + path: url.pathname, + status: res.status, + ms: Date.now() - start, + txnId, + eventId: jsonField(body, 'event_id'), + req, + res: body, + }); + + return res; +}; // Track if we're currently handling a key conflict to prevent loops let handlingKeyConflict = false; @@ -136,7 +217,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { const errorHandler = (...args: any[]) => { if (checkKeyConflict(args)) { - keyConflictCount++; + keyConflictCount += 1; console.log( `[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`, ); @@ -181,7 +262,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { console.error = errorHandler; console.warn = (...args: any[]) => { if (checkKeyConflict(args)) { - keyConflictCount++; + keyConflictCount += 1; } originalWarn.apply(console, args); }; @@ -236,6 +317,7 @@ export const initClient = async (session: Session): Promise => { timelineSupport: true, cryptoCallbacks: cryptoCallbacks as any, verificationMethods: ['m.sas.v1'], + fetchFn: debugFetch, }); await indexedDBStore.startup(); @@ -399,11 +481,11 @@ export const logoutAllSessions = async () => { // Clear all IndexedDB databases const dbs = await window.indexedDB.databases(); - for (const idbInfo of dbs) { + dbs.forEach((idbInfo) => { if (idbInfo.name) { window.indexedDB.deleteDatabase(idbInfo.name); } - } + }); window.location.reload(); }; diff --git a/src/ext.d.ts b/src/ext.d.ts index 31f6dc36..2c951220 100644 --- a/src/ext.d.ts +++ b/src/ext.d.ts @@ -1,5 +1,7 @@ /// +import type { DebugPacket } from './app/state/debugPackets'; + declare module 'browser-encrypt-attachment' { export interface EncryptedAttachmentInfo { v: string; @@ -67,6 +69,11 @@ interface ElectronAPI { }>; }; plugins?: PluginAPI; + debug?: { + openWindow: () => Promise<{ success: boolean; error?: string }>; + send: (packet: DebugPacket) => void; + onPacket: (callback: (packet: DebugPacket | DebugPacket[]) => void) => () => void; + }; protocol?: { getStatus: () => Promise<{ success: boolean;