From 73122e8da420c296e2d91582ad4da3efec4e8d12 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Wed, 18 Nov 2026 12:32:04 +0000 Subject: [PATCH 1/3] feat: deliver CDP events from pages and the service worker Add `CdpManager.subscribe({ events, enable?, onEvent, onError? })`. It attaches to every open page and the running Extension service worker, then to each new page and each new or restarted worker. On each target it enables the event domains once, shares the persistent session with `send` and other subscribers, and delivers `{ target, method, params, t }`. The service worker session now emits tunneled CDP events instead of dropping every message without an `id`. New workers are found with `Target.targetCreated` on the browser session (target discovery is already on); new pages with the context `page` event. Unsubscribe removes the listeners and disables domains no one else needs; `dispose()` ends every subscription. --- CHANGELOG.md | 1 + README.md | 2 +- SKILL.md | 2 +- src/platform/cdp-manager.test.ts | 1293 +++++++++++++++++++++++- src/platform/cdp-manager.ts | 1030 ++++++++++++++++++- src/platform/playwright-driver.test.ts | 38 + src/platform/playwright-driver.ts | 13 +- 7 files changed, 2348 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d7dfde0..af58a1b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- feat: deliver console and network CDP events from every browser page and the Extension service worker to event subscribers, re-attaching after page, session and MV3 worker restarts ([#107](https://github.com/MetaMask/client-mcp-core/pull/107)) - feat: `mm` sees and acts inside iframes on the browser, including cross-origin ones such as the candlestick chart. A page snapshot (`describe_screen`, `accessibility_snapshot` without `rootSelector`, observations) lists the content of up to 5 visible iframes after the page, with refs namespaced by frame (`f1e1`, `f2e1`, ...) and a `path` ending in `iframe:`; these refs act inside their iframe. Each iframe element also gets a ref, usable as `frame`. `describe_screen`, `click`, `type`, `hover`, `wait_for`, `get_text`, `inspect` and `screenshot` take `frame` (`--frame <iframe>`) to work inside one iframe, the way Playwright's `frameLocator` does. `mm screenshot` adds `--selector` ([#99](https://github.com/MetaMask/client-mcp-core/pull/99)) ## [0.14.0] diff --git a/README.md b/README.md index a6d7017b..82356077 100644 --- a/README.md +++ b/README.md @@ -695,7 +695,7 @@ mm cdp Runtime.evaluate '{"expression":"typeof globalThis.stateHooks","returnByV mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' --fresh ``` -The `params-json` argument must be a valid JSON object. The `--timeout` flag sets the per-command action timeout (default and max: 30 000 ms); the CLI waits up to 47 s for the default so the daemon can run the command and collect its observation. Browser commands share one persistent CDP session per target (page or service worker), so a domain enabled by one call stays enabled for later calls; the session is dropped and re-attached after the page or service worker restarts. `--fresh` opens a one-shot session for a single command and detaches it afterwards. The tool is categorized as `cdp`: by default it returns no observation and does not refresh refs, so pass `--observe full` (or run `mm describe-screen`) after a call that changes state. +The `params-json` argument must be a valid JSON object. The `--timeout` flag sets the per-command action timeout (default and max: 30 000 ms); the CLI waits up to 47 s for the default so the daemon can run the command and collect its observation. Browser commands share one persistent CDP session per target (page or service worker), so a domain enabled by one call stays enabled for later calls; the session is dropped and re-attached after the page or service worker restarts. An event subscription owns the domains it enables on a target: while it holds one, a `<Domain>.enable` or `<Domain>.disable` on that target is refused with `MM_CDP_BLOCKED` (send it with `--fresh` to run it on a session of its own). `--fresh` opens a one-shot session for a single command and detaches it afterwards. The tool is categorized as `cdp`: by default it returns no observation and does not refresh refs, so pass `--observe full` (or run `mm describe-screen`) after a call that changes state. #### Browser vs Mobile (Hermes) CDP diff --git a/SKILL.md b/SKILL.md index f8cc991c..eedba42e 100644 --- a/SKILL.md +++ b/SKILL.md @@ -732,7 +732,7 @@ mm cdp Runtime.evaluate '{"expression":"document.querySelector(\'#personalSign\' | Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached` | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | | Result shape | Standard CDP response | `Runtime.evaluate` nests the value at `result.result.value` | `Runtime.evaluate` nests the value at `result.result.value` | -Browser commands share one persistent CDP session per target, so a domain enabled by one call (e.g. `Network.enable`) stays enabled for the next calls on the same target. Use `--fresh` for a command that must run on its own session, detached afterwards. After an Extension service-worker restart the stale session is dropped and the next call re-attaches. +Browser commands share one persistent CDP session per target, so a domain enabled by one call (e.g. `Network.enable`) stays enabled for the next calls on the same target. An event subscription owns the domains it enables on a target: while it holds one, a `<Domain>.enable` or `<Domain>.disable` on that target is refused with `MM_CDP_BLOCKED`. Use `--fresh` for a command that must run on its own session, detached afterwards. After an Extension service-worker restart the stale session is dropped and the next call re-attaches. On mobile, `cdp` and `hermes-targets` use the Metro port the session was launched with (`mm launch --metro-port`), then the `HERMES_METRO_PORT` env var, then 8081. A per-call `--metro-port` / `--app-id` overrides it for that call only. When device-mcp exports `HermesClient` (needs a device-mcp release with MetaMask/device-mcp P2-02) the session keeps one Hermes connection for its Metro port and app id and reuses it across calls; otherwise each call opens its own connection. A mobile failure names the Metro port it used. diff --git a/src/platform/cdp-manager.test.ts b/src/platform/cdp-manager.test.ts index 377f3239..0b5baf02 100644 --- a/src/platform/cdp-manager.test.ts +++ b/src/platform/cdp-manager.test.ts @@ -1,6 +1,7 @@ import type { Browser, BrowserContext, Page, Worker } from '@playwright/test'; import { describe, it, expect, vi } from 'vitest'; +import type { CdpEvent } from './cdp-manager.js'; import { CdpManager, DEFAULT_SW_ATTACH_TIMEOUT_MS, @@ -115,6 +116,8 @@ type SwOptions = { browser?: Browser | null; /** The browser-level target list. Defaults to one Extension SW target. */ targets?: SwTargetInfo[]; + /** Give each worker attach its own session ID (`session-<n>`). */ + uniqueSessions?: boolean; /** Answers the service worker command tunneled over the browser session. */ swReply?: ( method: string, @@ -164,7 +167,12 @@ function createContext(options: SwOptions = {}): FakeContext { targetId: String(params?.targetId), flatten: Boolean(params?.flatten), }); - return { sessionId: SESSION_ID }; + return { + sessionId: + options.uniqueSessions === true + ? `session-${emittedTargetIds.length}` + : SESSION_ID, + }; } case 'Target.sendMessageToTarget': { const message = JSON.parse(String(params?.message)) as { @@ -1429,3 +1437,1286 @@ describe('getCdpManager', () => { expect(await disposeCdpManager(fake.context)).toBeUndefined(); }); }); + +type EventSession = FakeCdpSession & { + emitter: ReturnType<typeof createEmitter>; + on: ReturnType<typeof vi.fn>; + off: ReturnType<typeof vi.fn>; +}; + +/** + * Creates a fake page CDP session that emits CDP events like Playwright's. + * + * @param targetId - The CDP target ID the session reports. + * @param send - Answers other commands. + * @returns The session mock. + */ +function createEventSession( + targetId: string, + send: ( + method: string, + params?: Record<string, unknown>, + ) => unknown = () => ({}), +): EventSession { + const emitter = createEmitter(); + const session = createCdpSession((method, params) => + method === 'Target.getTargetInfo' + ? { targetInfo: { targetId } } + : send(method, params), + ); + return { ...session, emitter, on: emitter.on, off: emitter.off }; +} + +type FakePage = Page & { + emitter: ReturnType<typeof createEmitter>; + setUrl: (url: string) => void; + setClosed: (closed: boolean) => void; +}; + +/** + * Creates a fake page with `close` events and a mutable URL. + * + * @param url - Its URL. + * @returns The page mock. + */ +function createEventPage(url = PAGE_URL): FakePage { + const emitter = createEmitter(); + const state = { url, closed: false }; + return { + url: vi.fn(() => state.url), + isClosed: vi.fn(() => state.closed), + once: emitter.on, + emitter, + setUrl: (next: string) => { + state.url = next; + }, + setClosed: (closed: boolean) => { + state.closed = closed; + }, + } as unknown as FakePage; +} + +/** + * Emits a CDP event from the worker session over the browser session. + * + * @param fake - The fake context. + * @param method - The event name. + * @param params - The event parameters. + * @param sessionId - The worker session ID. + */ +function emitWorkerEvent( + fake: FakeContext, + method: string, + params: Record<string, unknown>, + sessionId = SESSION_ID, +): void { + fake.browserEmitter.emit('Target.receivedMessageFromTarget', { + sessionId, + message: JSON.stringify({ method, params }), + }); +} + +/** + * Lists the commands tunneled to a worker session. + * + * @param fake - The fake context. + * @param sessionId - Only this worker session, when given. + * @returns The tunneled method names. + */ +function workerCommands(fake: FakeContext, sessionId?: string): string[] { + return fake.browserSession.send.mock.calls.flatMap(([method, params]) => { + if ( + method !== 'Target.sendMessageToTarget' || + (sessionId !== undefined && params?.sessionId !== sessionId) + ) { + return []; + } + return [(JSON.parse(String(params?.message)) as { method: string }).method]; + }); +} + +/** + * Lists the commands sent on a page session. + * + * @param session - The page session. + * @returns The method names. + */ +function pageCommands(session: FakeCdpSession): string[] { + return session.send.mock.calls.map(([method]) => String(method)); +} + +const NET_EVENTS = [ + 'Network.requestWillBeSent', + 'Network.responseReceived', + 'Network.loadingFinished', + 'Network.loadingFailed', +]; +const LOG_EVENTS = ['Runtime.consoleAPICalled', 'Runtime.exceptionThrown']; + +describe('CdpManager subscribe', () => { + it('attaches eagerly to open pages and the worker and enables each domain once', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + const pageSession = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + + await manager.subscribe({ + events: [...NET_EVENTS, ...LOG_EVENTS, 'Runtime.consoleAPICalled'], + enable: { Network: { maxPostDataSize: 1024 } }, + onEvent, + }); + + expect(fake.newCDPSession).toHaveBeenCalledTimes(1); + expect(pageSession.send).toHaveBeenCalledWith('Network.enable', { + maxPostDataSize: 1024, + }); + expect(pageSession.send).toHaveBeenCalledWith('Runtime.enable', {}); + expect( + pageCommands(pageSession).filter((method) => method.endsWith('.enable')), + ).toStrictEqual(['Network.enable', 'Runtime.enable']); + expect(fake.emittedTargetIds).toStrictEqual([ + { targetId: TARGET_ID, flatten: false }, + ]); + expect(workerCommands(fake)).toStrictEqual([ + 'Network.enable', + 'Runtime.enable', + ]); + expect(onEvent).not.toHaveBeenCalled(); + }); + + it('delivers page and worker events tagged with their target', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + const pageSession = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const events: CdpEvent[] = []; + vi.spyOn(Date, 'now').mockReturnValue(1234); + + try { + await manager.subscribe({ + events: [...NET_EVENTS, ...LOG_EVENTS], + onEvent: (event) => events.push(event), + }); + pageSession.emitter.emit('Network.requestWillBeSent', { + requestId: 'p1', + }); + page.setUrl(`${EXTENSION_URL}popup.html`); + pageSession.emitter.emit('Runtime.consoleAPICalled', { type: 'error' }); + emitWorkerEvent(fake, 'Network.loadingFailed', { requestId: 'w1' }); + emitWorkerEvent(fake, 'Runtime.exceptionThrown', { + exceptionDetails: {}, + }); + emitWorkerEvent(fake, 'Network.dataReceived', { requestId: 'w1' }); + pageSession.emitter.emit('Page.frameNavigated', {}); + } finally { + vi.restoreAllMocks(); + } + + expect(events).toStrictEqual([ + { + target: { kind: 'page', targetId: 'page-1', url: PAGE_URL }, + method: 'Network.requestWillBeSent', + params: { requestId: 'p1' }, + t: 1234, + }, + { + target: { + kind: 'page', + targetId: 'page-1', + url: `${EXTENSION_URL}popup.html`, + }, + method: 'Runtime.consoleAPICalled', + params: { type: 'error' }, + t: 1234, + }, + { + target: { kind: 'sw', targetId: TARGET_ID, url: SW_URL }, + method: 'Network.loadingFailed', + params: { requestId: 'w1' }, + t: 1234, + }, + { + target: { kind: 'sw', targetId: TARGET_ID, url: SW_URL }, + method: 'Runtime.exceptionThrown', + params: { exceptionDetails: {} }, + t: 1234, + }, + ]); + }); + + it('keeps events of different targets apart', async () => { + const first = createEventPage(`${EXTENSION_URL}a.html`); + const second = createEventPage('https://dapp.test/'); + const fake = createContext({ pages: [first, second], targets: [] }); + const firstSession = createEventSession('page-a'); + const secondSession = createEventSession('page-b'); + fake.newCDPSession.mockImplementation(async (page: Page) => + page === first ? firstSession : secondSession, + ); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + secondSession.emitter.emit('Runtime.consoleAPICalled', { n: 2 }); + + expect(onEvent).toHaveBeenCalledTimes(1); + expect(onEvent.mock.calls[0]?.[0]).toMatchObject({ + target: { kind: 'page', targetId: 'page-b', url: 'https://dapp.test/' }, + params: { n: 2 }, + }); + }); + + it('tags a page with an empty target ID when the target info has none', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('ignored'); + session.send.mockImplementation(async () => undefined); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + session.emitter.emit('Runtime.consoleAPICalled', undefined); + + expect(onEvent.mock.calls[0]?.[0]).toMatchObject({ + target: { kind: 'page', targetId: '' }, + params: {}, + }); + }); + + it('attaches to a new page (popup, dapp tab) as it opens', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + const popup = createEventPage(`${EXTENSION_URL}notification.html`); + const session = createEventSession('popup-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + + fake.emitter.emit('page', popup); + await flush(); + session.emitter.emit('Runtime.exceptionThrown', { x: 1 }); + + expect(pageCommands(session)).toContain('Runtime.enable'); + expect(onEvent.mock.calls[0]?.[0]).toMatchObject({ + target: { kind: 'page', targetId: 'popup-1' }, + }); + }); + + it('attaches to a restarted worker and enables its domains again', async () => { + const fake = createContext({ pages: [], uniqueSessions: true }); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + await manager.subscribe({ events: NET_EVENTS, onEvent }); + expect(workerCommands(fake, 'session-1')).toStrictEqual(['Network.enable']); + + // MV3 stops the worker: its target is destroyed. + fake.browserEmitter.emit('Target.targetDestroyed', { targetId: TARGET_ID }); + fake.targets.splice(0, 1, { + type: 'service_worker', + url: SW_URL, + targetId: TARGET_ID_2, + }); + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: fake.targets[0], + }); + await flush(); + + expect(workerCommands(fake, 'session-2')).toStrictEqual(['Network.enable']); + emitWorkerEvent(fake, 'Network.requestWillBeSent', { a: 1 }, 'session-1'); + emitWorkerEvent(fake, 'Network.requestWillBeSent', { b: 2 }, 'session-2'); + expect(onEvent).toHaveBeenCalledTimes(1); + expect(onEvent.mock.calls[0]?.[0]).toMatchObject({ + target: { kind: 'sw', targetId: TARGET_ID_2 }, + params: { b: 2 }, + }); + + // `send` reuses the subscription's session on the new worker. + await manager.send({ kind: 'sw' }, 'Runtime.evaluate'); + expect(fake.emittedTargetIds).toHaveLength(2); + }); + + it('re-enables a worker that restarts with the same target ID', async () => { + // Chrome reused the target ID after `ServiceWorker.stopAllWorkers` and a + // wake in the P2-28 proof. + const fake = createContext({ pages: [], uniqueSessions: true }); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + + fake.browserEmitter.emit('Target.targetDestroyed', { targetId: TARGET_ID }); + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: fake.targets[0], + }); + await flush(); + emitWorkerEvent(fake, 'Runtime.consoleAPICalled', { a: 1 }, 'session-1'); + emitWorkerEvent(fake, 'Runtime.consoleAPICalled', { b: 2 }, 'session-2'); + + expect(fake.emittedTargetIds.map((entry) => entry.targetId)).toStrictEqual([ + TARGET_ID, + TARGET_ID, + ]); + expect(workerCommands(fake, 'session-2')).toStrictEqual(['Runtime.enable']); + expect(onEvent.mock.calls.map(([event]) => event.params)).toStrictEqual([ + { b: 2 }, + ]); + }); + + it('attaches to a worker reported by Playwright before target discovery', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + expect(fake.emittedTargetIds).toHaveLength(0); + + fake.targets.push({ + type: 'service_worker', + url: SW_URL, + targetId: TARGET_ID, + }); + fake.emitter.emit('serviceworker', createWorker()); + await flush(); + + expect(fake.emittedTargetIds).toHaveLength(1); + expect(workerCommands(fake)).toStrictEqual(['Runtime.enable']); + }); + + it('keeps the attached worker while the target list holds an old and a new one', async () => { + const fake = createContext({ pages: [] }); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + fake.targets.unshift({ + type: 'service_worker', + url: SW_URL, + targetId: TARGET_ID_2, + }); + + await manager.subscribe({ events: NET_EVENTS, onEvent: vi.fn() }); + + expect(fake.emittedTargetIds.map((entry) => entry.targetId)).toStrictEqual([ + TARGET_ID, + ]); + }); + + it('ignores created targets that are not the Extension worker', async () => { + const fake = createContext({ targets: [] }); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: { type: 'page', url: PAGE_URL, targetId: 'p' }, + }); + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: { + type: 'service_worker', + url: 'chrome-extension://zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz/bg.js', + targetId: 'other', + }, + }); + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: { + type: 'service_worker', + url: 'https://dapp.test/sw.js', + targetId: 'web', + }, + }); + await flush(); + + expect(fake.emittedTargetIds).toHaveLength(0); + }); + + it('accepts any Extension worker before the extension is known', async () => { + const fake = createContext({ pages: [], workers: [], targets: [] }); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: { type: 'service_worker', url: SW_URL, targetId: TARGET_ID }, + }); + await flush(); + + expect(fake.emittedTargetIds).toHaveLength(1); + }); + + it('shares one session per target between subscribers and enables once', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + const pageSession = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const logs = vi.fn(); + const network = vi.fn(); + + await Promise.all([ + manager.subscribe({ events: LOG_EVENTS, onEvent: logs }), + manager.subscribe({ + events: ['Network.requestWillBeSent', 'Runtime.consoleAPICalled'], + onEvent: network, + }), + ]); + pageSession.emitter.emit('Runtime.consoleAPICalled', {}); + pageSession.emitter.emit('Network.requestWillBeSent', {}); + emitWorkerEvent(fake, 'Runtime.exceptionThrown', {}); + + expect(fake.newCDPSession).toHaveBeenCalledTimes(1); + expect(fake.emittedTargetIds).toHaveLength(1); + expect( + pageCommands(pageSession).filter((method) => method.endsWith('.enable')), + ).toStrictEqual(['Runtime.enable', 'Network.enable']); + expect(workerCommands(fake)).toStrictEqual([ + 'Runtime.enable', + 'Network.enable', + ]); + expect(pageSession.emitter.listenerCount('Runtime.consoleAPICalled')).toBe( + 1, + ); + expect(logs.mock.calls.map(([event]) => event.method)).toStrictEqual([ + 'Runtime.consoleAPICalled', + 'Runtime.exceptionThrown', + ]); + expect(network.mock.calls.map(([event]) => event.method)).toStrictEqual([ + 'Runtime.consoleAPICalled', + 'Network.requestWillBeSent', + ]); + }); + + it('runs commands on the subscription session and never resends them', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + let evaluations = 0; + const pageSession = createEventSession('page-1', (method) => { + if (method === 'Runtime.evaluate') { + evaluations += 1; + throw new Error('Target closed'); + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + await expect( + manager.send({ kind: 'page', page }, 'Runtime.evaluate'), + ).rejects.toThrowError('Target closed'); + expect(evaluations).toBe(1); + await manager.send({ kind: 'sw' }, 'Runtime.evaluate'); + + expect(fake.emittedTargetIds).toHaveLength(1); + expect(workerCommands(fake)).toStrictEqual([ + 'Runtime.enable', + 'Runtime.evaluate', + ]); + }); + + it('keeps fresh calls on a one-shot session', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const pageSession = createEventSession('page-1'); + const fresh = createEventSession('page-1'); + fake.newCDPSession + .mockResolvedValueOnce(pageSession) + .mockResolvedValueOnce(fresh); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + await manager.send( + { kind: 'page', page }, + 'Runtime.evaluate', + {}, + { + fresh: true, + }, + ); + + expect(pageCommands(fresh)).toStrictEqual(['Runtime.evaluate']); + expect(fresh.detach).toHaveBeenCalledTimes(1); + expect(pageSession.detach).not.toHaveBeenCalled(); + }); + + it('re-attaches a page whose session closed while the page is open', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const first = createEventSession('page-1', (method) => { + if (method === 'Runtime.evaluate') { + throw new Error( + 'Session closed. Most likely the page has been closed.', + ); + } + return {}; + }); + const second = createEventSession('page-1'); + fake.newCDPSession + .mockResolvedValueOnce(first) + .mockResolvedValueOnce(second); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + + await expect( + manager.send({ kind: 'page', page }, 'Runtime.evaluate'), + ).rejects.toThrowError('Session closed'); + await flush(); + second.emitter.emit('Runtime.consoleAPICalled', {}); + + expect(pageCommands(second)).toContain('Runtime.enable'); + expect(onEvent).toHaveBeenCalledTimes(1); + }); + + it('does not re-attach a closed page', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + fake.newCDPSession.mockResolvedValueOnce(createEventSession('page-1')); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + page.setClosed(true); + page.emitter.emit('close', page); + await flush(); + + expect(fake.newCDPSession).toHaveBeenCalledTimes(1); + }); + + it('unsubscribes: removes listeners and disables domains no one else needs', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + const pageSession = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const logs = vi.fn(); + const network = vi.fn(); + const logSubscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: logs, + }); + const networkSubscription = await manager.subscribe({ + events: ['Network.requestWillBeSent', 'Runtime.consoleAPICalled'], + onEvent: network, + }); + + await logSubscription.unsubscribe(); + await logSubscription.unsubscribe(); + pageSession.emitter.emit('Runtime.consoleAPICalled', {}); + pageSession.emitter.emit('Runtime.exceptionThrown', {}); + + expect(logs).not.toHaveBeenCalled(); + expect(network).toHaveBeenCalledTimes(1); + expect(pageSession.emitter.listenerCount('Runtime.exceptionThrown')).toBe( + 0, + ); + expect(pageCommands(pageSession)).not.toContain('Runtime.disable'); + + await networkSubscription.unsubscribe(); + expect(pageCommands(pageSession)).toContain('Runtime.disable'); + expect(pageCommands(pageSession)).toContain('Network.disable'); + expect(workerCommands(fake)).toContain('Network.disable'); + expect(pageSession.emitter.listenerCount('Runtime.consoleAPICalled')).toBe( + 0, + ); + expect(fake.emitter.listenerCount('page')).toBe(0); + expect(fake.browserEmitter.listenerCount('Target.targetCreated')).toBe(0); + // The persistent sessions stay for `send`. + expect(pageSession.detach).not.toHaveBeenCalled(); + }); + + it('ignores a disable failure on unsubscribe', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const pageSession = createEventSession('page-1', (method) => { + if (method === 'Runtime.disable') { + throw new Error('Target closed'); + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + + expect(await subscription.unsubscribe()).toBeUndefined(); + }); + + it('unsubscribes after the target session went away', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const page = createEventPage(); + fake.newCDPSession.mockResolvedValueOnce(createEventSession('page-1')); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + fake.emitter.emit('page', page); + await flush(); + + page.setClosed(true); + page.emitter.emit('close', page); + await flush(); + + expect(await subscription.unsubscribe()).toBeUndefined(); + }); + + it('stops delivering and detaches everything on dispose', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + const pageSession = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent, + }); + + await manager.dispose(); + pageSession.emitter.emit('Runtime.consoleAPICalled', {}); + fake.emitter.emit('page', createEventPage()); + await flush(); + + expect(onEvent).not.toHaveBeenCalled(); + expect(pageSession.detach).toHaveBeenCalledTimes(1); + expect(fake.browserSession.detach).toHaveBeenCalledTimes(1); + expect(fake.emitter.listenerCount('page')).toBe(0); + expect(fake.browserEmitter.listenerCount('Target.targetCreated')).toBe(0); + expect(fake.newCDPSession).toHaveBeenCalledTimes(1); + expect(await subscription.unsubscribe()).toBeUndefined(); + await expect( + manager.subscribe({ events: LOG_EVENTS, onEvent }), + ).rejects.toThrowError('CDP manager is disposed'); + }); + + it('ignores created targets once the manager is disposed', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + const onTargetCreated = fake.browserEmitter; + await manager.dispose(); + + onTargetCreated.emit('Target.targetCreated', { + targetInfo: { type: 'service_worker', url: SW_URL, targetId: TARGET_ID }, + }); + await flush(); + + expect(fake.emittedTargetIds).toHaveLength(0); + }); + + it('reports enable failures and lets a later subscriber retry', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + let fail = true; + const pageSession = createEventSession('page-1', (method) => { + if (method === 'Network.enable' && fail) { + throw new Error('Network.enable failed'); + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ + events: [...NET_EVENTS, ...LOG_EVENTS], + onEvent: vi.fn(), + onError, + }); + fail = false; + await manager.subscribe({ events: NET_EVENTS, onEvent: vi.fn() }); + + expect(onError).toHaveBeenCalledWith(new Error('Network.enable failed')); + expect( + pageCommands(pageSession).filter((method) => method === 'Network.enable'), + ).toHaveLength(2); + }); + + it('reports attach failures and onEvent errors', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page] }); + const pageSession = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(pageSession); + const implementation = fake.browserSession.send.getMockImplementation(); + fake.browserSession.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => { + if (method === 'Target.attachToTarget') { + throw new Error('attach failed'); + } + return implementation?.(method, params); + }, + ); + const manager = new CdpManager(fake.context); + const onError = vi.fn(() => { + throw new Error('handler failed'); + }); + + await manager.subscribe({ + events: LOG_EVENTS, + onEvent: () => { + // A plain string, to check it is wrapped in an error. + // eslint-disable-next-line @typescript-eslint/only-throw-error + throw 'listener failed'; + }, + onError, + }); + pageSession.emitter.emit('Runtime.consoleAPICalled', {}); + + expect(onError.mock.calls).toStrictEqual([ + [new Error('attach failed')], + [new Error('listener failed')], + ]); + }); + + it('reports a page that cannot be attached and a target-info failure', async () => { + const broken = createEventPage(`${EXTENSION_URL}a.html`); + const noInfo = createEventPage(`${EXTENSION_URL}b.html`); + const fake = createContext({ pages: [broken, noInfo], targets: [] }); + const noInfoSession = createEventSession('b', () => ({})); + noInfoSession.send.mockImplementation(async (method: string) => { + if (method === 'Target.getTargetInfo') { + throw new Error('no info'); + } + return {}; + }); + fake.newCDPSession.mockImplementation(async (page: Page) => { + if (page === broken) { + throw new Error('cannot attach'); + } + return noInfoSession; + }); + const manager = new CdpManager(fake.context); + const errors: string[] = []; + + await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + onError: (error) => errors.push(error.message), + }); + + expect(errors.sort()).toStrictEqual(['cannot attach', 'no info']); + expect(pageCommands(noInfoSession)).not.toContain('Runtime.enable'); + }); + + it('drops errors without onError', async () => { + const fake = createContext({ pages: [] }); + const implementation = fake.browserSession.send.getMockImplementation(); + fake.browserSession.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => { + if (method === 'Target.getTargets') { + throw new Error('boom'); + } + return implementation?.(method, params); + }, + ); + const manager = new CdpManager(fake.context); + + expect( + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }), + ).toBeDefined(); + }); + + it('re-attaches the worker when Playwright closes it but its target lives', async () => { + const fake = createContext({ pages: [], uniqueSessions: true }); + const manager = new CdpManager(fake.context); + const worker = fake.workers[0] as FakeWorker; + const onEvent = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + + worker.emitter.emit('close', worker); + await flush(); + emitWorkerEvent(fake, 'Runtime.consoleAPICalled', { n: 1 }, 'session-2'); + + expect(workerCommands(fake, 'session-2')).toStrictEqual(['Runtime.enable']); + expect(onEvent).toHaveBeenCalledTimes(1); + }); + + it('waits for a restart when the worker stops', async () => { + const fake = createContext({ pages: [] }); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + + fake.targets.splice(0); + fake.browserEmitter.emit('Target.targetDestroyed', { targetId: TARGET_ID }); + await flush(); + + expect(fake.emittedTargetIds).toHaveLength(1); + expect(onError).not.toHaveBeenCalled(); + }); + + it('reports a failed created-target attach', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + const implementation = fake.browserSession.send.getMockImplementation(); + fake.browserSession.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => { + if (method === 'Target.attachToTarget') { + throw new Error( + { + gone: 'No target with given id found', + closing: 'Target page, context or browser has been closed', + }[String(params?.targetId)] ?? 'attach failed', + ); + } + return implementation?.(method, params); + }, + ); + + for (const targetId of ['gone', 'closing']) { + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: { type: 'service_worker', url: SW_URL, targetId }, + }); + } + await flush(); + expect(onError).not.toHaveBeenCalled(); + + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: { type: 'service_worker', url: SW_URL, targetId: TARGET_ID }, + }); + await flush(); + expect(onError).toHaveBeenCalledWith(new Error('attach failed')); + }); + + it('unsubscribes while a target is still attaching', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent, + }); + let resolveInfo!: (value: unknown) => void; + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => + method === 'Target.getTargetInfo' + ? new Promise((resolve) => { + resolveInfo = resolve; + }) + : {}, + ); + fake.newCDPSession.mockResolvedValueOnce(session); + + fake.emitter.emit('page', page); + await flush(); + const unsubscribing = subscription.unsubscribe(); + resolveInfo({ targetInfo: { targetId: 'page-1' } }); + await unsubscribing; + session.emitter.emit('Runtime.consoleAPICalled', {}); + + expect(onEvent).not.toHaveBeenCalled(); + expect(pageCommands(session)).not.toContain('Runtime.enable'); + expect(session.emitter.listenerCount('Runtime.consoleAPICalled')).toBe(0); + }); + + it('adds a subscriber to a worker session only once', async () => { + const fake = createContext({ pages: [] }); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent }); + + fake.emitter.emit('serviceworker', createWorker()); + fake.browserEmitter.emit('Target.targetCreated', { + targetInfo: fake.targets[0], + }); + await flush(); + emitWorkerEvent(fake, 'Runtime.consoleAPICalled', {}); + + expect(fake.emittedTargetIds).toHaveLength(1); + expect(workerCommands(fake)).toStrictEqual(['Runtime.enable']); + expect(onEvent).toHaveBeenCalledTimes(1); + }); + + it('does not attach a worker when disposed during subscribe', async () => { + const fake = createContext({ pages: [] }); + const manager = new CdpManager(fake.context); + + const subscribing = manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + await manager.dispose(); + await subscribing; + + expect(fake.emittedTargetIds).toHaveLength(0); + expect(fake.context.browser()?.newBrowserCDPSession).toHaveBeenCalledTimes( + 1, + ); + }); + + it('does not attach a worker found after dispose', async () => { + const fake = createContext({ pages: [] }); + const implementation = fake.browserSession.send.getMockImplementation(); + let resolveTargets!: () => void; + fake.browserSession.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => { + if (method === 'Target.getTargets') { + await new Promise<void>((resolve) => { + resolveTargets = resolve; + }); + } + return implementation?.(method, params); + }, + ); + const manager = new CdpManager(fake.context); + + const subscribing = manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + await flush(); + await manager.dispose(); + resolveTargets(); + await subscribing; + + expect(fake.emittedTargetIds).toHaveLength(0); + }); + + it('skips a page that finishes attaching after unsubscribe', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + const session = createEventSession('page-1'); + let resolveSession!: (value: EventSession) => void; + fake.newCDPSession.mockReturnValueOnce( + new Promise<EventSession>((resolve) => { + resolveSession = resolve; + }), + ); + + fake.emitter.emit('page', createEventPage()); + await flush(); + await subscription.unsubscribe(); + resolveSession(session); + await flush(); + + expect(pageCommands(session)).toStrictEqual([]); + expect(session.emitter.listenerCount('Runtime.consoleAPICalled')).toBe(0); + }); + + it('forgets a page that closes while its target info is pending', async () => { + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + const page = createEventPage(); + let resolveInfo!: (value: unknown) => void; + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => + method === 'Target.getTargetInfo' + ? new Promise((resolve) => { + resolveInfo = resolve; + }) + : {}, + ); + fake.newCDPSession.mockResolvedValueOnce(session); + + fake.emitter.emit('page', page); + await flush(); + const unsubscribing = subscription.unsubscribe(); + page.setClosed(true); + page.emitter.emit('close', page); + resolveInfo({ targetInfo: { targetId: 'page-1' } }); + await unsubscribing; + + expect(session.detach).toHaveBeenCalledTimes(1); + expect(pageCommands(session)).toStrictEqual(['Target.getTargetInfo']); + }); + + it('does not report errors after unsubscribe', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + onError, + }); + let rejectEnable!: (error: Error) => void; + const session = createEventSession('page-1'); + const answer = session.send.getMockImplementation(); + session.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => + method === 'Runtime.enable' + ? new Promise((_resolve, reject) => { + rejectEnable = reject; + }) + : answer?.(method, params), + ); + fake.newCDPSession.mockResolvedValueOnce(session); + + fake.emitter.emit('page', page); + await flush(); + const unsubscribing = subscription.unsubscribe(); + rejectEnable(new Error('Target closed')); + await unsubscribing; + + expect(onError).not.toHaveBeenCalled(); + }); + + it('ignores a worker that goes away while Runtime.enable is pending', async () => { + const fake = createContext({ + pages: [], + swReply: (method) => { + if (method === 'Runtime.enable') { + // The worker stopped: its target is gone from the target list too. + fake.targets.splice(0); + fake.browserEmitter.emit('Target.targetDestroyed', { + targetId: TARGET_ID, + }); + return { + error: { + message: 'Session closed. The service worker target is gone.', + }, + }; + } + return { result: {} }; + }, + }); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + await flush(); + + expect(onError).not.toHaveBeenCalled(); + }); + + it('ignores an enable failure on a page that closed meanwhile', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => { + if (method === 'Runtime.enable') { + page.setClosed(true); + throw new Error('Target page, context or browser has been closed'); + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + + expect(onError).not.toHaveBeenCalled(); + }); + + it('drops and re-attaches a live page whose target info failed on a closed session', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const first = createEventSession('page-1'); + first.send.mockImplementation(async (method: string) => { + if (method === 'Target.getTargetInfo') { + throw new Error( + 'Session closed. Most likely the page has been closed.', + ); + } + return {}; + }); + const second = createEventSession('page-2'); + fake.newCDPSession + .mockResolvedValueOnce(first) + .mockResolvedValueOnce(second); + const manager = new CdpManager(fake.context); + const onEvent = vi.fn(); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent, onError }); + await flush(); + second.emitter.emit('Runtime.consoleAPICalled', {}); + + expect(onError).not.toHaveBeenCalled(); + expect(fake.newCDPSession).toHaveBeenCalledTimes(2); + expect(first.detach).toHaveBeenCalledTimes(1); + expect(pageCommands(second)).toContain('Runtime.enable'); + expect(onEvent).toHaveBeenCalledTimes(1); + }); + + it('drops and re-attaches a live page whose enable failed on a closed session', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const first = createEventSession('page-1', (method) => { + if (method === 'Runtime.enable') { + throw new Error('Target closed'); + } + return {}; + }); + const second = createEventSession('page-2'); + fake.newCDPSession + .mockResolvedValueOnce(first) + .mockResolvedValueOnce(second); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + await flush(); + + expect(onError).not.toHaveBeenCalled(); + expect(fake.newCDPSession).toHaveBeenCalledTimes(2); + expect(first.detach).toHaveBeenCalledTimes(1); + expect(pageCommands(second)).toContain('Runtime.enable'); + }); + + it('reports once and stops re-attaching a page whose sessions keep closing', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + fake.newCDPSession.mockImplementation(async () => + createEventSession('page-loop', (method) => { + if (method === 'Runtime.enable') { + throw new Error('Target closed'); + } + return {}; + }), + ); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1)); + await flush(); + + // Three tries in quick succession, then silence: no endless re-attach. + expect(fake.newCDPSession).toHaveBeenCalledTimes(3); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError.mock.calls[0]?.[0]).toMatchObject({ + message: 'Target closed', + }); + }); + + it('retries a subscription whose first attach failed on a later attach trigger', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + let fail = true; + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => { + if (method === 'Target.getTargetInfo') { + if (fail) { + fail = false; + throw new Error('Protocol error (Target.getTargetInfo): boom'); + } + return { targetInfo: { targetId: 'page-1' } }; + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + expect(onError).toHaveBeenCalledTimes(1); + expect(pageCommands(session)).not.toContain('Runtime.enable'); + + fake.emitter.emit('page', page); + await flush(); + + expect(pageCommands(session)).toContain('Runtime.enable'); + expect(fake.newCDPSession).toHaveBeenCalledTimes(1); + }); + + it('keeps sending to the attached worker while an old target is listed', async () => { + const fake = createContext({ pages: [], uniqueSessions: true }); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + fake.targets.unshift({ + type: 'service_worker', + url: SW_URL, + targetId: 'target-old', + }); + + await manager.send({ kind: 'sw' }, 'Runtime.evaluate', { + expression: '1', + }); + + expect(fake.emittedTargetIds).toStrictEqual([ + { targetId: TARGET_ID, flatten: false }, + ]); + expect(workerCommands(fake, 'session-1')).toContain('Runtime.evaluate'); + }); + + it('refuses to enable or disable a domain a subscription holds', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + await expect( + manager.send({ kind: 'page', page }, 'Runtime.disable'), + ).rejects.toThrowError( + 'CDP method "Runtime.disable" is refused while an event subscription holds the Runtime domain', + ); + await expect( + manager.send({ kind: 'page', page }, 'Runtime.enable'), + ).rejects.toThrowError('is refused'); + // A domain no subscription holds is sent. + await manager.send({ kind: 'page', page }, 'Network.disable'); + expect(pageCommands(session)).toContain('Network.disable'); + // A one-shot session has its own domains: not refused. + await manager.send( + { kind: 'page', page }, + 'Runtime.disable', + {}, + { + fresh: true, + }, + ); + expect(fake.newCDPSession).toHaveBeenCalledTimes(2); + }); + + it('retries Target.getTargetInfo after a failure', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + let calls = 0; + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => { + if (method === 'Target.getTargetInfo') { + calls += 1; + if (calls === 1) { + throw new Error('no info'); + } + return { targetInfo: { targetId: 'page-1' } }; + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }); + await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); + + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(new Error('no info')); + expect( + pageCommands(session).filter((method) => method === 'Runtime.enable'), + ).toHaveLength(1); + }); + + it('rejects invalid event names', async () => { + const fake = createContext(); + const manager = new CdpManager(fake.context); + + await expect( + manager.subscribe({ events: ['Network'], onEvent: vi.fn() }), + ).rejects.toThrowError('Invalid CDP event name "Network"'); + await expect( + manager.subscribe({ events: ['.x'], onEvent: vi.fn() }), + ).rejects.toThrowError('Invalid CDP event name'); + await expect( + manager.subscribe({ events: ['Network.'], onEvent: vi.fn() }), + ).rejects.toThrowError('Invalid CDP event name'); + await expect( + manager.subscribe({ events: [], onEvent: vi.fn() }), + ).rejects.toThrowError('Subscribe to at least one CDP event'); + expect(fake.emitter.listenerCount('page')).toBe(0); + }); +}); diff --git a/src/platform/cdp-manager.ts b/src/platform/cdp-manager.ts index b0895134..03be3b67 100644 --- a/src/platform/cdp-manager.ts +++ b/src/platform/cdp-manager.ts @@ -5,6 +5,8 @@ import type { Worker as PlaywrightWorker, } from '@playwright/test'; +import { ErrorCodes } from '../tools/types/errors.js'; + /** * Target kinds a {@link CdpManager} can attach to. A string union so more * targets (for example a mobile `app`) can be added without changing the @@ -83,6 +85,74 @@ export type CdpManagerEvent = 'targetAttached' | 'targetDetached'; */ export type CdpManagerListener = (event: CdpTargetEvent) => void; +/** + * The target a CDP event came from. + */ +export type CdpEventTarget = { + kind: CdpTargetKind; + /** + * The CDP target ID. A page keeps its ID across navigations. Chrome can + * reuse a service worker's ID after the worker stops and starts again, so + * the ID does not tell worker runs apart. + */ + targetId: string; + /** The target URL when the event was delivered. */ + url: string; +}; + +/** + * A CDP event delivered to a subscriber. + * + * `params` is the raw CDP payload and is not redacted. A consumer that + * persists or prints it must redact it first: it can hold tokens, keys and + * other secrets (URLs, request bodies, console text). + */ +export type CdpEvent = { + target: CdpEventTarget; + /** The CDP event name, for example `Network.requestWillBeSent`. */ + method: string; + /** The raw, unredacted CDP event parameters. */ + params: Record<string, unknown>; + /** Daemon wall-clock time (ms since epoch) when the event was delivered. */ + t: number; +}; + +/** + * Options for {@link CdpManager.subscribe}. + */ +export type CdpSubscribeOptions = { + /** + * The CDP event names to deliver, for example + * `['Network.requestWillBeSent', 'Runtime.consoleAPICalled']`. The domain + * of each name (`Network`, `Runtime`) is enabled on every target. + */ + events: readonly string[]; + /** + * Parameters of `<Domain>.enable`, by domain, for example + * `{ Network: { maxPostDataSize: 65536 } }`. The first subscriber to enable + * a domain on a target sets them. + */ + enable?: Readonly<Record<string, Record<string, unknown>>>; + /** Called synchronously for each event, in the order of its target. */ + onEvent: (event: CdpEvent) => void; + /** + * Called when a target cannot be attached or enabled, or when `onEvent` + * throws. Errors are dropped when it is missing. + */ + onError?: (error: Error) => void; +}; + +/** + * A live subscription returned by {@link CdpManager.subscribe}. + */ +export type CdpSubscription = { + /** + * Stops delivering events. Removes the event listeners and disables + * domains that no other subscriber needs. Idempotent. + */ + unsubscribe(): Promise<void>; +}; + /** How long to wait for the extension service worker by default. */ export const DEFAULT_SW_ATTACH_TIMEOUT_MS = 30_000; @@ -104,8 +174,42 @@ export const STOPPED_WORKER_MESSAGE = 'The Extension service worker is not running (MV3 workers stop when idle). ' + 'Interact with the Extension (open or reload an Extension page) to start it, then retry.'; +/** + * Error for a `<Domain>.enable` or `<Domain>.disable` refused while an event + * subscription holds that domain on the same target. A subscription owns the + * domains it enabled: disabling one would silently stop the events, and a + * second enable would not be counted, so its last unsubscribe would disable a + * domain the user asked for. + */ +export class CdpDomainInUseError extends Error { + /** The `MM_CDP_BLOCKED` tool error code. */ + readonly code: typeof ErrorCodes.MM_CDP_BLOCKED = ErrorCodes.MM_CDP_BLOCKED; + + /** + * @param method - The refused CDP method. + * @param domain - The CDP domain that a subscription holds. + */ + constructor(method: string, domain: string) { + super( + `CDP method "${method}" is refused while an event subscription holds the ` + + `${domain} domain on this target: it would change the events the ` + + 'subscription receives. Use --fresh to send it on a one-shot session.', + ); + this.name = 'CdpDomainInUseError'; + } +} + const EXTENSION_URL = /^chrome-extension:\/\/([a-z]{32})\//u; +/** + * Closed-session attach failures allowed for a live page before the manager + * reports them once and stops re-attaching it. + */ +const MAX_PAGE_REATTACH_FAILURES = 3; + +/** How close together (ms) page attach failures must be to count as a loop. */ +const PAGE_REATTACH_WINDOW_MS = 30_000; + /** * Errors Playwright throws when a session, its page or its worker is gone. * There is no close event on `CDPSession` in the installed typings, so a @@ -174,10 +278,24 @@ function stoppedWorkerError(): Error { type WorkerMessage = { id?: number; + method?: string; + params?: Record<string, unknown>; result?: unknown; error?: { code?: number; message?: string }; }; +type CdpEventListener = (params: Record<string, unknown> | undefined) => void; + +/** + * A cached session that also emits the CDP events of its target, by event + * name: a Playwright `CDPSession` for a page, or a + * {@link ServiceWorkerCdpSession}. + */ +type EventCdpSession = CdpSession & { + on(method: string, listener: CdpEventListener): unknown; + off(method: string, listener: CdpEventListener): unknown; +}; + type PendingCommand = { resolve: (result: unknown) => void; reject: (error: Error) => void; @@ -191,8 +309,10 @@ type PendingCommand = { * `Target.attachToTarget` (not flattened, because the wrapper cannot send on * a flattened session) and tunnel commands through * `Target.sendMessageToTarget`. Chrome still supports that deprecated pair. + * Tunneled messages without an `id` are CDP events; they are emitted by + * name, like a Playwright `CDPSession` does. */ -class ServiceWorkerCdpSession implements CdpSession { +class ServiceWorkerCdpSession implements EventCdpSession { readonly #browserSession: CDPSession; readonly #sessionId: string; @@ -203,6 +323,8 @@ class ServiceWorkerCdpSession implements CdpSession { readonly #pending = new Map<number, PendingCommand>(); + readonly #eventListeners = new Map<string, Set<CdpEventListener>>(); + #nextId = 1; #closed = false; @@ -258,6 +380,35 @@ class ServiceWorkerCdpSession implements CdpSession { return reply; } + /** + * Listens for a CDP event of the service worker target. + * + * @param method - The CDP event name. + * @param listener - Called with the event parameters. + * @returns This session. + */ + on(method: string, listener: CdpEventListener): this { + let listeners = this.#eventListeners.get(method); + if (!listeners) { + listeners = new Set(); + this.#eventListeners.set(method, listeners); + } + listeners.add(listener); + return this; + } + + /** + * Removes a CDP event listener. + * + * @param method - The CDP event name. + * @param listener - The listener to remove. + * @returns This session. + */ + off(method: string, listener: CdpEventListener): this { + this.#eventListeners.get(method)?.delete(listener); + return this; + } + /** * Detaches this session and fails its pending commands. */ @@ -291,6 +442,15 @@ class ServiceWorkerCdpSession implements CdpSession { return; } if (message.id === undefined) { + if (message.method !== undefined) { + for (const listener of this.#eventListeners.get(message.method) ?? []) { + try { + listener(message.params); + } catch { + // A failing listener must not break the others. + } + } + } return; } const pending = this.#pending.get(message.id); @@ -346,6 +506,7 @@ class ServiceWorkerCdpSession implements CdpSession { ); this.#browserSession.off('Target.detachedFromTarget', this.#onDetached); this.#browserSession.off('Target.targetDestroyed', this.#onTargetDestroyed); + this.#eventListeners.clear(); for (const pending of this.#pending.values()) { pending.reject(this.#closedError()); } @@ -373,8 +534,8 @@ class ServiceWorkerCdpSession implements CdpSession { type CdpEntryBase = { event: CdpTargetEvent; - session?: CdpSession; - opening?: Promise<CdpSession>; + session?: EventCdpSession; + opening?: Promise<EventCdpSession>; /** Set when the entry is dropped, so an in-flight open does not revive it. */ dropped?: boolean; }; @@ -384,6 +545,8 @@ type PageEntry = CdpEntryBase & { page: Page }; type ServiceWorkerEntry = CdpEntryBase & { /** The CDP target ID; a restarted worker has a new one. */ targetId: string; + /** The worker script URL. */ + url: string; /** * The Playwright worker, when Playwright reported one. It is only used to * notice the worker stopping: the CDP target list decides liveness. @@ -400,6 +563,84 @@ type ServiceWorkerTarget = { url: string; }; +/** A `Target.TargetInfo` as reported by the browser session. */ +type TargetInfo = { type: string; url: string; targetId: string }; + +/** One active {@link CdpManager.subscribe} call. */ +type Subscription = { + options: CdpSubscribeOptions; + /** `options.events` without duplicates. */ + events: string[]; + /** The domains of `options.events`, in first-seen order. */ + domains: string[]; + /** What this subscription added to each session it reached. */ + records: Map<EventCdpSession, SubscriptionRecord>; + active: boolean; +}; + +/** What one subscription added to one session. */ +type SubscriptionRecord = { + /** Settles when the listeners are on and the domains are enabled. */ + ready: Promise<void>; + /** Event names this subscription listens to on the session. */ + methods: string[]; + /** Domains this subscription holds enabled on the session. */ + domains: string[]; +}; + +/** + * Shared subscription state of one session: one CDP listener per event name + * (dispatching to every subscriber) and one reference count per enabled + * domain, so subscribers share the session and its enables. + */ +type SessionSubscriptionState = { + targetId?: Promise<string>; + methods: Map< + string, + { listener: CdpEventListener; subscriptions: Set<Subscription> } + >; + domains: Map<string, { count: number; enabled: Promise<void> }>; +}; + +/** + * Reads an Extension service worker target from a target info. + * + * @param info - The target info. + * @returns The target, or undefined for another kind of target. + */ +function toServiceWorkerTarget( + info: TargetInfo, +): ServiceWorkerTarget | undefined { + if (info.type !== 'service_worker') { + return undefined; + } + const extensionId = extensionIdFromUrl(info.url); + return extensionId === undefined + ? undefined + : { extensionId, targetId: info.targetId, url: info.url }; +} + +/** + * Converts a thrown value to an error. + * + * @param error - The thrown value. + * @returns The value when it is an error, else an error with its text. + */ +function toError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} + +/** + * Tells whether a target is gone: its page is closed, or its entry was + * dropped after the target went away. + * + * @param entry - The target entry. + * @returns True when nothing can be attached to it any more. + */ +function isTargetGone(entry: CdpEntry): boolean { + return entry.dropped === true || ('page' in entry && entry.page.isClosed()); +} + /** * Persistent CDP sessions for one browser session. * @@ -429,6 +670,27 @@ export class CdpManager { readonly #listeners = new Map<CdpManagerEvent, Set<CdpManagerListener>>(); + readonly #subscriptions = new Set<Subscription>(); + + /** + * Closed-session attach failures per live page: the manager re-attaches a + * page whose session died, and a page that keeps failing would otherwise be + * dropped and re-attached forever, silently. `reported` marks a page over + * budget, which `#detach` no longer re-attaches. + */ + readonly #pageAttachFailures = new WeakMap< + Page, + { count: number; since: number; reported: boolean } + >(); + + readonly #sessionStates = new WeakMap< + EventCdpSession, + SessionSubscriptionState + >(); + + /** The browser session watched for new service worker targets. */ + #watchedBrowserSession: CDPSession | undefined; + #browserSession: Promise<CDPSession> | undefined; /** Whether an Extension service worker was seen during this manager's life. */ @@ -468,6 +730,12 @@ export class CdpManager { * A command that may have reached the target is never re-sent. Only a * failure to open the session is retried once. * + * A `<Domain>.enable` or `<Domain>.disable` is refused with + * {@link CdpDomainInUseError} while a subscription holds that domain on + * the target (see {@link subscribe}): the subscription enabled the domain + * and would disable it on its last unsubscribe. `fresh` commands are not + * refused, because they run on a session of their own. + * * @param target - The page, or the extension service worker. * @param method - The CDP method. * @param params - The CDP method parameters. @@ -485,7 +753,7 @@ export class CdpManager { return this.#sendFresh(target, method, params, options); } - let acquired: { entry: CdpEntry; session: CdpSession }; + let acquired: { entry: CdpEntry; session: EventCdpSession }; try { acquired = await this.#acquireSession(target, options); } catch (error) { @@ -496,6 +764,7 @@ export class CdpManager { acquired = await this.#acquireSession(target, options); } + this.#assertDomainFree(acquired.session, method); try { return await this.#race( acquired.session.send(method, params), @@ -510,6 +779,26 @@ export class CdpManager { } } + /** + * Refuses a `<Domain>.enable` or `<Domain>.disable` while a subscription + * holds that domain on the session. + * + * @param session - The session the command would run on. + * @param method - The CDP method. + */ + #assertDomainFree(session: EventCdpSession, method: string): void { + const match = /^([^.]+)\.(?:enable|disable)$/u.exec(method); + const domain = match?.[1]; + if (domain === undefined) { + return; + } + if ( + (this.#sessionStates.get(session)?.domains.get(domain)?.count ?? 0) > 0 + ) { + throw new CdpDomainInUseError(method, domain); + } + } + /** * Subscribes to a target event. * @@ -539,6 +828,80 @@ export class CdpManager { return this; } + /** + * Delivers CDP events from every page and the Extension service worker. + * + * Attaches at once to every open page and to the running service worker, + * then to each new page (tab, popup) and each new or restarted worker as + * it appears. On each target it enables the domains of `events` once and + * shares the target's persistent session with `send` and other + * subscribers. A worker that restarts as a new target gets a new session, + * so its domains are enabled again. + * + * Network traffic sent before a target is attached is not delivered. + * `Runtime.enable` replays the console messages Chrome kept for the target, + * so a late subscriber can receive older console events. + * + * The subscription owns the domains of `events` on each target it reaches: + * while it is active, {@link send} refuses `<Domain>.enable` and + * `<Domain>.disable` for those domains, and its last unsubscribe disables + * them. A domain the user enabled by hand before subscribing is not + * tracked separately. + * + * Only pages and the Extension service worker are covered: out-of-process + * iframes and MV3 offscreen documents are not attached. + * + * `onEvent` receives the raw CDP `params`, which are not redacted; a + * consumer that stores or prints them must redact them first. + * + * @param options - The event names, enable parameters and callbacks. + * @returns The subscription, once the targets open now are attached. + */ + async subscribe(options: CdpSubscribeOptions): Promise<CdpSubscription> { + this.#assertLive(); + const domains: string[] = []; + for (const method of options.events) { + const dot = method.indexOf('.'); + if (dot <= 0 || dot === method.length - 1) { + throw new Error( + `Invalid CDP event name "${method}". Use <Domain>.<event>.`, + ); + } + const domain = method.slice(0, dot); + if (!domains.includes(domain)) { + domains.push(domain); + } + } + if (domains.length === 0) { + throw new Error('Subscribe to at least one CDP event'); + } + + const subscription: Subscription = { + options, + events: [...new Set(options.events)], + domains, + records: new Map(), + active: true, + }; + if (this.#subscriptions.size === 0) { + this.#context.on('page', this.#onPage); + } + this.#subscriptions.add(subscription); + + await Promise.all([ + ...this.#context + .pages() + .map(async (page) => + this.#attachPageForSubscribers(page, [subscription]), + ), + this.#attachWorkerForSubscribers([subscription]), + ]); + + return { + unsubscribe: async (): Promise<void> => this.#unsubscribe(subscription), + }; + } + /** * Detaches every cached session and stops listening for service workers. * Idempotent. @@ -549,6 +912,14 @@ export class CdpManager { } this.#disposed = true; this.#context.off('serviceworker', this.#onServiceWorker); + for (const subscription of this.#subscriptions) { + subscription.active = false; + } + if (this.#subscriptions.size > 0) { + this.#context.off('page', this.#onPage); + } + this.#subscriptions.clear(); + this.#unwatchTargets(); const entries = [...this.#entries]; const browserSession = this.#browserSession; this.#browserSession = undefined; @@ -576,8 +947,576 @@ export class CdpManager { } this.#extensionWorkerSeen = true; this.#observeWorker(worker); + if (this.#subscriptions.size > 0) { + // A backup for `Target.targetCreated`; the target list decides. + // eslint-disable-next-line no-void + void this.#attachWorkerForSubscribers([...this.#subscriptions]); + } + }; + + /** + * Attaches subscribers to a new page (tab, popup, dapp page). + * + * @param page - The new page. + */ + readonly #onPage = (page: Page): void => { + // eslint-disable-next-line no-void + void this.#attachPageForSubscribers(page, [...this.#subscriptions]); }; + /** + * Attaches subscribers to a new Extension service worker target, such as + * a worker that restarted after MV3 stopped it. + * + * @param event - The `Target.targetCreated` payload. + * @param event.targetInfo - The new target. + */ + readonly #onTargetCreated = (event: { targetInfo: TargetInfo }): void => { + const target = toServiceWorkerTarget(event.targetInfo); + const knownExtensionId = this.#extensionId(); + if ( + target === undefined || + (knownExtensionId !== undefined && + target.extensionId !== knownExtensionId) + ) { + return; + } + const subscriptions = [...this.#subscriptions]; + this.#attachWorkerTarget(target, subscriptions).catch((error: unknown) => + this.#reportAttachError(subscriptions, error, false), + ); + }; + + /** + * Starts watching the browser session for new service worker targets, + * once per browser session. + */ + async #watchTargets(): Promise<void> { + const browserSession = await this.#getBrowserSession(); + if ( + this.#disposed || + this.#subscriptions.size === 0 || + this.#watchedBrowserSession === browserSession + ) { + return; + } + this.#unwatchTargets(); + browserSession.on('Target.targetCreated', this.#onTargetCreated); + this.#watchedBrowserSession = browserSession; + } + + /** + * Stops watching the browser session for new targets. + */ + #unwatchTargets(): void { + this.#watchedBrowserSession?.off( + 'Target.targetCreated', + this.#onTargetCreated, + ); + this.#watchedBrowserSession = undefined; + } + + /** + * Attaches subscribers to a page. Failures go to their `onError`. + * + * @param page - The page. + * @param subscriptions - The subscribers to attach. + * @param retry - Whether this is the re-attach after a failure (it counts + * against the page's budget) rather than a new trigger. + */ + async #attachPageForSubscribers( + page: Page, + subscriptions: Subscription[], + retry = false, + ): Promise<void> { + if (!retry) { + // A new trigger (a subscription, a new page) gets a fresh budget; only + // the re-attach after a failure counts against it. + this.#pageAttachFailures.delete(page); + } + try { + const { entry, session } = await this.#acquireSession( + { kind: 'page', page }, + {}, + ); + await Promise.all( + subscriptions.map(async (subscription) => + this.#addToSession(subscription, entry, session), + ), + ); + } catch (error) { + this.#reportAttachError( + subscriptions, + error, + page.isClosed?.(), + undefined, + page, + ); + } + } + + /** + * Watches for new worker targets and attaches subscribers to the running + * Extension service worker, if any. Does not wait for a stopped worker: a + * new worker is attached when its target is created. Failures go to the + * subscribers' `onError`. + * + * @param subscriptions - The subscribers to attach. + */ + async #attachWorkerForSubscribers( + subscriptions: Subscription[], + ): Promise<void> { + try { + await this.#watchTargets(); + if (this.#disposed) { + return; + } + const knownExtensionId = this.#extensionId(); + const targets = (await this.#serviceWorkerTargets()).filter( + (candidate) => + knownExtensionId === undefined || + candidate.extensionId === knownExtensionId, + ); + // While a worker restarts, the list can briefly hold the old and the + // new target. Keep the worker already attached (a newer one is + // attached by `Target.targetCreated`) rather than switching back. + const target = + targets.find((candidate) => + this.#workerEntries.has(candidate.targetId), + ) ?? targets[0]; + if (target !== undefined) { + await this.#attachWorkerTarget(target, subscriptions); + } + } catch (error) { + this.#reportAttachError(subscriptions, error, false); + } + } + + /** + * Reports a failure to attach subscribers. Target loss is not an error: a + * page that closed, or an MV3 worker that stopped and will be attached + * again when it restarts, fails routine attaches (for example + * `<Domain>.enable` on a session that just closed). A dead session on a + * live target is not an error either: the entry is dropped so `#detach` + * attaches the subscribers to the live target again. + * + * @param subscriptions - The subscribers. + * @param error - The error. + * @param targetGone - Whether the target itself is gone. + * @param entry - The target entry, when the failure has one. + * @param page - The page, when the failure happens before an entry exists. + */ + #reportAttachError( + subscriptions: Subscription[], + error: unknown, + targetGone: boolean, + entry?: CdpEntry, + page?: Page, + ): void { + if (isClosedSessionError(error)) { + if (!targetGone) { + this.#notePageAttachFailure( + subscriptions, + error, + page ?? + (entry !== undefined && 'page' in entry ? entry.page : undefined), + ); + } + if (entry !== undefined) { + // The target outlives its session: drop the entry so `#detach` + // attaches the subscribers again on a fresh session. + this.#drop(entry); + } + return; + } + if (targetGone || toError(error).message === STOPPED_WORKER_MESSAGE) { + return; + } + this.#report(subscriptions, error); + } + + /** + * Counts a closed-session attach failure for a live page. After + * {@link MAX_PAGE_REATTACH_FAILURES} failures in + * {@link PAGE_REATTACH_WINDOW_MS}, it reports once and marks the page so + * `#detach` stops re-attaching it; a new trigger clears the budget. + * + * @param subscriptions - The subscribers of the failed attach. + * @param error - The closed-session error. + * @param page - The live page, when known. + */ + #notePageAttachFailure( + subscriptions: Subscription[], + error: unknown, + page: Page | undefined, + ): void { + if (page === undefined) { + return; + } + const now = Date.now(); + const previous = this.#pageAttachFailures.get(page); + const inWindow = + previous !== undefined && now - previous.since <= PAGE_REATTACH_WINDOW_MS; + const state = { + count: inWindow ? previous.count + 1 : 1, + since: inWindow ? previous.since : now, + reported: inWindow && previous.reported, + }; + if (state.count >= MAX_PAGE_REATTACH_FAILURES) { + // Report once, then stay quiet: the subscribers hear about the page + // once and the manager stops trying until a new trigger. + if (!state.reported) { + this.#report(subscriptions, error); + } + state.reported = true; + } + this.#pageAttachFailures.set(page, state); + } + + /** + * Opens (or reuses) the session of a live service worker target and adds + * subscribers to it. + * + * @param target - The live service worker target. + * @param subscriptions - The subscribers to attach. + */ + async #attachWorkerTarget( + target: ServiceWorkerTarget, + subscriptions: Subscription[], + ): Promise<void> { + if (this.#disposed) { + return; + } + const entry = this.#workerEntryFor(target); + const session = await this.#openEntry(entry, async () => + this.#openWorkerSession(entry.targetId, () => this.#drop(entry)), + ); + await Promise.all( + subscriptions.map(async (subscription) => + this.#addToSession(subscription, entry, session), + ), + ); + } + + /** + * Adds a subscriber to a session once: listens for its events and enables + * its domains, sharing both with the other subscribers of the session. + * + * @param subscription - The subscriber. + * @param entry - The target entry of the session. + * @param session - The session. + * @returns Settles when the subscriber is ready on the session. Never + * rejects: failures go to the subscriber's `onError`. + */ + async #addToSession( + subscription: Subscription, + entry: CdpEntry, + session: EventCdpSession, + ): Promise<void> { + const existing = subscription.records.get(session); + if (existing) { + return existing.ready; + } + if (!subscription.active) { + return undefined; + } + const record: SubscriptionRecord = { + ready: Promise.resolve(), + methods: [], + domains: [], + }; + subscription.records.set(session, record); + record.ready = this.#fillRecord(subscription, entry, session, record); + return record.ready; + } + + /** + * Registers the event listeners and domain enables of one subscriber on a + * session. + * + * @param subscription - The subscriber. + * @param entry - The target entry of the session. + * @param session - The session. + * @param record - Where to note what was added. + */ + async #fillRecord( + subscription: Subscription, + entry: CdpEntry, + session: EventCdpSession, + record: SubscriptionRecord, + ): Promise<void> { + const state = this.#sessionState(session); + let describe: () => CdpEventTarget; + try { + describe = await this.#describeTarget(entry, session, state); + } catch (error) { + // A record only guards a successful attach: delete it so a later + // attach trigger retries instead of reusing `record.ready`. + if (subscription.records.get(session) === record) { + subscription.records.delete(session); + } + this.#reportAttachError( + [subscription], + error, + isTargetGone(entry), + entry, + ); + return; + } + if (!subscription.active || subscription.records.get(session) !== record) { + return; + } + + for (const method of subscription.events) { + let handler = state.methods.get(method); + if (!handler) { + const subscriptions = new Set<Subscription>(); + const listener: CdpEventListener = (params) => { + const event: CdpEvent = { + target: describe(), + method, + params: params ?? {}, + t: Date.now(), + }; + for (const subscriber of [...subscriptions]) { + this.#deliver(subscriber, event); + } + }; + handler = { listener, subscriptions }; + state.methods.set(method, handler); + session.on(method, listener); + } + handler.subscriptions.add(subscription); + record.methods.push(method); + } + + const results = await Promise.allSettled( + subscription.domains.map(async (domain) => + this.#enableDomain(subscription, session, state, record, domain), + ), + ); + for (const result of results) { + if (result.status === 'rejected') { + this.#reportAttachError( + [subscription], + result.reason, + isTargetGone(entry), + entry, + ); + } + } + if ( + results.every((result) => result.status === 'fulfilled') && + 'page' in entry + ) { + // The domains are on: the page's attach failures, if any, are over. + this.#pageAttachFailures.delete(entry.page); + } + } + + /** + * Enables a domain on a session for one subscriber. The first subscriber + * sends `<Domain>.enable`; later ones share it. + * + * @param subscription - The subscriber. + * @param session - The session. + * @param state - The session's shared subscription state. + * @param record - Where to note the enabled domain. + * @param domain - The CDP domain. + */ + async #enableDomain( + subscription: Subscription, + session: EventCdpSession, + state: SessionSubscriptionState, + record: SubscriptionRecord, + domain: string, + ): Promise<void> { + let enabled = state.domains.get(domain); + if (!enabled) { + enabled = { + count: 0, + enabled: session + .send(`${domain}.enable`, subscription.options.enable?.[domain] ?? {}) + .then(() => undefined), + }; + state.domains.set(domain, enabled); + } + enabled.count += 1; + record.domains.push(domain); + try { + await enabled.enabled; + } catch (error) { + record.domains.splice(record.domains.indexOf(domain), 1); + enabled.count -= 1; + if (enabled.count === 0) { + // Let a later attach try again. + state.domains.delete(domain); + } + throw error; + } + } + + /** + * Returns the shared subscription state of a session. + * + * @param session - The session. + * @returns Its state, created on first use. + */ + #sessionState(session: EventCdpSession): SessionSubscriptionState { + let state = this.#sessionStates.get(session); + if (!state) { + state = { methods: new Map(), domains: new Map() }; + this.#sessionStates.set(session, state); + } + return state; + } + + /** + * Resolves how to tag the events of a session's target. + * + * @param entry - The target entry. + * @param session - The target session. + * @param state - The session's shared subscription state. + * @returns A function returning the current target tag. + */ + async #describeTarget( + entry: CdpEntry, + session: EventCdpSession, + state: SessionSubscriptionState, + ): Promise<() => CdpEventTarget> { + if (!('page' in entry)) { + const target: CdpEventTarget = { + kind: 'sw', + targetId: entry.targetId, + url: entry.url, + }; + return () => target; + } + if (state.targetId === undefined) { + const lookup = session + .send('Target.getTargetInfo', {}) + .then( + (result) => + (result as { targetInfo?: { targetId?: string } } | undefined) + ?.targetInfo?.targetId ?? '', + ); + state.targetId = lookup; + // A failed lookup is not the target's ID: let a later attach retry. + lookup.catch(() => { + if (state.targetId === lookup) { + state.targetId = undefined; + } + }); + } + const targetId = await state.targetId; + const { page } = entry; + return () => ({ kind: 'page', targetId, url: page.url() }); + } + + /** + * Removes one subscriber from a session, and disables the domains that no + * other subscriber needs. + * + * @param subscription - The subscriber. + * @param session - The session. + * @param record - What the subscriber added to the session. + */ + async #release( + subscription: Subscription, + session: EventCdpSession, + record: SubscriptionRecord, + ): Promise<void> { + const state = this.#sessionStates.get(session); + if (!state) { + // The session was detached while attaching; its listeners and domains + // went with it. + return; + } + for (const method of record.methods) { + const handler = state.methods.get(method); + handler?.subscriptions.delete(subscription); + if (handler?.subscriptions.size === 0) { + session.off(method, handler.listener); + state.methods.delete(method); + } + } + const disables: Promise<unknown>[] = []; + for (const domain of record.domains) { + const enabled = state.domains.get(domain); + if (enabled) { + enabled.count -= 1; + if (enabled.count === 0) { + state.domains.delete(domain); + disables.push( + session.send(`${domain}.disable`, {}).catch(() => undefined), + ); + } + } + } + await Promise.all(disables); + } + + /** + * Ends a subscription. Idempotent. + * + * @param subscription - The subscription. + */ + async #unsubscribe(subscription: Subscription): Promise<void> { + if (!subscription.active) { + return; + } + subscription.active = false; + this.#subscriptions.delete(subscription); + if (this.#subscriptions.size === 0) { + this.#context.off('page', this.#onPage); + this.#unwatchTargets(); + } + const records = [...subscription.records]; + await Promise.all( + records.map(async ([session, record]) => { + await record.ready; + subscription.records.delete(session); + await this.#release(subscription, session, record); + }), + ); + } + + /** + * Delivers an event to one subscriber. + * + * @param subscription - The subscriber. + * @param event - The event. + */ + #deliver(subscription: Subscription, event: CdpEvent): void { + if (!subscription.active) { + return; + } + try { + subscription.options.onEvent(event); + } catch (error) { + this.#report([subscription], error); + } + } + + /** + * Reports an error to subscribers that have `onError`. + * + * @param subscriptions - The subscribers. + * @param error - The error. + */ + #report(subscriptions: Subscription[], error: unknown): void { + for (const subscription of subscriptions) { + if (!subscription.active) { + continue; + } + try { + subscription.options.onError?.(toError(error)); + } catch { + // A failing error handler must not break the other subscribers. + } + } + } + /** * Watches a service worker once for its `close` event. MV3 workers stop * when idle, and Playwright's `close` event is a signal to forget the @@ -611,19 +1550,19 @@ export class CdpManager { async #acquireTarget( target: CdpTarget, options: CdpAttachOptions, - ): Promise<{ entry: CdpEntry; open: () => Promise<CdpSession> }> { + ): Promise<{ entry: CdpEntry; open: () => Promise<EventCdpSession> }> { if (target.kind === 'page') { const entry = this.#pageEntry(target.page); return { entry, - open: async (): Promise<CdpSession> => + open: async (): Promise<EventCdpSession> => this.#openPageSession(target.page), }; } const entry = await this.#workerEntry(options); return { entry, - open: async (): Promise<CdpSession> => + open: async (): Promise<EventCdpSession> => this.#openWorkerSession(entry.targetId, () => this.#drop(entry)), }; } @@ -638,7 +1577,7 @@ export class CdpManager { async #acquireSession( target: CdpTarget, options: CdpAttachOptions, - ): Promise<{ entry: CdpEntry; session: CdpSession }> { + ): Promise<{ entry: CdpEntry; session: EventCdpSession }> { const { entry, open } = await this.#acquireTarget(target, options); return { entry, session: await this.#openEntry(entry, open) }; } @@ -681,6 +1620,17 @@ export class CdpManager { knownExtensionId, options, ); + return this.#workerEntryFor(target); + } + + /** + * Returns the cached entry of a live service worker target, creating it on + * first use and dropping the entry of any previous worker. + * + * @param target - The live service worker target. + * @returns Its entry. + */ + #workerEntryFor(target: ServiceWorkerTarget): ServiceWorkerEntry { this.#extensionWorkerSeen = true; const cached = this.#workerEntries.get(target.targetId); if (cached) { @@ -697,6 +1647,7 @@ export class CdpManager { } const entry: ServiceWorkerEntry = { targetId: target.targetId, + url: target.url, worker, event: { kind: 'sw', target: worker }, }; @@ -728,16 +1679,9 @@ export class CdpManager { async #serviceWorkerTargets(): Promise<ServiceWorkerTarget[]> { const browserSession = await this.#getBrowserSession(); const { targetInfos } = await browserSession.send('Target.getTargets'); - return ( - targetInfos as { type: string; url: string; targetId: string }[] - ).flatMap((info) => { - if (info.type !== 'service_worker') { - return []; - } - const extensionId = extensionIdFromUrl(info.url); - return extensionId === undefined - ? [] - : [{ extensionId, targetId: info.targetId, url: info.url }]; + return (targetInfos as TargetInfo[]).flatMap((info) => { + const target = toServiceWorkerTarget(info); + return target === undefined ? [] : [target]; }); } @@ -756,12 +1700,18 @@ export class CdpManager { options: CdpAttachOptions, ): Promise<ServiceWorkerTarget> { const find = async (): Promise<ServiceWorkerTarget | undefined> => { - const targets = await this.#serviceWorkerTargets(); - return targets.find( + const targets = (await this.#serviceWorkerTargets()).filter( (target) => knownExtensionId === undefined || target.extensionId === knownExtensionId, ); + // While a worker restarts, the list can briefly hold the old and the + // new target. Keep the worker already attached, like + // `#attachWorkerForSubscribers` does, rather than switching back. + return ( + targets.find((target) => this.#workerEntries.has(target.targetId)) ?? + targets[0] + ); }; const existing = await find(); @@ -837,9 +1787,11 @@ export class CdpManager { * @param page - The page. * @returns Its session. */ - async #openPageSession(page: Page): Promise<CdpSession> { - // A Playwright CDPSession has this send/detach surface. - return (await this.#context.newCDPSession(page)) as unknown as CdpSession; + async #openPageSession(page: Page): Promise<EventCdpSession> { + // A Playwright CDPSession has this send/detach/on/off surface. + return (await this.#context.newCDPSession( + page, + )) as unknown as EventCdpSession; } /** @@ -853,7 +1805,7 @@ export class CdpManager { async #openWorkerSession( targetId: string, onClose: () => void, - ): Promise<CdpSession> { + ): Promise<EventCdpSession> { const browserSession = await this.#getBrowserSession(); let sessionId: string; try { @@ -911,12 +1863,12 @@ export class CdpManager { */ async #openEntry( entry: CdpEntry, - open: () => Promise<CdpSession>, - ): Promise<CdpSession> { + open: () => Promise<EventCdpSession>, + ): Promise<EventCdpSession> { if (entry.session) { return entry.session; } - entry.opening ??= (async (): Promise<CdpSession> => { + entry.opening ??= (async (): Promise<EventCdpSession> => { const session = await open(); if (this.#disposed) { await session.detach().catch(() => undefined); @@ -1050,8 +2002,32 @@ export class CdpManager { if (!session) { return; } + // The session's listeners and enabled domains go with it. + this.#sessionStates.delete(session); + for (const subscription of this.#subscriptions) { + subscription.records.delete(session); + } this.#emit('targetDetached', entry.event); await session.detach().catch(() => undefined); + if (this.#disposed || this.#subscriptions.size === 0) { + return; + } + // Subscribers keep their events when the target outlives its session: + // a page whose session failed, or a worker whose Playwright `close` + // fired while its CDP target is still live. A stopped worker is attached + // again by `Target.targetCreated` when it restarts. + if (!('page' in entry)) { + await this.#attachWorkerForSubscribers([...this.#subscriptions]); + } else if ( + !entry.page.isClosed() && + !this.#pageAttachFailures.get(entry.page)?.reported + ) { + await this.#attachPageForSubscribers( + entry.page, + [...this.#subscriptions], + true, + ); + } } /** diff --git a/src/platform/playwright-driver.test.ts b/src/platform/playwright-driver.test.ts index b6cf1376..1235350d 100644 --- a/src/platform/playwright-driver.test.ts +++ b/src/platform/playwright-driver.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; +import { getCdpManager } from './cdp-manager.js'; import { PlaywrightPlatformDriver } from './playwright-driver.js'; import type { IPlatformDriver } from './types.js'; import { createMockSessionManager } from '../tools/test-utils/mock-factories.js'; @@ -1007,6 +1008,43 @@ describe('PlaywrightPlatformDriver', () => { ); }); + it('maps a domain held by a subscription to MM_CDP_BLOCKED', async () => { + const cdpSession = { + send: vi.fn(async (method: string) => + method === 'Target.getTargetInfo' + ? { targetInfo: { targetId: 'page-1' } } + : {}, + ), + detach: vi.fn().mockResolvedValue(undefined), + on: vi.fn(), + off: vi.fn(), + }; + const page = createCdpPage(cdpSession); + const driver = createDriver(page); + const manager = getCdpManager(page.contextMock as never); + await manager.subscribe({ + events: ['Runtime.consoleAPICalled'], + onEvent: vi.fn(), + }); + + const outcome = await driver.cdp({ + method: 'Runtime.disable', + timeoutMs: TIMEOUT_MS, + }); + + expect(outcome.ok).toBe(false); + if (!outcome.ok) { + expect(outcome.code).toBe('MM_CDP_BLOCKED'); + expect(outcome.message).toContain('Runtime.disable'); + expect(outcome.message).toContain('Use --fresh'); + } + expect(cdpSession.send).not.toHaveBeenCalledWith( + 'Runtime.disable', + expect.anything(), + ); + await manager.dispose(); + }); + it.each([ 'Browser.close', 'Target.closeTarget', diff --git a/src/platform/playwright-driver.ts b/src/platform/playwright-driver.ts index 071f4230..1f1e3316 100644 --- a/src/platform/playwright-driver.ts +++ b/src/platform/playwright-driver.ts @@ -1,6 +1,10 @@ import type { BrowserContext, Page } from '@playwright/test'; -import { disposeCdpManager, getCdpManager } from './cdp-manager.js'; +import { + CdpDomainInUseError, + disposeCdpManager, + getCdpManager, +} from './cdp-manager.js'; import type { IPlatformDriver, TargetType, @@ -537,6 +541,13 @@ export class PlaywrightPlatformDriver implements IPlatformDriver { ); return { ok: true, result }; } catch (error) { + if (error instanceof CdpDomainInUseError) { + return { + ok: false, + code: ErrorCodes.MM_CDP_BLOCKED, + message: error.message, + }; + } const message = error instanceof Error ? error.message : String(error); return { ok: false, From 34d4b3d1e6b16b92b727fa7e064731dc4fac7650 Mon Sep 17 00:00:00 2001 From: cryptotavares <joao.tavares@consensys.net> Date: Thu, 19 Nov 2026 16:21:19 +0000 Subject: [PATCH 2/3] chore: drop the manual CHANGELOG entry --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af58a1b8..1d7dfde0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- feat: deliver console and network CDP events from every browser page and the Extension service worker to event subscribers, re-attaching after page, session and MV3 worker restarts ([#107](https://github.com/MetaMask/client-mcp-core/pull/107)) - feat: `mm` sees and acts inside iframes on the browser, including cross-origin ones such as the candlestick chart. A page snapshot (`describe_screen`, `accessibility_snapshot` without `rootSelector`, observations) lists the content of up to 5 visible iframes after the page, with refs namespaced by frame (`f1e1`, `f2e1`, ...) and a `path` ending in `iframe:<title>`; these refs act inside their iframe. Each iframe element also gets a ref, usable as `frame`. `describe_screen`, `click`, `type`, `hover`, `wait_for`, `get_text`, `inspect` and `screenshot` take `frame` (`--frame <iframe>`) to work inside one iframe, the way Playwright's `frameLocator` does. `mm screenshot` adds `--selector` ([#99](https://github.com/MetaMask/client-mcp-core/pull/99)) ## [0.14.0] From d8102aa6501d52d316fdbc47de9521da5dbb6de4 Mon Sep 17 00:00:00 2001 From: cryptotavares <joao.tavares@consensys.net> Date: Fri, 20 Nov 2026 13:30:09 +0000 Subject: [PATCH 3/3] fix: let a held <Domain>.enable succeed and bound each subscription attach step Review of #107: - A <Domain>.enable with no params (or the subscription's own params) on a domain an event subscription holds now sends nothing and returns the subscription's enable result, so `mm cdp Network.enable` keeps working once the session event sources hold Network. An enable with other params and a <Domain>.disable stay refused with MM_CDP_BLOCKED, with a message that says why. - Each attach step of a subscription (opening the session, the target info, the worker target list, each <Domain>.enable) and each <Domain>.disable is bounded by CDP_ATTACH_STEP_TIMEOUT_MS (5 s). A timeout goes to onError, the subscriber is released from that target (listeners off, the domain disabled in case the enable lands late), and the subscription stays live on the other targets. unsubscribe waits at most one bound for an attach in progress. - Errors of a subscriber without onError go to the debug log. - Conflicting <Domain>.enable params are reported through onError with the target and the domain; the first subscriber's params stay in effect. - Rename CdpTargetEvent to CdpTargetLifecycleEvent. --- README.md | 2 +- SKILL.md | 2 +- src/platform/cdp-manager.test.ts | 551 ++++++++++++++++++++++++- src/platform/cdp-manager.ts | 441 ++++++++++++++++---- src/platform/playwright-driver.test.ts | 9 + 5 files changed, 904 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 82356077..806402a8 100644 --- a/README.md +++ b/README.md @@ -695,7 +695,7 @@ mm cdp Runtime.evaluate '{"expression":"typeof globalThis.stateHooks","returnByV mm cdp Runtime.evaluate '{"expression":"1+1","returnByValue":true}' --fresh ``` -The `params-json` argument must be a valid JSON object. The `--timeout` flag sets the per-command action timeout (default and max: 30 000 ms); the CLI waits up to 47 s for the default so the daemon can run the command and collect its observation. Browser commands share one persistent CDP session per target (page or service worker), so a domain enabled by one call stays enabled for later calls; the session is dropped and re-attached after the page or service worker restarts. An event subscription owns the domains it enables on a target: while it holds one, a `<Domain>.enable` or `<Domain>.disable` on that target is refused with `MM_CDP_BLOCKED` (send it with `--fresh` to run it on a session of its own). `--fresh` opens a one-shot session for a single command and detaches it afterwards. The tool is categorized as `cdp`: by default it returns no observation and does not refresh refs, so pass `--observe full` (or run `mm describe-screen`) after a call that changes state. +The `params-json` argument must be a valid JSON object. The `--timeout` flag sets the per-command action timeout (default and max: 30 000 ms); the CLI waits up to 47 s for the default so the daemon can run the command and collect its observation. Browser commands share one persistent CDP session per target (page or service worker), so a domain enabled by one call stays enabled for later calls; the session is dropped and re-attached after the page or service worker restarts. An event subscription owns the domains it enables on a target. While it holds one, a `<Domain>.enable` on that target with no params (or the subscription's own params) sends nothing and returns the result of the subscription's enable (`{}` for the standard domains): the domain is already enabled. A `<Domain>.enable` with other params and a `<Domain>.disable` are refused with `MM_CDP_BLOCKED`, because they would change or stop the subscription's events (send them with `--fresh` to run them on a session of their own). `--fresh` opens a one-shot session for a single command and detaches it afterwards. The tool is categorized as `cdp`: by default it returns no observation and does not refresh refs, so pass `--observe full` (or run `mm describe-screen`) after a call that changes state. #### Browser vs Mobile (Hermes) CDP diff --git a/SKILL.md b/SKILL.md index eedba42e..89cdd9dc 100644 --- a/SKILL.md +++ b/SKILL.md @@ -732,7 +732,7 @@ mm cdp Runtime.evaluate '{"expression":"document.querySelector(\'#personalSign\' | Blocked methods | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | `Runtime.terminateExecution`, `Inspector.detached` | `Browser.close`, `Target.closeTarget`, `Target.disposeBrowserContext`, `Browser.crashGpuProcess` | | Result shape | Standard CDP response | `Runtime.evaluate` nests the value at `result.result.value` | `Runtime.evaluate` nests the value at `result.result.value` | -Browser commands share one persistent CDP session per target, so a domain enabled by one call (e.g. `Network.enable`) stays enabled for the next calls on the same target. An event subscription owns the domains it enables on a target: while it holds one, a `<Domain>.enable` or `<Domain>.disable` on that target is refused with `MM_CDP_BLOCKED`. Use `--fresh` for a command that must run on its own session, detached afterwards. After an Extension service-worker restart the stale session is dropped and the next call re-attaches. +Browser commands share one persistent CDP session per target, so a domain enabled by one call (e.g. `Network.enable`) stays enabled for the next calls on the same target. An event subscription owns the domains it enables on a target. While it holds one, `<Domain>.enable` with no params (or the subscription's own params) succeeds without sending anything, since the domain is already enabled, and returns `{}`; `<Domain>.enable` with other params and `<Domain>.disable` are refused with `MM_CDP_BLOCKED`, because they would change or stop the subscription's events. Use `--fresh` for a command that must run on its own session, detached afterwards. After an Extension service-worker restart the stale session is dropped and the next call re-attaches. On mobile, `cdp` and `hermes-targets` use the Metro port the session was launched with (`mm launch --metro-port`), then the `HERMES_METRO_PORT` env var, then 8081. A per-call `--metro-port` / `--app-id` overrides it for that call only. When device-mcp exports `HermesClient` (needs a device-mcp release with MetaMask/device-mcp P2-02) the session keeps one Hermes connection for its Metro port and app id and reuses it across calls; otherwise each call opens its own connection. A mobile failure names the Metro port it used. diff --git a/src/platform/cdp-manager.test.ts b/src/platform/cdp-manager.test.ts index 0b5baf02..45cfccb9 100644 --- a/src/platform/cdp-manager.test.ts +++ b/src/platform/cdp-manager.test.ts @@ -3,6 +3,8 @@ import { describe, it, expect, vi } from 'vitest'; import type { CdpEvent } from './cdp-manager.js'; import { + CDP_ATTACH_STEP_TIMEOUT_MS, + CdpDomainInUseError, CdpManager, DEFAULT_SW_ATTACH_TIMEOUT_MS, STOPPED_WORKER_MESSAGE, @@ -2641,7 +2643,7 @@ describe('CdpManager subscribe', () => { expect(workerCommands(fake, 'session-1')).toContain('Runtime.evaluate'); }); - it('refuses to enable or disable a domain a subscription holds', async () => { + it('refuses to disable a domain a subscription holds', async () => { const page = createEventPage(); const fake = createContext({ pages: [page], targets: [] }); const session = createEventSession('page-1'); @@ -2649,14 +2651,13 @@ describe('CdpManager subscribe', () => { const manager = new CdpManager(fake.context); await manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn() }); - await expect( - manager.send({ kind: 'page', page }, 'Runtime.disable'), - ).rejects.toThrowError( - 'CDP method "Runtime.disable" is refused while an event subscription holds the Runtime domain', + const refusal = manager.send({ kind: 'page', page }, 'Runtime.disable'); + await expect(refusal).rejects.toThrowError( + 'CDP method "Runtime.disable" is refused while an event subscription holds the Runtime domain on this target: it would stop the events the subscription receives. Use --fresh', ); - await expect( - manager.send({ kind: 'page', page }, 'Runtime.enable'), - ).rejects.toThrowError('is refused'); + await expect(refusal).rejects.toBeInstanceOf(CdpDomainInUseError); + await expect(refusal).rejects.toMatchObject({ code: 'MM_CDP_BLOCKED' }); + expect(pageCommands(session)).not.toContain('Runtime.disable'); // A domain no subscription holds is sent. await manager.send({ kind: 'page', page }, 'Network.disable'); expect(pageCommands(session)).toContain('Network.disable'); @@ -2720,3 +2721,537 @@ describe('CdpManager subscribe', () => { expect(fake.emitter.listenerCount('page')).toBe(0); }); }); + +describe('CdpManager send on a held domain', () => { + it('answers a held <Domain>.enable with no or the same params without sending it', async () => { + const page = createEventPage(); + const fake = createContext({ + pages: [page], + swReply: () => ({ result: {} }), + }); + const session = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { maxPostDataSize: 1024, maxTotalBufferSize: 10 } }, + onEvent: vi.fn(), + }); + + expect( + await manager.send({ kind: 'page', page }, 'Network.enable'), + ).toStrictEqual({}); + expect( + await manager.send({ kind: 'page', page }, 'Network.enable', { + maxTotalBufferSize: 10, + maxPostDataSize: 1024, + }), + ).toStrictEqual({}); + expect(await manager.send({ kind: 'sw' }, 'Network.enable')).toStrictEqual( + {}, + ); + + expect( + pageCommands(session).filter((method) => method === 'Network.enable'), + ).toHaveLength(1); + expect( + workerCommands(fake).filter((method) => method === 'Network.enable'), + ).toHaveLength(1); + }); + + it('refuses a held <Domain>.enable with other params', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { maxPostDataSize: 1024 } }, + onEvent: vi.fn(), + }); + + const refusal = manager.send({ kind: 'page', page }, 'Network.enable', { + maxPostDataSize: 1, + }); + + await expect(refusal).rejects.toThrowError( + 'CDP method "Network.enable" is refused while an event subscription holds the Network domain on this target: the domain is already enabled, with parameters this call would change. Send it without parameters (it then succeeds without sending anything). Use --fresh to send it on a one-shot session.', + ); + await expect(refusal).rejects.toMatchObject({ code: 'MM_CDP_BLOCKED' }); + expect( + pageCommands(session).filter((method) => method === 'Network.enable'), + ).toHaveLength(1); + }); + + it('sends a <Domain>.enable once its last subscriber is gone', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + await subscription.unsubscribe(); + + await manager.send({ kind: 'page', page }, 'Runtime.enable'); + await manager.send({ kind: 'page', page }, 'Runtime.disable'); + + expect(pageCommands(session)).toStrictEqual([ + 'Target.getTargetInfo', + 'Runtime.enable', + 'Runtime.disable', + 'Runtime.enable', + 'Runtime.disable', + ]); + }); + + it('fails a held <Domain>.enable the same way the subscription enable failed', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + let rejectEnable!: (error: Error) => void; + const session = createEventSession('page-1', (method) => + method === 'Runtime.enable' + ? new Promise((_resolve, reject) => { + rejectEnable = reject; + }) + : {}, + ); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const subscribing = manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + onError: vi.fn(), + }); + await flush(); + + const enabling = manager.send({ kind: 'page', page }, 'Runtime.enable'); + rejectEnable(new Error('Runtime.enable failed')); + + await expect(enabling).rejects.toThrowError('Runtime.enable failed'); + await subscribing; + }); +}); + +describe('CdpManager subscribe bounds each attach step', () => { + /** + * Tracks whether a promise settled. + * + * @param promise - The promise. + * @returns Read `settled` later. + */ + function track(promise: Promise<unknown>): { settled: boolean } { + const state = { settled: false }; + promise + .catch(() => undefined) + .finally(() => { + state.settled = true; + }) + .catch(() => undefined); + return state; + } + + /** + * Answers a method with a promise that never settles. + * + * @param stuck - The method that never answers. + * @returns A send implementation. + */ + function never(stuck: string) { + return (method: string): unknown => + method === stuck ? new Promise(() => undefined) : {}; + } + + it('reports a page whose Runtime.enable never answers and keeps the other targets', async () => { + vi.useFakeTimers(); + try { + const stuckPage = createEventPage(`https://dapp.test/a?token=secret`); + const goodPage = createEventPage(`${EXTENSION_URL}b.html`); + const fake = createContext({ pages: [stuckPage, goodPage] }); + const stuck = createEventSession('stuck', never('Runtime.enable')); + const good = createEventSession('good'); + fake.newCDPSession.mockImplementation(async (page: Page) => + page === stuckPage ? stuck : good, + ); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const onEvent = vi.fn(); + const subscribing = manager.subscribe({ + events: LOG_EVENTS, + onEvent, + onError, + }); + const state = track(subscribing); + + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS - 1); + expect(state.settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(state.settled).toBe(true); + const subscription = await subscribing; + + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ + message: `Runtime.enable on page https://dapp.test/a timed out after ${CDP_ATTACH_STEP_TIMEOUT_MS}ms`, + }), + ); + // No half-attached state: the stuck page has no listener left, and + // its domain is disabled in case the enable lands late. + expect(stuck.emitter.listenerCount('Runtime.consoleAPICalled')).toBe(0); + expect(pageCommands(stuck)).toContain('Runtime.disable'); + good.emitter.emit('Runtime.consoleAPICalled', {}); + emitWorkerEvent(fake, 'Runtime.exceptionThrown', {}); + expect(onEvent).toHaveBeenCalledTimes(2); + + // Nothing is left on the session: a later subscriber enables the + // domain on it again. + stuck.send.mockImplementation(async (method: string) => + method === 'Target.getTargetInfo' + ? { targetInfo: { targetId: 'stuck' } } + : {}, + ); + const later = vi.fn(); + await manager.subscribe({ events: LOG_EVENTS, onEvent: later }); + stuck.emitter.emit('Runtime.consoleAPICalled', {}); + expect(later).toHaveBeenCalledTimes(1); + expect( + pageCommands(stuck).filter((method) => method === 'Runtime.enable'), + ).toHaveLength(2); + + const unsubscribing = track(subscription.unsubscribe()); + await vi.advanceTimersByTimeAsync(0); + expect(unsubscribing.settled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it('reports a page whose Target.getTargetInfo never answers', async () => { + vi.useFakeTimers(); + try { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1'); + session.send.mockImplementation(async (method: string) => + never('Target.getTargetInfo')(method), + ); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const state = track( + manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }), + ); + + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS); + + expect(state.settled).toBe(true); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ + message: `Target.getTargetInfo on page ${PAGE_URL} timed out after ${CDP_ATTACH_STEP_TIMEOUT_MS}ms`, + }), + ); + expect(pageCommands(session)).toStrictEqual(['Target.getTargetInfo']); + expect(session.emitter.listenerCount('Runtime.consoleAPICalled')).toBe(0); + } finally { + vi.useRealTimers(); + } + }); + + it('drops a page whose session never opens and detaches it if it opens late', async () => { + vi.useFakeTimers(); + try { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const late = createEventSession('page-1'); + let resolveSession!: (session: EventSession) => void; + fake.newCDPSession.mockReturnValueOnce( + new Promise<EventSession>((resolve) => { + resolveSession = resolve; + }), + ); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const state = track( + manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }), + ); + + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS); + expect(state.settled).toBe(true); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ + message: `Opening a CDP session on page ${PAGE_URL} timed out after ${CDP_ATTACH_STEP_TIMEOUT_MS}ms`, + }), + ); + + resolveSession(late); + await vi.advanceTimersByTimeAsync(0); + expect(late.detach).toHaveBeenCalledTimes(1); + expect(pageCommands(late)).toStrictEqual([]); + } finally { + vi.useRealTimers(); + } + }); + + it('reports a worker whose enable never answers', async () => { + vi.useFakeTimers(); + try { + const fake = createContext({ pages: [] }); + const tunnel = fake.browserSession.send.getMockImplementation(); + fake.browserSession.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => { + if ( + method === 'Target.sendMessageToTarget' && + String(params?.message).includes('"Runtime.enable"') + ) { + return {}; + } + return tunnel?.(method, params); + }, + ); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const state = track( + manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }), + ); + + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS); + + expect(state.settled).toBe(true); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ + message: `Runtime.enable on the Extension service worker (target ${TARGET_ID}) timed out after ${CDP_ATTACH_STEP_TIMEOUT_MS}ms`, + }), + ); + } finally { + vi.useRealTimers(); + } + }); + + it('reports a worker target list that never answers', async () => { + vi.useFakeTimers(); + try { + const fake = createContext({ pages: [] }); + const original = fake.browserSession.send.getMockImplementation(); + fake.browserSession.send.mockImplementation( + async (method: string, params?: Record<string, unknown>) => + method === 'Target.getTargets' + ? new Promise(() => undefined) + : original?.(method, params), + ); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const state = track( + manager.subscribe({ events: LOG_EVENTS, onEvent: vi.fn(), onError }), + ); + + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS); + + expect(state.settled).toBe(true); + expect(onError).toHaveBeenCalledWith( + expect.objectContaining({ + message: `Listing the Extension service worker targets timed out after ${CDP_ATTACH_STEP_TIMEOUT_MS}ms`, + }), + ); + } finally { + vi.useRealTimers(); + } + }); + + it('does not wait on unsubscribe for an enable that never answers', async () => { + vi.useFakeTimers(); + try { + const page = createEventPage(); + const fake = createContext({ pages: [], targets: [] }); + const manager = new CdpManager(fake.context); + const onError = vi.fn(); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + onError, + }); + const session = createEventSession( + 'page-1', + async () => new Promise(() => undefined), + ); + fake.newCDPSession.mockResolvedValueOnce(session); + fake.emitter.emit('page', page); + await vi.advanceTimersByTimeAsync(0); + expect(pageCommands(session)).toContain('Runtime.enable'); + + const state = track(subscription.unsubscribe()); + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS - 1); + expect(state.settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(state.settled).toBe(true); + + expect(session.emitter.listenerCount('Runtime.consoleAPICalled')).toBe(0); + // The enable may still land: the domain is disabled, once. + expect( + pageCommands(session).filter((method) => method === 'Runtime.disable'), + ).toHaveLength(1); + // An ended subscription hears nothing. + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS); + expect(onError).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it('bounds each disable on unsubscribe', async () => { + vi.useFakeTimers(); + try { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1', (method) => + method === 'Runtime.disable' ? new Promise(() => undefined) : {}, + ); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + const subscription = await manager.subscribe({ + events: LOG_EVENTS, + onEvent: vi.fn(), + }); + + const state = track(subscription.unsubscribe()); + await vi.advanceTimersByTimeAsync(CDP_ATTACH_STEP_TIMEOUT_MS - 1); + expect(state.settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + + expect(state.settled).toBe(true); + expect(pageCommands(session)).toContain('Runtime.disable'); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('CdpManager subscribe enable parameters', () => { + it('reports conflicting enable params with the target and the domain', async () => { + const page = createEventPage('https://dapp.test/x?apiKey=k'); + const fake = createContext({ pages: [page] }); + const session = createEventSession('page-1'); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new CdpManager(fake.context); + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { maxPostDataSize: 1024 } }, + onEvent: vi.fn(), + }); + const onError = vi.fn(); + const onEvent = vi.fn(); + + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { maxPostDataSize: 65536 } }, + onEvent, + onError, + }); + + expect(onError.mock.calls.map(([error]) => error.message)).toStrictEqual([ + 'Network.enable parameters {"maxPostDataSize":65536} were not applied on page https://dapp.test/x: another subscription enabled Network there with {"maxPostDataSize":1024}, which stay in effect.', + `Network.enable parameters {"maxPostDataSize":65536} were not applied on the Extension service worker (target ${TARGET_ID}): another subscription enabled Network there with {"maxPostDataSize":1024}, which stay in effect.`, + ]); + // The subscription still receives the events. + session.emitter.emit('Network.requestWillBeSent', {}); + expect(onEvent).toHaveBeenCalledTimes(1); + expect( + pageCommands(session).filter((method) => method === 'Network.enable'), + ).toHaveLength(1); + }); + + it('accepts no params or the same params in another key order', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + fake.newCDPSession.mockResolvedValueOnce(createEventSession('page-1')); + const manager = new CdpManager(fake.context); + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { maxPostDataSize: 1, maxTotalBufferSize: 2 } }, + onEvent: vi.fn(), + }); + const onError = vi.fn(); + + await manager.subscribe({ events: NET_EVENTS, onEvent: vi.fn(), onError }); + await manager.subscribe({ + events: NET_EVENTS, + enable: { + Network: { + maxTotalBufferSize: 2, + maxPostDataSize: 1, + unset: undefined, + }, + }, + onEvent: vi.fn(), + onError, + }); + + expect(onError).not.toHaveBeenCalled(); + }); + + it('reports a conflict about nested and list params', async () => { + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + fake.newCDPSession.mockResolvedValueOnce(createEventSession('page-1')); + const manager = new CdpManager(fake.context); + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { list: [1, { a: null }] } }, + onEvent: vi.fn(), + }); + const onError = vi.fn(); + + await manager.subscribe({ + events: NET_EVENTS, + enable: { Network: { list: [1, { a: 2 }] } }, + onEvent: vi.fn(), + onError, + }); + + expect(onError).toHaveBeenCalledWith( + new Error( + `Network.enable parameters {"list":[1,{"a":2}]} were not applied on page ${PAGE_URL}: another subscription enabled Network there with {"list":[1,{"a":null}]}, which stay in effect.`, + ), + ); + }); +}); + +describe('CdpManager subscribe without onError', () => { + it('writes errors to the debug log instead', async () => { + vi.resetModules(); + vi.stubEnv('DEBUG', 'true'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + const fresh = await import('./cdp-manager.js'); + const page = createEventPage(); + const fake = createContext({ pages: [page], targets: [] }); + const session = createEventSession('page-1', (method) => { + if (method === 'Runtime.enable') { + throw new Error('Runtime.enable failed'); + } + return {}; + }); + fake.newCDPSession.mockResolvedValueOnce(session); + const manager = new fresh.CdpManager(fake.context); + + await manager.subscribe({ + events: LOG_EVENTS, + onEvent: () => { + throw new Error('onEvent failed'); + }, + }); + session.emitter.emit('Runtime.consoleAPICalled', {}); + + expect(warn.mock.calls).toStrictEqual([ + ['[Server:cdp-manager.subscribe] Runtime.enable failed'], + ['[Server:cdp-manager.subscribe] onEvent failed'], + ]); + } finally { + warn.mockRestore(); + vi.unstubAllEnvs(); + vi.resetModules(); + } + }); +}); diff --git a/src/platform/cdp-manager.ts b/src/platform/cdp-manager.ts index 03be3b67..def59fea 100644 --- a/src/platform/cdp-manager.ts +++ b/src/platform/cdp-manager.ts @@ -6,6 +6,7 @@ import type { } from '@playwright/test'; import { ErrorCodes } from '../tools/types/errors.js'; +import { debugWarn } from '../utils/logger.js'; /** * Target kinds a {@link CdpManager} can attach to. A string union so more @@ -39,7 +40,7 @@ export type CdpSession = { /** * Payload of the `targetAttached` and `targetDetached` events. */ -export type CdpTargetEvent = { +export type CdpTargetLifecycleEvent = { kind: CdpTargetKind; /** * The page of a page target, or the worker of a service worker target when @@ -83,7 +84,7 @@ export type CdpManagerEvent = 'targetAttached' | 'targetDetached'; /** * Listener of a {@link CdpManagerEvent}. */ -export type CdpManagerListener = (event: CdpTargetEvent) => void; +export type CdpManagerListener = (event: CdpTargetLifecycleEvent) => void; /** * The target a CDP event came from. @@ -130,14 +131,19 @@ export type CdpSubscribeOptions = { /** * Parameters of `<Domain>.enable`, by domain, for example * `{ Network: { maxPostDataSize: 65536 } }`. The first subscriber to enable - * a domain on a target sets them. + * a domain on a target sets them. Parameters are not merged: a later + * subscriber that passes other parameters for a domain already enabled on + * a target gets the first subscriber's, and an error through `onError` + * that names the target and the domain. */ enable?: Readonly<Record<string, Record<string, unknown>>>; /** Called synchronously for each event, in the order of its target. */ onEvent: (event: CdpEvent) => void; /** - * Called when a target cannot be attached or enabled, or when `onEvent` - * throws. Errors are dropped when it is missing. + * Called when a target cannot be attached or enabled in time, when the + * `enable` parameters conflict with another subscriber's, or when + * `onEvent` throws. Without it, errors go to the debug log + * (`DEBUG=true`). It must not throw; an error it throws is ignored. */ onError?: (error: Error) => void; }; @@ -166,6 +172,16 @@ export const STOPPED_WORKER_WAIT_MS = 2_000; /** How often to poll the browser target list while waiting for a worker. */ export const SW_TARGET_POLL_MS = 200; +/** + * How long each step of attaching a subscription to a target may take: + * opening the target's session, reading its target info, and each + * `<Domain>.enable`. The same bound applies to each `<Domain>.disable` and to + * the wait for an attach in progress when a subscription ends. A target that + * does not answer (paused in the debugger, frozen) then costs one bound, not + * a hang. + */ +export const CDP_ATTACH_STEP_TIMEOUT_MS = 5_000; + /** * Error for a CDP command that needs the Extension service worker while it is * not running. @@ -175,11 +191,11 @@ export const STOPPED_WORKER_MESSAGE = 'Interact with the Extension (open or reload an Extension page) to start it, then retry.'; /** - * Error for a `<Domain>.enable` or `<Domain>.disable` refused while an event - * subscription holds that domain on the same target. A subscription owns the - * domains it enabled: disabling one would silently stop the events, and a - * second enable would not be counted, so its last unsubscribe would disable a - * domain the user asked for. + * Error for a `<Domain>.disable`, or a `<Domain>.enable` with other + * parameters, refused while an event subscription holds that domain on the + * same target. A subscription owns the domains it enabled: disabling one + * would silently stop the events, and an enable with other parameters would + * change them (Chrome applies the last `Network.enable`), or be ignored. */ export class CdpDomainInUseError extends Error { /** The `MM_CDP_BLOCKED` tool error code. */ @@ -190,15 +206,69 @@ export class CdpDomainInUseError extends Error { * @param domain - The CDP domain that a subscription holds. */ constructor(method: string, domain: string) { + const reason = method.endsWith('.disable') + ? 'it would stop the events the subscription receives.' + : 'the domain is already enabled, with parameters this call would ' + + 'change. Send it without parameters (it then succeeds without ' + + 'sending anything).'; super( `CDP method "${method}" is refused while an event subscription holds the ` + - `${domain} domain on this target: it would change the events the ` + - 'subscription receives. Use --fresh to send it on a one-shot session.', + `${domain} domain on this target: ${reason} Use --fresh to send it on ` + + 'a one-shot session.', ); this.name = 'CdpDomainInUseError'; } } +/** + * Error of a CDP step that did not finish in time. + */ +class CdpTimeoutError extends Error { + /** + * @param message - What timed out. + */ + constructor(message: string) { + super(message); + this.name = 'CdpTimeoutError'; + } +} + +/** + * Serializes CDP parameters with sorted object keys, so equal parameters + * compare equal whatever their key order. + * + * @param value - The parameters. + * @returns A stable JSON text. + */ +function stableJson(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(stableJson).join(',')}]`; + } + if (value !== null && typeof value === 'object') { + const entries = Object.entries(value as Record<string, unknown>) + .filter(([, item]) => item !== undefined) + .sort(([left], [right]) => (left < right ? -1 : 1)); + return `{${entries + .map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`) + .join(',')}}`; + } + return JSON.stringify(value) ?? 'null'; +} + +/** + * Tells whether two sets of `<Domain>.enable` parameters are the same. + * + * @param left - The first parameters. + * @param right - The second parameters. + * @returns True when they are equal. + */ +function sameParams( + left: Record<string, unknown>, + right: Record<string, unknown>, +): boolean { + return stableJson(left) === stableJson(right); +} + const EXTENSION_URL = /^chrome-extension:\/\/([a-z]{32})\//u; /** @@ -533,7 +603,7 @@ class ServiceWorkerCdpSession implements EventCdpSession { } type CdpEntryBase = { - event: CdpTargetEvent; + event: CdpTargetLifecycleEvent; session?: EventCdpSession; opening?: Promise<EventCdpSession>; /** Set when the entry is dropped, so an in-flight open does not revive it. */ @@ -599,7 +669,17 @@ type SessionSubscriptionState = { string, { listener: CdpEventListener; subscriptions: Set<Subscription> } >; - domains: Map<string, { count: number; enabled: Promise<void> }>; + domains: Map<string, HeldDomain>; +}; + +/** A domain that subscribers hold enabled on one session. */ +type HeldDomain = { + /** Subscribers holding it. */ + count: number; + /** The bounded `<Domain>.enable`, settled with its CDP result. */ + enabled: Promise<unknown>; + /** The parameters of that enable (the first subscriber's). */ + params: Record<string, unknown>; }; /** @@ -630,6 +710,39 @@ function toError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } +/** + * Waits for a promise to settle, at most for a time. + * + * @param promise - The promise. It must not reject. + * @param timeoutMs - The longest wait. + */ +async function settleWithin( + promise: Promise<void>, + timeoutMs: number, +): Promise<void> { + let timer: ReturnType<typeof setTimeout> | undefined; + await Promise.race([ + promise, + new Promise<void>((resolve) => { + timer = setTimeout(resolve, timeoutMs); + }), + ]).finally(() => clearTimeout(timer)); +} + +/** + * Names a target in an error message. A page is named by its URL without + * the query and the fragment, which can hold tokens. + * + * @param entry - The target entry. + * @returns The target name. + */ +function describeEntry(entry: CdpEntry): string { + if (!('page' in entry)) { + return `the Extension service worker (target ${entry.targetId})`; + } + return `page ${entry.page.url().split(/[?#]/u)[0]}`; +} + /** * Tells whether a target is gone: its page is closed, or its entry was * dropped after the target went away. @@ -730,11 +843,14 @@ export class CdpManager { * A command that may have reached the target is never re-sent. Only a * failure to open the session is retried once. * - * A `<Domain>.enable` or `<Domain>.disable` is refused with - * {@link CdpDomainInUseError} while a subscription holds that domain on - * the target (see {@link subscribe}): the subscription enabled the domain - * and would disable it on its last unsubscribe. `fresh` commands are not - * refused, because they run on a session of their own. + * While a subscription holds a domain on the target (see + * {@link subscribe}), a `<Domain>.enable` with no parameters, or with the + * parameters the subscription enabled it with, sends nothing: the domain + * is already enabled, and the call returns the result of the + * subscription's enable. A `<Domain>.enable` with other parameters and a + * `<Domain>.disable` are refused with {@link CdpDomainInUseError}: they + * would change or stop the subscription's events. `fresh` commands are + * never refused or skipped, because they run on a session of their own. * * @param target - The page, or the extension service worker. * @param method - The CDP method. @@ -764,11 +880,11 @@ export class CdpManager { acquired = await this.#acquireSession(target, options); } - this.#assertDomainFree(acquired.session, method); + const held = this.#heldDomainEnable(acquired.session, method, params); try { return await this.#race( - acquired.session.send(method, params), - method, + held ?? acquired.session.send(method, params), + `CDP call "${method}"`, options, ); } catch (error) { @@ -780,23 +896,39 @@ export class CdpManager { } /** - * Refuses a `<Domain>.enable` or `<Domain>.disable` while a subscription - * holds that domain on the session. + * Checks a `<Domain>.enable` or `<Domain>.disable` against the domains + * that subscriptions hold on the session. * * @param session - The session the command would run on. * @param method - The CDP method. + * @param params - The CDP method parameters. + * @returns The subscription's enable, when the command is a held + * `<Domain>.enable` with no or the same parameters (nothing is sent); + * undefined when the command must be sent. + * @throws {CdpDomainInUseError} For a held `<Domain>.disable`, or a held + * `<Domain>.enable` with other parameters. */ - #assertDomainFree(session: EventCdpSession, method: string): void { - const match = /^([^.]+)\.(?:enable|disable)$/u.exec(method); - const domain = match?.[1]; + #heldDomainEnable( + session: EventCdpSession, + method: string, + params: Record<string, unknown>, + ): Promise<unknown> | undefined { + const match = /^(?<domain>[^.]+)\.(?<action>enable|disable)$/u.exec(method); + const { domain, action } = match?.groups ?? {}; if (domain === undefined) { - return; + return undefined; + } + const held = this.#sessionStates.get(session)?.domains.get(domain); + if (held === undefined || held.count === 0) { + return undefined; } if ( - (this.#sessionStates.get(session)?.domains.get(domain)?.count ?? 0) > 0 + action === 'enable' && + (Object.keys(params).length === 0 || sameParams(params, held.params)) ) { - throw new CdpDomainInUseError(method, domain); + return held.enabled; } + throw new CdpDomainInUseError(method, domain); } /** @@ -1035,9 +1167,9 @@ export class CdpManager { this.#pageAttachFailures.delete(page); } try { - const { entry, session } = await this.#acquireSession( - { kind: 'page', page }, - {}, + const entry = this.#pageEntry(page); + const session = await this.#openForSubscribers(entry, async () => + this.#openPageSession(page), ); await Promise.all( subscriptions.map(async (subscription) => @@ -1067,12 +1199,19 @@ export class CdpManager { subscriptions: Subscription[], ): Promise<void> { try { - await this.#watchTargets(); - if (this.#disposed) { + const listed = await this.#race( + (async (): Promise<ServiceWorkerTarget[] | undefined> => { + await this.#watchTargets(); + return this.#disposed ? undefined : this.#serviceWorkerTargets(); + })(), + 'Listing the Extension service worker targets', + { timeoutMs: CDP_ATTACH_STEP_TIMEOUT_MS }, + ); + if (listed === undefined || this.#disposed) { return; } const knownExtensionId = this.#extensionId(); - const targets = (await this.#serviceWorkerTargets()).filter( + const targets = (listed as ServiceWorkerTarget[]).filter( (candidate) => knownExtensionId === undefined || candidate.extensionId === knownExtensionId, @@ -1188,7 +1327,7 @@ export class CdpManager { return; } const entry = this.#workerEntryFor(target); - const session = await this.#openEntry(entry, async () => + const session = await this.#openForSubscribers(entry, async () => this.#openWorkerSession(entry.targetId, () => this.#drop(entry)), ); await Promise.all( @@ -1198,6 +1337,34 @@ export class CdpManager { ); } + /** + * Opens (or reuses) the session of a target for subscribers, bounded by + * {@link CDP_ATTACH_STEP_TIMEOUT_MS}. On a timeout the entry is dropped: a + * session that opens later is detached, and a later attach trigger opens + * a new one. + * + * @param entry - The target entry. + * @param open - Opens a new session for the entry's target. + * @returns The session. + */ + async #openForSubscribers( + entry: CdpEntry, + open: () => Promise<EventCdpSession>, + ): Promise<EventCdpSession> { + try { + return await this.#bound( + this.#openEntry(entry, open), + 'Opening a CDP session', + entry, + ); + } catch (error) { + if (error instanceof CdpTimeoutError) { + this.#drop(entry); + } + throw error; + } + } + /** * Adds a subscriber to a session once: listens for its events and enables * its domains, sharing both with the other subscribers of the session. @@ -1234,6 +1401,14 @@ export class CdpManager { * Registers the event listeners and domain enables of one subscriber on a * session. * + * Each step (the target info, each `<Domain>.enable`) is bounded by + * {@link CDP_ATTACH_STEP_TIMEOUT_MS}. A step that times out is reported, + * and the subscriber is removed from this session again (its listeners and + * domains are released) so a later attach trigger can retry it; the + * subscription stays live on its other targets. Another enable failure is + * a definite answer: it is reported, and the subscriber keeps its other + * domains on the session. + * * @param subscription - The subscriber. * @param entry - The target entry of the session. * @param session - The session. @@ -1292,18 +1467,32 @@ export class CdpManager { const results = await Promise.allSettled( subscription.domains.map(async (domain) => - this.#enableDomain(subscription, session, state, record, domain), + this.#enableDomain(subscription, entry, session, state, record, domain), ), ); - for (const result of results) { - if (result.status === 'rejected') { - this.#reportAttachError( - [subscription], - result.reason, - isTargetGone(entry), - entry, - ); + const timedOut: string[] = []; + results.forEach((result, index) => { + if (result.status === 'fulfilled') { + return; } + if (result.reason instanceof CdpTimeoutError) { + timedOut.push(subscription.domains[index]); + } + this.#reportAttachError( + [subscription], + result.reason, + isTargetGone(entry), + entry, + ); + }); + if (timedOut.length > 0) { + if (subscription.records.get(session) === record) { + subscription.records.delete(session); + // Not awaited: the target is slow. Never rejects. + // eslint-disable-next-line no-void + void this.#release(subscription, session, record, timedOut); + } + return; } if ( results.every((result) => result.status === 'fulfilled') && @@ -1316,9 +1505,12 @@ export class CdpManager { /** * Enables a domain on a session for one subscriber. The first subscriber - * sends `<Domain>.enable`; later ones share it. + * sends `<Domain>.enable`, bounded by {@link CDP_ATTACH_STEP_TIMEOUT_MS}; + * later ones share it. A later subscriber that asks for other parameters + * gets the first ones, and an error through `onError`. * * @param subscription - The subscriber. + * @param entry - The target entry of the session. * @param session - The session. * @param state - The session's shared subscription state. * @param record - Where to note the enabled domain. @@ -1326,31 +1518,52 @@ export class CdpManager { */ async #enableDomain( subscription: Subscription, + entry: CdpEntry, session: EventCdpSession, state: SessionSubscriptionState, record: SubscriptionRecord, domain: string, ): Promise<void> { - let enabled = state.domains.get(domain); - if (!enabled) { - enabled = { + const params = subscription.options.enable?.[domain] ?? {}; + let held = state.domains.get(domain); + if (held) { + if (Object.keys(params).length > 0 && !sameParams(params, held.params)) { + this.#report( + [subscription], + new Error( + `${domain}.enable parameters ${stableJson(params)} were not ` + + `applied on ${describeEntry(entry)}: another subscription ` + + `enabled ${domain} there with ${stableJson(held.params)}, ` + + 'which stay in effect.', + ), + ); + } + } else { + held = { count: 0, - enabled: session - .send(`${domain}.enable`, subscription.options.enable?.[domain] ?? {}) - .then(() => undefined), + enabled: this.#bound( + session.send(`${domain}.enable`, params), + `${domain}.enable`, + entry, + ), + params, }; - state.domains.set(domain, enabled); + state.domains.set(domain, held); } - enabled.count += 1; + held.count += 1; record.domains.push(domain); try { - await enabled.enabled; + await held.enabled; } catch (error) { - record.domains.splice(record.domains.indexOf(domain), 1); - enabled.count -= 1; - if (enabled.count === 0) { - // Let a later attach try again. - state.domains.delete(domain); + const index = record.domains.indexOf(domain); + // The record may have been released meanwhile (unsubscribe). + if (index !== -1) { + record.domains.splice(index, 1); + held.count -= 1; + if (held.count === 0 && state.domains.get(domain) === held) { + // Let a later attach try again. + state.domains.delete(domain); + } } throw error; } @@ -1393,13 +1606,15 @@ export class CdpManager { return () => target; } if (state.targetId === undefined) { - const lookup = session - .send('Target.getTargetInfo', {}) - .then( - (result) => - (result as { targetInfo?: { targetId?: string } } | undefined) - ?.targetInfo?.targetId ?? '', - ); + const lookup = this.#bound( + session.send('Target.getTargetInfo', {}), + 'Target.getTargetInfo', + entry, + ).then( + (result) => + (result as { targetInfo?: { targetId?: string } } | undefined) + ?.targetInfo?.targetId ?? '', + ); state.targetId = lookup; // A failed lookup is not the target's ID: let a later attach retry. lookup.catch(() => { @@ -1415,24 +1630,31 @@ export class CdpManager { /** * Removes one subscriber from a session, and disables the domains that no - * other subscriber needs. + * other subscriber needs. Each disable is bounded by + * {@link CDP_ATTACH_STEP_TIMEOUT_MS} and its failure is ignored. * * @param subscription - The subscriber. * @param session - The session. * @param record - What the subscriber added to the session. + * @param timedOut - Domains whose enable timed out: the enable may still + * land, so each one no subscriber holds is disabled too. */ async #release( subscription: Subscription, session: EventCdpSession, record: SubscriptionRecord, + timedOut: readonly string[] = [], ): Promise<void> { const state = this.#sessionStates.get(session); + const { methods, domains } = record; + record.methods = []; + record.domains = []; if (!state) { // The session was detached while attaching; its listeners and domains // went with it. return; } - for (const method of record.methods) { + for (const method of methods) { const handler = state.methods.get(method); handler?.subscriptions.delete(subscription); if (handler?.subscriptions.size === 0) { @@ -1440,24 +1662,33 @@ export class CdpManager { state.methods.delete(method); } } - const disables: Promise<unknown>[] = []; - for (const domain of record.domains) { - const enabled = state.domains.get(domain); - if (enabled) { - enabled.count -= 1; - if (enabled.count === 0) { + const disable = new Set<string>( + timedOut.filter((domain) => !state.domains.has(domain)), + ); + for (const domain of domains) { + const held = state.domains.get(domain); + if (held) { + held.count -= 1; + if (held.count === 0) { state.domains.delete(domain); - disables.push( - session.send(`${domain}.disable`, {}).catch(() => undefined), - ); + disable.add(domain); } } } - await Promise.all(disables); + await Promise.all( + [...disable].map(async (domain) => + this.#race( + session.send(`${domain}.disable`, {}), + `CDP call "${domain}.disable"`, + { timeoutMs: CDP_ATTACH_STEP_TIMEOUT_MS }, + ).catch(() => undefined), + ), + ); } /** - * Ends a subscription. Idempotent. + * Ends a subscription. Idempotent. Waits for an attach in progress at + * most {@link CDP_ATTACH_STEP_TIMEOUT_MS} per target before releasing it. * * @param subscription - The subscription. */ @@ -1474,7 +1705,7 @@ export class CdpManager { const records = [...subscription.records]; await Promise.all( records.map(async ([session, record]) => { - await record.ready; + await settleWithin(record.ready, CDP_ATTACH_STEP_TIMEOUT_MS); subscription.records.delete(session); await this.#release(subscription, session, record); }), @@ -1499,7 +1730,8 @@ export class CdpManager { } /** - * Reports an error to subscribers that have `onError`. + * Reports an error to subscribers: to their `onError`, or to the debug + * log for a subscriber without one. Never throws. * * @param subscriptions - The subscribers. * @param error - The error. @@ -1509,8 +1741,13 @@ export class CdpManager { if (!subscription.active) { continue; } + const { onError } = subscription.options; + if (onError === undefined) { + debugWarn('cdp-manager.subscribe', error); + continue; + } try { - subscription.options.onError?.(toError(error)); + onError(toError(error)); } catch { // A failing error handler must not break the other subscribers. } @@ -1912,7 +2149,11 @@ export class CdpManager { target.kind === 'page' ? await this.#openPageSession(target.page) : await this.#openFreshWorkerSession(options); - return await this.#race(session.send(method, params), method, options); + return await this.#race( + session.send(method, params), + `CDP call "${method}"`, + options, + ); } finally { await session?.detach().catch(() => undefined); } @@ -1934,17 +2175,37 @@ export class CdpManager { return this.#openWorkerSession(target.targetId, () => undefined); } + /** + * Bounds one step of attaching a subscription to a target (or of ending + * it) by {@link CDP_ATTACH_STEP_TIMEOUT_MS}. + * + * @param operation - The step. + * @param what - What the step does, used in the timeout error. + * @param entry - The target, named in the timeout error. + * @returns The step result. + */ + async #bound<Result>( + operation: Promise<Result>, + what: string, + entry: CdpEntry, + ): Promise<Result> { + return this.#race(operation, `${what} on ${describeEntry(entry)}`, { + timeoutMs: CDP_ATTACH_STEP_TIMEOUT_MS, + }) as Promise<Result>; + } + /** * Races an operation against the timeout and the abort signal. * * @param operation - The CDP send. - * @param method - The method name, used in the timeout error. + * @param label - What the operation does, used in the timeout error, for + * example `CDP call "Runtime.evaluate"`. * @param options - Timeout and abort signal. * @returns The operation result. */ async #race( operation: Promise<unknown>, - method: string, + label: string, options: CdpAttachOptions, ): Promise<unknown> { const { timeoutMs, signal } = options; @@ -1961,9 +2222,7 @@ export class CdpManager { timer = setTimeout( () => reject( - new Error( - `CDP call "${method}" timed out after ${timeoutMs}ms`, - ), + new CdpTimeoutError(`${label} timed out after ${timeoutMs}ms`), ), timeoutMs, ); @@ -2056,7 +2315,7 @@ export class CdpManager { * @param event - The event name. * @param payload - The target payload. */ - #emit(event: CdpManagerEvent, payload: CdpTargetEvent): void { + #emit(event: CdpManagerEvent, payload: CdpTargetLifecycleEvent): void { for (const listener of this.#listeners.get(event) ?? []) { listener(payload); } diff --git a/src/platform/playwright-driver.test.ts b/src/platform/playwright-driver.test.ts index 1235350d..63c9c18a 100644 --- a/src/platform/playwright-driver.test.ts +++ b/src/platform/playwright-driver.test.ts @@ -1042,6 +1042,15 @@ describe('PlaywrightPlatformDriver', () => { 'Runtime.disable', expect.anything(), ); + // A held enable with no params succeeds without being sent again. + expect( + await driver.cdp({ method: 'Runtime.enable', timeoutMs: TIMEOUT_MS }), + ).toStrictEqual({ ok: true, result: {} }); + expect( + cdpSession.send.mock.calls.filter( + ([method]) => method === 'Runtime.enable', + ), + ).toHaveLength(1); await manager.dispose(); });