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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/bin/chrome-devtools-mcp-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import '../polyfill.js';
import '../puppeteer-patches.js';

import process from 'node:process';

Expand Down
97 changes: 97 additions & 0 deletions src/puppeteer-patches.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

import './third_party/index.js';

import {
InternalConnection as Connection,
type InternalCallbackRegistry as CallbackRegistry,
} from './third_party/index.js';

// 1. Map active command IDs directly to their sessionId
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it a reason for the lighthouse timeouts? sounds like it would be easier to fix in Puppeter?

const idToSessionIdMap = new Map<number, string>();

// 2. Intercept _rawSend to map request IDs to their sessionIds
const originalRawSend = Connection.prototype._rawSend;
Connection.prototype._rawSend = function (
this: Connection,
...args: Parameters<typeof Connection.prototype._rawSend>
) {
const [callbacks, method, params, sessionId, options] = args;

const wrappedCallbacks = Object.create(callbacks) as CallbackRegistry;
wrappedCallbacks.create = function (
label: string,
timeout: number | undefined,
request: (id: number) => void,
) {
const wrappedRequest = (id: number) => {
if (sessionId) {
idToSessionIdMap.set(id, sessionId);
}
return request(id);
};
return callbacks.create(label, timeout, wrappedRequest);
};

return originalRawSend.call(
this,
wrappedCallbacks,
method,
params,
sessionId,
options,
);
};

// 3. Repair missing sessionId in Chrome error responses
const onMessageDescriptor = Object.getOwnPropertyDescriptor(
Connection.prototype,
'onMessage',
);

if (onMessageDescriptor && typeof onMessageDescriptor.value === 'function') {
const originalOnMessage = onMessageDescriptor.value;
const patchedOnMessage = async function (this: Connection, message: string) {
try {
const object = JSON.parse(message);
if (object.id) {
let modified = false;
const sessionId = idToSessionIdMap.get(object.id);
if (sessionId) {
if (!object.sessionId) {
object.sessionId = sessionId;
modified = true;
}
idToSessionIdMap.delete(object.id);
}
// Clear "session not found" errors coming from dead sessions to prevent uncaught exceptions
if (
object.error &&
(object.error.code === -32001 ||
object.error.message?.includes('Session with given id not found.'))
) {
delete object.error;
object.result = {};
modified = true;
}
if (modified) {
message = JSON.stringify(object);
}
}
} catch {
// Suppress JSON parsing errors to let the original handler deal with them
}
if (typeof originalOnMessage === 'function') {
return originalOnMessage.call(this, message);
}
};

Object.defineProperty(Connection.prototype, 'onMessage', {
...onMessageDescriptor,
value: patchedOnMessage,
});
}
2 changes: 2 additions & 0 deletions src/third_party/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export {
export {default as puppeteer} from 'puppeteer-core';
export type * from 'puppeteer-core';
export {PipeTransport} from 'puppeteer-core/internal/node/PipeTransport.js';
export {Connection as InternalConnection} from 'puppeteer-core/internal/cdp/Connection.js';
export {CallbackRegistry as InternalCallbackRegistry} from 'puppeteer-core/internal/common/CallbackRegistry.js';
export type {CdpPage} from 'puppeteer-core/internal/cdp/Page.js';
export type {JSONSchema7, JSONSchema7Definition} from 'json-schema';
export {
Expand Down
113 changes: 113 additions & 0 deletions tests/puppeteer-patches.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

import assert from 'node:assert';
import {describe, it, afterEach} from 'node:test';

import {CdpCDPSession} from 'puppeteer-core/internal/cdp/CdpSession.js';
import sinon from 'sinon';

import {InternalConnection as Connection} from '../src/third_party/index.js';

describe('puppeteer-patches', () => {
afterEach(() => {
sinon.restore();
});

it('restores missing sessionId in responses', async () => {
const mockTransport: {
send(msg: string): void;
onmessage?: (msg: string) => void;
onclose?: () => void;
close(): void;
} = {
send() {
/* No-op */
},
close() {
/* No-op */
},
};
const transportSendSpy = sinon.spy(mockTransport, 'send');
const connection = new Connection('http://localhost', mockTransport);
const sessionId = 'test-session-id';
const session = new CdpCDPSession(
connection,
'page',
sessionId,
undefined,
false,
);
const onMessageSpy = sinon.spy(session, 'onMessage');
connection._sessions.set(sessionId, session);

// Trigger send through session to establish mapping
const sendPromise = session.send('Browser.getVersion');

// Get the ID from the sent message
sinon.assert.calledOnce(transportSendSpy);
const sentMessage = transportSendSpy.getCall(0).args[0];
const messageId = JSON.parse(sentMessage).id;

// Simulate message without sessionId
await mockTransport.onmessage?.(
JSON.stringify({id: messageId, result: {}}),
);

// Wait for the send to resolve to clean up
await sendPromise;

// Verify that session.onMessage was called because the patch added sessionId
sinon.assert.calledOnce(onMessageSpy);

const receivedMessage = onMessageSpy.getCall(0).args[0];

function hasSessionId(obj: unknown): obj is {sessionId: string} {
return typeof obj === 'object' && obj !== null && 'sessionId' in obj;
}

if (!hasSessionId(receivedMessage)) {
throw new Error('Message missing sessionId');
}
assert.strictEqual(receivedMessage.sessionId, sessionId);
});

it('suppresses session not found errors', async () => {
const mockTransport: {
send(msg: string): void;
onmessage?: (msg: string) => void;
onclose?: () => void;
close(): void;
} = {
send() {
/* No-op */
},
close() {
/* No-op */
},
};
const transportSendSpy = sinon.spy(mockTransport, 'send');
const connection = new Connection('http://localhost', mockTransport);
const promise = connection.send('Browser.getVersion', undefined);

// Get the ID from the sent message
sinon.assert.calledOnce(transportSendSpy);
const sentMessage = transportSendSpy.getCall(0).args[0];
const messageId = JSON.parse(sentMessage).id;

// Simulate receiving the specific error
await mockTransport.onmessage?.(
JSON.stringify({
id: messageId,
error: {code: -32001, message: 'Session with given id not found.'},
}),
);

// Verify that the promise resolved (error was suppressed)
const result = await promise;
assert.deepStrictEqual(result, {});
});
});
1 change: 1 addition & 0 deletions tests/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import '../src/polyfill.js';
import '../src/puppeteer-patches.js';

import path from 'node:path';
import {it} from 'node:test';
Expand Down
Loading