1 Commits
Author SHA1 Message Date
litruv 230ca4fcf0 Add the debug packet recorder behind the developer-tools toggle.
Checks / checks (push) Successful in 2m14s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 09:01:38 +11:00
6 changed files with 150 additions and 4 deletions
@@ -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<string | null>();
const [profileExpand, setProfileExpand] = useState(false);
@@ -162,6 +163,30 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
/>
}
/>
<SettingTile
title="Debug Packets"
description="Record every Matrix HTTP request and response."
after={
<Switch variant="Primary" value={debugPackets} onChange={setDebugPackets} />
}
/>
{window.electron?.debug && (
<SettingTile
title="Packet Window"
after={
<Button
onClick={() => window.electron?.debug?.openWindow()}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
outlined
>
<Text size="B300">Open packet window</Text>
</Button>
}
/>
)}
</SequenceCard>
{developerTools && (
<SequenceCard
@@ -253,6 +253,11 @@ export const SETTINGS_SEARCH_CATALOG: SettingsSearchEntry[] = [
keywords: ['debug'],
},
{ page: SettingsPages.DeveloperToolsPage, title: 'Access Token', keywords: ['auth', 'secret'] },
{
page: SettingsPages.DeveloperToolsPage,
title: 'Debug Packets',
keywords: ['http', 'network', 'request', 'response'],
},
{ page: SettingsPages.DeveloperToolsPage, title: 'Account Data', keywords: ['global', 'events'] },
{
page: SettingsPages.DeveloperToolsPage,
+25
View File
@@ -0,0 +1,25 @@
export interface DebugPacket {
id: number;
ts: number;
phase: 'start' | 'end';
method: string;
url: string;
path: string;
status?: number;
ms?: number;
txnId?: string;
eventId?: string;
req?: string;
res?: string;
error?: string;
}
let nextId = 0;
export function recordPacket(packet: Omit<DebugPacket, 'id'>) {
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);
}
+2
View File
@@ -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,
+86 -4
View File
@@ -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<Response> => {
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<MatrixClient> => {
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();
};
+7
View File
@@ -1,5 +1,7 @@
/// <reference types="vite/client" />
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;