From 7a9fbc05a7fc0beb121c11fae008e2f1e0e4406d Mon Sep 17 00:00:00 2001 From: Thomas Bachem Date: Sun, 8 Nov 2026 08:13:23 +0100 Subject: [PATCH 1/2] feat: list errors a page raises while a tool runs --- src/McpPage.ts | 13 ++++ src/McpResponse.ts | 75 ++++++++++++++++++- src/ToolHandler.ts | 4 + src/tools/ToolDefinition.ts | 7 ++ src/tools/pages.ts | 1 + src/tools/script.ts | 2 + tests/McpResponse.test.ts | 143 ++++++++++++++++++++++++++++++++++++ tests/ToolHandler.test.ts | 50 +++++++++++++ tests/mocks.ts | 2 + tests/tools/pages.test.ts | 31 +++++++- tests/tools/script.test.ts | 132 +++++++++++++++++++++++++++++++++ 11 files changed, 456 insertions(+), 4 deletions(-) diff --git a/src/McpPage.ts b/src/McpPage.ts index b40eab911e..2b94a1600b 100644 --- a/src/McpPage.ts +++ b/src/McpPage.ts @@ -832,6 +832,19 @@ export class McpPage implements ContextPage { return this.consoleCollector.getById(id); } + getLatestConsoleMessageId(): number { + const latest = this.consoleCollector.getData(true).at(-1); + return latest ? this.consoleCollector.getIdForResource(latest) : 0; + } + + getConsoleDataAfter( + id: number, + ): Array { + return this.consoleCollector + .getData(true) + .filter(item => this.consoleCollector.getIdForResource(item) > id); + } + getNetworkRequestById(reqid: number): HTTPRequest { return this.networkCollector.getById(reqid); } diff --git a/src/McpResponse.ts b/src/McpResponse.ts index 63f9508183..30f1057404 100644 --- a/src/McpResponse.ts +++ b/src/McpResponse.ts @@ -59,6 +59,7 @@ import { import {handleDialog, listPages} from './tools/pages.js'; import type {ToolGroups} from './tools/thirdPartyDeveloper.js'; import type { + ContextPage, DevToolsData, ImageContentData, LighthouseData, @@ -67,6 +68,7 @@ import type { SnapshotParams, WebAuthnAuthenticatorState, } from './tools/ToolDefinition.js'; +import {LIST_CONSOLE_MESSAGES_TOOL_NAME} from './tools/toolNames.js'; import { type InsightName, type TraceResult, @@ -82,6 +84,9 @@ import type {WaitForEventsResult} from './utils/WaitForHelper.js'; const {formatBytesToKb} = DevTools.I18n.ByteUtilities; +/** How many errors raised during a call the response lists. */ +const MAX_CONSOLE_ERRORS = 10; + export type DataFormat = 'default' | 'toon' | 'gcf'; interface TraceInsightData { @@ -156,6 +161,7 @@ export class McpResponse implements Response { #page?: McpPage; #error?: Error; #attachedWaitForResult?: WaitForEventsResult; + #consoleErrorsFrom?: {page: ContextPage; lastMessageId: number}; #reconnectNotice = false; #devToolsComments?: CD4ACommentThread[]; #webAuthnFormatter?: WebAuthnFormatter; @@ -277,6 +283,13 @@ export class McpResponse implements Response { }; } + includeConsoleErrorsFrom(page: ContextPage): void { + this.#consoleErrorsFrom = { + page, + lastMessageId: page.getLatestConsoleMessageId(), + }; + } + setIncludeCssStyles( matchedStyles: MatchedStyles, options: CssFormatterOptions & PaginationOptions, @@ -671,8 +684,42 @@ export class McpResponse implements Response { ); } - if (this.#consoleDataOptions.types?.length) { - const normalizedTypes = new Set(this.#consoleDataOptions.types); + return await this.#formatConsoleData( + messages, + page, + this.#consoleDataOptions, + ); + } + + async #handleConsoleErrors(): Promise< + Array | undefined + > { + const errorsFrom = this.#consoleErrorsFrom; + // A tool that lists or shows console messages itself already covers these. + if ( + !errorsFrom || + this.#consoleDataOptions?.include || + this.#attachedConsoleMessageId !== undefined || + errorsFrom.page.isClosed() + ) { + return undefined; + } + return await this.#formatConsoleData( + errorsFrom.page.getConsoleDataAfter(errorsFrom.lastMessageId), + this.#page, + {types: ['error']}, + ); + } + + async #formatConsoleData( + messages: Array< + ConsoleMessage | Error | DevTools.AggregatedIssue | UncaughtError + >, + page: McpPage | undefined, + options: {types?: string[]; includeStackTraces?: boolean}, + ): Promise> { + if (options.types?.length) { + const normalizedTypes = new Set(options.types); messages = messages.filter(message => { if ('type' in message) { return normalizedTypes.has(message.type()); @@ -694,7 +741,7 @@ export class McpResponse implements Response { return await ConsoleFormatter.from(consoleMessage, { id: consoleMessageStableId, fetchDetailedData: false, - fetchStackTrace: this.#consoleDataOptions?.includeStackTraces, + fetchStackTrace: options.includeStackTraces, devTools: page ? page.devtoolsUniverse : undefined, }); } @@ -808,6 +855,7 @@ export class McpResponse implements Response { thirdPartyDeveloperTools, webmcpTools, consoleMessages, + consoleErrors, networkRequests, commentsResult, ] = await Promise.all([ @@ -817,6 +865,7 @@ export class McpResponse implements Response { this.#handleThirdPartyDeveloperTools(), this.#handleWebMCP(), this.#handleConsoleList(context), + this.#handleConsoleErrors(), this.#handleNetworkRequestList(context), this.#handleComments(), ]); @@ -835,6 +884,7 @@ export class McpResponse implements Response { { detailedConsoleMessage, consoleMessages, + consoleErrors, snapshot, detailedNetworkRequest, networkRequests, @@ -868,6 +918,7 @@ export class McpResponse implements Response { data: { detailedConsoleMessage: ConsoleFormatter | IssueFormatter | undefined; consoleMessages: Array | undefined; + consoleErrors?: Array; snapshot: SnapshotFormatter | string | undefined; detailedNetworkRequest?: NetworkFormatter; networkRequests?: NetworkFormatter[]; @@ -894,6 +945,7 @@ export class McpResponse implements Response { networkRequests?: object[]; consoleMessage?: object; consoleMessages?: object[]; + consoleErrors?: object[]; traceSummary?: string; traceInsights?: Array<{ insightName: string; @@ -1735,6 +1787,23 @@ Call ${handleDialog(this.#config.resolved).name} to handle it before continuing. } } + if (data.consoleErrors?.length) { + const grouped = ConsoleFormatter.groupConsecutive(data.consoleErrors); + const shown = grouped.slice(0, MAX_CONSOLE_ERRORS); + structuredContent.consoleErrors = shown.map(item => item.toJSON()); + response.push('## Console errors during this call'); + if (compactEncode) { + response.push(compactEncode(structuredContent.consoleErrors)); + } else { + response.push(...shown.map(item => item.toString())); + } + if (grouped.length > shown.length) { + response.push( + `${grouped.length - shown.length} more not shown. Call ${LIST_CONSOLE_MESSAGES_TOOL_NAME} to list them.`, + ); + } + } + if (data.comments) { const commentsJson = data.comments.toJSON(); structuredContent.comments = commentsJson; diff --git a/src/ToolHandler.ts b/src/ToolHandler.ts index ead3fa1324..7354c60250 100644 --- a/src/ToolHandler.ts +++ b/src/ToolHandler.ts @@ -406,6 +406,10 @@ export class ToolHandler { : context.getSelectedMcpPage(); await page?.init({emulateFocus: true}); response.setPage(page); + // A call that runs beside others can't tell its own errors apart. + if (tool.concurrency !== 'none') { + response.includeConsoleErrorsFrom(page); + } if (tool.blockedByDialog) { page.throwIfDialogOpen(); } diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.ts index dde134f79f..81d24c982d 100644 --- a/src/tools/ToolDefinition.ts +++ b/src/tools/ToolDefinition.ts @@ -300,6 +300,11 @@ export interface Response { serviceWorkerId?: string; }, ): void; + /** + * Lists the console errors and uncaught exceptions that the page raises from + * now until the response is handled. + */ + includeConsoleErrorsFrom(page: ContextPage): void; setIncludeCssStyles( matchedStyles: MatchedStyles, options: CssFormatterOptions & PaginationOptions, @@ -532,6 +537,8 @@ export type ContextPage = Readonly<{ setScreenRecorder(data: ScreenRecorderData | null): void; isRunningPerformanceTrace(): boolean; setIsRunningPerformanceTrace(x: boolean): void; + getLatestConsoleMessageId(): number; + getConsoleDataAfter(id: number): ReturnType; waitForEventsAfterAction( action: (signal: AbortSignal) => Promise, options?: { diff --git a/src/tools/pages.ts b/src/tools/pages.ts index 5a96cf3052..7982342863 100644 --- a/src/tools/pages.ts +++ b/src/tools/pages.ts @@ -150,6 +150,7 @@ export const newPage: ToolFactory = defineTool((args: ParsedArguments) => { request.params.background, request.params.isolatedContext, ); + response.includeConsoleErrorsFrom(page); try { await page.waitForEventsAfterAction( diff --git a/src/tools/script.ts b/src/tools/script.ts index 0cb6d75564..0a43c863bb 100644 --- a/src/tools/script.ts +++ b/src/tools/script.ts @@ -197,6 +197,8 @@ Example with arguments: \`(el) => el.innerText\` const evaluatable = await getPageOrFrame(page, frames); + // ToolHandler hands over the page of page-scoped tools only. + response.includeConsoleErrorsFrom(mcpPage); const result = await mcpPage.waitForEventsAfterAction( async () => { await performEvaluation( diff --git a/tests/McpResponse.test.ts b/tests/McpResponse.test.ts index dc09ae2cc8..cba0a2d851 100644 --- a/tests/McpResponse.test.ts +++ b/tests/McpResponse.test.ts @@ -71,6 +71,7 @@ import { html, stabilizeResponseOutput, stabilizeStructuredContent, + waitExecutionFor, withMcpContext, } from './utils.js'; @@ -676,6 +677,148 @@ describe('McpResponse', () => { }); }); + describe('console errors of a handed over page', () => { + const heading = '## Console errors during this call'; + + async function logOnPage( + context: McpContext, + log: () => void, + expected = 1, + ): Promise { + const mcpPage = context.getSelectedMcpPage(); + const count = mcpPage.getConsoleData().length; + await mcpPage.pptrPage.evaluate(log); + await waitExecutionFor(async () => { + assert.ok(mcpPage.getConsoleData().length >= count + expected); + }, 5000); + } + + it('lists the errors raised after the hand-over', async () => { + await withMcpContext(async (response, context) => { + await logOnPage(context, () => { + console.error('logged before'); + }); + response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); + await logOnPage(context, () => { + console.warn('warned after'); + console.error('logged after'); + }); + const {content} = await response.handle(context); + const text = getTextContent(content[0]); + assert.ok(text.includes(heading)); + assert.ok(text.includes('logged after')); + assert.ok(!text.includes('logged before')); + assert.ok(!text.includes('warned after')); + }); + }); + + it('lists the first errors and points to the rest', async () => { + await withMcpContext(async (response, context) => { + response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); + await logOnPage( + context, + () => { + for (let i = 0; i < 12; i++) { + console.error(`error ${String(i).padStart(2, '0')}`); + } + }, + 12, + ); + const {content} = await response.handle(context); + const text = getTextContent(content[0]); + assert.ok(text.includes('error 09')); + assert.ok(!text.includes('error 10')); + assert.ok(text.includes('2 more not shown.')); + }); + }); + + it('leaves the section out when there are none', async () => { + await withMcpContext(async (response, context) => { + await logOnPage(context, () => { + console.error('logged before'); + }); + response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); + const {content} = await response.handle(context); + assert.ok(!getTextContent(content[0]).includes(heading)); + }); + }); + + it('keeps the listing of a tool that lists console messages', async () => { + await withMcpContext(async (response, context) => { + response.setIncludeConsoleData(true); + response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); + await logOnPage(context, () => { + console.error('logged after'); + }); + const {content} = await response.handle(context); + const text = getTextContent(content[0]); + assert.strictEqual(text.split('logged after').length, 2); + assert.ok(text.includes('## Console messages')); + assert.ok(!text.includes(heading)); + }); + }); + + it('leaves the errors out next to a single attached message', async () => { + await withMcpContext(async (response, context) => { + const mcpPage = context.getSelectedMcpPage(); + await logOnPage(context, () => { + console.error('logged before'); + }); + response.attachConsoleMessage(mcpPage.getLatestConsoleMessageId()); + response.includeConsoleErrorsFrom(mcpPage); + await logOnPage(context, () => { + console.error('logged after'); + }); + const {content} = await response.handle(context); + const text = getTextContent(content[0]); + assert.ok(text.includes('logged before')); + assert.ok(!text.includes('logged after')); + }); + }); + + it('keeps the pagination of the list the tool asked for', async () => { + await withMcpContext(async (response, context) => { + const mcpPage = context.getSelectedMcpPage(); + mcpPage.getNetworkRequests = () => { + return [getMockRequest({stableId: 1}), getMockRequest({stableId: 2})]; + }; + response.setIncludeNetworkRequests(true, {pageSize: 1}); + response.includeConsoleErrorsFrom(mcpPage); + await logOnPage(context, () => { + console.error('logged after'); + }); + const {content, structuredContent} = await response.handle(context); + assert.ok(getTextContent(content[0]).includes('logged after')); + assert.ok('consoleErrors' in structuredContent); + assert.ok(Array.isArray(structuredContent.consoleErrors)); + assert.strictEqual(structuredContent.consoleErrors.length, 1); + assert.ok('pagination' in structuredContent); + assert.deepStrictEqual(structuredContent.pagination, { + currentPage: 0, + totalPages: 2, + hasNextPage: true, + hasPreviousPage: false, + startIndex: 0, + endIndex: 1, + invalidPage: false, + }); + }); + }); + + it('leaves out the errors of a page closed meanwhile', async () => { + await withMcpContext(async (response, context) => { + const page = await context.newPage(); + response.includeConsoleErrorsFrom(page); + await logOnPage(context, () => { + console.error('logged before closing'); + }); + await context.closePage(page.id); + const {content} = await response.handle(context); + assert.ok(!getTextContent(content[0]).includes(heading)); + }); + }); + }); + it("doesn't list the issue message if mapping returns null", async t => { await withMcpContext(async (response, context) => { const mockAggregatedIssue = getMockAggregatedIssue(); diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.ts index add8f1de1d..7c14bd55d3 100644 --- a/tests/ToolHandler.test.ts +++ b/tests/ToolHandler.test.ts @@ -274,6 +274,7 @@ describe('ToolHandler', () => { .stub(McpResponse.prototype, 'handle') .resolves({content: [], structuredContent: {}}); const mockContext = createContext(); + mockContext.getPageById.returns(createMockMcpPage()); const events: string[] = []; const {promise: release, resolve: finishBlocking} = Promise.withResolvers(); @@ -1969,6 +1970,7 @@ describe('ToolHandler', () => { mockContext.getDevToolsData.resolves({}); const mockPage = sinon.createStubInstance(McpPage); mockPage.getDialog.returns(undefined); + mockPage.getConsoleDataAfter.returns([]); sinon.stub(mockPage, 'networkConditions').get(() => undefined); sinon.stub(mockPage, 'geolocation').get(() => undefined); sinon.stub(mockPage, 'viewport').get(() => undefined); @@ -2192,6 +2194,54 @@ describe('ToolHandler', () => { assert.deepStrictEqual(focusStates, [false, true]); }); + const handOverCases: Array<{ + concurrency: DefinedPageTool['concurrency']; + handedOver: boolean; + }> = [ + {concurrency: 'exclusive', handedOver: true}, + {concurrency: 'none', handedOver: false}, + ]; + for (const {concurrency, handedOver} of handOverCases) { + it(`${handedOver ? 'hands' : 'does not hand'} the page of a page tool with concurrency '${concurrency}' to the response`, async () => { + sinon + .stub(McpResponse.prototype, 'handle') + .resolves({content: [], structuredContent: {}}); + const includeConsoleErrorsFrom = sinon.spy( + McpResponse.prototype, + 'includeConsoleErrorsFrom', + ); + const config = parseConfig(); + const mockContext = createMockMcpContext(); + mockContext.ensureBrowser.resolves( + getMockBrowser({process: sinon.createStubInstance(ChildProcess)}), + ); + const mockPage = createMockMcpPage(); + mockContext.getPageById.returns(mockPage); + const tool = definePageTool(() => ({ + name: 'page_tool', + description: 'A page scoped tool', + annotations: {category: ToolCategory.INPUT, readOnlyHint: false}, + schema: {}, + blockedByDialog: false, + concurrency, + verifyFilesSchema: {}, + handler: async () => {}, + }))(config.resolved); + + await new ToolHandler( + tool, + config, + async () => mockContext, + sinon.spy(), + ).handle({pageId: 1}); + + assert.deepStrictEqual( + includeConsoleErrorsFrom.args, + handedOver ? [[mockPage]] : [], + ); + }); + } + describe('browserless tools', () => { function createBrowserlessTool( handler: BrowserlessToolDefinition['handler'], diff --git a/tests/mocks.ts b/tests/mocks.ts index 1bf96c12e8..08696e326a 100644 --- a/tests/mocks.ts +++ b/tests/mocks.ts @@ -472,6 +472,8 @@ export function createMockMcpPage( return {}; }); page.getWebMcpTools.returns([]); + page.getLatestConsoleMessageId.returns(0); + page.getConsoleDataAfter.returns([]); page.discoverThirdPartyDeveloperTools.resolves([]); page.getWebAuthnAuthenticator.returns(undefined); Object.defineProperty(page, 'pptrPage', { diff --git a/tests/tools/pages.test.ts b/tests/tools/pages.test.ts index 8ba2b98e61..f2dd1c324f 100644 --- a/tests/tools/pages.test.ts +++ b/tests/tools/pages.test.ts @@ -28,7 +28,12 @@ import { createMockMcpPage, createMockParsedArguments, } from '../mocks.js'; -import {assertNoServiceWorkerReported, html, withMcpContext} from '../utils.js'; +import { + assertNoServiceWorkerReported, + getTextContent, + html, + withMcpContext, +} from '../utils.js'; const EXTENSION_SW_PATH = path.join( import.meta.dirname, @@ -254,6 +259,14 @@ describe('pages', () => { sinon.assert.calledOnceWithExactly( response.setListThirdPartyDeveloperTools, ); + sinon.assert.calledOnceWithExactly( + response.includeConsoleErrorsFrom, + page, + ); + sinon.assert.callOrder( + response.includeConsoleErrorsFrom, + page.pptrPage.goto, + ); }); it('closes the new tab and restores the selection when navigation fails', async () => { const { @@ -346,6 +359,22 @@ describe('pages', () => { assert.ok(response.includePages); }); }); + it('lists the errors the page raises while it loads', async () => { + await withMcpContext(async (response, context, args) => { + await newPage(args).handler( + { + params: { + url: 'data:text/html,', + }, + }, + response, + context, + ); + const {content} = await response.handle(context); + // The page list shows the URL, so match the message line. + assert.ok(getTextContent(content[0]).includes('[error] on load')); + }); + }); it('throws when navigating to a javascript URL and javascriptEvaluation is false', async () => { const {context, response, args} = createHandlerMocks({ javascriptEvaluation: false, diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.ts index ab0694f7da..d03d6cd199 100644 --- a/tests/tools/script.test.ts +++ b/tests/tools/script.test.ts @@ -24,7 +24,9 @@ import { assertNoServiceWorkerReported, createTempDir, extractExtensionId, + getTextContent, html, + waitExecutionFor, withMcpContext, } from '../utils.js'; @@ -172,6 +174,136 @@ describe('script', () => { ); }); }); + it('lists errors the page raised while the function ran', async () => { + await withMcpContext(async (response, context, args) => { + await evaluateScript(args).handler( + { + params: { + function: String( + () => + new Promise(resolve => { + console.warn('warned in the function'); + setTimeout(() => { + throw new Error('thrown in a timer'); + }, 0); + setTimeout(() => resolve('done'), 50); + }), + ), + }, + }, + response, + context, + ); + const {content} = await response.handle(context); + const text = getTextContent(content[0]); + assert.ok(text.includes('"done"')); + assert.ok(text.includes('## Console errors during this call')); + assert.ok(text.includes('thrown in a timer')); + assert.ok(!text.includes('warned in the function')); + }); + }); + it('lists errors raised before the function threw', async () => { + await withMcpContext(async (response, context, args) => { + await assert.rejects( + evaluateScript(args).handler( + { + params: { + function: String(async () => { + setTimeout(() => { + throw new Error('thrown in a timer'); + }, 0); + await new Promise(resolve => setTimeout(resolve, 50)); + throw new Error('thrown by the function'); + }), + }, + }, + response, + context, + ), + ); + const {content} = await response.handle(context); + assert.ok(getTextContent(content[0]).includes('thrown in a timer')); + }); + }); + it('keeps errors raised before the function reloads the page', async () => { + server.addHtmlRoute('/reload', html`
Reloads
`); + await withMcpContext(async (response, context, args) => { + const page = context.getSelectedMcpPage().pptrPage; + await page.goto(server.getRoute('/reload')); + await evaluateScript(args) + .handler( + { + params: { + function: String( + () => + new Promise(resolve => { + setTimeout(() => { + throw new Error('thrown before the reload'); + }, 0); + setTimeout(() => { + location.reload(); + resolve('reloading'); + }, 50); + }), + ), + }, + }, + response, + context, + ) + .catch(() => {}); + const {content} = await response.handle(context); + assert.ok( + getTextContent(content[0]).includes('thrown before the reload'), + ); + }); + }); + it('leaves out errors from before the function ran, on earlier pages too', async () => { + server.addHtmlRoute( + '/logs', + html``, + ); + server.addHtmlRoute('/quiet', html`
Quiet
`); + await withMcpContext(async (response, context, args) => { + const mcpPage = context.getSelectedMcpPage(); + await mcpPage.pptrPage.goto(server.getRoute('/logs')); + await waitExecutionFor(async () => { + assert.ok(mcpPage.getConsoleData().length); + }, 5000); + await mcpPage.pptrPage.goto(server.getRoute('/quiet')); + await evaluateScript(args).handler( + {params: {function: String(() => 1)}}, + response, + context, + ); + const {content} = await response.handle(context); + assert.ok( + !getTextContent(content[0]).includes( + '## Console errors during this call', + ), + ); + }); + }); + it('hands its page to the response before the function runs', async () => { + const {page, response, context, args} = createHandlerMocks(); + page.waitForEventsAfterAction.callsFake(async () => { + sinon.assert.calledOnceWithExactly( + response.includeConsoleErrorsFrom, + page, + ); + return {}; + }); + + await evaluateScript(args).handler( + {params: {function: String(() => 1)}}, + response, + context, + ); + + sinon.assert.calledOnce(page.waitForEventsAfterAction); + }); it('loads function source from a local file', async () => { const {page, response, context, args} = createHandlerMocks(); const sourcePath = path.join(os.tmpdir(), 'function.js'); From a9119d9d93d2ae4010a9a3f4356f780700671256 Mon Sep 17 00:00:00 2001 From: Thomas Bachem Date: Thu, 12 Nov 2026 16:16:50 +0100 Subject: [PATCH 2/2] refactor: address review of the console errors listing Keeps getLatestConsoleMessageId() and getConsoleDataAfter() off ContextPage, formats the errors with their page's DevTools universe and moves the tests to mocks. --- src/McpResponse.ts | 7 +- src/tools/ToolDefinition.ts | 2 - tests/McpPage.test.ts | 49 ++++++ tests/McpResponse.test.ts | 307 ++++++++++++++++++++++-------------- tests/ToolHandler.test.ts | 89 +++++------ tests/tools/script.test.ts | 85 ---------- 6 files changed, 289 insertions(+), 250 deletions(-) diff --git a/src/McpResponse.ts b/src/McpResponse.ts index 30f1057404..940873c740 100644 --- a/src/McpResponse.ts +++ b/src/McpResponse.ts @@ -59,7 +59,6 @@ import { import {handleDialog, listPages} from './tools/pages.js'; import type {ToolGroups} from './tools/thirdPartyDeveloper.js'; import type { - ContextPage, DevToolsData, ImageContentData, LighthouseData, @@ -161,7 +160,7 @@ export class McpResponse implements Response { #page?: McpPage; #error?: Error; #attachedWaitForResult?: WaitForEventsResult; - #consoleErrorsFrom?: {page: ContextPage; lastMessageId: number}; + #consoleErrorsFrom?: {page: McpPage; lastMessageId: number}; #reconnectNotice = false; #devToolsComments?: CD4ACommentThread[]; #webAuthnFormatter?: WebAuthnFormatter; @@ -283,7 +282,7 @@ export class McpResponse implements Response { }; } - includeConsoleErrorsFrom(page: ContextPage): void { + includeConsoleErrorsFrom(page: McpPage): void { this.#consoleErrorsFrom = { page, lastMessageId: page.getLatestConsoleMessageId(), @@ -706,7 +705,7 @@ export class McpResponse implements Response { } return await this.#formatConsoleData( errorsFrom.page.getConsoleDataAfter(errorsFrom.lastMessageId), - this.#page, + errorsFrom.page, {types: ['error']}, ); } diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.ts index 81d24c982d..3ef0b26e36 100644 --- a/src/tools/ToolDefinition.ts +++ b/src/tools/ToolDefinition.ts @@ -537,8 +537,6 @@ export type ContextPage = Readonly<{ setScreenRecorder(data: ScreenRecorderData | null): void; isRunningPerformanceTrace(): boolean; setIsRunningPerformanceTrace(x: boolean): void; - getLatestConsoleMessageId(): number; - getConsoleDataAfter(id: number): ReturnType; waitForEventsAfterAction( action: (signal: AbortSignal) => Promise, options?: { diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.ts index fdac2a2858..83294724b8 100644 --- a/tests/McpPage.test.ts +++ b/tests/McpPage.test.ts @@ -575,6 +575,55 @@ describe('McpPage', () => { }); }); + describe('getLatestConsoleMessageId() and getConsoleDataAfter()', () => { + function createUncaughtError(exceptionId: number): UncaughtError { + return new UncaughtError( + { + exceptionId, + text: `error-${exceptionId}`, + lineNumber: 0, + columnNumber: 0, + }, + '', + ); + } + + it('getLatestConsoleMessageId() returns 0 and getConsoleDataAfter() nothing for an empty collector', async () => { + const {mcpPage} = await createMcpPage(); + + assert.strictEqual(mcpPage.getLatestConsoleMessageId(), 0); + assert.deepStrictEqual(mcpPage.getConsoleDataAfter(0), []); + }); + + it('getLatestConsoleMessageId() includes messages from an earlier navigation', async () => { + const {mcpPage, pptrPage} = await createMcpPage(); + const error = createUncaughtError(1); + pptrPage.emit('uncaughtError', error); + pptrPage.emit('framenavigated', pptrPage.mainFrame()); + + const id = mcpPage.getLatestConsoleMessageId(); + + assert.strictEqual(id, mcpPage.consoleCollector.getIdForResource(error)); + assert.deepStrictEqual(mcpPage.getConsoleDataAfter(id), []); + }); + + it('getConsoleDataAfter() returns the messages after the id, from an earlier navigation too', async () => { + const {mcpPage, pptrPage} = await createMcpPage(); + pptrPage.emit('uncaughtError', createUncaughtError(1)); + const id = mcpPage.getLatestConsoleMessageId(); + const beforeNavigation = createUncaughtError(2); + pptrPage.emit('uncaughtError', beforeNavigation); + pptrPage.emit('framenavigated', pptrPage.mainFrame()); + const afterNavigation = createUncaughtError(3); + pptrPage.emit('uncaughtError', afterNavigation); + + assert.deepStrictEqual(mcpPage.getConsoleDataAfter(id), [ + beforeNavigation, + afterNavigation, + ]); + }); + }); + describe('getTitle()', () => { function createPage(url: string, title: string): McpPage { const target = createMockPuppeteerTarget({url, title}); diff --git a/tests/McpResponse.test.ts b/tests/McpResponse.test.ts index cba0a2d851..11b446f377 100644 --- a/tests/McpResponse.test.ts +++ b/tests/McpResponse.test.ts @@ -12,6 +12,8 @@ import {after, describe, it} from 'node:test'; import sinon from 'sinon'; import type {ParsedArguments} from '../src/config/mcp-options.js'; +import type {TargetUniverse} from '../src/devtools/DevtoolsUtils.js'; +import {ConsoleFormatter} from '../src/formatters/ConsoleFormatter.js'; import type {McpContext} from '../src/McpContext.js'; import {McpResponse} from '../src/McpResponse.js'; import {TextSnapshot} from '../src/TextSnapshot.js'; @@ -37,6 +39,7 @@ import { createHandlerMocks, createMockConsoleMessage, createMockHeapSnapshotAggregate, + createMockCDPSession, createMockCSSMatchedStyles, createMockCSSProperty, createMockCSSStyleDeclaration, @@ -71,7 +74,6 @@ import { html, stabilizeResponseOutput, stabilizeStructuredContent, - waitExecutionFor, withMcpContext, } from './utils.js'; @@ -680,142 +682,217 @@ describe('McpResponse', () => { describe('console errors of a handed over page', () => { const heading = '## Console errors during this call'; - async function logOnPage( - context: McpContext, - log: () => void, - expected = 1, - ): Promise { - const mcpPage = context.getSelectedMcpPage(); - const count = mcpPage.getConsoleData().length; - await mcpPage.pptrPage.evaluate(log); - await waitExecutionFor(async () => { - assert.ok(mcpPage.getConsoleData().length >= count + expected); - }, 5000); + function createHandedOverPage( + messages: Array>, + universe?: TargetUniverse, + ) { + const page = createMockMcpPage(); + page.getConsoleDataAfter.returns(messages); + sinon.stub(page, 'devtoolsUniverse').get(() => universe); + return { + page, + context: createMockMcpContext({selectedPage: page}), + response: new McpResponse(createMockServerConfig()), + }; } - it('lists the errors raised after the hand-over', async () => { - await withMcpContext(async (response, context) => { - await logOnPage(context, () => { - console.error('logged before'); - }); - response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); - await logOnPage(context, () => { - console.warn('warned after'); - console.error('logged after'); - }); - const {content} = await response.handle(context); - const text = getTextContent(content[0]); - assert.ok(text.includes(heading)); - assert.ok(text.includes('logged after')); - assert.ok(!text.includes('logged before')); - assert.ok(!text.includes('warned after')); - }); + function createErrors(...texts: string[]) { + return texts.map(text => createMockConsoleMessage({type: 'error', text})); + } + + it('lists the errors after the message id read at the hand-over', async () => { + const {page, context, response} = createHandedOverPage([ + createMockConsoleMessage({type: 'warn', text: 'warned after'}), + ...createErrors('logged after'), + ]); + page.getLatestConsoleMessageId.returns(7); + response.includeConsoleErrorsFrom(page); + page.getLatestConsoleMessageId.returns(9); + + const {content} = await response.handle(context); + + sinon.assert.calledOnceWithExactly(page.getConsoleDataAfter, 7); + const text = getTextContent(content[0]); + assert.ok(text.includes(heading)); + assert.ok(text.includes('logged after')); + assert.ok(!text.includes('warned after')); }); it('lists the first errors and points to the rest', async () => { - await withMcpContext(async (response, context) => { - response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); - await logOnPage( - context, - () => { - for (let i = 0; i < 12; i++) { - console.error(`error ${String(i).padStart(2, '0')}`); - } - }, - 12, - ); - const {content} = await response.handle(context); - const text = getTextContent(content[0]); - assert.ok(text.includes('error 09')); - assert.ok(!text.includes('error 10')); - assert.ok(text.includes('2 more not shown.')); - }); + const {page, context, response} = createHandedOverPage( + createErrors( + ...Array.from( + {length: 12}, + (_, i) => `error ${String(i).padStart(2, '0')}`, + ), + ), + ); + response.includeConsoleErrorsFrom(page); + + const {content} = await response.handle(context); + + const text = getTextContent(content[0]); + assert.ok(text.includes('error 09')); + assert.ok(!text.includes('error 10')); + assert.ok(text.includes('2 more not shown.')); + }); + + it('lists ten errors without a pointer to the rest', async () => { + const {page, context, response} = createHandedOverPage( + createErrors(...Array.from({length: 10}, (_, i) => `error ${i}`)), + ); + response.includeConsoleErrorsFrom(page); + + const {content} = await response.handle(context); + + const text = getTextContent(content[0]); + assert.ok(text.includes('error 9')); + assert.ok(!text.includes('more not shown')); + }); + + it('counts a repeated error once toward the cap', async () => { + const {page, context, response} = createHandedOverPage( + createErrors(...Array.from({length: 12}, () => 'thrown in a loop')), + ); + response.includeConsoleErrorsFrom(page); + + const {content, structuredContent} = await response.handle(context); + + assert.ok('consoleErrors' in structuredContent); + assert.ok(Array.isArray(structuredContent.consoleErrors)); + assert.strictEqual(structuredContent.consoleErrors.length, 1); + assert.ok(!getTextContent(content[0]).includes('more not shown')); }); it('leaves the section out when there are none', async () => { - await withMcpContext(async (response, context) => { - await logOnPage(context, () => { - console.error('logged before'); - }); - response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); - const {content} = await response.handle(context); - assert.ok(!getTextContent(content[0]).includes(heading)); + const {page, context, response} = createHandedOverPage([]); + response.includeConsoleErrorsFrom(page); + + const {content} = await response.handle(context); + + assert.ok(!getTextContent(content[0]).includes(heading)); + }); + + it('lists the errors next to the error of a tool that threw', async () => { + const {page, context, response} = createHandedOverPage( + createErrors('thrown in a timer'), + ); + response.includeConsoleErrorsFrom(page); + response.setError(new Error('thrown by the function')); + + const {content} = await response.handle(context); + + const text = getTextContent(content[0]); + assert.ok(text.includes('thrown by the function')); + assert.ok(text.includes(heading)); + assert.ok(text.includes('thrown in a timer')); + }); + + it('formats the errors with the DevTools universe of the handed over page', async () => { + const universe: TargetUniverse = { + universe: sinon.createStubInstance( + DevTools.Foundation.Universe.Universe, + ), + target: sinon.createStubInstance(DevTools.Target), + session: createMockCDPSession(), + }; + const [message] = createErrors('logged after'); + const {page, context, response} = createHandedOverPage( + [message], + universe, + ); + const formatter = await ConsoleFormatter.from(message, { + id: -1, + fetchDetailedData: false, + }); + const from = sinon.stub(ConsoleFormatter, 'from').resolves(formatter); + response.includeConsoleErrorsFrom(page); + + await response.handle(context); + + sinon.assert.calledOnceWithExactly(from, message, { + id: -1, + fetchDetailedData: false, + fetchStackTrace: undefined, + devTools: universe, }); }); it('keeps the listing of a tool that lists console messages', async () => { - await withMcpContext(async (response, context) => { - response.setIncludeConsoleData(true); - response.includeConsoleErrorsFrom(context.getSelectedMcpPage()); - await logOnPage(context, () => { - console.error('logged after'); - }); - const {content} = await response.handle(context); - const text = getTextContent(content[0]); - assert.strictEqual(text.split('logged after').length, 2); - assert.ok(text.includes('## Console messages')); - assert.ok(!text.includes(heading)); - }); + const messages = createErrors('logged after'); + const {page, context, response} = createHandedOverPage(messages); + page.getConsoleData.returns(messages); + response.setPage(page); + response.setIncludeConsoleData(true); + response.includeConsoleErrorsFrom(page); + + const {content} = await response.handle(context); + + sinon.assert.notCalled(page.getConsoleDataAfter); + const text = getTextContent(content[0]); + assert.ok(text.includes('## Console messages')); + assert.ok(!text.includes(heading)); }); it('leaves the errors out next to a single attached message', async () => { - await withMcpContext(async (response, context) => { - const mcpPage = context.getSelectedMcpPage(); - await logOnPage(context, () => { - console.error('logged before'); - }); - response.attachConsoleMessage(mcpPage.getLatestConsoleMessageId()); - response.includeConsoleErrorsFrom(mcpPage); - await logOnPage(context, () => { - console.error('logged after'); - }); - const {content} = await response.handle(context); - const text = getTextContent(content[0]); - assert.ok(text.includes('logged before')); - assert.ok(!text.includes('logged after')); - }); + const {page, context, response} = createHandedOverPage( + createErrors('logged after'), + ); + const [attached] = createErrors('logged before'); + page.getConsoleMessageById.returns(attached); + response.setPage(page); + response.attachConsoleMessage(1); + response.includeConsoleErrorsFrom(page); + + const {content} = await response.handle(context); + + sinon.assert.notCalled(page.getConsoleDataAfter); + const text = getTextContent(content[0]); + assert.ok(text.includes('logged before')); + assert.ok(!text.includes(heading)); }); it('keeps the pagination of the list the tool asked for', async () => { - await withMcpContext(async (response, context) => { - const mcpPage = context.getSelectedMcpPage(); - mcpPage.getNetworkRequests = () => { - return [getMockRequest({stableId: 1}), getMockRequest({stableId: 2})]; - }; - response.setIncludeNetworkRequests(true, {pageSize: 1}); - response.includeConsoleErrorsFrom(mcpPage); - await logOnPage(context, () => { - console.error('logged after'); - }); - const {content, structuredContent} = await response.handle(context); - assert.ok(getTextContent(content[0]).includes('logged after')); - assert.ok('consoleErrors' in structuredContent); - assert.ok(Array.isArray(structuredContent.consoleErrors)); - assert.strictEqual(structuredContent.consoleErrors.length, 1); - assert.ok('pagination' in structuredContent); - assert.deepStrictEqual(structuredContent.pagination, { - currentPage: 0, - totalPages: 2, - hasNextPage: true, - hasPreviousPage: false, - startIndex: 0, - endIndex: 1, - invalidPage: false, - }); + const {page, context, response} = createHandedOverPage( + createErrors('logged after'), + ); + page.getNetworkRequests.returns([ + getMockRequest({stableId: 1}), + getMockRequest({stableId: 2}), + ]); + response.setPage(page); + response.setIncludeNetworkRequests(true, {pageSize: 1}); + response.includeConsoleErrorsFrom(page); + + const {content, structuredContent} = await response.handle(context); + + assert.ok(getTextContent(content[0]).includes('logged after')); + assert.ok('consoleErrors' in structuredContent); + assert.ok(Array.isArray(structuredContent.consoleErrors)); + assert.strictEqual(structuredContent.consoleErrors.length, 1); + assert.ok('pagination' in structuredContent); + assert.deepStrictEqual(structuredContent.pagination, { + currentPage: 0, + totalPages: 2, + hasNextPage: true, + hasPreviousPage: false, + startIndex: 0, + endIndex: 1, + invalidPage: false, }); }); it('leaves out the errors of a page closed meanwhile', async () => { - await withMcpContext(async (response, context) => { - const page = await context.newPage(); - response.includeConsoleErrorsFrom(page); - await logOnPage(context, () => { - console.error('logged before closing'); - }); - await context.closePage(page.id); - const {content} = await response.handle(context); - assert.ok(!getTextContent(content[0]).includes(heading)); - }); + const {page, context, response} = createHandedOverPage( + createErrors('logged before closing'), + ); + response.includeConsoleErrorsFrom(page); + page.isClosed.callsFake(() => true); + + const {content} = await response.handle(context); + + sinon.assert.notCalled(page.getConsoleDataAfter); + assert.ok(!getTextContent(content[0]).includes(heading)); }); }); diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.ts index 7c14bd55d3..4c78970afa 100644 --- a/tests/ToolHandler.test.ts +++ b/tests/ToolHandler.test.ts @@ -2194,54 +2194,55 @@ describe('ToolHandler', () => { assert.deepStrictEqual(focusStates, [false, true]); }); - const handOverCases: Array<{ - concurrency: DefinedPageTool['concurrency']; - handedOver: boolean; - }> = [ - {concurrency: 'exclusive', handedOver: true}, - {concurrency: 'none', handedOver: false}, - ]; - for (const {concurrency, handedOver} of handOverCases) { - it(`${handedOver ? 'hands' : 'does not hand'} the page of a page tool with concurrency '${concurrency}' to the response`, async () => { - sinon - .stub(McpResponse.prototype, 'handle') - .resolves({content: [], structuredContent: {}}); - const includeConsoleErrorsFrom = sinon.spy( - McpResponse.prototype, - 'includeConsoleErrorsFrom', - ); - const config = parseConfig(); - const mockContext = createMockMcpContext(); - mockContext.ensureBrowser.resolves( - getMockBrowser({process: sinon.createStubInstance(ChildProcess)}), - ); - const mockPage = createMockMcpPage(); - mockContext.getPageById.returns(mockPage); - const tool = definePageTool(() => ({ - name: 'page_tool', - description: 'A page scoped tool', - annotations: {category: ToolCategory.INPUT, readOnlyHint: false}, - schema: {}, - blockedByDialog: false, - concurrency, - verifyFilesSchema: {}, - handler: async () => {}, - }))(config.resolved); + async function handlePageToolCall( + concurrency: DefinedPageTool['concurrency'], + ) { + sinon + .stub(McpResponse.prototype, 'handle') + .resolves({content: [], structuredContent: {}}); + const includeConsoleErrorsFrom = sinon.spy( + McpResponse.prototype, + 'includeConsoleErrorsFrom', + ); + const config = parseConfig(); + const mockContext = createMockMcpContext(); + mockContext.ensureBrowser.resolves( + getMockBrowser({process: sinon.createStubInstance(ChildProcess)}), + ); + const mockPage = createMockMcpPage(); + mockContext.getPageById.returns(mockPage); + const tool = definePageTool(() => ({ + name: 'page_tool', + description: 'A page scoped tool', + annotations: {category: ToolCategory.INPUT, readOnlyHint: false}, + schema: {}, + blockedByDialog: false, + concurrency, + verifyFilesSchema: {}, + handler: async () => {}, + }))(config.resolved); - await new ToolHandler( - tool, - config, - async () => mockContext, - sinon.spy(), - ).handle({pageId: 1}); + await new ToolHandler( + tool, + config, + async () => mockContext, + sinon.spy(), + ).handle({pageId: 1}); - assert.deepStrictEqual( - includeConsoleErrorsFrom.args, - handedOver ? [[mockPage]] : [], - ); - }); + return {includeConsoleErrorsFrom, mockPage}; } + it("hands the page of a page tool with concurrency 'exclusive' to the response", async () => { + const {includeConsoleErrorsFrom, mockPage} = + await handlePageToolCall('exclusive'); + sinon.assert.calledOnceWithExactly(includeConsoleErrorsFrom, mockPage); + }); + + it("does not hand the page of a page tool with concurrency 'none' to the response", async () => { + const {includeConsoleErrorsFrom} = await handlePageToolCall('none'); + sinon.assert.notCalled(includeConsoleErrorsFrom); + }); + describe('browserless tools', () => { function createBrowserlessTool( handler: BrowserlessToolDefinition['handler'], diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.ts index d03d6cd199..0cd572d429 100644 --- a/tests/tools/script.test.ts +++ b/tests/tools/script.test.ts @@ -26,7 +26,6 @@ import { extractExtensionId, getTextContent, html, - waitExecutionFor, withMcpContext, } from '../utils.js'; @@ -202,90 +201,6 @@ describe('script', () => { assert.ok(!text.includes('warned in the function')); }); }); - it('lists errors raised before the function threw', async () => { - await withMcpContext(async (response, context, args) => { - await assert.rejects( - evaluateScript(args).handler( - { - params: { - function: String(async () => { - setTimeout(() => { - throw new Error('thrown in a timer'); - }, 0); - await new Promise(resolve => setTimeout(resolve, 50)); - throw new Error('thrown by the function'); - }), - }, - }, - response, - context, - ), - ); - const {content} = await response.handle(context); - assert.ok(getTextContent(content[0]).includes('thrown in a timer')); - }); - }); - it('keeps errors raised before the function reloads the page', async () => { - server.addHtmlRoute('/reload', html`
Reloads
`); - await withMcpContext(async (response, context, args) => { - const page = context.getSelectedMcpPage().pptrPage; - await page.goto(server.getRoute('/reload')); - await evaluateScript(args) - .handler( - { - params: { - function: String( - () => - new Promise(resolve => { - setTimeout(() => { - throw new Error('thrown before the reload'); - }, 0); - setTimeout(() => { - location.reload(); - resolve('reloading'); - }, 50); - }), - ), - }, - }, - response, - context, - ) - .catch(() => {}); - const {content} = await response.handle(context); - assert.ok( - getTextContent(content[0]).includes('thrown before the reload'), - ); - }); - }); - it('leaves out errors from before the function ran, on earlier pages too', async () => { - server.addHtmlRoute( - '/logs', - html``, - ); - server.addHtmlRoute('/quiet', html`
Quiet
`); - await withMcpContext(async (response, context, args) => { - const mcpPage = context.getSelectedMcpPage(); - await mcpPage.pptrPage.goto(server.getRoute('/logs')); - await waitExecutionFor(async () => { - assert.ok(mcpPage.getConsoleData().length); - }, 5000); - await mcpPage.pptrPage.goto(server.getRoute('/quiet')); - await evaluateScript(args).handler( - {params: {function: String(() => 1)}}, - response, - context, - ); - const {content} = await response.handle(context); - assert.ok( - !getTextContent(content[0]).includes( - '## Console errors during this call', - ), - ); - }); - }); it('hands its page to the response before the function runs', async () => { const {page, response, context, args} = createHandlerMocks(); page.waitForEventsAfterAction.callsFake(async () => {