From 7a64f970f9e964e425db550c3d5efaac004d8327 Mon Sep 17 00:00:00 2001 From: maihaopeng <127769758+haopengmai@users.noreply.github.com> Date: Fri, 31 Jul 2026 12:24:08 +0800 Subject: [PATCH] fix: manage third-party element handle lifetimes --- src/McpPage.ts | 121 ++++++- src/TextSnapshot.ts | 13 +- tests/TextSnapshot.test.ts | 7 + tests/tools/thirdPartyDeveloper.test.ts | 411 +++++++++++++++++++++--- 4 files changed, 493 insertions(+), 59 deletions(-) diff --git a/src/McpPage.ts b/src/McpPage.ts index 1483d7aab4..d054549481 100644 --- a/src/McpPage.ts +++ b/src/McpPage.ts @@ -77,6 +77,7 @@ import { type WebMCPTool, type Protocol, type Page, + type Frame, type ConsoleMessage, type HTTPRequest, type DevTools, @@ -103,6 +104,7 @@ import { type WaitForEventsResult, type DialogAction, } from './WaitForHelper.js'; +type DisposableStackInstance = InstanceType; /** * Per-page state wrapper. Consolidates dialog, snapshot, emulation, @@ -120,6 +122,9 @@ export class McpPage implements ContextPage { textSnapshot: TextSnapshot | null = null; uniqueBackendNodeIdToMcpId = new Map(); extraHandles: ElementHandle[] = []; + #extraHandleResources = new DisposableStack(); + #extraHandleGeneration = 0; + #disposed = false; // Emulation emulationSettings: EmulationSettings = {}; @@ -131,6 +136,7 @@ export class McpPage implements ContextPage { // Dialog #dialog?: Dialog; #dialogHandler: (dialog: Dialog) => void; + #frameNavigatedHandler: (frame: Frame) => void; thirdPartyDeveloperTools: ToolGroups = []; @@ -157,7 +163,13 @@ export class McpPage implements ContextPage { this.#dialogHandler = (dialog: Dialog): void => { this.#dialog = dialog; }; + this.#frameNavigatedHandler = (frame: Frame): void => { + if (frame === page.mainFrame()) { + this.#invalidateExtraHandles(); + } + }; page.on('dialog', this.#dialogHandler); + page.on('framenavigated', this.#frameNavigatedHandler); this.networkCollector = new NetworkCollector(page); this.consoleCollector = new ConsoleCollector(page, collect => { @@ -428,9 +440,57 @@ export class McpPage implements ContextPage { } dispose(): void { + if (this.#disposed) { + return; + } + this.#disposed = true; this.pptrPage.off('dialog', this.#dialogHandler); + this.pptrPage.off('framenavigated', this.#frameNavigatedHandler); this.networkCollector.dispose(); this.consoleCollector.dispose(); + this.#invalidateExtraHandles(); + } + + #invalidateExtraHandles(): void { + this.#extraHandleGeneration++; + this.#clearExtraHandles(); + } + + #clearExtraHandles(): void { + this.#extraHandleResources.dispose(); + this.#extraHandleResources = new DisposableStack(); + this.extraHandles = []; + } + + #replaceExtraHandles( + handles: ElementHandle[], + resources: DisposableStackInstance, + generation: number, + ): void { + if (this.#disposed) { + resources.dispose(); + throw new Error( + `Page ${this.id} was disposed before retaining element handles.`, + ); + } + if (generation !== this.#extraHandleGeneration) { + resources.dispose(); + throw new Error( + `Page ${this.id} changed before retaining element handles.`, + ); + } + const previousResources = this.#extraHandleResources; + this.#extraHandleResources = resources; + this.extraHandles = handles; + previousResources.dispose(); + } + + async #clearStashedElements(): Promise { + await this.pptrPage.evaluate(() => { + if (window.__dtmcp) { + window.__dtmcp.stashedElements = []; + } + }); } async executeThirdPartyDeveloperTool( @@ -438,10 +498,12 @@ export class McpPage implements ContextPage { params: Record, response: Response, ): Promise { + const extraHandleGeneration = this.#extraHandleGeneration; // Creates array of ElementHandles from the UIDs in the params. // We do not replace the uids with the ElementsHandles yet, because // the `evaluate` function only turns them into DOM elements if they // are passed as non-nested arguments. + using inputHandleResources = new DisposableStack(); const handles: ElementHandle[] = []; for (const value of Object.values(params)) { if ( @@ -450,11 +512,13 @@ export class McpPage implements ContextPage { typeof value.uid === 'string' && Object.keys(value).length === 1 ) { - handles.push(await this.getElementByUid(value.uid)); + handles.push( + inputHandleResources.use(await this.getElementByUid(value.uid)), + ); } } - const result = await this.pptrPage.evaluate( + const toolExecution = this.pptrPage.evaluate( async (name, args, ...elements) => { // Replace the UIDs with DOM elements. for (const [key, value] of Object.entries(args)) { @@ -471,6 +535,7 @@ export class McpPage implements ContextPage { if (!window.__dtmcp?.executeTool) { throw new Error('No tools found on the page'); } + window.__dtmcp.stashedElements = []; const toolResult = await window.__dtmcp.executeTool(name, args); const stashDOMElement = (el: Element) => { @@ -548,27 +613,51 @@ export class McpPage implements ContextPage { params, ...handles, ); + let result: Awaited; + try { + result = await toolExecution; + } catch (error) { + try { + await this.#clearStashedElements(); + } catch (clearError) { + logger?.('Failed to clear stashed elements', clearError); + } + throw error; + } + using extraHandleResources = new DisposableStack(); const elementHandles: ElementHandle[] = []; - for (let i = 0; i < (result.stashed ?? 0); i++) { - const elementHandle = await this.pptrPage.evaluateHandle(index => { - const el = window.__dtmcp?.stashedElements?.[index]; - if (!el) { - throw new Error(`Stashed element at index ${index} not found`); - } - return el; - }, i); - elementHandles.push(elementHandle); + try { + for (let i = 0; i < (result.stashed ?? 0); i++) { + const elementHandle = await this.pptrPage.evaluateHandle(index => { + const el = window.__dtmcp?.stashedElements?.[index]; + if (!el) { + throw new Error(`Stashed element at index ${index} not found`); + } + return el; + }, i); + elementHandles.push(extraHandleResources.use(elementHandle)); + } + } catch (error) { + try { + await this.#clearStashedElements(); + } catch (clearError) { + logger?.('Failed to clear stashed elements', clearError); + } + throw error; } + await this.#clearStashedElements(); if (elementHandles.length) { - using stack = new DisposableStack(); - for (const handle of elementHandles) { - stack.use(handle); - } - this.textSnapshot = await TextSnapshot.create(this, { + const textSnapshot = await TextSnapshot.create(this, { extraHandles: elementHandles, }); + this.#replaceExtraHandles( + elementHandles, + extraHandleResources.move(), + extraHandleGeneration, + ); + this.textSnapshot = textSnapshot; response.includeSnapshot(); } diff --git a/src/TextSnapshot.ts b/src/TextSnapshot.ts index a65d53e67c..93052e2b88 100644 --- a/src/TextSnapshot.ts +++ b/src/TextSnapshot.ts @@ -112,6 +112,7 @@ export class TextSnapshot { const rootNodeWithId = assignIds(rootNode); + const extraHandles = options.extraHandles ?? page.extraHandles; await TextSnapshot.insertExtraNodes( page, idToNode, @@ -120,7 +121,7 @@ export class TextSnapshot { idCounter, rootNodeWithId, seenBackendNodeIds, - options.extraHandles ?? [], + extraHandles, ); const snapshot = new TextSnapshot({ @@ -206,14 +207,15 @@ export class TextSnapshot { } seenUniqueIds.add(uniqueBackendId); - const tagHandle = await handle.getProperty('localName'); + using tagHandle = await handle.getProperty('localName'); const tagValue = await tagHandle.jsonValue(); const extraNode: TextSnapshotNode = { role: tagValue, id, backendNodeId, children: [], - elementHandle: async () => handle, + elementHandle: async () => + await handle.evaluateHandle((element: Element) => element), }; return extraNode; }; @@ -317,16 +319,13 @@ export class TextSnapshot { : 0; }; - if (extraHandles.length) { - page.extraHandles = extraHandles; - } const reorgInfo: Array<{ extraNode: TextSnapshotNode; attachTarget: TextSnapshotNode; descendantIds: Set; }> = []; - for (const handle of page.extraHandles) { + for (const handle of extraHandles) { const extraNode = await createExtraNode(handle); if (!extraNode) { continue; diff --git a/tests/TextSnapshot.test.ts b/tests/TextSnapshot.test.ts index 7627ea9c17..47e8d4a0f9 100644 --- a/tests/TextSnapshot.test.ts +++ b/tests/TextSnapshot.test.ts @@ -88,10 +88,17 @@ describe('TextSnapshot', () => { ); // Now take snapshot with extra handle + const getPropertySpy = sinon.spy(middleHandle, 'getProperty'); const snapshot = await TextSnapshot.create(page, { verbose: false, extraHandles: [middleHandle], }); + assert.strictEqual(getPropertySpy.callCount, 1); + const tagHandle = await getPropertySpy.firstCall.returnValue; + await assert.rejects( + tagHandle.evaluate(value => value), + /disposed/, + ); // Find the extra node in idToNode let extraNode: TextSnapshotNode | undefined; diff --git a/tests/tools/thirdPartyDeveloper.test.ts b/tests/tools/thirdPartyDeveloper.test.ts index 3268d31c6f..462307b5a3 100644 --- a/tests/tools/thirdPartyDeveloper.test.ts +++ b/tests/tools/thirdPartyDeveloper.test.ts @@ -10,6 +10,7 @@ import {describe, it} from 'node:test'; import sinon from 'sinon'; import type {McpContext} from '../../src/McpContext.js'; +import type {McpPage} from '../../src/McpPage.js'; import type {McpResponse} from '../../src/McpResponse.js'; import {TextSnapshot} from '../../src/TextSnapshot.js'; import { @@ -19,6 +20,17 @@ import { import type {ToolGroups} from '../../src/tools/thirdPartyDeveloper.js'; import {withMcpContext} from '../utils.js'; +function parseUidResult(responseLine: string): string { + const result: unknown = JSON.parse(responseLine); + assert.ok( + result !== null && + typeof result === 'object' && + 'uid' in result && + typeof result.uid === 'string', + ); + return result.uid; +} + describe('thirdPartyDeveloperTools', () => { describe('list_3p_developer_tools', () => { it('lists tools', async () => { @@ -307,6 +319,71 @@ describe('thirdPartyDeveloperTools', () => { await response.handle(context); } + async function setupDirectThirdPartyDeveloperTool( + response: McpResponse, + context: McpContext, + evaluateFn: () => void, + ) { + const page = await context.newPage(); + response.setPage(page); + page.thirdPartyDeveloperTools = [ + { + name: 'test-group', + description: 'test description', + tools: [ + { + name: 'test-tool', + description: 'test tool description', + inputSchema: {}, + }, + ], + }, + ]; + await page.pptrPage.evaluate(evaluateFn); + return page; + } + + async function executeTestTool( + page: McpPage, + response: McpResponse, + context: McpContext, + ): Promise { + await executeThirdPartyDeveloperTool.handler( + { + params: { + toolName: 'test-tool', + params: JSON.stringify({}), + }, + page: page, + }, + response, + context, + ); + } + + function pauseSnapshotCreation() { + const snapshotStarted = Promise.withResolvers(); + const continueSnapshot = Promise.withResolvers(); + const createSnapshot = TextSnapshot.create; + const snapshotStub = sinon + .stub(TextSnapshot, 'create') + .callsFake(async (mcpPage, options) => { + snapshotStarted.resolve(); + await continueSnapshot.promise; + return await createSnapshot(mcpPage, options); + }); + + return { + started: snapshotStarted.promise, + resume: () => { + continueSnapshot.resolve(); + }, + restore: () => { + snapshotStub.restore(); + }, + }; + } + it('executes a tool', async () => { await withMcpContext( async (response, context) => { @@ -572,6 +649,10 @@ describe('thirdPartyDeveloperTools', () => { 2, ), ); + await assert.rejects( + handle.evaluate(element => element.id), + /disposed/, + ); }); }); @@ -721,53 +802,314 @@ describe('thirdPartyDeveloperTools', () => { ); }); - it('stashDOMElement stashes elements and returns UID', async () => { + it('clears stashed elements when serializing a tool result fails', async () => { await withMcpContext( async (response, context) => { - const page = await context.newPage(); - response.setPage(page); + const page = await setupDirectThirdPartyDeveloperTool( + response, + context, + () => { + window.__dtmcp = { + executeTool: async () => [ + document.createElement('div'), + new Proxy( + {}, + { + getPrototypeOf: () => { + throw new Error('Failed to serialize tool result'); + }, + }, + ), + ], + }; + }, + ); - page.thirdPartyDeveloperTools = [ - { - name: 'test-group', - description: 'test description', - tools: [ - { - name: 'test-tool', - description: 'test tool description', - inputSchema: {}, + await assert.rejects( + executeTestTool(page, response, context), + /Failed to serialize tool result/, + ); + + assert.strictEqual( + await page.pptrPage.evaluate( + () => window.__dtmcp?.stashedElements?.length, + ), + 0, + ); + }, + undefined, + {categoryExperimentalThirdParty: true}, + ); + }); + + it('preserves handle extraction errors when stash cleanup fails', async () => { + await withMcpContext( + async (response, context) => { + const page = await setupDirectThirdPartyDeveloperTool( + response, + context, + () => { + window.__dtmcp = { + executeTool: async () => document.createElement('div'), + }; + }, + ); + const evaluateHandleStub = sinon + .stub(page.pptrPage, 'evaluateHandle') + .callsFake(async () => { + await page.pptrPage.close(); + throw new Error('Primary handle extraction failed'); + }); + + try { + await assert.rejects( + executeTestTool(page, response, context), + /Primary handle extraction failed/, + ); + } finally { + evaluateHandleStub.restore(); + } + }, + undefined, + {categoryExperimentalThirdParty: true}, + ); + }); + + it('keeps stashed element UIDs reusable', async () => { + await withMcpContext( + async (response, context) => { + const page = await setupDirectThirdPartyDeveloperTool( + response, + context, + () => { + window.__dtmcp = { + executeTool: async () => { + const div = document.createElement('div'); + div.id = 'test-element'; + return div; }, - ], + }; }, - ]; + ); + + await executeTestTool(page, response, context); + + const uid = parseUidResult(response.responseLines[0]); + + { + using firstHandle = await page.getElementByUid(uid); + assert.strictEqual( + await firstHandle.evaluate(element => element.id), + 'test-element', + ); + } + { + using secondHandle = await page.getElementByUid(uid); + assert.strictEqual( + await secondHandle.evaluate(element => element.id), + 'test-element', + ); + } + }, + undefined, + {categoryExperimentalThirdParty: true}, + ); + }); + it('disposes stashed element handles when replaced and on teardown', async () => { + await withMcpContext( + async (response, context) => { + const page = await setupDirectThirdPartyDeveloperTool( + response, + context, + () => { + let elementCounter = 0; + window.__dtmcp = { + executeTool: async () => { + const div = document.createElement('div'); + div.id = `test-element-${elementCounter++}`; + return div; + }, + }; + }, + ); + + await executeTestTool(page, response, context); + const originalUid = parseUidResult(response.responseLines[0]); + const originalHandle = page.extraHandles[0]; + assert.ok(originalHandle); + assert.strictEqual( + await originalHandle.evaluate(element => element.id), + 'test-element-0', + ); + assert.strictEqual( + await page.pptrPage.evaluate( + () => window.__dtmcp?.stashedElements?.length, + ), + 0, + ); + + await executeTestTool(page, response, context); + await assert.rejects( + originalHandle.evaluate(element => element.id), + /disposed/, + ); + assert.strictEqual(page.extraHandles.length, 1); + await assert.rejects(async () => { + using oldHandle = await page.getElementByUid(originalUid); + await oldHandle.evaluate(element => element.id); + }, /not found/); + + const currentHandle = page.extraHandles.at(-1); + assert.ok(currentHandle); + assert.strictEqual( + await currentHandle.evaluate(element => element.id), + 'test-element-1', + ); + + const currentSnapshot = page.textSnapshot; await page.pptrPage.evaluate(() => { - window.__dtmcp = { - executeTool: async () => { - const div = document.createElement('div'); - div.id = 'test-element'; - document.body.appendChild(div); - return div; - }, - }; + if (window.__dtmcp) { + window.__dtmcp.executeTool = async () => 'simple-result'; + } }); + await executeTestTool(page, response, context); + assert.strictEqual(page.textSnapshot, currentSnapshot); + assert.strictEqual( + response.responseLines.at(-1), + JSON.stringify('simple-result', null, 2), + ); - await executeThirdPartyDeveloperTool.handler( - { - params: { - toolName: 'test-tool', - params: JSON.stringify({}), - }, - page: page, + context.dispose(); + await assert.rejects( + currentHandle.evaluate(element => element.id), + /disposed/, + ); + }, + undefined, + {categoryExperimentalThirdParty: true}, + ); + }); + + it('releases stashed element handles after main frame navigation', async () => { + await withMcpContext( + async (response, context) => { + const page = await setupDirectThirdPartyDeveloperTool( + response, + context, + () => { + window.__dtmcp = { + executeTool: async () => { + const div = document.createElement('div'); + div.id = 'test-element'; + return div; + }, + }; }, + ); + + await executeTestTool(page, response, context); + + const uid = parseUidResult(response.responseLines[0]); + const retainedHandle = page.extraHandles[0]; + assert.ok(retainedHandle); + + await page.pptrPage.goto( + 'data:text/html,
Navigated page
', + ); + + assert.deepStrictEqual(page.extraHandles, []); + await assert.rejects( + retainedHandle.evaluate(element => element.id), + /disposed/, + ); + + page.textSnapshot = await TextSnapshot.create(page); + await assert.rejects(async () => { + using oldHandle = await page.getElementByUid(uid); + await oldHandle.evaluate(element => element.id); + }, /not found/); + }, + undefined, + {categoryExperimentalThirdParty: true}, + ); + }); + + it('does not retain stashed handles if navigation occurs during snapshot creation', async () => { + await withMcpContext( + async (response, context) => { + const page = await setupDirectThirdPartyDeveloperTool( response, context, + () => { + window.__dtmcp = { + executeTool: async () => document.createElement('div'), + }; + }, ); + const pausedSnapshot = pauseSnapshotCreation(); + + try { + const execution = executeTestTool(page, response, context); + await pausedSnapshot.started; + + await Promise.all([ + page.pptrPage.waitForNavigation({timeout: 5_000}), + page.pptrPage.evaluate(() => { + window.location.hash = 'navigation-during-snapshot'; + }), + ]); + pausedSnapshot.resume(); + + await assert.rejects(execution, /changed/); + assert.deepStrictEqual(page.extraHandles, []); + } finally { + pausedSnapshot.resume(); + pausedSnapshot.restore(); + page.dispose(); + } + }, + undefined, + {categoryExperimentalThirdParty: true}, + ); + }); - assert.strictEqual( - response.responseLines[0], - JSON.stringify({uid: '1_1'}, null, 2), + it('does not retain stashed handles after page teardown', async () => { + await withMcpContext( + async (response, context) => { + const page = await setupDirectThirdPartyDeveloperTool( + response, + context, + () => { + window.__dtmcp = { + executeTool: async () => document.createElement('div'), + }; + }, ); + + const pausedSnapshot = pauseSnapshotCreation(); + const evaluateHandleSpy = sinon.spy(page.pptrPage, 'evaluateHandle'); + + try { + const execution = executeTestTool(page, response, context); + + await pausedSnapshot.started; + const pendingHandle = await evaluateHandleSpy.firstCall.returnValue; + context.dispose(); + pausedSnapshot.resume(); + + await assert.rejects(execution, /disposed/); + assert.deepStrictEqual(page.extraHandles, []); + await assert.rejects( + pendingHandle.evaluate(element => element), + /disposed/, + ); + } finally { + pausedSnapshot.resume(); + pausedSnapshot.restore(); + evaluateHandleSpy.restore(); + page.dispose(); + } }, undefined, {categoryExperimentalThirdParty: true}, @@ -817,10 +1159,7 @@ describe('thirdPartyDeveloperTools', () => { context, ); - assert.strictEqual( - response.responseLines[0], - JSON.stringify({uid: '1_1'}, null, 2), - ); + assert.ok(parseUidResult(response.responseLines[0])); }, undefined, {categoryExperimentalThirdParty: true},