Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,11 @@ If you run into any issues, checkout our [troubleshooting guide](./docs/troubles
- [`take_snapshot`](docs/tool-reference.md#take_snapshot)
- [`screencast_start`](docs/tool-reference.md#screencast_start)
- [`screencast_stop`](docs/tool-reference.md#screencast_stop)
- **Memory** (9 tools)
- **Memory** (11 tools)
- [`take_heapsnapshot`](docs/tool-reference.md#take_heapsnapshot)
- [`close_heapsnapshot`](docs/tool-reference.md#close_heapsnapshot)
- [`compare_heapsnapshots_class_nodes`](docs/tool-reference.md#compare_heapsnapshots_class_nodes)
- [`compare_heapsnapshots_summary`](docs/tool-reference.md#compare_heapsnapshots_summary)
- [`get_heapsnapshot_class_nodes`](docs/tool-reference.md#get_heapsnapshot_class_nodes)
- [`get_heapsnapshot_details`](docs/tool-reference.md#get_heapsnapshot_details)
- [`get_heapsnapshot_dominators`](docs/tool-reference.md#get_heapsnapshot_dominators)
Expand Down
27 changes: 26 additions & 1 deletion docs/tool-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@
- [`take_snapshot`](#take_snapshot)
- [`screencast_start`](#screencast_start)
- [`screencast_stop`](#screencast_stop)
- **[Memory](#memory)** (9 tools)
- **[Memory](#memory)** (11 tools)
- [`take_heapsnapshot`](#take_heapsnapshot)
- [`close_heapsnapshot`](#close_heapsnapshot)
- [`compare_heapsnapshots_class_nodes`](#compare_heapsnapshots_class_nodes)
- [`compare_heapsnapshots_summary`](#compare_heapsnapshots_summary)
- [`get_heapsnapshot_class_nodes`](#get_heapsnapshot_class_nodes)
- [`get_heapsnapshot_details`](#get_heapsnapshot_details)
- [`get_heapsnapshot_dominators`](#get_heapsnapshot_dominators)
Expand Down Expand Up @@ -469,6 +471,29 @@ in the DevTools Elements panel (if any).

---

### `compare_heapsnapshots_class_nodes`

**Description:** Loads two memory heapsnapshots and returns the diff details (added/deleted instances) for a specific class. (requires flag: --memoryDebugging=true)

**Parameters:**

- **baseFilePath** (string) **(required)**: A path to the base .heapsnapshot file (earlier snapshot).
- **classIndex** (number) **(required)**: 0-based index of the class in the summary list to filter results, showing individual objects.
- **currentFilePath** (string) **(required)**: A path to the current .heapsnapshot file (later snapshot).

---

### `compare_heapsnapshots_summary`

**Description:** Loads two memory heapsnapshots and returns the summary diff between them (classes with changes). (requires flag: --memoryDebugging=true)

**Parameters:**

- **baseFilePath** (string) **(required)**: A path to the base .heapsnapshot file (earlier snapshot).
- **currentFilePath** (string) **(required)**: A path to the current .heapsnapshot file (later snapshot).

---

### `get_heapsnapshot_class_nodes`

**Description:** Loads a memory heapsnapshot and returns instances of a specific class with their IDs. (requires flag: --memoryDebugging=true)
Expand Down
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default defineConfig([
'**/node_modules',
'**/build/',
'tests/tools/fixtures/',
'tests/fixtures/',
'src/third_party/lighthouse-devtools-mcp-bundle.js',
]),
importPlugin.flatConfigs.typescript,
Expand Down
99 changes: 99 additions & 0 deletions src/HeapSnapshotManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,33 @@ import {
export type AggregatedInfoWithId =
WithSymbolId<DevTools.HeapSnapshotModel.HeapSnapshotModel.AggregatedInfo>;

export interface HeapSnapshotClassDiff {
className: string;
addedCount: number;
removedCount: number;
countDelta: number;
addedSize: number;
removedSize: number;
sizeDelta: number;
}

export interface HeapSnapshotDetailedClassDiff extends HeapSnapshotClassDiff {
addedIds: number[];
addedSelfSizes: number[];
deletedIds: number[];
deletedSelfSizes: number[];
}

export class HeapSnapshotManager {
#snapshotIdGenerator = createIdGenerator();
#snapshots = new Map<
string,
{
snapshot: DevTools.HeapSnapshotModel.HeapSnapshotProxy.HeapSnapshotProxy;
worker: DevTools.HeapSnapshotModel.HeapSnapshotProxy.HeapSnapshotWorkerProxy;
// DevTools calculateSnapshotDiff requires a unique baseSnapshotId to cache
// the calculated diffs on the worker. We use this key for that purpose.
diffCacheKey: number;
// TODO: use a multimap
idToClassKey: Map<number, string>;
classKeyToId: Map<string, number>;
Expand All @@ -43,6 +64,7 @@ export class HeapSnapshotManager {
this.#snapshots.set(absolutePath, {
snapshot,
worker,
diffCacheKey: this.#snapshotIdGenerator(),
idToClassKey: new Map<number, string>(),
classKeyToId: new Map<string, number>(),
idGenerator: createIdGenerator(),
Expand Down Expand Up @@ -173,6 +195,56 @@ export class HeapSnapshotManager {
return await provider.serializeItemsRange(0, Infinity);
}

async getClassDiffs(
baseFilePath: string,
currentFilePath: string,
): Promise<HeapSnapshotClassDiff[]> {
const rawDiffs = await this.#getSortedRawClassDiffs(
baseFilePath,
currentFilePath,
);
return rawDiffs.map(rawDiff => ({
className: rawDiff.name,
addedCount: rawDiff.addedCount,
removedCount: rawDiff.removedCount,
countDelta: rawDiff.countDelta,
addedSize: rawDiff.addedSize,
removedSize: rawDiff.removedSize,
sizeDelta: rawDiff.sizeDelta,
}));
}

async getDetailedClassDiff(
baseFilePath: string,
currentFilePath: string,
classIndex: number,
): Promise<HeapSnapshotDetailedClassDiff> {
const classDiffs = await this.#getSortedRawClassDiffs(
baseFilePath,
currentFilePath,
);
const result = classDiffs[classIndex];
if (!result) {
throw new Error(
`Invalid classIndex: ${classIndex}. Total classes with changes: ${classDiffs.length}`,
);
}
const rawDiff = result;
return {
className: rawDiff.name,
addedCount: rawDiff.addedCount,
removedCount: rawDiff.removedCount,
countDelta: rawDiff.countDelta,
addedSize: rawDiff.addedSize,
removedSize: rawDiff.removedSize,
sizeDelta: rawDiff.sizeDelta,
addedIds: rawDiff.addedIds ?? [],
addedSelfSizes: rawDiff.addedSelfSizes ?? [],
deletedIds: rawDiff.deletedIds ?? [],
deletedSelfSizes: rawDiff.deletedSelfSizes ?? [],
};
}

#getCachedSnapshot(filePath: string) {
const absolutePath = path.resolve(filePath);
const cached = this.#snapshots.get(absolutePath);
Expand All @@ -182,6 +254,33 @@ export class HeapSnapshotManager {
return cached;
}

async #getSortedRawClassDiffs(
baseFilePath: string,
currentFilePath: string,
): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.Diff[]> {
const baseSnapshot = await this.getSnapshot(baseFilePath);
const currentSnapshot = await this.getSnapshot(currentFilePath);

const interfaceDefinitions = await currentSnapshot.interfaceDefinitions();
const aggregatesForDiff =
await baseSnapshot.aggregatesForDiff(interfaceDefinitions);
const cachedBaseSnapshot = this.#getCachedSnapshot(baseFilePath);
// DevTools calculateSnapshotDiff uses the first parameter (baseSnapshotId)
// as a cache key. We pass the unique diffCacheKey we generated when loading
// the base snapshot.
const rawDiffs = await currentSnapshot.calculateSnapshotDiff(
cachedBaseSnapshot.diffCacheKey,
aggregatesForDiff,
);

// Return a filtered and sorted array here to ensure that
// compare_heapsnapshot_summary and compare_heapsnapshot_details agree
// on indices.
return Object.values(rawDiffs)
.filter(diff => diff.addedCount > 0 || diff.removedCount > 0)
.sort((a, b) => b.sizeDelta - a.sizeDelta);
}

async resolveClassKeyFromId(
filePath: string,
id: number,
Expand Down
28 changes: 27 additions & 1 deletion src/McpContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import {
UniverseManager,
} from './devtools/DevtoolsUtils.js';
import {HeapSnapshotManager} from './HeapSnapshotManager.js';
import type {AggregatedInfoWithId} from './HeapSnapshotManager.js';
import type {
AggregatedInfoWithId,
HeapSnapshotClassDiff,
HeapSnapshotDetailedClassDiff,
} from './HeapSnapshotManager.js';
import {McpPage} from './McpPage.js';
import {
NetworkCollector,
Expand Down Expand Up @@ -1016,4 +1020,26 @@ export class McpContext implements Context {
): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange> {
return await this.#heapSnapshotManager.getEdges(filePath, nodeId);
}

async getHeapSnapshotClassDiffs(
baseFilePath: string,
currentFilePath: string,
): Promise<HeapSnapshotClassDiff[]> {
return await this.#heapSnapshotManager.getClassDiffs(
baseFilePath,
currentFilePath,
);
}

async getHeapSnapshotDetailedClassDiff(
baseFilePath: string,
currentFilePath: string,
classIndex: number,
): Promise<HeapSnapshotDetailedClassDiff> {
return await this.#heapSnapshotManager.getDetailedClassDiff(
baseFilePath,
currentFilePath,
classIndex,
);
}
}
53 changes: 51 additions & 2 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ import type {WebMCPTool} from 'puppeteer-core';

import type {ParsedArguments} from './bin/chrome-devtools-mcp-cli-options.js';
import {ConsoleFormatter} from './formatters/ConsoleFormatter.js';
import {HeapSnapshotFormatter} from './formatters/HeapSnapshotFormatter.js';
import {isEdgeLike, isNodeLike} from './formatters/HeapSnapshotFormatter.js';
import {
HeapSnapshotFormatter,
isEdgeLike,
isNodeLike,
} from './formatters/HeapSnapshotFormatter.js';
import {IssueFormatter} from './formatters/IssueFormatter.js';
import {NetworkFormatter} from './formatters/NetworkFormatter.js';
import {SnapshotFormatter} from './formatters/SnapshotFormatter.js';
import type {
HeapSnapshotClassDiff,
HeapSnapshotDetailedClassDiff,
} from './HeapSnapshotManager.js';
import type {McpContext} from './McpContext.js';
import type {McpPage} from './McpPage.js';
import {UncaughtError} from './PageCollector.js';
Expand Down Expand Up @@ -225,6 +232,8 @@ export class McpResponse implements Response {
nodes?: DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange;
retainingPaths?: DevTools.HeapSnapshotModel.HeapSnapshotModel.RetainingPaths;
dominators?: DevTools.HeapSnapshotModel.HeapSnapshotModel.DominatorChain;
classDiffs?: HeapSnapshotClassDiff[];
detailedClassDiff?: HeapSnapshotDetailedClassDiff;
};
#networkRequestsOptions?: {
include: boolean;
Expand Down Expand Up @@ -501,6 +510,24 @@ export class McpResponse implements Response {
};
}

setHeapSnapshotClassDiffs(classDiffs: HeapSnapshotClassDiff[]) {
this.#heapSnapshotOptions = {
...this.#heapSnapshotOptions,
include: true,
classDiffs,
};
}

setHeapSnapshotDetailedClassDiff(
detailedClassDiff: HeapSnapshotDetailedClassDiff,
) {
this.#heapSnapshotOptions = {
...this.#heapSnapshotOptions,
include: true,
detailedClassDiff,
};
}

attachImage(value: ImageContentData): void {
this.#images.push(value);
}
Expand Down Expand Up @@ -832,6 +859,8 @@ export class McpResponse implements Response {
heapSnapshotNodes?: readonly object[];
heapSnapshotRetainingPaths?: object;
heapSnapshotDominators?: readonly object[];
heapSnapshotClassDiffs?: HeapSnapshotClassDiff[];
heapSnapshotDetailedClassDiff?: HeapSnapshotDetailedClassDiff;
extensionServiceWorkers?: object[];
extensionPages?: object[];
errorMessage?: string;
Expand Down Expand Up @@ -1156,6 +1185,26 @@ Call ${handleDialog.name} to handle it before continuing.`);
}
structuredContent.heapSnapshotDominators = dominators;
}
const classDiffs = this.#heapSnapshotOptions.classDiffs;
if (classDiffs) {
response.push('### Heap Snapshot Diff');
response.push(
useToon
? toonEncode(classDiffs)
: HeapSnapshotFormatter.formatDiffSummary(classDiffs),
);
structuredContent.heapSnapshotClassDiffs = classDiffs;
}
const detailedClassDiff = this.#heapSnapshotOptions.detailedClassDiff;
if (detailedClassDiff) {
response.push('### Heap Snapshot Detailed Diff');
response.push(
useToon
? toonEncode(detailedClassDiff)
: HeapSnapshotFormatter.formatDiffDetails(detailedClassDiff),
);
structuredContent.heapSnapshotDetailedClassDiff = detailedClassDiff;
}
}

if (data.detailedNetworkRequest) {
Expand Down
49 changes: 49 additions & 0 deletions src/bin/chrome-devtools-cli-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,55 @@ export const commands: Commands = {
},
},
},
compare_heapsnapshots_class_nodes: {
description:
'Loads two memory heapsnapshots and returns the diff details (added/deleted instances) for a specific class. (requires flag: --memoryDebugging=true)',
category: 'Memory',
args: {
baseFilePath: {
name: 'baseFilePath',
type: 'string',
description:
'A path to the base .heapsnapshot file (earlier snapshot).',
required: true,
},
currentFilePath: {
name: 'currentFilePath',
type: 'string',
description:
'A path to the current .heapsnapshot file (later snapshot).',
required: true,
},
classIndex: {
name: 'classIndex',
type: 'number',
description:
'0-based index of the class in the summary list to filter results, showing individual objects.',
required: true,
},
},
},
compare_heapsnapshots_summary: {
description:
'Loads two memory heapsnapshots and returns the summary diff between them (classes with changes). (requires flag: --memoryDebugging=true)',
category: 'Memory',
args: {
baseFilePath: {
name: 'baseFilePath',
type: 'string',
description:
'A path to the base .heapsnapshot file (earlier snapshot).',
required: true,
},
currentFilePath: {
name: 'currentFilePath',
type: 'string',
description:
'A path to the current .heapsnapshot file (later snapshot).',
required: true,
},
},
},
drag: {
description: 'Drag an element onto another element',
category: 'Input automation',
Expand Down
Loading
Loading