Chrome DevTools for coding agents
chore: split withBrowser into withBrowser and withMcpContext (#620)
Simon Zünd8e90a92780d5
diff --git a/tests/McpContext.test.ts b/tests/McpContext.test.tsindex 4b5de091..e1c34f52 100644--- a/tests/McpContext.test.ts+++ b/tests/McpContext.test.ts@@ -11,11 +11,11 @@ import sinon from 'sinon';import type {TraceResult} from '../src/trace-processing/parse.js';-import {html, withBrowser} from './utils.js';+import {html, withMcpContext} from './utils.js';describe('McpContext', () => {it('list pages', async () => {- await withBrowser(async (_response, context) => {+ await withMcpContext(async (_response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button>Click me</button@@ -40,7 +40,7 @@ describe('McpContext', () => {});it('can store and retrieve performance traces', async () => {- await withBrowser(async (_response, context) => {+ await withMcpContext(async (_response, context) => {const fakeTrace1 = {} as unknown as TraceResult;const fakeTrace2 = {} as unknown as TraceResult;context.storeTraceRecording(fakeTrace1);@@ -50,7 +50,7 @@ describe('McpContext', () => {});it('should update default timeout when cpu throttling changes', async () => {- await withBrowser(async (_response, context) => {+ await withMcpContext(async (_response, context) => {const page = await context.newPage();const timeoutBefore = page.getDefaultTimeout();context.setCpuThrottlingRate(2);@@ -60,7 +60,7 @@ describe('McpContext', () => {});it('should update default timeout when network conditions changes', async () => {- await withBrowser(async (_response, context) => {+ await withMcpContext(async (_response, context) => {const page = await context.newPage();const timeoutBefore = page.getDefaultNavigationTimeout();context.setNetworkConditions('Slow 3G');@@ -70,7 +70,7 @@ describe('McpContext', () => {});it('should call waitForEventsAfterAction with correct multipliers', async () => {- await withBrowser(async (_response, context) => {+ await withMcpContext(async (_response, context) => {const page = await context.newPage();context.setCpuThrottlingRate(2);@@ -86,7 +86,7 @@ describe('McpContext', () => {});it('should should detect open DevTools pages', async () => {- await withBrowser(+ await withMcpContext(async (_response, context) => {const page = await context.newPage();// TODO: we do not know when the CLI flag to auto open DevTools will rundiff --git a/tests/McpResponse.test.ts b/tests/McpResponse.test.tsindex 9031f6dd..5feb66fd 100644--- a/tests/McpResponse.test.ts+++ b/tests/McpResponse.test.ts@@ -16,12 +16,12 @@ import {getMockResponse,html,stabilizeResponseOutput,- withBrowser,+ withMcpContext,} from './utils.js';describe('McpResponse', () => {it('list pages', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludePages(true);const result = await response.handle('test', context);assert.equal(result[0].type, 'text');@@ -30,7 +30,7 @@ describe('McpResponse', () => {});it('allows response text lines to be added', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.appendResponseLine('Testing 1');response.appendResponseLine('Testing 2');const result = await response.handle('test', context);@@ -40,7 +40,7 @@ describe('McpResponse', () => {});it('does not include anything in response if snapshot is null', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();page.accessibility.snapshot = async () => null;const result = await response.handle('test', context);@@ -50,7 +50,7 @@ describe('McpResponse', () => {});it('returns correctly formatted snapshot for a simple tree', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button>Click me</button@@ -68,7 +68,7 @@ describe('McpResponse', () => {});it('returns values for textboxes', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<label@@ -86,7 +86,7 @@ describe('McpResponse', () => {});it('returns verbose snapshot', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<aside>test</aside>`);response.includeSnapshot({@@ -101,7 +101,7 @@ describe('McpResponse', () => {it('saves snapshot to file', async t => {const filePath = join(tmpdir(), 'test-screenshot.png');try {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<aside>test</aside>`);response.includeSnapshot({@@ -120,7 +120,7 @@ describe('McpResponse', () => {});it('adds throttling setting when it is not null', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setNetworkConditions('Slow 3G');const result = await response.handle('test', context);assert.equal(result[0].type, 'text');@@ -129,7 +129,7 @@ describe('McpResponse', () => {});it('does not include throttling setting when it is null', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const result = await response.handle('test', context);context.setNetworkConditions(null);assert.equal(result[0].type, 'text');@@ -137,7 +137,7 @@ describe('McpResponse', () => {});});it('adds image when image is attached', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.attachImage({data: 'imageBase64', mimeType: 'image/png'});const result = await response.handle('test', context);assert.strictEqual(result[0].text, `# test response`);@@ -148,7 +148,7 @@ describe('McpResponse', () => {});it('adds cpu throttling setting when it is over 1', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setCpuThrottlingRate(4);const result = await response.handle('test', context);t.assert.snapshot?.(result[0].text);@@ -156,7 +156,7 @@ describe('McpResponse', () => {});it('does not include cpu throttling setting when it is 1', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setCpuThrottlingRate(1);const result = await response.handle('test', context);assert.strictEqual(result[0].text, `# test response`);@@ -164,7 +164,7 @@ describe('McpResponse', () => {});it('adds a prompt dialog', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const dialogPromise = new Promise<void>(resolve => {page.on('dialog', () => {@@ -182,7 +182,7 @@ describe('McpResponse', () => {});it('adds an alert dialog', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const dialogPromise = new Promise<void>(resolve => {page.on('dialog', () => {@@ -200,7 +200,7 @@ describe('McpResponse', () => {});it('add network requests when setting is true', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true);context.getNetworkRequests = () => {return [getMockRequest({stableId: 1}), getMockRequest({stableId: 2})];@@ -211,7 +211,7 @@ describe('McpResponse', () => {});it('does not include network requests when setting is false', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(false);context.getNetworkRequests = () => {return [getMockRequest()];@@ -222,7 +222,7 @@ describe('McpResponse', () => {});it('add network request when attached with POST data', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true);const httpResponse = getMockResponse();httpResponse.buffer = () => {@@ -254,7 +254,7 @@ describe('McpResponse', () => {});it('add network request when attached', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true);const request = getMockRequest();context.getNetworkRequests = () => {@@ -270,7 +270,7 @@ describe('McpResponse', () => {});it('adds console messages when the setting is true', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeConsoleData(true);const page = context.getSelectedPage();const consoleMessagePromise = new Promise<void>(resolve => {@@ -289,7 +289,7 @@ describe('McpResponse', () => {});it('adds a message when no console messages exist', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeConsoleData(true);const result = await response.handle('test', context);assert.ok(result[0].text);@@ -298,7 +298,7 @@ describe('McpResponse', () => {});it("doesn't list the issue message if mapping returns null", async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const mockAggregatedIssue = getMockAggregatedIssue();const mockDescription = {file: 'not-existing-description-file.md',@@ -317,7 +317,7 @@ describe('McpResponse', () => {});it('throws error if mapping returns null on get issue details', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const mockAggregatedIssue = getMockAggregatedIssue();const mockDescription = {file: 'not-existing-description-file.md',@@ -340,7 +340,7 @@ describe('McpResponse', () => {describe('McpResponse network request filtering', () => {it('filters network requests by resource type', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true, {resourceTypes: ['script', 'stylesheet'],});@@ -358,7 +358,7 @@ describe('McpResponse network request filtering', () => {});it('filters network requests by single resource type', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true, {resourceTypes: ['image'],});@@ -375,7 +375,7 @@ describe('McpResponse network request filtering', () => {});it('shows no requests when filter matches nothing', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true, {resourceTypes: ['font'],});@@ -392,7 +392,7 @@ describe('McpResponse network request filtering', () => {});it('shows all requests when no filters are provided', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true);context.getNetworkRequests = () => {return [@@ -410,7 +410,7 @@ describe('McpResponse network request filtering', () => {});it('shows all requests when empty resourceTypes array is provided', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {response.setIncludeNetworkRequests(true, {resourceTypes: [],});@@ -431,7 +431,7 @@ describe('McpResponse network request filtering', () => {describe('McpResponse network pagination', () => {it('returns all requests when pagination is not provided', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const requests = Array.from({length: 5}, () => getMockRequest());context.getNetworkRequests = () => requests;response.setIncludeNetworkRequests(true);@@ -444,7 +444,7 @@ describe('McpResponse network pagination', () => {});it('returns first page by default', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const requests = Array.from({length: 30}, (_, idx) =>getMockRequest({method: `GET-${idx}`}),);@@ -461,7 +461,7 @@ describe('McpResponse network pagination', () => {});it('returns subsequent page when pageIdx provided', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const requests = Array.from({length: 25}, (_, idx) =>getMockRequest({method: `GET-${idx}`}),);@@ -479,7 +479,7 @@ describe('McpResponse network pagination', () => {});it('handles invalid page number by showing first page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const requests = Array.from({length: 5}, () => getMockRequest());context.getNetworkRequests = () => requests;response.setIncludeNetworkRequests(true, {diff --git a/tests/PageCollector.test.ts b/tests/PageCollector.test.tsindex bcf17ff5..b9dd15cc 100644--- a/tests/PageCollector.test.ts+++ b/tests/PageCollector.test.ts@@ -7,14 +7,7 @@import assert from 'node:assert';import {afterEach, beforeEach, describe, it} from 'node:test';-import type {- Browser,- Frame,- HTTPRequest,- Page,- Target,- Protocol,-} from 'puppeteer-core';+import type {Frame, HTTPRequest, Target, Protocol} from 'puppeteer-core';import sinon from 'sinon';import {AggregatedIssue} from '../node_modules/chrome-devtools-frontend/mcp/mcp.js';@@ -26,58 +19,7 @@ import {PageCollector,} from '../src/PageCollector.js';-import {getMockRequest} from './utils.js';--function mockListener() {- const listeners: Record<string, Array<(data: unknown) => void>> = {};- return {- on(eventName: string, listener: (data: unknown) => void) {- if (listeners[eventName]) {- listeners[eventName].push(listener);- } else {- listeners[eventName] = [listener];- }- },- off(_eventName: string, _listener: (data: unknown) => void) {- // no-op- },- emit(eventName: string, data: unknown) {- for (const listener of listeners[eventName] ?? []) {- listener(data);- }- },- };-}--function getMockPage(): Page {- const mainFrame = {} as Frame;- const cdpSession = {- ...mockListener(),- send: () => {- // no-op- },- };- return {- mainFrame() {- return mainFrame;- },- ...mockListener(),- // @ts-expect-error internal API.- _client() {- return cdpSession;- },- } satisfies Page;-}--function getMockBrowser(): Browser {- const pages = [getMockPage()];- return {- pages() {- return Promise.resolve(pages);- },- ...mockListener(),- } as Browser;-}+import {getMockRequest, getMockBrowser} from './utils.js';describe('PageCollector', () => {it('works', async () => {diff --git a/tests/tools/console.test.ts b/tests/tools/console.test.tsindex 06bcbc18..446f32d2 100644--- a/tests/tools/console.test.ts+++ b/tests/tools/console.test.ts@@ -16,7 +16,7 @@ import {listConsoleMessages,} from '../../src/tools/console.js';import {serverHooks} from '../server.js';-import {withBrowser} from '../utils.js';+import {withMcpContext} from '../utils.js';describe('console', () => {before(async () => {@@ -24,14 +24,14 @@ describe('console', () => {});describe('list_console_messages', () => {it('list messages', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await listConsoleMessages.handler({params: {}}, response, context);assert.ok(response.includeConsoleData);});});it('lists error messages', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();await page.setContent('<script>console.error("This is an error")</script>',@@ -46,7 +46,7 @@ describe('console', () => {});it('work with primitive unhandled errors', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();await page.setContent('<script>throw undefined;</script>');await listConsoleMessages.handler({params: {}}, response, context);@@ -66,7 +66,7 @@ describe('console', () => {setIssuesEnabled(false);});it('lists issues', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();const issuePromise = new Promise<void>(resolve => {page.once('issue', () => {@@ -87,7 +87,7 @@ describe('console', () => {});it('lists issues after a page reload', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();const issuePromise = new Promise<void>(resolve => {page.once('issue', () => {@@ -132,7 +132,7 @@ describe('console', () => {describe('get_console_message', () => {it('gets a specific console message', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();await page.setContent('<script>console.error("This is an error")</script>',@@ -163,7 +163,7 @@ describe('console', () => {});it('gets issue details with node id parsing', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();const issuePromise = new Promise<void>(resolve => {page.once('issue', () => {@@ -191,7 +191,7 @@ describe('console', () => {res.end(JSON.stringify({data: 'test data'}));});- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();const issuePromise = new Promise<void>(resolve => {page.once('issue', () => {diff --git a/tests/tools/emulation.test.ts b/tests/tools/emulation.test.tsindex 35b79ea6..1af4a9df 100644--- a/tests/tools/emulation.test.ts+++ b/tests/tools/emulation.test.ts@@ -8,12 +8,12 @@ import assert from 'node:assert';import {describe, it} from 'node:test';import {emulate} from '../../src/tools/emulation.js';-import {withBrowser} from '../utils.js';+import {withMcpContext} from '../utils.js';describe('emulation', () => {describe('network', () => {it('emulates offline network conditions', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {@@ -28,7 +28,7 @@ describe('emulation', () => {});});it('emulates network throttling when the throttling option is valid', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {@@ -44,7 +44,7 @@ describe('emulation', () => {});it('disables network emulation', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {@@ -60,7 +60,7 @@ describe('emulation', () => {});it('does not set throttling when the network throttling is not one of the predefined options', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {@@ -76,7 +76,7 @@ describe('emulation', () => {});it('report correctly for the currently selected page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {@@ -99,7 +99,7 @@ describe('emulation', () => {describe('cpu', () => {it('emulates cpu throttling when the rate is valid (1-20x)', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {@@ -115,7 +115,7 @@ describe('emulation', () => {});it('disables cpu throttling', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setCpuThrottlingRate(4); // Set it to something first.await emulate.handler({@@ -132,7 +132,7 @@ describe('emulation', () => {});it('report correctly for the currently selected page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await emulate.handler({params: {diff --git a/tests/tools/input.test.ts b/tests/tools/input.test.tsindex 230b8a5d..f1f7fc59 100644--- a/tests/tools/input.test.ts+++ b/tests/tools/input.test.ts@@ -20,14 +20,14 @@ import {} from '../../src/tools/input.js';import {parseKey} from '../../src/utils/keyboard.js';import {serverHooks} from '../server.js';-import {html, withBrowser} from '../utils.js';+import {html, withMcpContext} from '../utils.js';describe('input', () => {const server = serverHooks();describe('click', () => {it('clicks', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button onclick="this.innerText = 'clicked';">test</button>`,@@ -51,7 +51,7 @@ describe('input', () => {});});it('double clicks', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button ondblclick="this.innerText = 'dblclicked';"@@ -89,7 +89,7 @@ describe('input', () => {res.end();});- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto(server.getRoute('/link'));await context.createTextSnapshot();@@ -131,7 +131,7 @@ describe('input', () => {</script>`,);- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto(server.getRoute('/unstable'));await context.createTextSnapshot();@@ -158,7 +158,7 @@ describe('input', () => {describe('hover', () => {it('hovers', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button onmouseover="this.innerText = 'hovered';">test</button>`,@@ -185,7 +185,7 @@ describe('input', () => {describe('fill', () => {it('fills out an input', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<input />`);await context.createTextSnapshot();@@ -209,7 +209,7 @@ describe('input', () => {});it('fills out a select by text', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<select@@ -243,7 +243,7 @@ describe('input', () => {describe('drags', () => {it('drags one element onto another', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<div@@ -297,7 +297,7 @@ describe('input', () => {describe('fill form', () => {it('successfully fills out the form', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<form>@@ -361,7 +361,7 @@ describe('input', () => {const testFilePath = path.join(process.cwd(), 'test.txt');await fs.writeFile(testFilePath, 'test file content');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<form>@@ -396,7 +396,7 @@ describe('input', () => {const testFilePath = path.join(process.cwd(), 'test.txt');await fs.writeFile(testFilePath, 'test file content');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button id="file-chooser-button">Upload file</button>@@ -443,7 +443,7 @@ describe('input', () => {const testFilePath = path.join(process.cwd(), 'test.txt');await fs.writeFile(testFilePath, 'test file content');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<div>Not a file input</div>`);await context.createTextSnapshot();@@ -502,7 +502,7 @@ describe('input', () => {});it('processes press_key', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<script>diff --git a/tests/tools/network.test.ts b/tests/tools/network.test.tsindex 740fb3a1..44c6bc9e 100644--- a/tests/tools/network.test.ts+++ b/tests/tools/network.test.ts@@ -12,13 +12,13 @@ import {listNetworkRequests,} from '../../src/tools/network.js';import {serverHooks} from '../server.js';-import {html, withBrowser, stabilizeResponseOutput} from '../utils.js';+import {html, withMcpContext, stabilizeResponseOutput} from '../utils.js';describe('network', () => {const server = serverHooks();describe('network_list_requests', () => {it('list requests', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await listNetworkRequests.handler({params: {}}, response, context);assert.ok(response.includeNetworkRequests);assert.strictEqual(response.networkRequestsPageIdx, undefined);@@ -30,7 +30,7 @@ describe('network', () => {server.addHtmlRoute('/two', html`<main>Second</main>`);server.addHtmlRoute('/three', html`<main>Third</main>`);- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await context.setUpNetworkCollectorForTesting();const page = context.getSelectedPage();await page.goto(server.getRoute('/one'));@@ -53,7 +53,7 @@ describe('network', () => {server.addHtmlRoute('/two', html`<main>Second</main>`);server.addHtmlRoute('/three', html`<main>Third</main>`);- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await context.setUpNetworkCollectorForTesting();const page = context.getSelectedPage();await page.goto(server.getRoute('/one'));@@ -93,7 +93,7 @@ describe('network', () => {html`<main>I was redirected 2 times</main>`,);- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await context.setUpNetworkCollectorForTesting();const page = context.getSelectedPage();await page.goto(server.getRoute('/redirect'));@@ -113,7 +113,7 @@ describe('network', () => {});describe('network_get_request', () => {it('attaches request', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto('data:text/html,<div>Hello MCP</div>');await getNetworkRequest.handler(@@ -126,7 +126,7 @@ describe('network', () => {});});it('should not add the request list', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto('data:text/html,<div>Hello MCP</div>');await getNetworkRequest.handler(@@ -142,7 +142,7 @@ describe('network', () => {server.addHtmlRoute('/two', html`<main>Second</main>`);server.addHtmlRoute('/three', html`<main>Third</main>`);- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await context.setUpNetworkCollectorForTesting();const page = context.getSelectedPage();await page.goto(server.getRoute('/one'));diff --git a/tests/tools/pages.test.ts b/tests/tools/pages.test.tsindex d116e352..76b99cb1 100644--- a/tests/tools/pages.test.ts+++ b/tests/tools/pages.test.ts@@ -18,12 +18,12 @@ import {resizePage,handleDialog,} from '../../src/tools/pages.js';-import {withBrowser} from '../utils.js';+import {withMcpContext} from '../utils.js';describe('pages', () => {describe('list_pages', () => {it('list pages', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await listPages.handler({params: {}}, response, context);assert.ok(response.includePages);});@@ -31,7 +31,7 @@ describe('pages', () => {});describe('new_page', () => {it('create a page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {assert.strictEqual(context.getPageByIdx(0), context.getSelectedPage());await newPage.handler({params: {url: 'about:blank'}},@@ -45,7 +45,7 @@ describe('pages', () => {});describe('close_page', () => {it('closes a page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();assert.strictEqual(context.getPageByIdx(1), context.getSelectedPage());assert.strictEqual(context.getPageByIdx(1), page);@@ -55,7 +55,7 @@ describe('pages', () => {});});it('cannot close the last page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await closePage.handler({params: {pageIdx: 0}}, response, context);assert.deepStrictEqual(@@ -69,7 +69,7 @@ describe('pages', () => {});describe('select_page', () => {it('selects a page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await context.newPage();assert.strictEqual(context.getPageByIdx(1), context.getSelectedPage());await selectPage.handler({params: {pageIdx: 0}}, response, context);@@ -80,7 +80,7 @@ describe('pages', () => {});describe('navigate_page', () => {it('navigates to correct page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await navigatePage.handler({params: {url: 'data:text/html,<div>Hello MCP</div>'}},response,@@ -96,7 +96,7 @@ describe('pages', () => {});it('throws an error if the page was closed not by the MCP server', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = await context.newPage();assert.strictEqual(context.getPageByIdx(1), context.getSelectedPage());assert.strictEqual(context.getPageByIdx(1), page);@@ -119,7 +119,7 @@ describe('pages', () => {});});it('go back', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto('data:text/html,<div>Hello MCP</div>');await navigatePage.handler({params: {type: 'back'}}, response, context);@@ -132,7 +132,7 @@ describe('pages', () => {});});it('go forward', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto('data:text/html,<div>Hello MCP</div>');await page.goBack();@@ -150,7 +150,7 @@ describe('pages', () => {});});it('reload', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto('data:text/html,<div>Hello MCP</div>');await navigatePage.handler(@@ -167,7 +167,7 @@ describe('pages', () => {});});it('go forward with error', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await navigatePage.handler({params: {type: 'forward'}},response,@@ -183,7 +183,7 @@ describe('pages', () => {});});it('go back with error', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await navigatePage.handler({params: {type: 'back'}}, response, context);assert.ok(@@ -197,7 +197,7 @@ describe('pages', () => {});describe('resize', () => {it('create a page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const resizePromise = page.evaluate(() => {return new Promise(resolve => {@@ -220,7 +220,7 @@ describe('pages', () => {describe('dialogs', () => {it('can accept dialogs', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const dialogPromise = new Promise<void>(resolve => {page.on('dialog', () => {@@ -248,7 +248,7 @@ describe('pages', () => {});});it('can dismiss dialogs', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const dialogPromise = new Promise<void>(resolve => {page.on('dialog', () => {@@ -276,7 +276,7 @@ describe('pages', () => {});});it('can dismiss already dismissed dialog dialogs', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const dialogPromise = new Promise<Dialog>(resolve => {page.on('dialog', dialog => {diff --git a/tests/tools/performance.test.ts b/tests/tools/performance.test.tsindex 900a10c2..cb390b33 100644--- a/tests/tools/performance.test.ts+++ b/tests/tools/performance.test.ts@@ -20,7 +20,7 @@ import {traceResultIsSuccess,} from '../../src/trace-processing/parse.js';import {loadTraceAsBuffer} from '../trace-processing/fixtures/load.js';-import {withBrowser} from '../utils.js';+import {withMcpContext} from '../utils.js';describe('performance', () => {afterEach(() => {@@ -29,7 +29,7 @@ describe('performance', () => {describe('performance_start_trace', () => {it('starts a trace recording', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setIsRunningPerformanceTrace(false);const selectedPage = context.getSelectedPage();const startTracingStub = sinon.stub(selectedPage.tracing, 'start');@@ -49,7 +49,7 @@ describe('performance', () => {});it('can navigate to about:blank and record a page reload', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const selectedPage = context.getSelectedPage();sinon.stub(selectedPage, 'url').callsFake(() => 'https://www.test.com');const gotoStub = sinon.stub(selectedPage, 'goto');@@ -78,7 +78,7 @@ describe('performance', () => {it('can autostop and store a recording', async () => {const rawData = loadTraceAsBuffer('basic-trace.json.gz');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const selectedPage = context.getSelectedPage();sinon.stub(selectedPage, 'url').callsFake(() => 'https://www.test.com');sinon.stub(selectedPage, 'goto').callsFake(() => Promise.resolve(null));@@ -121,7 +121,7 @@ describe('performance', () => {});it('errors if a recording is already active', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setIsRunningPerformanceTrace(true);const selectedPage = context.getSelectedPage();const startTracingStub = sinon.stub(selectedPage.tracing, 'start');@@ -152,7 +152,7 @@ describe('performance', () => {it('returns the information on the insight', async t => {const trace = await parseTrace('web-dev-with-commit.json.gz');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.storeTraceRecording(trace);context.setIsRunningPerformanceTrace(false);@@ -173,7 +173,7 @@ describe('performance', () => {it('returns an error if the insight does not exist', async () => {const trace = await parseTrace('web-dev-with-commit.json.gz');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.storeTraceRecording(trace);context.setIsRunningPerformanceTrace(false);@@ -196,7 +196,7 @@ describe('performance', () => {});it('returns an error if no trace has been recorded', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await analyzeInsight.handler({params: {@@ -220,7 +220,7 @@ describe('performance', () => {describe('performance_stop_trace', () => {it('does nothing if the trace is not running and does not error', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setIsRunningPerformanceTrace(false);const selectedPage = context.getSelectedPage();const stopTracingStub = sinon.stub(selectedPage.tracing, 'stop');@@ -232,7 +232,7 @@ describe('performance', () => {it('will stop the trace and return trace info when a trace is running', async () => {const rawData = loadTraceAsBuffer('basic-trace.json.gz');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setIsRunningPerformanceTrace(true);const selectedPage = context.getSelectedPage();const stopTracingStub = sinon@@ -252,7 +252,7 @@ describe('performance', () => {});it('returns an error message if parsing the trace buffer fails', async t => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setIsRunningPerformanceTrace(true);const selectedPage = context.getSelectedPage();sinon@@ -265,7 +265,7 @@ describe('performance', () => {it('returns the high level summary of the performance trace', async t => {const rawData = loadTraceAsBuffer('web-dev-with-commit.json.gz');- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {context.setIsRunningPerformanceTrace(true);const selectedPage = context.getSelectedPage();sinon.stub(selectedPage.tracing, 'stop').callsFake(async () => {diff --git a/tests/tools/screenshot.test.ts b/tests/tools/screenshot.test.tsindex 69e70fe1..dab54141 100644--- a/tests/tools/screenshot.test.ts+++ b/tests/tools/screenshot.test.ts@@ -12,12 +12,12 @@ import {describe, it} from 'node:test';import {screenshot} from '../../src/tools/screenshot.js';import {screenshots} from '../snapshot.js';-import {html, withBrowser} from '../utils.js';+import {html, withMcpContext} from '../utils.js';describe('screenshot', () => {describe('browser_take_screenshot', () => {it('with default options', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const fixture = screenshots.basic;const page = context.getSelectedPage();await page.setContent(fixture.html);@@ -32,7 +32,7 @@ describe('screenshot', () => {});});it('ignores quality', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const fixture = screenshots.basic;const page = context.getSelectedPage();await page.setContent(fixture.html);@@ -51,7 +51,7 @@ describe('screenshot', () => {});});it('with jpeg', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await screenshot.handler({params: {format: 'jpeg'}}, response, context);assert.equal(response.images.length, 1);@@ -63,7 +63,7 @@ describe('screenshot', () => {});});it('with webp', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await screenshot.handler({params: {format: 'webp'}}, response, context);assert.equal(response.images.length, 1);@@ -75,7 +75,7 @@ describe('screenshot', () => {});});it('with full page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const fixture = screenshots.viewportOverflow;const page = context.getSelectedPage();await page.setContent(fixture.html);@@ -95,7 +95,7 @@ describe('screenshot', () => {});it('with full page resulting in a large screenshot', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(@@ -129,7 +129,7 @@ describe('screenshot', () => {});it('with element uid', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const fixture = screenshots.button;const page = context.getSelectedPage();@@ -156,7 +156,7 @@ describe('screenshot', () => {});it('with filePath', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const filePath = join(tmpdir(), 'test-screenshot.png');try {const fixture = screenshots.basic;@@ -198,7 +198,7 @@ describe('screenshot', () => {await chmod(filePath, 0o400);try {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const fixture = screenshots.basic;const page = context.getSelectedPage();await page.setContent(fixture.html);@@ -222,7 +222,7 @@ describe('screenshot', () => {const filePath = join(dir, 'test-screenshot.png');try {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const fixture = screenshots.basic;const page = context.getSelectedPage();await page.setContent(fixture.html);@@ -242,7 +242,7 @@ describe('screenshot', () => {});it('with malformed filePath', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {// Use a platform-specific invalid character.// On Windows, characters like '<', '>', ':', '"', '/', '\', '|', '?', '*' are invalid.// On POSIX, the null byte is invalid.diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.tsindex b6d52507..06c4875f 100644--- a/tests/tools/script.test.ts+++ b/tests/tools/script.test.ts@@ -9,14 +9,14 @@ import {describe, it} from 'node:test';import {evaluateScript} from '../../src/tools/script.js';import {serverHooks} from '../server.js';-import {html, withBrowser} from '../utils.js';+import {html, withMcpContext} from '../utils.js';describe('script', () => {const server = serverHooks();describe('browser_evaluate_script', () => {it('evaluates', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await evaluateScript.handler({params: {function: String(() => 2 * 5)}},response,@@ -27,7 +27,7 @@ describe('script', () => {});});it('runs in selected page', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await evaluateScript.handler({params: {function: String(() => document.title)}},response,@@ -57,7 +57,7 @@ describe('script', () => {});it('work for complex objects', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<script src="./scripts.js"></script> `);@@ -85,7 +85,7 @@ describe('script', () => {});it('work for async functions', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<script src="./scripts.js"></script> `);@@ -108,7 +108,7 @@ describe('script', () => {});it('work with one argument', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button id="test">test</button>`);@@ -133,7 +133,7 @@ describe('script', () => {});it('work with multiple args', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(html`<button id="test">test</button>`);@@ -164,7 +164,7 @@ describe('script', () => {);server.addHtmlRoute('/main', html`<iframe src="/iframe"></iframe>`);- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.goto(server.getRoute('/main'));await context.createTextSnapshot();diff --git a/tests/tools/snapshot.test.ts b/tests/tools/snapshot.test.tsindex 9dc48d94..795e3d41 100644--- a/tests/tools/snapshot.test.ts+++ b/tests/tools/snapshot.test.ts@@ -8,12 +8,12 @@ import assert from 'node:assert';import {describe, it} from 'node:test';import {takeSnapshot, waitFor} from '../../src/tools/snapshot.js';-import {html, withBrowser} from '../utils.js';+import {html, withMcpContext} from '../utils.js';describe('snapshot', () => {describe('browser_snapshot', () => {it('includes a snapshot', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {await takeSnapshot.handler({params: {}}, response, context);assert.ok(response.includeSnapshot);});@@ -21,7 +21,7 @@ describe('snapshot', () => {});describe('browser_wait_for', () => {it('should work', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(@@ -45,7 +45,7 @@ describe('snapshot', () => {});});it('should work with element that show up later', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();const handlePromise = waitFor.handler(@@ -72,7 +72,7 @@ describe('snapshot', () => {});});it('should work with aria elements', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(@@ -98,7 +98,7 @@ describe('snapshot', () => {});it('should work with iframe content', async () => {- await withBrowser(async (response, context) => {+ await withMcpContext(async (response, context) => {const page = context.getSelectedPage();await page.setContent(diff --git a/tests/utils.ts b/tests/utils.tsindex 8cd5d03e..6fefd649 100644--- a/tests/utils.ts+++ b/tests/utils.ts@@ -12,6 +12,7 @@ import type {HTTPRequest,HTTPResponse,LaunchOptions,+ Page,} from 'puppeteer-core';import sinon from 'sinon';@@ -24,7 +25,7 @@ const browsers = new Map<string, Browser>();let context: McpContext | undefined;export async function withBrowser(- cb: (response: McpResponse, context: McpContext) => Promise<void>,+ cb: (browser: Browser, page: Page) => Promise<void>,options: {debug?: boolean; autoOpenDevTools?: boolean} = {},) {const launchOptions: LaunchOptions = {@@ -51,20 +52,30 @@ export async function withBrowser(}}),);- const response = new McpResponse();- if (context) {- context.dispose();- }- context = await McpContext.from(- browser,- logger('test'),- {- experimentalDevToolsDebugging: false,- },- Locator,- );- await cb(response, context);+ await cb(browser, newPage);+}++export async function withMcpContext(+ cb: (response: McpResponse, context: McpContext) => Promise<void>,+ options: {debug?: boolean; autoOpenDevTools?: boolean} = {},+) {+ await withBrowser(async browser => {+ const response = new McpResponse();+ if (context) {+ context.dispose();+ }+ context = await McpContext.from(+ browser,+ logger('test'),+ {+ experimentalDevToolsDebugging: false,+ },+ Locator,+ );++ await cb(response, context);+ }, options);}export function getMockRequest(@@ -193,3 +204,54 @@ export function getMockAggregatedIssue(): sinon.SinonStubbedInstance<AggregatedImockAggregatedIssue.getMixedContentIssues.returns(new Set());return mockAggregatedIssue;}++export function mockListener() {+ const listeners: Record<string, Array<(data: unknown) => void>> = {};+ return {+ on(eventName: string, listener: (data: unknown) => void) {+ if (listeners[eventName]) {+ listeners[eventName].push(listener);+ } else {+ listeners[eventName] = [listener];+ }+ },+ off(_eventName: string, _listener: (data: unknown) => void) {+ // no-op+ },+ emit(eventName: string, data: unknown) {+ for (const listener of listeners[eventName] ?? []) {+ listener(data);+ }+ },+ };+}++export function getMockPage(): Page {+ const mainFrame = {} as Frame;+ const cdpSession = {+ ...mockListener(),+ send: () => {+ // no-op+ },+ };+ return {+ mainFrame() {+ return mainFrame;+ },+ ...mockListener(),+ // @ts-expect-error internal API.+ _client() {+ return cdpSession;+ },+ } satisfies Page;+}++export function getMockBrowser(): Browser {+ const pages = [getMockPage()];+ return {+ pages() {+ return Promise.resolve(pages);+ },+ ...mockListener(),+ } as Browser;+}