Skip to content
Merged
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
12 changes: 11 additions & 1 deletion src/extension/browserModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class BrowserModel {
private _autoAttach = false;
private _nextSessionId = 1;

constructor(sendToExtension: SendCommand) {
constructor(sendToExtension: SendCommand, private _connectPagePrefix?: string) {
this._sendToExtension = sendToExtension;
}

Expand Down Expand Up @@ -115,6 +115,16 @@ export class BrowserModel {
throw new Error('Failed to create tab');
this._knownTabs.set(tab.id, tab);
const tabSession = await this._attachTab(tab.id);
if (this._connectPagePrefix) {
const connectPagePrefix = this._connectPagePrefix;
await Promise.allSettled([...this._knownTabs]
.filter(([tabId, knownTab]) => tabId !== tab.id && knownTab.url?.startsWith(connectPagePrefix))
.map(async ([tabId]) => {
const result = await this._sendDebuggerCommand({ tabId }, 'Target.getTargetInfo', undefined);
if (result?.targetInfo?.url?.startsWith(connectPagePrefix))
await this._sendToExtension('chrome.tabs.remove', [tabId]);
}));
}
return { targetId: tabSession.targetInfo?.targetId };
}

Expand Down
10 changes: 6 additions & 4 deletions src/extension/cdpRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export class CDPRelayServer {
private _executablePath?: string;
private _cdpPath: string;
private _extensionPath: string;
private _connectPagePrefix: string;
private _wss: WebSocketServer;
private _playwrightConnection: WebSocket | null = null;
private _extensionConnection: ExtensionConnection | null = null;
Expand All @@ -74,6 +75,9 @@ export class CDPRelayServer {
const uuid = crypto.randomUUID();
this._cdpPath = `/cdp/${uuid}`;
this._extensionPath = `/extension/${uuid}`;
const connectPageUrl = new URL(`chrome-extension://${protocol.EXTENSION_ID}/connect.html`);
connectPageUrl.searchParams.set('mcpRelayUrl', this.extensionEndpoint());
this._connectPagePrefix = connectPageUrl.toString();

this._resetExtensionConnection();
this._wss = new WebSocketServer({ server });
Expand Down Expand Up @@ -105,10 +109,8 @@ export class CDPRelayServer {
}

private _connectBrowser(clientInfo: ClientInfo) {
const mcpRelayEndpoint = `${this._wsHost}${this._extensionPath}`;
// Need to specify "key" in the manifest.json to make the id stable when loading from file.
const url = new URL(`chrome-extension://${protocol.EXTENSION_ID}/connect.html`);
url.searchParams.set('mcpRelayUrl', mcpRelayEndpoint);
const url = new URL(this._connectPagePrefix);
const client = {
name: clientInfo.name,
version: clientInfo.version,
Expand Down Expand Up @@ -216,7 +218,7 @@ export class CDPRelayServer {
if (!this._extensionConnection)
throw new Error('Extension not connected');
return this._extensionConnection.send(method as keyof ExtensionCommandV2, params);
});
}, this._connectPagePrefix);
}

private _closePlaywrightConnection(reason: string) {
Expand Down
4 changes: 2 additions & 2 deletions src/extension/cdpRelayV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ export class ExtensionProtocolV2 {
private _model: BrowserModel;
private _ready = new ManualPromise<void>();

constructor(sendCommand: SendCommand) {
this._model = new BrowserModel(sendCommand);
constructor(sendCommand: SendCommand, connectPagePrefix?: string) {
this._model = new BrowserModel(sendCommand, connectPagePrefix);
void this._ready.catch(logUnhandledError);
}

Expand Down
32 changes: 32 additions & 0 deletions tests/extension-protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,38 @@ describe('extension protocol v2', () => {
.rejects.toThrow('attach failed');
});

it('best-effort removes only this relay\'s seed while it is still on the connect page', async () => {
const connectPage = new URL(`chrome-extension://${EXTENSION_ID}/connect.html`);
connectPage.searchParams.set('mcpRelayUrl', 'ws://127.0.0.1/current');
const connectPagePrefix = connectPage.toString();
const sendCommand = vi.fn(async (method: string, params: any[]) => {
if (method === 'chrome.tabs.create')
return { id: 8, url: params[0].url };
if (method === 'chrome.debugger.sendCommand' && params[1] === 'Target.getTargetInfo') {
const tabId = params[0].tabId;
const url = tabId === 7 ? `${connectPagePrefix}&client=current` : tabId === 10 ? 'https://example.com' : undefined;
return { targetInfo: { targetId: `target-${tabId}`, type: 'page', url } };
}
if (method === 'chrome.tabs.remove')
throw new Error('tab already closed');
return {};
});
const handler = new ExtensionProtocolV2(sendCommand, connectPagePrefix);
handler.handleExtensionEvent('chrome.tabs.onCreated', [
{ id: 7, url: `${connectPagePrefix}&client=current` },
{ id: 9, url: `chrome-extension://${EXTENSION_ID}/connect.html?mcpRelayUrl=ws%3A%2F%2F127.0.0.1%2Fother` },
{ id: 10, url: `${connectPagePrefix}&client=current` },
]);

await handler.handleCDPCommand('Target.setAutoAttach', { autoAttach: true }, undefined);
await expect(handler.handleCDPCommand('Target.createTarget', {}, undefined))
.resolves.toEqual({ result: { targetId: 'target-8' } });

expect(sendCommand).toHaveBeenCalledWith('chrome.tabs.remove', [7]);
expect(sendCommand).not.toHaveBeenCalledWith('chrome.tabs.remove', [9]);
expect(sendCommand).not.toHaveBeenCalledWith('chrome.tabs.remove', [10]);
});

it('serializes concurrent auto-attach state changes', async () => {
let resolveDetach!: () => void;
const detach = new Promise<void>(resolve => resolveDetach = resolve);
Expand Down