// Isolated real-Electron memory workload. Never connects or captures a microphone. // node scripts/audit-memory.mjs --out [--label baseline|after] import { launchApp } from './lib/electron-app.mjs'; import { mkdirSync, writeFileSync, appendFileSync, readFileSync, 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', 'audit'); const fakeCapture = opt('capture', 'generated') === 'fake'; mkdirSync(out, { recursive: true }); const profile = mkdtempSync(path.join(tmpdir(), 'teamspeach-memory-')); const result = { label, workload: 'generated silent capture/playback, synthetic chat, real device enumeration; disconnected', gc: 'CDP HeapProfiler.collectGarbage at every checkpoint, test only', samples: [], errors: [] }; result.captureSource = fakeCapture ? 'Chromium fake media device (launch flags, no physical capture)' : 'silent generated MediaStream clones'; let app; try { app = await launchApp({ exe: opt('exe'), profile, args: fakeCapture ? ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] : [], 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', 'MemoryAudit'); await page.click('#onboarding-submit'); await page.waitForSelector('#view-app', { state: 'visible' }); const cdp = await page.context().newCDPSession(page); await cdp.send('HeapProfiler.enable'); await cdp.send('Performance.enable'); const audioNodes = new Map(); cdp.on('WebAudio.audioNodeCreated', ({ node }) => audioNodes.set(node.nodeId, node)); cdp.on('WebAudio.audioNodeWillBeDestroyed', ({ nodeId }) => audioNodes.delete(nodeId)); cdp.on('WebAudio.contextWillBeDestroyed', ({ contextId }) => { for (const [id, node] of audioNodes) if (node.contextId === contextId) audioNodes.delete(id); }); // Chromium does not emit node-destroyed events for every node of a closed context. cdp.on('WebAudio.contextChanged', ({ context }) => { if (context.contextState === 'closed') { for (const [id, node] of audioNodes) if (node.contextId === context.contextId) audioNodes.delete(id); } }); await cdp.send('WebAudio.enable'); await page.evaluate(async (fakeCapture) => { const { AudioEngine } = await import('./js/audio/engine.js'); const chat = await import('./js/chat.js'); const { S } = await import('./js/state.js'); const generator = new AudioContext({ sampleRate: 48000 }); const destination = generator.createMediaStreamDestination(); const source = generator.createConstantSource(); source.offset.value = 0; source.connect(destination); source.start(); const original = navigator.mediaDevices.getUserMedia; if (!fakeCapture) navigator.mediaDevices.getUserMedia = async () => destination.stream.clone(); const engine = new AudioEngine({ onFrame() {} }); await engine.init(); window.__memoryAudit = { engine, playbackContext: engine.ctx, generator, destination, source, original, chat, S, sequence: 0, captureStarts: 0, captureStartTotalMs: 0, captureStartMaxMs: 0 }; }, fakeCapture); async function sample(stage) { await page.waitForTimeout(500); await cdp.send('HeapProfiler.collectGarbage'); await cdp.send('HeapProfiler.collectGarbage'); const heap = await cdp.send('Runtime.getHeapUsage'); const dom = await cdp.send('Memory.getDOMCounters'); const counts = {}; for (const name of ['AudioWorkletNode', 'MediaStreamAudioSourceNode', 'GainNode', 'MediaStream', 'HTMLLIElement']) { const proto = await cdp.send('Runtime.evaluate', { expression: `${name}.prototype`, objectGroup: 'audit-count' }); const objects = await cdp.send('Runtime.queryObjects', { prototypeObjectId: proto.result.objectId, objectGroup: 'audit-count' }); const count = await cdp.send('Runtime.callFunctionOn', { objectId: objects.objects.objectId, functionDeclaration: 'function(){return this.length}', returnByValue: true }); counts[name] = count.result.value; } await cdp.send('Runtime.releaseObjectGroup', { objectGroup: 'audit-count' }); const ui = await page.evaluate(() => ({ rows: document.querySelector('#chat-log').children.length, tabs: document.querySelector('#chat-tabs').children.length, menus: document.querySelectorAll('.device-menu').length, capturing: window.__memoryAudit?.engine.capturing ?? false, connection: window.__memoryAudit?.S.conn.state ?? 'closed' })); const playback = await page.evaluate(async () => { const a = window.__memoryAudit; if (!a) return null; return { sameContext: a.playbackContext === a.engine.ctx, state: a.engine.ctx.state, currentTime: a.engine.ctx.currentTime, stats: await a.engine.playbackStats(), captureStarts: a.captureStarts, captureStartMeanMs: a.captureStartTotalMs / a.captureStarts, captureStartMaxMs: a.captureStartMaxMs }; }); const processes = await app.evaluate(async ({ app }) => ({ main: { ...process.memoryUsage(), ...await process.getProcessMemoryInfo() }, metrics: app.getAppMetrics().map(p => ({ pid: p.pid, type: p.type, memory: p.memory })) })); const nativeAudio = {}; for (const { nodeType } of audioNodes.values()) nativeAudio[nodeType] = (nativeAudio[nodeType] ?? 0) + 1; result.samples.push({ stage, heap, dom, counts, nativeAudio, ui, playback, processes }); writeFileSync(path.join(out, `${label}.json`), JSON.stringify(result, null, 2)); console.log(label, stage, JSON.stringify({ heap: heap.usedSize, dom, counts, ui })); } async function cycle(captures, messages, menus) { await page.evaluate(async ({ captures, messages, menus }) => { const a = __memoryAudit; for (let n = 0; n < captures; n++) { const before = performance.now(); await a.engine.startCapture({}); const elapsed = performance.now() - before; a.captureStarts++; a.captureStartTotalMs += elapsed; a.captureStartMaxMs = Math.max(a.captureStartMaxMs, elapsed); a.engine.pushPlayback(new Uint8Array(1920)); await new Promise(r => setTimeout(r, 25)); a.engine.stopCapture(); } for (let n = 0; n < messages; n++) { a.chat.onText({ target: 'channel', from_client_id: n % 2 + 10, from_nickname: 'Generated', message: `Memory audit ${++a.sequence}: ${'synthetic text '.repeat(20)}` }); } for (let n = 0; n < menus; n++) { document.querySelector('#btn-mute').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true })); await new Promise(r => setTimeout(r, 10)); document.querySelector('.device-menu')?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); } }, { captures, messages, menus }); } await cycle(5, 500, 5); await sample('warm'); for (let n = 1; n <= 3; n++) { await cycle(40, 1000, 20); await sample(`cycle-${n}`); } // Fake-device native capture shutdown is asynchronous; separate it from retained context leaks. await page.waitForTimeout(12000); await sample('settled-12s'); const snapshotFile = path.join(out, `${label}.heapsnapshot`); writeFileSync(snapshotFile, ''); const snapshotChunk = ({ chunk }) => appendFileSync(snapshotFile, chunk); cdp.on('HeapProfiler.addHeapSnapshotChunk', snapshotChunk); await cdp.send('HeapProfiler.takeHeapSnapshot'); cdp.off('HeapProfiler.addHeapSnapshotChunk', snapshotChunk); const heapSnapshot = JSON.parse(readFileSync(snapshotFile, 'utf8')); const nativeHeapCounts = {}; const nodeWidth = heapSnapshot.snapshot.meta.node_fields.length; const nodeTypes = heapSnapshot.snapshot.meta.node_types[0]; for (let i = 0; i < heapSnapshot.nodes.length; i += nodeWidth) { if (nodeTypes[heapSnapshot.nodes[i]] !== 'native') continue; const name = heapSnapshot.strings[heapSnapshot.nodes[i + 1]]; if (['AudioContext', 'AudioWorkletNode', 'MediaStreamAudioSourceNode', 'MediaStream', 'GainNode'].includes(name)) nativeHeapCounts[name] = (nativeHeapCounts[name] ?? 0) + 1; } result.nativeHeapCounts = nativeHeapCounts; await page.evaluate(() => __memoryAudit.chat.renderLog()); await sample('chat-rerender'); await page.evaluate(async () => { const a = __memoryAudit; a.engine.stopCapture(); await a.engine.ctx.close(); a.source.stop(); for (const track of a.destination.stream.getTracks()) track.stop(); await a.generator.close(); navigator.mediaDevices.getUserMedia = a.original; delete window.__memoryAudit; }); await sample('contexts-closed').catch(e => result.errors.push(`final sample: ${e.message}`)); result.initFailure = await page.evaluate(async () => { const { AudioEngine } = await import('./js/audio/engine.js'); const original = AudioWorklet.prototype.addModule; let calls = 0; AudioWorklet.prototype.addModule = function(...args) { if (++calls === 1) return Promise.reject(new Error('injected module failure')); return original.apply(this, args); }; const engine = new AudioEngine({ onFrame() {} }); let firstError; let retryError; try { try { await engine.init(); } catch (e) { firstError = e.message; } const afterFailure = { context: engine.ctx?.state ?? null, playback: Boolean(engine.playback) }; try { await engine.init(); } catch (e) { retryError = e.message; } const afterRetry = { context: engine.ctx?.state ?? null, playback: Boolean(engine.playback) }; return { firstError, retryError, calls, afterFailure, afterRetry }; } finally { AudioWorklet.prototype.addModule = original; if (engine.ctx && engine.ctx.state !== 'closed') await engine.ctx.close(); } }); result.chatChecks = await page.evaluate(async () => { const chat = await import('./js/chat.js'); chat.openPrivate(99, { nickname: 'Generated' }); const send = n => chat.onText({ target: 'client', from_client_id: 99, from_nickname: 'Generated', message: `Private generated message ${n}` }); for (let n = 0; n < 501; n++) send(n); const log = document.querySelector('#chat-log'); const anchor = log.children[300]; log.scrollTop = anchor.offsetTop - log.offsetTop; await new Promise(requestAnimationFrame); const before = anchor.getBoundingClientRect().top; send(501); await new Promise(requestAnimationFrame); const checks = { rows: log.children.length, firstText: log.firstElementChild.querySelector('.msg-body')?.textContent, firstHasHeader: Boolean(log.firstElementChild.querySelector('.msg-head')), scrollAnchorDelta: anchor.getBoundingClientRect().top - before }; document.querySelector('#chat-tabs .tab-close').click(); checks.tabsAfterClose = document.querySelector('#chat-tabs').children.length; return checks; }); if (args.includes('--verify')) { for (const sample of result.samples.filter(s => s.stage.startsWith('cycle-'))) { assert.equal(sample.ui.rows, 500, 'rendered chat must match its existing retained history'); assert.equal(sample.ui.menus, 0); assert.equal(sample.ui.capturing, false); assert.equal(sample.playback.sameContext, true); assert.equal(sample.playback.state, 'running'); assert.equal(sample.playback.stats.framesIn, sample.playback.captureStarts); } assert.ok((nativeHeapCounts.MediaStreamAudioSourceNode ?? 0) <= 1, 'native heap must not retain stopped capture sources'); assert.ok(nativeHeapCounts.AudioWorkletNode <= 3, 'native heap must retain playback nodes only'); assert.ok(nativeHeapCounts.AudioContext <= 4, 'closed capture contexts must be collectible'); assert.equal(result.initFailure.afterFailure.context, null); assert.equal(result.initFailure.afterRetry.playback, true); assert.equal(result.chatChecks.rows, 500); assert.equal(result.chatChecks.firstText, 'Private generated message 2'); assert.equal(result.chatChecks.firstHasHeader, true); assert.ok(Math.abs(result.chatChecks.scrollAnchorDelta) <= 1, 'retained visible chat anchor must not jump'); assert.equal(result.chatChecks.tabsAfterClose, 2); 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)); }