Chrome DevTools for coding agents
feat: Add analyze_heapsnapshot_contexts MCP tool (#2791)
Dominik Inführ190aeee80f91
diff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex eb4c01e9..2eb7ef45 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -40,8 +40,9 @@- [`take_snapshot`](#take_snapshot)- [`screencast_start`](#screencast_start)- [`screencast_stop`](#screencast_stop)-- **[Memory](#memory)** (13 tools)+- **[Memory](#memory)** (14 tools)- [`take_heapsnapshot`](#take_heapsnapshot)+ - [`analyze_heapsnapshot_contexts`](#analyze_heapsnapshot_contexts)- [`close_heapsnapshot`](#close_heapsnapshot)- [`compare_heapsnapshots`](#compare_heapsnapshots)- [`get_heapsnapshot_class_nodes`](#get_heapsnapshot_class_nodes)@@ -507,6 +508,20 @@ in the DevTools Elements panel (if any).---+### `analyze_heapsnapshot_contexts`++**Description:** Loads a memory heapsnapshot to identify and rank closure contexts holding dead captured fields—variables no remaining live closure can read. Scopes are ranked globally by the retained size of these dead values to provide a prioritizing heuristic, rather than an exact measure of reclaimable bytes. (requires flag: --memoryDebugging=true)++**Parameters:**++- **filePath** (string) **(required)**: A path to a .heapsnapshot file to read.+- **pageIdx** (integer) _(optional)_: The zero-based page index. Defaults to 0.+- **pageSize** (integer) _(optional)_: The number of contexts to return per page. Defaults to 20.+- **retainedSize** (string) _(optional)_: Inclusive range for the dead-field score of a context (e.g. "10KB", "1MB-2MB", "-1MB", or "1MB-"). A single value is treated as a minimum.+- **scopeInfoNodeId** (integer) _(optional)_: Only return contexts declared by the scope with this ScopeInfo node id, as reported in the scope header of a previous call.++---+### `close_heapsnapshot`**Description:** Closes a previously loaded memory heapsnapshot, freeing its memory. (requires flag: --memoryDebugging=true)diff --git a/src/McpContext.ts b/src/McpContext.tsindex 20db12a1..f42a2841 100644--- a/src/McpContext.ts+++ b/src/McpContext.ts@@ -854,6 +854,12 @@ export class McpContext implements Context {return await this.#heapSnapshotManager.getObjectInfo(filePath, nodeId);}+ async analyzeHeapSnapshotContexts(+ filePath: string,+ ): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult> {+ return await this.#heapSnapshotManager.analyzeContexts(filePath);+ }+async closeHeapSnapshot(filePath: string): Promise<boolean> {return this.#heapSnapshotManager.disposeSnapshot(filePath);}diff --git a/src/McpResponse.ts b/src/McpResponse.tsindex cc23b4aa..0e4e7f2f 100644--- a/src/McpResponse.ts+++ b/src/McpResponse.ts@@ -19,6 +19,9 @@ import {resolveContainerQueries,} from './formatters/CssFormatter.js';import {+ collectRankedContexts,+ type ContextAnalysisReport,+ type ContextFilterOptions,HeapSnapshotFormatter,isEdgeLike,isNodeLike,@@ -78,6 +81,9 @@ interface TraceInsightData {insightName: InsightName;}+interface ContextAnalysisOptions+ extends PaginationOptions, ContextFilterOptions {}+export class McpResponse implements Response {#includePages = false;#includeExtensionServiceWorkers = false;@@ -109,6 +115,8 @@ export class McpResponse implements Response {detailedClassDiff?: HeapSnapshotDetailedClassDiff;duplicateStrings?: DuplicateStringGroup[];objectInfo?: DevTools.HeapSnapshotModel.HeapSnapshotModel.ObjectInfo;+ contextAnalysis?: DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult;+ contextAnalysisOptions?: ContextAnalysisOptions;};#networkRequestsOptions?: {include: boolean;@@ -461,6 +469,18 @@ export class McpResponse implements Response {};}+ setHeapSnapshotContextAnalysis(+ contextAnalysis: DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult,+ options?: ContextAnalysisOptions,+ ) {+ this.#heapSnapshotOptions = {+ ...this.#heapSnapshotOptions,+ include: true,+ contextAnalysis,+ contextAnalysisOptions: options,+ };+ }+attachImage(value: ImageContentData): void {this.#images.push(value);}@@ -857,6 +877,7 @@ export class McpResponse implements Response {heapSnapshotDetailedClassDiff?: HeapSnapshotDetailedClassDiff;heapSnapshotDuplicateStrings?: readonly DuplicateStringGroup[];heapSnapshotObjectDetails?: DevTools.HeapSnapshotModel.HeapSnapshotModel.ObjectInfo;+ heapSnapshotContextAnalysis?: ContextAnalysisReport;extensionServiceWorkers?: object[];extensionPages?: object[];comments?: StructuredCommentThread[];@@ -1316,6 +1337,33 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`););structuredContent.heapSnapshotObjectDetails = objectInfo;}+ const contextAnalysis = this.#heapSnapshotOptions.contextAnalysis;+ if (contextAnalysis) {+ const contextAnalysisOptions =+ this.#heapSnapshotOptions.contextAnalysisOptions;+ const rankedContexts = collectRankedContexts(contextAnalysis, {+ retainedSize: contextAnalysisOptions?.retainedSize,+ scopeInfoNodeId: contextAnalysisOptions?.scopeInfoNodeId,+ });+ const paginationData = this.#dataWithPagination(rankedContexts, {+ pageIdx: contextAnalysisOptions?.pageIdx ?? 0,+ pageSize: contextAnalysisOptions?.pageSize,+ });+ const report: ContextAnalysisReport = {+ contexts: paginationData.items,+ scriptsWithoutScopes: contextAnalysis.scriptsWithoutScopes,+ };++ response.push('### Context Analysis');+ structuredContent.pagination = paginationData.pagination;+ response.push(...paginationData.info);+ response.push(+ compactEncode+ ? compactEncode(report)+ : HeapSnapshotFormatter.formatContextAnalysis(report),+ );+ structuredContent.heapSnapshotContextAnalysis = report;+ }}if (data.detailedNetworkRequest) {@@ -1536,8 +1584,9 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);}const {startIndex, endIndex, currentPage, totalPages} = paginationResult;+ const displayStartIndex = data.length === 0 ? 0 : startIndex + 1;response.push(- `Showing ${startIndex + 1}-${endIndex} of ${data.length} (Page ${currentPage + 1} of ${totalPages}).`,+ `Showing ${displayStartIndex}-${endIndex} of ${data.length} (Page ${currentPage + 1} of ${totalPages}).`,);if (pagination) {if (paginationResult.hasNextPage) {diff --git a/src/config/cli-options.ts b/src/config/cli-options.tsindex 586e39ce..a130d796 100644--- a/src/config/cli-options.ts+++ b/src/config/cli-options.ts@@ -27,6 +27,46 @@ export type Commands = Record<}>;export const commands: Commands = {+ analyze_heapsnapshot_contexts: {+ description:+ 'Loads a memory heapsnapshot to identify and rank closure contexts holding dead captured fields—variables no remaining live closure can read. Scopes are ranked globally by the retained size of these dead values to provide a prioritizing heuristic, rather than an exact measure of reclaimable bytes. (requires flag: --memoryDebugging=true)',+ category: 'Memory',+ args: {+ filePath: {+ name: 'filePath',+ type: 'string',+ description: 'A path to a .heapsnapshot file to read.',+ required: true,+ },+ retainedSize: {+ name: 'retainedSize',+ type: 'string',+ description:+ 'Inclusive range for the dead-field score of a context (e.g. "10KB", "1MB-2MB", "-1MB", or "1MB-"). A single value is treated as a minimum.',+ required: false,+ },+ scopeInfoNodeId: {+ name: 'scopeInfoNodeId',+ type: 'integer',+ description:+ 'Only return contexts declared by the scope with this ScopeInfo node id, as reported in the scope header of a previous call.',+ required: false,+ },+ pageIdx: {+ name: 'pageIdx',+ type: 'integer',+ description: 'The zero-based page index. Defaults to 0.',+ required: false,+ },+ pageSize: {+ name: 'pageSize',+ type: 'integer',+ description:+ 'The number of contexts to return per page. Defaults to 20.',+ required: false,+ },+ },+ },click: {description: 'Clicks on the provided element',category: 'Input automation',diff --git a/src/formatters/HeapSnapshotFormatter.ts b/src/formatters/HeapSnapshotFormatter.tsindex adebb501..60f31d82 100644--- a/src/formatters/HeapSnapshotFormatter.ts+++ b/src/formatters/HeapSnapshotFormatter.ts@@ -11,6 +11,7 @@ import type {DuplicateStringGroup,} from '../processors/HeapSnapshotManager.js';import {DevTools} from '../third_party/index.js';+import type {ByteSizeRange} from '../utils/bytes.js';import {stableIdSymbol} from '../utils/id.js';const {formatBytesToKb} = DevTools.I18n.ByteUtilities;@@ -23,6 +24,57 @@ export interface FormattedSnapshotEntry {retainedSize: string;}+export interface ContextAnalysisReport {+ contexts: readonly ScopedContext[];+ scriptsWithoutScopes: readonly DevTools.HeapSnapshotModel.HeapSnapshotModel.ScriptWithoutScopes[];+}++/** A context paired with the scope that declares it. */+export interface ScopedContext {+ scope: DevTools.HeapSnapshotModel.HeapSnapshotModel.ScopeAnalysis;+ context: DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysis;+}++export interface ContextFilterOptions {+ /** Inclusive dead-field retained-size score range a context must fall into. */+ retainedSize?: ByteSizeRange;+ /** Restricts the result to contexts declared by this scope. */+ scopeInfoNodeId?: number;+}++/**+ * Flattens the analysis into the contexts matching `options`, ranked descending+ * by their dead-field retained-size score across all scopes.+ */+export function collectRankedContexts(+ analysis: DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult,+ options: ContextFilterOptions = {},+): ScopedContext[] {+ const {min = 0, max} = options.retainedSize ?? {};+ const contexts: ScopedContext[] = [];+ for (const scope of analysis.scopes) {+ if (+ options.scopeInfoNodeId !== undefined &&+ scope.scopeInfoNodeId !== options.scopeInfoNodeId+ ) {+ continue;+ }+ for (const context of scope.contexts) {+ const score = context.deadFieldsRetainedSizeSum;+ if (score < min || (max !== undefined && score > max)) {+ continue;+ }+ contexts.push({scope, context});+ }+ }+ contexts.sort(+ (left, right) =>+ right.context.deadFieldsRetainedSizeSum -+ left.context.deadFieldsRetainedSizeSum,+ );+ return contexts;+}+export function isNodeLike(item: unknown,): item is DevTools.HeapSnapshotModel.HeapSnapshotModel.Node {@@ -275,6 +327,51 @@ export class HeapSnapshotFormatter {];return lines.join('\n');}++ static formatContextAnalysis(report: ContextAnalysisReport): string {+ const lines: string[] = [];++ if (report.contexts.length === 0) {+ lines.push('No live contexts with dead fields were found.');+ }++ for (const {scope, context} of report.contexts) {+ if (lines.length > 0) {+ lines.push('');+ }+ lines.push(+ `#### Context @${context.contextNodeId} in \`${formatScopeName(scope)}\` — ${formatBytesToKb(context.deadFieldsRetainedSizeSum)}`,+ `Script @${scope.scriptNodeId}, ScopeInfo @${scope.scopeInfoNodeId}, offsets ${scope.scopeStart}-${scope.scopeEnd}, ${formatCount(scope.contextFieldCount, 'context field')}`,+ );+ for (const field of context.deadFields) {+ lines.push(+ `- \`${field.name}\` (${field.valueName} @${field.valueNodeId}) — ${formatBytesToKb(field.retainedSize)}`,+ );+ }+ }++ if (report.scriptsWithoutScopes.length > 0) {+ lines.push('', 'Scripts without scope metadata could not be analyzed:');+ for (const script of report.scriptsWithoutScopes) {+ lines.push(+ `- \`${script.scriptName || `script @${script.scriptNodeId}`}\` (@${script.scriptNodeId}) — ${formatCount(script.contextCount, 'context')}`,+ );+ }+ }++ return lines.join('\n');+ }+}++function formatCount(count: number, singular: string): string {+ return `${count} ${singular}${count === 1 ? '' : 's'}`;+}++function formatScopeName(+ scope: DevTools.HeapSnapshotModel.HeapSnapshotModel.ScopeAnalysis,+): string {+ const scriptName = scope.scriptName || `script @${scope.scriptNodeId}`;+ return scope.scopeName ? `${scope.scopeName} (${scriptName})` : scriptName;}function formatDOMLinkState(diff --git a/src/processors/HeapSnapshotManager.ts b/src/processors/HeapSnapshotManager.tsindex 170d66c4..7c706dff 100644--- a/src/processors/HeapSnapshotManager.ts+++ b/src/processors/HeapSnapshotManager.ts@@ -229,6 +229,13 @@ export class HeapSnapshotManager {return await snapshot.getObjectInfo(nodeIndex);}+ async analyzeContexts(+ filePath: string,+ ): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult> {+ const snapshot = await this.getSnapshot(filePath);+ return await snapshot.analyzeContexts();+ }+async getRetainingPaths(filePath: string,nodeId: number,diff --git a/src/telemetry/tool_call_metrics.json b/src/telemetry/tool_call_metrics.jsonindex ba6f7068..c3d43e42 100644--- a/src/telemetry/tool_call_metrics.json+++ b/src/telemetry/tool_call_metrics.json@@ -1197,5 +1197,30 @@"argType": "number"}]+ },+ {+ "name": "analyze_heapsnapshot_contexts",+ "args": [+ {+ "name": "file_path_length",+ "argType": "number"+ },+ {+ "name": "retained_size_length",+ "argType": "number"+ },+ {+ "name": "scope_info_node_id",+ "argType": "number"+ },+ {+ "name": "page_idx",+ "argType": "number"+ },+ {+ "name": "page_size",+ "argType": "number"+ }+ ]}]diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.tsindex 4df83339..1c534ee9 100644--- a/src/tools/ToolDefinition.ts+++ b/src/tools/ToolDefinition.ts@@ -16,6 +16,7 @@ import type {import type {McpPage} from '../McpPage.js';import type {DevToolsCommentBridge} from '../devtools/DevToolsCommentBridge.js';import type {CssFormatterOptions} from '../formatters/CssFormatter.js';+import type {ContextFilterOptions} from '../formatters/HeapSnapshotFormatter.js';import {zod} from '../third_party/index.js';import type {Dialog,@@ -180,6 +181,10 @@ export interface Response {setHeapSnapshotObjectDetails(objectInfo: DevTools.HeapSnapshotModel.HeapSnapshotModel.ObjectInfo,): void;+ setHeapSnapshotContextAnalysis(+ analysis: DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult,+ options?: PaginationOptions & ContextFilterOptions,+ ): void;setIncludePages(value: boolean): void;setIncludeNetworkRequests(value: boolean,@@ -320,6 +325,9 @@ export type Context = Readonly<{filePath: string,nodeId: number,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ObjectInfo>;+ analyzeHeapSnapshotContexts(+ filePath: string,+ ): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult>;closeHeapSnapshot(filePath: string): Promise<boolean>;getHeapSnapshotRetainingPaths(filePath: string,diff --git a/src/tools/memory.ts b/src/tools/memory.tsindex 16955220..a9e75a8f 100644--- a/src/tools/memory.ts+++ b/src/tools/memory.ts@@ -533,3 +533,55 @@ export const queryHeapSnapshotObjects = defineTool(() => ({});},}));++export const analyzeHeapSnapshotContexts = defineTool(() => ({+ name: 'analyze_heapsnapshot_contexts',+ description:+ 'Loads a memory heapsnapshot to identify and rank closure contexts holding dead captured fields—variables no remaining live closure can read. Scopes are ranked globally by the retained size of these dead values to provide a prioritizing heuristic, rather than an exact measure of reclaimable bytes.',+ annotations: {+ category: ToolCategory.MEMORY,+ readOnlyHint: true,+ conditions: ['memoryDebugging'],+ },+ blockedByDialog: false,+ verifyFilesSchema: {+ filePath: true,+ },+ schema: {+ filePath: zod.string().describe('A path to a .heapsnapshot file to read.'),+ retainedSize: byteSizeRangeSchema(+ 'Inclusive range for the dead-field score of a context (e.g. "10KB", "1MB-2MB", "-1MB", or "1MB-"). A single value is treated as a minimum.',+ ).optional(),+ scopeInfoNodeId: zod+ .number()+ .int()+ .optional()+ .describe(+ 'Only return contexts declared by the scope with this ScopeInfo node id, as reported in the scope header of a previous call.',+ ),+ pageIdx: zod+ .number()+ .int()+ .nonnegative()+ .optional()+ .describe('The zero-based page index. Defaults to 0.'),+ pageSize: zod+ .number()+ .int()+ .positive()+ .optional()+ .describe('The number of contexts to return per page. Defaults to 20.'),+ },+ handler: async (request, response, context) => {+ const analysis = await context.analyzeHeapSnapshotContexts(+ request.params.filePath,+ );++ response.setHeapSnapshotContextAnalysis(analysis, {+ retainedSize: request.params.retainedSize,+ scopeInfoNodeId: request.params.scopeInfoNodeId,+ pageIdx: request.params.pageIdx,+ pageSize: request.params.pageSize,+ });+ },+}));diff --git a/tests/McpResponse.test.ts b/tests/McpResponse.test.tsindex cf8b1447..402ac7ce 100644--- a/tests/McpResponse.test.ts+++ b/tests/McpResponse.test.ts@@ -15,6 +15,7 @@ import type {ParsedArguments} from '../src/config/mcp-options.js';import type {McpContext} from '../src/McpContext.js';import {McpResponse} from '../src/McpResponse.js';import {DevTools, type Extension} from '../src/third_party/index.js';+import {parseByteSizeRange} from '../src/utils/bytes.js';import {stableIdSymbol} from '../src/utils/id.js';import {closePage,@@ -39,6 +40,7 @@ import {createMockCSSStyleDeclaration,createMockCSSStyleRule,createMockClassDiffs,+ createMockContextAnalysisResult,createMockDetailedClassDiff,createMockHeapSnapshotEdge,createMockHeapSnapshotNode,@@ -1574,4 +1576,22 @@ describe('McpResponse heap snapshot formatting', () => {assert.ok(objectText.includes('id: @1'));assert.ok(objectText.includes('name: Object'));});++ it('renders the context field usage section for the filtered contexts', async () => {+ const response = new McpResponse(createMockParsedArguments());+ response.setHeapSnapshotContextAnalysis(createMockContextAnalysisResult(), {+ retainedSize: parseByteSizeRange('1000'),+ });++ const context = createMockMcpContext();+ const {content, structuredContent} = await response.handle(context);+ const text = getTextContent(content[0]);++ assert.ok(text.includes('### Context Analysis'));+ assert.ok(text.includes('Showing 1-2 of 2 (Page 1 of 1).'));+ assert.ok(text.includes('Context @101'));+ assert.ok(text.includes('Context @111'));+ assert.ok(!text.includes('Context @102'));+ assert.ok('heapSnapshotContextAnalysis' in structuredContent);+ });});diff --git a/tests/formatters/HeapSnapshotFormatter.test.js.snapshot b/tests/formatters/HeapSnapshotFormatter.test.js.snapshotindex e715dd25..f3b917ce 100644--- a/tests/formatters/HeapSnapshotFormatter.test.js.snapshot+++ b/tests/formatters/HeapSnapshotFormatter.test.js.snapshot@@ -1,3 +1,20 @@+exports[`HeapSnapshotFormatter > formatContextAnalysis > formats contexts in ranked order with their scope 1`] = `+#### Context @101 in \`createClosure (test.js)\` — 2.0 kB+Script @301, ScopeInfo @303, offsets 14-104, 2 context fields+- \`dead\` (Object @202) — 2.0 kB++#### Context @111 in \`createOtherClosure (other-scope.js)\` — 1.5 kB+Script @311, ScopeInfo @313, offsets 20-60, 1 context field+- \`captured\` (Map @206) — 1.5 kB++#### Context @102 in \`createClosure (test.js)\` — 0.5 kB+Script @301, ScopeInfo @303, offsets 14-104, 2 context fields+- \`alsoDead\` (Array @204) — 0.5 kB++Scripts without scope metadata could not be analyzed:+- \`other.js\` (@401) — 2 contexts+`;+exports[`HeapSnapshotFormatter > toString > formats data as CSV and sorts by retained size 1`] = `id,name,count,selfSize,retainedSize1,ObjectA,10,0.1 kB,1.0 kBdiff --git a/tests/formatters/HeapSnapshotFormatter.test.ts b/tests/formatters/HeapSnapshotFormatter.test.tsindex 65e52a5e..0fab1e49 100644--- a/tests/formatters/HeapSnapshotFormatter.test.ts+++ b/tests/formatters/HeapSnapshotFormatter.test.ts@@ -8,11 +8,16 @@ import assert from 'node:assert';import {join} from 'node:path';import {describe, it, before, after} from 'node:test';-import {HeapSnapshotFormatter} from '../../src/formatters/HeapSnapshotFormatter.js';+import {+ collectRankedContexts,+ type ContextAnalysisReport,+ HeapSnapshotFormatter,+} from '../../src/formatters/HeapSnapshotFormatter.js';import {HeapSnapshotManager} from '../../src/processors/HeapSnapshotManager.js';import {DevTools} from '../../src/third_party/index.js';import {parseByteSizeRange} from '../../src/utils/bytes.js';import {stableIdSymbol} from '../../src/utils/id.js';+import {createMockContextAnalysisResult} from '../mocks.js';const {formatBytesToKb} = DevTools.I18n.ByteUtilities;@@ -597,4 +602,87 @@ describe('HeapSnapshotFormatter', () => {});});});++ describe('formatContextAnalysis', () => {+ it('formats contexts in ranked order with their scope', t => {+ const analysis = createMockContextAnalysisResult();+ const report: ContextAnalysisReport = {+ contexts: collectRankedContexts(analysis),+ scriptsWithoutScopes: analysis.scriptsWithoutScopes,+ };++ t.assert.snapshot(HeapSnapshotFormatter.formatContextAnalysis(report));+ });++ it('reports when there are no contexts with dead fields', () => {+ const report: ContextAnalysisReport = {+ contexts: [],+ scriptsWithoutScopes: [],+ };++ const result = HeapSnapshotFormatter.formatContextAnalysis(report);++ assert.strictEqual(+ result,+ 'No live contexts with dead fields were found.',+ );+ });+ });+});++describe('context analysis report', () => {+ it('ranks contexts by dead-field score across scopes', () => {+ const analysis = createMockContextAnalysisResult();+ const [firstScope, secondScope] = analysis.scopes;++ assert.deepStrictEqual(collectRankedContexts(analysis), [+ {scope: firstScope, context: firstScope.contexts[0]},+ {scope: secondScope, context: secondScope.contexts[0]},+ {scope: firstScope, context: firstScope.contexts[1]},+ ]);+ });++ it('drops contexts outside the dead-field retained size range', () => {+ const analysis = createMockContextAnalysisResult();+ const [firstScope, secondScope] = analysis.scopes;++ assert.deepStrictEqual(+ collectRankedContexts(analysis, {+ retainedSize: parseByteSizeRange('1500'),+ }),+ [+ {scope: firstScope, context: firstScope.contexts[0]},+ {scope: secondScope, context: secondScope.contexts[0]},+ ],+ );+ assert.deepStrictEqual(+ collectRankedContexts(analysis, {+ retainedSize: parseByteSizeRange('600-1900'),+ }),+ [{scope: secondScope, context: secondScope.contexts[0]}],+ );+ assert.deepStrictEqual(+ collectRankedContexts(analysis, {+ retainedSize: parseByteSizeRange('2001'),+ }),+ [],+ );+ });++ it('restricts contexts to the requested scope', () => {+ const analysis = createMockContextAnalysisResult();+ const [firstScope] = analysis.scopes;++ assert.deepStrictEqual(+ collectRankedContexts(analysis, {scopeInfoNodeId: 303}),+ [+ {scope: firstScope, context: firstScope.contexts[0]},+ {scope: firstScope, context: firstScope.contexts[1]},+ ],+ );+ assert.deepStrictEqual(+ collectRankedContexts(analysis, {scopeInfoNodeId: 999}),+ [],+ );+ });});diff --git a/tests/mocks.ts b/tests/mocks.tsindex ef90b8c3..08b97ac8 100644--- a/tests/mocks.ts+++ b/tests/mocks.ts@@ -877,6 +877,98 @@ export function createMockObjectInfo(): DevTools.HeapSnapshotModel.HeapSnapshotM};}+export function createMockContextAnalysisResult(): DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult {+ return {+ scopes: [+ {+ scopeInfoNodeIndex: 30,+ scopeInfoNodeId: 303,+ scriptNodeIndex: 7,+ scriptNodeId: 301,+ scriptName: 'test.js',+ scopeName: 'createClosure',+ scopeStart: 14,+ scopeEnd: 104,+ contextFieldCount: 2,+ contexts: [+ {+ contextNodeIndex: 10,+ contextNodeId: 101,+ retainedSize: 5000,+ deadFieldsRetainedSizeSum: 2000,+ deadFields: [+ {+ name: 'dead',+ valueNodeIndex: 50,+ valueNodeId: 202,+ valueName: 'Object',+ valueType: 'object',+ selfSize: 200,+ retainedSize: 2000,+ },+ ],+ },+ {+ contextNodeIndex: 11,+ contextNodeId: 102,+ retainedSize: 1000,+ deadFieldsRetainedSizeSum: 500,+ deadFields: [+ {+ name: 'alsoDead',+ valueNodeIndex: 60,+ valueNodeId: 204,+ valueName: 'Array',+ valueType: 'object',+ selfSize: 100,+ retainedSize: 500,+ },+ ],+ },+ ],+ },+ {+ scopeInfoNodeIndex: 40,+ scopeInfoNodeId: 313,+ scriptNodeIndex: 8,+ scriptNodeId: 311,+ scriptName: 'other-scope.js',+ scopeName: 'createOtherClosure',+ scopeStart: 20,+ scopeEnd: 60,+ contextFieldCount: 1,+ contexts: [+ {+ contextNodeIndex: 12,+ contextNodeId: 111,+ retainedSize: 3000,+ deadFieldsRetainedSizeSum: 1500,+ deadFields: [+ {+ name: 'captured',+ valueNodeIndex: 70,+ valueNodeId: 206,+ valueName: 'Map',+ valueType: 'object',+ selfSize: 150,+ retainedSize: 1500,+ },+ ],+ },+ ],+ },+ ],+ scriptsWithoutScopes: [+ {+ scriptNodeIndex: 9,+ scriptNodeId: 401,+ scriptName: 'other.js',+ contextCount: 2,+ },+ ],+ };+}+export function createMockParsedArguments(options: Partial<ParsedArguments> = {},): ParsedArguments {diff --git a/tests/tools/memory.test.ts b/tests/tools/memory.test.tsindex 8a2cf787..172c8463 100644--- a/tests/tools/memory.test.ts+++ b/tests/tools/memory.test.ts@@ -25,12 +25,14 @@ import {getHeapSnapshotDuplicateStrings,getHeapSnapshotObjectDetails,queryHeapSnapshotObjects,+ analyzeHeapSnapshotContexts,} from '../../src/tools/memory.js';import {parseByteSizeRange} from '../../src/utils/bytes.js';import {resolveCanonicalPath} from '../../src/utils/files.js';import {createHandlerMocks,createMockClassDiffs,+ createMockContextAnalysisResult,createMockDetailedClassDiff,createMockDominatorChain,createMockDuplicateStrings,@@ -338,6 +340,43 @@ describe('memory', () => {});});+ describe('analyze_heapsnapshot_contexts', () => {+ it('delegates to analyzeHeapSnapshotContexts and forwards options', async () => {+ const {context, response, args} = createHandlerMocks();+ const analysis = createMockContextAnalysisResult();+ context.analyzeHeapSnapshotContexts.resolves(analysis);++ await analyzeHeapSnapshotContexts(args).handler(+ {+ params: {+ filePath: 'test.heapsnapshot',+ retainedSize: parseByteSizeRange('10KB'),+ scopeInfoNodeId: 303,+ pageIdx: 1,+ pageSize: 5,+ },+ },+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(+ context.analyzeHeapSnapshotContexts,+ 'test.heapsnapshot',+ );+ sinon.assert.calledOnceWithExactly(+ response.setHeapSnapshotContextAnalysis,+ analysis,+ {+ retainedSize: {min: 10000, max: undefined},+ scopeInfoNodeId: 303,+ pageIdx: 1,+ pageSize: 5,+ },+ );+ });+ });+describe('close_heapsnapshot', () => {it('closes loaded snapshot', async () => {const {context, response, args} = createHandlerMocks();