// Disposable generated-state regression: no server, no microphone, no account data. import { launchApp } from './lib/electron-app.mjs'; import { mkdirSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import assert from 'node:assert/strict'; const args = process.argv.slice(2); const opt = (key, fallback) => args.includes(`--${key}`) ? args[args.indexOf(`--${key}`) + 1] : fallback; const out = path.resolve(opt('out', 'smoke-out/memory')); const label = opt('label', 'state'); mkdirSync(out, { recursive: true }); const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-state-memory-')); const result = { label, synthetic: true, errors: [], samples: [] }; let app; try { app = await launchApp({ exe: opt('exe'), profile, env: { TEAMSPEACH_DEVTOOLS: '1' } }); const page = await app.firstWindow(); page.on('pageerror', e => result.errors.push(e.message)); await page.waitForSelector('#view-onboarding', { state: 'visible' }); await page.fill('#onboarding-nick', 'StateMemoryAudit'); await page.click('#onboarding-submit'); await page.waitForSelector('#view-app', { state: 'visible' }); await app.evaluate(({ ipcMain }) => { const data = Buffer.from(``).toString('base64'); ipcMain.removeHandler('core:request'); ipcMain.handle('core:request', (_event, connectionId, cmd) => cmd.startsWith('fetch_') ? { ok: true, result: { mime: 'image/svg+xml', data } } : cmd === 'stream_list' ? { ok: true, result: { streams: [] } } : { ok: false, error: { code: 'not_connected', message: 'Synthetic fixture, no server' } }); }); await page.evaluate(() => { const live = new Map(); const create = URL.createObjectURL.bind(URL); const revoke = URL.revokeObjectURL.bind(URL); URL.createObjectURL = blob => { const url = create(blob); live.set(url, blob.size); return url; }; URL.revokeObjectURL = url => { live.delete(url); revoke(url); }; window.__stateAudit = { live, microphoneRequests: 0 }; navigator.mediaDevices.getUserMedia = async () => { __stateAudit.microphoneRequests++; throw new Error('Microphone forbidden in state fixture'); }; }); const cdp = await page.context().newCDPSession(page); await cdp.send('HeapProfiler.enable'); async function sample(stage) { await page.waitForTimeout(100); await cdp.send('HeapProfiler.collectGarbage'); await cdp.send('HeapProfiler.collectGarbage'); const memory = await cdp.send('Runtime.getHeapUsage'); const state = await page.evaluate(() => ({ blobs: __stateAudit.live.size, blobBytes: [...__stateAudit.live.values()].reduce((a, b) => a + b, 0), images: document.querySelectorAll('#tree .avatar img').length, rows: document.querySelectorAll('#tree .member-row').length, microphoneRequests: __stateAudit.microphoneRequests })); result.samples.push({ stage, memory, state }); console.log(label, stage, JSON.stringify(state)); } async function snapshot(generation, avatars) { await app.evaluate(({ BrowserWindow }, { generation, avatars }) => { BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...{ event: 'snapshot', memoryAuditSnapshot: generation, own_client_id: 1, own_channel_id: 1, server: { name: `Generated server ${generation}`, version: 'fixture', welcome_message: '' }, channels: [{ id: 1, parent_id: 0, depth: 0, name: 'Generated', codec: 'opus_voice' }], clients: Array.from({ length: 10 }, (_, i) => ({ id: i + 1, uid: `fixture-${i}`, nickname: `Member ${i}`, channel_id: 1, is_self: i === 0, input_hardware: true, talk_power: 0, avatar_hash: avatars ? `hash-${generation}-${i}` : null, description: `Generation ${generation}, member ${i}: ${'generated description '.repeat(512)}` })), server_groups: [], channel_groups: [], }, connectionId: 'c1' }); }, { generation, avatars }); await page.waitForFunction(() => document.querySelectorAll('#tree .member-row').length === 10); await page.waitForTimeout(30); } async function disconnect() { await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.send('core:event', { ...{ event: 'state', state: 'disconnected' }, connectionId: 'c1' })); await page.waitForFunction(() => document.querySelectorAll('#tree .member-row').length === 0); } await sample('initial'); for (let n = 0; n < 20; n++) { await snapshot(n, true); if (n % 5 === 4) await sample(`avatar-${n + 1}`); } await disconnect(); await sample('avatars-disconnected'); for (let n = 0; n < 20; n++) { await snapshot(100 + n, false); await disconnect(); } await sample('reconnects-disconnected'); const chunks = []; const chunk = ({ chunk }) => chunks.push(chunk); cdp.on('HeapProfiler.addHeapSnapshotChunk', chunk); await cdp.send('HeapProfiler.takeHeapSnapshot'); cdp.off('HeapProfiler.addHeapSnapshotChunk', chunk); const text = chunks.join(''); writeFileSync(path.join(out, `${label}.heapsnapshot`), text); const heap = JSON.parse(text); const fields = heap.snapshot.meta.edge_fields; const types = heap.snapshot.meta.edge_types[0]; let retainedSnapshots = 0; for (let i = 0; i < heap.edges.length; i += fields.length) { if (types[heap.edges[i]] === 'property' && heap.strings[heap.edges[i + 1]] === 'memoryAuditSnapshot') retainedSnapshots++; } result.retainedSnapshots = retainedSnapshots; if (args.includes('--verify')) { for (const s of result.samples.filter(s => s.stage.startsWith('avatar-'))) { assert.equal(s.state.blobs, 10); assert.equal(s.state.images, 10); } assert.equal(result.samples.at(-1).state.blobs, 0); assert.equal(result.samples.at(-1).state.microphoneRequests, 0); assert.equal(retainedSnapshots, 0); assert.equal(result.errors.length, 0); } } catch (e) { result.errors.push(e.stack); process.exitCode = 1; } finally { if (app) await app.close(); rmSync(profile, { recursive: true, force: true }); writeFileSync(path.join(out, `${label}.json`), JSON.stringify(result, null, 2)); }