Skip to content

Chrome DevTools for coding agents

fix: dispose heap snapshot workers on context teardown (#2428)

Gunjan Jaswalf245c7605706
diff --git a/src/HeapSnapshotManager.ts b/src/HeapSnapshotManager.ts
index 0a10ed92..c335a874 100644
--- a/src/HeapSnapshotManager.ts
+++ b/src/HeapSnapshotManager.ts
@@ -403,4 +403,11 @@ export class HeapSnapshotManager {
}
return false;
}
+
+ disposeAll(): void {
+ for (const cached of this.#snapshots.values()) {
+ cached.worker.dispose();
+ }
+ this.#snapshots.clear();
+ }
}
diff --git a/src/McpContext.ts b/src/McpContext.ts
index 1ae83fe9..b078e4a5 100644
--- a/src/McpContext.ts
+++ b/src/McpContext.ts
@@ -139,6 +139,7 @@ export class McpContext implements Context {
this.browser.off('targetdestroyed', this.#onTargetDestroyed);
this.#serviceWorkerConsoleCollector.dispose();
+ this.#heapSnapshotManager.disposeAll();
for (const mcpPage of this.#mcpPages.values()) {
mcpPage.dispose();
}
diff --git a/src/index.ts b/src/index.ts
index 1e8b0867..84b71b76 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -147,6 +147,7 @@ export async function createMcpServer(
});
if (context?.browser !== browser) {
+ context?.dispose();
context = await McpContext.from(browser, logger, {
experimentalDevToolsDebugging: devtools,
experimentalIncludeAllPages: serverArgs.experimentalIncludeAllPages,
diff --git a/tests/McpContext.test.ts b/tests/McpContext.test.ts
index 009076a1..f4b5a5ee 100644
--- a/tests/McpContext.test.ts
+++ b/tests/McpContext.test.ts
@@ -18,7 +18,7 @@ import sinon from 'sinon';
import {NetworkFormatter} from '../src/formatters/NetworkFormatter.js';
import {McpContext} from '../src/McpContext.js';
import {TextSnapshot} from '../src/TextSnapshot.js';
-import type {HTTPResponse} from '../src/third_party/index.js';
+import {type HTTPResponse} from '../src/third_party/index.js';
import type {TraceResult} from '../src/trace-processing/parse.js';
import {getMockRequest, html, withBrowser, withMcpContext} from './utils.js';
@@ -285,6 +285,24 @@ describe('McpContext', () => {
});
});
+ it('disposes loaded heap snapshots on teardown', async () => {
+ await withMcpContext(async (_response, context) => {
+ const filePath = path.join(
+ process.cwd(),
+ 'tests/fixtures/example.heapsnapshot',
+ );
+ await context.getHeapSnapshotStats(filePath);
+ assert.ok(context.hasHeapSnapshots(), 'snapshot loaded before teardown');
+
+ context.dispose();
+
+ assert.ok(
+ !context.hasHeapSnapshots(),
+ 'heap snapshots freed on teardown',
+ );
+ });
+ });
+
it('should include network requests in structured content', async t => {
await withMcpContext(async (response, context) => {
const mockRequest = getMockRequest({