diff --git a/.gitignore b/.gitignore index 9331ae0a..977b7b65 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,9 @@ platforms/ # Release APKs from scripts/release.sh dist/ +# CPU captures and source maps pulled from the installed app +profiles/ + # Logs logs *.log diff --git a/package.json b/package.json index 81a0f3ac..12869539 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "private": false, "scripts": { "input": "node scripts/faceclaw-input.cjs", + "profile:android": "node scripts/profile-android.cjs", "native:android": "node scripts/kotlin-build.cjs android", "native:ios": "node scripts/kotlin-build.cjs ios", "test:kotlin": "bash scripts/test-kotlin.sh", diff --git a/scripts/profile-android.cjs b/scripts/profile-android.cjs new file mode 100644 index 00000000..1db1d30c --- /dev/null +++ b/scripts/profile-android.cjs @@ -0,0 +1,304 @@ +#!/usr/bin/env node +'use strict'; + +// Host-side only: ART samples the process; V8 samples each JS isolate over CDP. +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); +const { SourceMap } = require('node:module'); + +const HELP = `Usage: npm run profile:android -- [options] + + --device SERIAL ADB device (or ANDROID_SERIAL; required if ambiguous) + --seconds N Recording duration, 1–300 (default: 10) + --mode all|js|art V8 TypeScript/JS, ART Java/Kotlin, or both (default: all) + --interval N Sampling interval in microseconds, 100–1000000 (default: 1000) + --out DIRECTORY New output directory (default: profiles/) + --package ID App package (default: com.faceclaw.app) + --no-source-maps Keep only generated JS locations + +Requires Node 22+, adb, and an already running debug build. No rebuild or restart. +Reproduce the workload while recording. Ctrl-C stops and saves early. +Disconnect other debuggers/profilers first. See scripts/profile-android.md. +`; + +function parseArgs(args, env = process.env) { + const options = { device: env.ANDROID_SERIAL, seconds: 10, mode: 'all', interval: 1000, + package: 'com.faceclaw.app', sourceMaps: true }; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--help' || arg === '-h') return { help: true }; + if (arg === '--no-source-maps') { options.sourceMaps = false; continue; } + if (!['--device', '--seconds', '--mode', '--interval', '--out', '--package'].includes(arg)) { + throw new Error(`Unknown option: ${arg}`); + } + const value = args[++i]; + if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}`); + options[arg.slice(2)] = ['--seconds', '--interval'].includes(arg) ? Number(value) : value; + } + if (!Number.isFinite(options.seconds) || options.seconds < 1 || options.seconds > 300) throw new Error('--seconds must be between 1 and 300.'); + if (!Number.isInteger(options.interval) || options.interval < 100 || options.interval > 1000000) throw new Error('--interval must be an integer between 100 and 1000000.'); + if (!['all', 'js', 'art'].includes(options.mode)) throw new Error('--mode must be all, js, or art.'); + // ADB shell joins arguments into a remote shell command. Keep all interpolated + // remote paths and package names restricted, even though execFile uses no shell. + if (!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/.test(options.package)) throw new Error('Invalid Android package ID.'); + return options; +} + +class Inspector { + constructor(socket) { + this.socket = socket; + this.nextId = 0; + this.pending = new Map(); + this.onEvent = () => {}; + socket.addEventListener('message', ({ data }) => { + const message = JSON.parse(data); + if (!message.id) { this.onEvent(message); return; } + const pending = this.pending.get(message.id); + if (!pending) return; + this.pending.delete(message.id); + clearTimeout(pending.timer); + if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.message}`)); + else pending.resolve(message.result); + }); + const disconnected = () => { + for (const pending of this.pending.values()) { + clearTimeout(pending.timer); + pending.reject(new Error('NativeScript inspector disconnected.')); + } + this.pending.clear(); + }; + socket.addEventListener('close', disconnected); + socket.addEventListener('error', disconnected); + } + + static async connect(port) { + const socket = new WebSocket(`ws://127.0.0.1:${port}`); + const inspector = new Inspector(socket); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { socket.close(); reject(new Error('Inspector connection timed out. Is this a running NativeScript debug build?')); }, 10000); + socket.addEventListener('open', () => { clearTimeout(timer); resolve(); }, { once: true }); + socket.addEventListener('error', () => { clearTimeout(timer); reject(new Error('Cannot connect to NativeScript inspector. Use a running debug build.')); }, { once: true }); + }); + return inspector; + } + + call(method, params = {}, sessionId) { + if (this.socket.readyState !== WebSocket.OPEN) return Promise.reject(new Error('Inspector is not connected.')); + const id = ++this.nextId; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(id); + reject(new Error(`${method} timed out${sessionId ? ` (${sessionId})` : ''}.`)); + }, 10000); + this.pending.set(id, { resolve, reject, timer, method }); + this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + } + + close() { this.socket.close(); } +} + +function remapProfile(profile, maps) { + const mapped = structuredClone(profile); + let mappedNodes = 0; + for (const node of mapped.nodes) { + const frame = node.callFrame; + const map = maps.get(frame.url); + if (!map || frame.lineNumber < 0 || frame.columnNumber < 0) continue; + const entry = map.findEntry(frame.lineNumber, frame.columnNumber); + if (!entry.originalSource || entry.originalLine === undefined) continue; + frame.url = entry.originalSource; + frame.lineNumber = entry.originalLine; + frame.columnNumber = entry.originalColumn; + if (entry.name) frame.functionName = entry.name; + // V8's generated line ticks no longer describe this source file. Keep them + // in the raw profile, but don't show misleading line counts in the mapped one. + delete node.positionTicks; + mappedNodes++; + } + return { profile: mapped, mappedNodes }; +} + +function traceSummary(buffer) { + const end = buffer.indexOf('*end\n'); + if (end < 0 || buffer.subarray(0, 8).toString() !== '*version') throw new Error('ART did not produce a valid method trace.'); + const header = buffer.subarray(0, end).toString(); + const methods = header.split('*methods\n')[1]?.trim().split('\n') || []; + return { bytes: buffer.length, overflow: header.includes('data-file-overflow=true'), + methods: methods.length, + faceclawMethods: methods.filter(line => line.includes('\tcom.faceclaw.')).length, + kotlinMethods: methods.filter(line => /\.kt(?:\t|$)/.test(line)).length }; +} + +async function record(options) { + if (typeof WebSocket === 'undefined') throw new Error('Node 22+ is required (built-in WebSocket).'); + const adb = (...args) => execFileSync('adb', [...(options.device ? ['-s', options.device] : []), ...args], + { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, timeout: 30000, stdio: ['ignore', 'pipe', 'pipe'] }); + if (!options.device) { + const devices = adb('devices').split('\n').filter(line => /\tdevice\s*$/.test(line)).map(line => line.split('\t')[0]); + if (devices.length !== 1) throw new Error(`Found ${devices.length} ADB devices. Select one with --device SERIAL.`); + options.device = devices[0]; + } + const pids = adb('shell', 'pidof', options.package).trim().split(/\s+/); + if (pids.length !== 1 || !/^\d+$/.test(pids[0])) throw new Error('Start Faceclaw before profiling; expected one app process.'); + const pid = pids[0]; + try { adb('shell', 'run-as', options.package, 'id'); } + catch { throw new Error('Profiling requires an installed debug build (run-as failed). Build with ./build.sh --env.sourceMap=source-map.'); } + const stamp = new Date().toISOString().replace(/[:.]/g, '-'); + const output = path.resolve(options.out || path.join('profiles', stamp)); + fs.mkdirSync(path.dirname(output), { recursive: true }); + fs.mkdirSync(output); // Refuse to overwrite an earlier capture. + const remoteTrace = `/data/local/tmp/faceclaw-${stamp}-${process.pid}.trace`; + const summary = { device: options.device, package: options.package, pid, mode: options.mode, + intervalUs: options.interval, requestedSeconds: options.seconds, startedAt: new Date().toISOString(), + profiles: [], warnings: [] }; + const warn = message => { summary.warnings.push(message); console.error(`Warning: ${message}`); }; + let port, inspector, artStarted = false, stopping = false, interrupted = false, wake; + const targets = new Map(); + const stopEarly = () => { interrupted = true; if (wake) wake(); }; + process.on('SIGINT', stopEarly); + process.on('SIGTERM', stopEarly); + let failure; + + async function startTarget(sessionId, title) { + const key = sessionId || 'main'; + if (targets.has(key) || stopping) return; + const target = { sessionId, title, key, started: false }; + targets.set(key, target); + target.ready = (async () => { + await inspector.call('Profiler.enable', {}, sessionId); + await inspector.call('Profiler.setSamplingInterval', { interval: options.interval }, sessionId); + await inspector.call('Profiler.start', {}, sessionId); + target.started = true; + target.startedAt = new Date().toISOString(); + console.log(`V8 recording: ${title}`); + })().catch(error => { warn(`Cannot profile ${title}: ${error.message}`); }); + await target.ready; + } + + try { + if (options.mode !== 'art') { + port = adb('forward', 'tcp:0', `localabstract:${options.package}-inspectorServer`).trim(); + if (!/^\d+$/.test(port)) throw new Error('ADB did not allocate an inspector port.'); + inspector = await Inspector.connect(port); + inspector.onEvent = message => { + if (message.method === 'Target.attachedToTarget') { + const { sessionId, targetInfo } = message.params; + if (targetInfo.type === 'worker') void startTarget(sessionId, targetInfo.url || targetInfo.title); + } else if (message.method === 'Target.detachedFromTarget') { + const target = targets.get(message.params.sessionId); + if (target) { target.detached = true; warn(`Worker exited before its profile could be saved: ${target.title}`); } + } + }; + await startTarget(undefined, 'main'); + if (!targets.get('main').started) throw new Error('Main V8 profiler failed to start.'); + try { + await inspector.call('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }); + await Promise.all([...targets.values()].map(target => target.ready)); + } catch (error) { warn(`Worker discovery unavailable; main V8 profile still active: ${error.message}`); } + } + if (options.mode !== 'js') { + const result = adb('shell', 'am', 'profile', 'start', '--sampling', String(options.interval), pid, remoteTrace); + if (/error|exception|failed/i.test(result)) throw new Error(result.trim()); + artStarted = true; + console.log('ART recording: Java/Kotlin across the app process'); + } + console.log(`Reproduce the workload now (${options.seconds}s; Ctrl-C saves early).`); + if (!interrupted) await new Promise(resolve => { + const timer = setTimeout(resolve, options.seconds * 1000); + wake = () => { clearTimeout(timer); resolve(); }; + }); + } catch (error) { failure = error; } + finally { + stopping = true; + // Stop every profiler before pulling maps/files. Failures in one profiler + // must not prevent the others from stopping or their data from being saved. + if (artStarted) { + try { adb('shell', 'am', 'profile', 'stop', pid); } + catch (error) { warn(`Could not stop ART: ${error.message}. Run adb -s ${options.device} shell am profile stop ${pid}`); } + } + await Promise.all([...targets.values()].map(async target => { + await target.ready; + if (!target.started || target.detached) return; + try { + const { profile } = await inspector.call('Profiler.stop', {}, target.sessionId); + if (!Array.isArray(profile?.nodes)) throw new Error('Inspector returned no CPU profile.'); + const name = `js-${target.key.replace(/[^A-Za-z0-9_-]/g, '_')}`; + fs.writeFileSync(path.join(output, `${name}.raw.cpuprofile`), JSON.stringify(profile)); + target.profile = profile; + summary.profiles.push({ name, title: target.title, startedAt: target.startedAt, + samples: profile.samples?.length || 0, nodes: profile.nodes.length }); + } catch (error) { warn(`Could not save ${target.title}: ${error.message}`); } + })); + inspector?.close(); + if (port) { + try { adb('forward', '--remove', `tcp:${port}`); } + catch (error) { warn(`Could not remove ADB forward tcp:${port}: ${error.message}`); } + } + process.removeListener('SIGINT', stopEarly); + process.removeListener('SIGTERM', stopEarly); + } + + summary.stoppedAt = new Date().toISOString(); + summary.interrupted = interrupted; + if (artStarted) { + try { + const file = path.join(output, 'java-kotlin.trace'); + adb('pull', remoteTrace, file); + summary.art = traceSummary(fs.readFileSync(file)); + if (summary.art.overflow) warn('ART trace buffer overflowed. Use a shorter capture or a larger --interval.'); + adb('shell', 'rm', remoteTrace); + } catch (error) { warn(`Could not retrieve ART trace (left at ${remoteTrace}): ${error.message}`); } + } + + if (options.sourceMaps && summary.profiles.length) { + // Use maps from the installed app, never a potentially mismatched local build. + const maps = new Map(); + const urls = new Set([...targets.values()].flatMap(target => target.profile?.nodes.map(node => node.callFrame.url) || [])); + for (const url of urls) { + const prefix = `file:///data/data/${options.package}/files/app/`; + const alternate = `file:///data/user/0/${options.package}/files/app/`; + const relative = url.startsWith(prefix) ? url.slice(prefix.length) : url.startsWith(alternate) ? url.slice(alternate.length) : ''; + if (!/^[A-Za-z0-9_.-]+\.(?:m?js)$/.test(relative)) continue; + try { + let payload; + try { payload = adb('exec-out', 'run-as', options.package, 'cat', `files/app/${relative}.map`); } + catch { + const source = adb('exec-out', 'run-as', options.package, 'cat', `files/app/${relative}`); + const inline = source.match(/sourceMappingURL=data:application\/json[^,\n]*;base64,([A-Za-z0-9+/=]+)/); + if (!inline) throw new Error('no external or inline map'); + payload = Buffer.from(inline[1], 'base64').toString('utf8'); + } + maps.set(url, new SourceMap(JSON.parse(payload))); + fs.mkdirSync(path.join(output, 'source-maps'), { recursive: true }); + fs.writeFileSync(path.join(output, 'source-maps', `${relative}.map`), payload); + } catch (error) { warn(`Source map unavailable for ${relative}: ${error.message}. Generated locations remain usable.`); } + } + for (const target of targets.values()) { + if (!target.profile) continue; + const name = `js-${target.key.replace(/[^A-Za-z0-9_-]/g, '_')}`; + const mapped = remapProfile(target.profile, maps); + fs.writeFileSync(path.join(output, `${name}.cpuprofile`), JSON.stringify(mapped.profile)); + summary.profiles.find(item => item.name === name).mappedNodes = mapped.mappedNodes; + } + } + if (failure) summary.error = failure.message; + fs.writeFileSync(path.join(output, 'capture.json'), JSON.stringify(summary, null, 2) + '\n'); + console.log(`Saved ${output}`); + for (const profile of summary.profiles) console.log(` ${profile.name}: ${profile.samples} samples, ${profile.mappedNodes || 0} source-mapped nodes`); + if (summary.art) console.log(` ART: ${summary.art.methods} methods (${summary.art.faceclawMethods} Faceclaw, ${summary.art.kotlinMethods} with Kotlin source)`); + if (failure) throw failure; + if ((options.mode !== 'js' && !summary.art) || (options.mode !== 'art' && !summary.profiles.length)) throw new Error('Capture incomplete; see capture.json.'); + return summary; +} + +if (require.main === module) { + Promise.resolve().then(() => { + const options = parseArgs(process.argv.slice(2)); + if (options.help) console.log(HELP); + else return record(options); + }).catch(error => { console.error(`Profiling failed: ${error.message}`); process.exitCode = 1; }); +} + +module.exports = { parseArgs, Inspector, remapProfile, traceSummary, record }; diff --git a/scripts/profile-android.md b/scripts/profile-android.md new file mode 100644 index 00000000..fb4a7414 --- /dev/null +++ b/scripts/profile-android.md @@ -0,0 +1,105 @@ +# Android CPU profiling + +Faceclaw can capture all three languages without adding instrumentation to the +app: Android Runtime (ART) sampling for Java/Kotlin, and V8 sampling for the +TypeScript compiled to JavaScript. The host script attaches to a running debug +build, records for a bounded duration, stops the profilers, and saves their files. +Nothing runs in the app when a capture is not active. + +## Record + +Use Node 22+ and `adb` on your PATH. Install and launch a **debug** build first. +For a new build, external source maps make capture extraction faster: + +```sh +./build_and_run.sh --env.sourceMap=source-map +adb devices -l +npm run profile:android -- --device SERIAL --seconds 15 +``` + +An existing debug build works too; the script also handles inline source maps. +No rebuild, app restart, Android Studio, root, or additional npm dependencies are +needed to record. Release APKs are not supported by this command. + +Reproduce the slow operation after the command prints `Reproduce the workload +now`. Ctrl-C stops and saves early. Disconnect Chrome/NativeScript debuggers and +Android Studio CPU recordings first; this command needs exclusive profiler use. +If USB and wireless ADB both point to the same phone, select one with `--device`. +`ANDROID_SERIAL` also works, or omit the device when exactly one is connected. + +```sh +# Java/Kotlin only, all threads in the app process +npm run profile:android -- --device SERIAL --mode art --seconds 15 + +# TypeScript/JavaScript only: main isolate and live NativeScript workers +npm run profile:android -- --device SERIAL --mode js --seconds 15 + +# Less frequent sampling (microseconds), with a named output directory +npm run profile:android -- --device SERIAL --interval 5000 --out profiles/scrolling +``` + +Default interval is 1,000 microseconds (1 ms); default duration is 10 seconds. +The output directory must not already exist. Captures go under git-ignored +`profiles/` by default. `--no-source-maps` skips source-map extraction. + +## Read the results + +| File | Contents | Viewer | +| --- | --- | --- | +| `java-kotlin.trace` | Sampled managed stacks across app threads, with Java and Kotlin method names | Android Studio Profiler: import/open a trace | +| `js-main.cpuprofile` | Main V8 isolate, locations mapped back to TypeScript where available | Chrome DevTools Performance: load profile, or [Speedscope](https://www.speedscope.app/) | +| `js-NS_WORKER_*.cpuprofile` | One profile per attached NativeScript worker | Same CPU-profile viewers | +| `*.raw.cpuprofile` | Original V8 profile with generated bundle locations and line ticks | Same CPU-profile viewers | +| `capture.json` | Worker names, capture parameters, sample counts, mapped-node counts, warnings | Text editor | +| `source-maps/` | Maps copied from the installed application, including embedded sources when available | Retained for interpreting the capture | + +Use flame charts and bottom-up views to find expensive stacks. The worker URL in +`capture.json` identifies which app each numbered worker belongs to. Only raw +profiles are written with `--no-source-maps`; otherwise both versions are saved, +even when some locations cannot be mapped. Maps come from the installed app, +so a different local checkout cannot silently mislabel its frames. + +## Coverage and interpretation + +* **Java and Kotlin:** ART samples all managed threads in the app process, + including shared Kotlin code packaged by `@faceclaw/kotlin`. Inlined Kotlin + functions may appear as their callers. This is sampling, not an exact count + of every method invocation. +* **TypeScript:** V8 samples the main isolate and workers already running or + created during recording. Workers must survive until capture stops to return + their profiles; exited workers are reported as warnings. Older NativeScript + runtimes without worker auto-attach can still capture the main isolate. +* **Separate runtimes:** These are overlapping captures, not a single stitched + cross-language call tree. Starts/stops have a small skew. V8 may show time + inside a native bridge call; inspect ART to see the Java/Kotlin side. Embedded + WebView JavaScript and native C/C++ stacks are outside this command's coverage. +* **Overhead:** Profiling changes timing, especially with both profilers active. + Use separate `--mode js` / `--mode art` runs and larger intervals when needed. + Keep the existing frame timings for end-to-end latency. Idle/background + workers can return very few samples; exercise the code you want to measure. +* **Failures:** Raw profiles are saved before source mapping. `capture.json` + reports partial captures and ART buffer overflow. On overflow, shorten the + capture or increase the interval. Missing maps leave generated JS locations + usable; build with `--env.sourceMap=source-map` for TypeScript locations. + +On normal completion, Ctrl-C, or a handled capture error, the script attempts to +stop every profiler it started and removes its own ADB forwarding. A killed host +process or disconnected phone can prevent cleanup. Reconnect and stop ART with +`adb -s SERIAL shell am profile stop com.faceclaw.app`; restart the app if V8 +profiling remains active. A failed pull leaves the trace at the device path +printed in the warning for manual recovery. + +## Verified setup + +Verified on a Pixel 7a running Android 16, with Faceclaw 0.7.2 and this checkout's +NativeScript Android 9.1.1 runtime. A 10-second capture produced Java/Kotlin +method data, a TypeScript-mapped main profile, and profiles for terminal and +Flappy Bird workers (Flappy was idle). No APK changes were required. + +The implementation uses Android's `am profile start --sampling` / `stop` and +NativeScript's ADB-forwarded `PACKAGE-inspectorServer` WebSocket, with CDP +`Profiler` commands and flattened `Target.setAutoAttach` worker sessions. + +References: [Android sampled method tracing](https://developer.android.com/studio/profile/generate-trace-logs), +[NativeScript debugging and profiling](https://docs.nativescript.org/guide/debugging), +[V8 inspector CPU profiling protocol](https://chromedevtools.github.io/devtools-protocol/tot/Profiler/). diff --git a/tests/profile-android.test.cjs b/tests/profile-android.test.cjs new file mode 100644 index 00000000..57d9816c --- /dev/null +++ b/tests/profile-android.test.cjs @@ -0,0 +1,68 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { SourceMap } = require('node:module'); +const { parseArgs, remapProfile, traceSummary, Inspector } = require('../scripts/profile-android.cjs'); + +test('profiling CLI validates remote shell arguments and sampling limits', () => { + assert.equal(parseArgs([], {}).mode, 'all'); + assert.equal(parseArgs([], { ANDROID_SERIAL: 'usb-device' }).device, 'usb-device'); + for (const args of [ + ['--package', 'com.faceclaw.app;id'], ['--package', '../app'], + ['--seconds', 'NaN'], ['--seconds', '0'], ['--seconds', '301'], + ['--interval', '1'], ['--interval', '100.5'], ['--mode', 'native'], ['--device'], + ]) assert.throws(() => parseArgs(args, {})); +}); + +test('source mapping keeps V8 sample structure and raw locations intact', () => { + const map = new SourceMap({ version: 3, sources: ['webpack://faceclaw/app/example.ts'], + names: ['originalName'], mappings: 'AASEA', sourcesContent: [''] }); + const raw = { nodes: [{ id: 1, callFrame: { url: 'bundle.mjs', functionName: 'minified', + lineNumber: 0, columnNumber: 0 }, hitCount: 2, positionTicks: [{ line: 1, ticks: 2 }] }, + { id: 2, callFrame: { url: '', functionName: '(idle)', lineNumber: -1, columnNumber: -1 } }], + samples: [1, 2, 1], timeDeltas: [1000, 1500, 2000], startTime: 123, endTime: 4623 }; + const result = remapProfile(raw, new Map([['bundle.mjs', map]])); + assert.equal(result.mappedNodes, 1); + assert.deepEqual(result.profile.nodes[0].callFrame, { url: 'webpack://faceclaw/app/example.ts', + functionName: 'originalName', lineNumber: 9, columnNumber: 2 }); + assert.equal(result.profile.nodes[0].positionTicks, undefined); + assert.equal(raw.nodes[0].callFrame.url, 'bundle.mjs'); + assert.ok(raw.nodes[0].positionTicks); + assert.deepEqual(result.profile.samples, raw.samples); + assert.deepEqual(result.profile.timeDeltas, raw.timeDeltas); + assert.deepEqual(result.profile.nodes[1], raw.nodes[1]); +}); + +test('ART validation detects overflow and recognizes Kotlin source names', () => { + const trace = Buffer.from('*version\n3\ndata-file-overflow=true\n*methods\n' + + '0x4\tcom.faceclaw.Example\tfoo\t()V\tExample.kt\n' + + '0x8\tandroid.Example\tbar\t()V\tExample.java\n*end\nSLOW'); + assert.deepEqual(traceSummary(trace), { bytes: trace.length, overflow: true, methods: 2, faceclawMethods: 1, kotlinMethods: 1 }); + assert.throws(() => traceSummary(Buffer.from('Permission denied'))); +}); + +test('CDP routes worker sessions and handles out-of-order replies and disconnects', async () => { + class Socket extends EventTarget { + readyState = WebSocket.OPEN; + sent = []; + send(data) { this.sent.push(JSON.parse(data)); } + receive(data) { this.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(data) })); } + close() { this.readyState = WebSocket.CLOSED; this.dispatchEvent(new Event('close')); } + } + const socket = new Socket(); + const inspector = new Inspector(socket); + const main = inspector.call('Profiler.stop'); + const worker = inspector.call('Profiler.stop', {}, 'NS_WORKER_1'); + assert.equal(socket.sent[1].sessionId, 'NS_WORKER_1'); + socket.receive({ id: 2, sessionId: 'NS_WORKER_1', result: { worker: true } }); + socket.receive({ id: 1, result: { main: true } }); + assert.deepEqual(await worker, { worker: true }); + assert.deepEqual(await main, { main: true }); + const failed = inspector.call('Profiler.start'); + socket.receive({ id: 3, error: { message: 'already started' } }); + await assert.rejects(failed, /already started/); + const disconnected = inspector.call('Profiler.stop'); + inspector.close(); + await assert.rejects(disconnected, /disconnected/); + await assert.rejects(inspector.call('Profiler.stop'), /not connected/); +});