From 149aba6c61451be5fe649bfe40fbad2a59a9ab05 Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Thu, 26 Nov 2026 12:19:08 +0000 Subject: [PATCH] Require session ID on inspector proxy device messages --- .../src/__tests__/InspectorDeviceUtils.js | 20 ++++- .../InspectorProxyReactNativeReloads-test.js | 82 +++++++++---------- .../src/inspector-proxy/Device.js | 74 ++++------------- .../src/inspector-proxy/__docs__/README.md | 13 ++- .../src/inspector-proxy/types.js | 6 +- 5 files changed, 83 insertions(+), 112 deletions(-) diff --git a/packages/dev-middleware/src/__tests__/InspectorDeviceUtils.js b/packages/dev-middleware/src/__tests__/InspectorDeviceUtils.js index 41b7cdd59dc6..d96c24c0e7a5 100644 --- a/packages/dev-middleware/src/__tests__/InspectorDeviceUtils.js +++ b/packages/dev-middleware/src/__tests__/InspectorDeviceUtils.js @@ -25,6 +25,7 @@ import WebSocket from 'ws'; export class DeviceAgent { #ws: ?WebSocket; #readyPromise: Promise; + #lastSessionIdByPageId: Map = new Map(); constructor(url: string, signal?: AbortSignal, host?: ?string) { const ws = new WebSocket(url, { @@ -40,7 +41,14 @@ export class DeviceAgent { }); this.#ws = ws; ws.on('message', data => { - this.__handle(JSON.parse(data.toString())); + const message: MessageToDevice = JSON.parse(data.toString()); + if (message.event === 'connect') { + this.#lastSessionIdByPageId.set( + message.payload.pageId, + message.payload.sessionId, + ); + } + this.__handle(message); }); if (signal != null) { signal.addEventListener('abort', () => { @@ -80,12 +88,20 @@ export class DeviceAgent { this.#ws = null; } - sendWrappedEvent(pageId: string, event: JSONSerializable) { + sendWrappedEvent( + pageId: string, + event: JSONSerializable, + sessionId: string = nullthrows( + this.#lastSessionIdByPageId.get(pageId), + `No session connected to page ${pageId}`, + ), + ) { this.send({ event: 'wrappedEvent', payload: { pageId, wrappedEvent: JSON.stringify(event), + sessionId, }, }); } diff --git a/packages/dev-middleware/src/__tests__/InspectorProxyReactNativeReloads-test.js b/packages/dev-middleware/src/__tests__/InspectorProxyReactNativeReloads-test.js index 8af4456f5210..c86139e99f1a 100644 --- a/packages/dev-middleware/src/__tests__/InspectorProxyReactNativeReloads-test.js +++ b/packages/dev-middleware/src/__tests__/InspectorProxyReactNativeReloads-test.js @@ -198,6 +198,7 @@ describe('inspector proxy React Native reloads', () => { syntheticPage.webSocketDebuggerUrl, autoCleanup.signal, ); + await until(() => expect(device1.connect).toBeCalledTimes(1)); device1.sendWrappedEvent('originalPage-initial', { error: 'Mock error', @@ -237,6 +238,7 @@ describe('inspector proxy React Native reloads', () => { * We can reuse our existing debugger connection to the synthetic page. * Messages from the updated page will be routed to the debugger. */ + await until(() => expect(device1.connect).toBeCalledTimes(2)); device1.sendWrappedEvent('originalPage-updated', { error: 'Another mock error', }); @@ -402,51 +404,45 @@ describe('inspector proxy React Native reloads', () => { } }); - test.each([ - ['with', true], - ['without', false], - ])( - "device disconnect event %s session ID closes the debugger connection when target has 'nativePageReloads' capability flag", - async (_, includeSessionId) => { - const {device, debugger_, sessionId} = await createAndConnectTarget( - serverRef, - autoCleanup.signal, - { - app: 'bar-app', - id: 'page1', - title: 'bar-title', - vm: 'bar-vm', - capabilities: { - nativePageReloads: true, - }, + test("device disconnect event closes the debugger connection when target has 'nativePageReloads' capability flag", async () => { + const {device, debugger_, sessionId} = await createAndConnectTarget( + serverRef, + autoCleanup.signal, + { + app: 'bar-app', + id: 'page1', + title: 'bar-title', + vm: 'bar-vm', + capabilities: { + nativePageReloads: true, }, - ); - const debuggerClosed = new Promise<{code: number, reason: string}>( - resolve => - debugger_.socket.once('close', (code: number, reason: Buffer) => - resolve({code, reason: reason.toString()}), - ), - ); + }, + ); + const debuggerClosed = new Promise<{code: number, reason: string}>( + resolve => + debugger_.socket.once('close', (code: number, reason: Buffer) => + resolve({code, reason: reason.toString()}), + ), + ); - try { - device.send({ - event: 'disconnect', - payload: { - pageId: 'page1', - ...(includeSessionId ? {sessionId} : {}), - }, - }); - expect(await debuggerClosed).toEqual({ - code: 1000, - reason: WS_CLOSE_REASON.PAGE_REMOVED, - }); - expect(debugger_.handle).not.toBeCalledWith({method: 'reload'}); - } finally { - device.close(); - debugger_.close(); - } - }, - ); + try { + device.send({ + event: 'disconnect', + payload: { + pageId: 'page1', + sessionId, + }, + }); + expect(await debuggerClosed).toEqual({ + code: 1000, + reason: WS_CLOSE_REASON.PAGE_REMOVED, + }); + expect(debugger_.handle).not.toBeCalledWith({method: 'reload'}); + } finally { + device.close(); + debugger_.close(); + } + }); test("disabled when target has 'nativePageReloads' capability flag", async () => { let device1; diff --git a/packages/dev-middleware/src/inspector-proxy/Device.js b/packages/dev-middleware/src/inspector-proxy/Device.js index d690e25b4c17..28889f1f9ebf 100644 --- a/packages/dev-middleware/src/inspector-proxy/Device.js +++ b/packages/dev-middleware/src/inspector-proxy/Device.js @@ -601,71 +601,31 @@ export default class Device { // TODO(moti): Handle null case explicitly, e.g. swallow disconnect events // for unknown pages. const page: ?Page = this.#pages.get(pageId); + const debuggerConnection = this.#debuggerConnections.get(sessionId); if (page != null && this.#pageHasCapability(page, 'nativePageReloads')) { - for (const [sid, debuggerConnection] of this.#debuggerConnections) { - if ( - sessionId != null - ? sid === sessionId - : debuggerConnection.pageId === pageId - ) { - this.#debuggerConnections.delete(sid); - debuggerConnection.socket.close( - WS_CLOSURE_CODE.NORMAL, - WS_CLOSE_REASON.PAGE_REMOVED, - ); - } + if (debuggerConnection != null) { + this.#debuggerConnections.delete(sessionId); + debuggerConnection.socket.close( + WS_CLOSURE_CODE.NORMAL, + WS_CLOSE_REASON.PAGE_REMOVED, + ); } return; } - // Find the debugger connection(s) for this page - if (sessionId != null) { - // Disconnect specific session - const debuggerConnection = this.#debuggerConnections.get(sessionId); - if ( - debuggerConnection && - debuggerConnection.socket.readyState === WS.OPEN - ) { - if (debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID) { - debug( - `Legacy page ${pageId} is reloading (sessionId: ${sessionId}).`, - ); - debuggerConnection.socket.send(JSON.stringify({method: 'reload'})); - } - } - } else { - // Legacy mode: send to all connected debuggers for this page - for (const debuggerConnection of this.#debuggerConnections.values()) { - if ( - debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID && - debuggerConnection.socket.readyState === WS.OPEN - ) { - debug(`Legacy page ${pageId} is reloading.`); - debuggerConnection.socket.send(JSON.stringify({method: 'reload'})); - } - } + if ( + debuggerConnection && + debuggerConnection.socket.readyState === WS.OPEN && + debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID + ) { + debug(`Legacy page ${pageId} is reloading (sessionId: ${sessionId}).`); + debuggerConnection.socket.send(JSON.stringify({method: 'reload'})); } } else if (message.event === 'wrappedEvent') { - const sessionId = message.payload.sessionId; - - // Route message to the correct debugger connection by sessionId - let debuggerConnection: ?DebuggerConnection = null; - if (sessionId != null) { - debuggerConnection = this.#debuggerConnections.get(sessionId); - } else { - // Legacy mode: route to the first (and only) debugger connection - // ASSERT: In legacy mode, there should be at most one debugger connected. - if (this.#debuggerConnections.size > 1) { - debug( - 'WARNING: Device sent message without sessionId but multiple debuggers are connected. ' + - 'This indicates a device/proxy version mismatch.', - ); - } - debuggerConnection = - this.#debuggerConnections.values().next().value ?? null; - } - + const debuggerConnection = this.#debuggerConnections.get( + message.payload.sessionId, + ); if (debuggerConnection == null) { return; } diff --git a/packages/dev-middleware/src/inspector-proxy/__docs__/README.md b/packages/dev-middleware/src/inspector-proxy/__docs__/README.md index 5c0b13e9f871..cbc524fe32a5 100644 --- a/packages/dev-middleware/src/inspector-proxy/__docs__/README.md +++ b/packages/dev-middleware/src/inspector-proxy/__docs__/README.md @@ -110,11 +110,11 @@ interface Message { #### Device → Proxy Messages -| Event | Payload | Description | -| -------------- | -------------------------------------------------------------- | ----------------------------------------------------- | -| `getPages` | `Page[]` | Current list of inspectable pages. | -| `disconnect` | `{ pageId: string, sessionId?: string }` | Notify that page disconnected or rejected connection. | -| `wrappedEvent` | `{ pageId: string, sessionId?: string, wrappedEvent: string }` | Forward CDP message (JSON string) from page. | +| Event | Payload | Description | +| -------------- | ------------------------------------------------------------- | ----------------------------------------------------- | +| `getPages` | `Page[]` | Current list of inspectable pages. | +| `disconnect` | `{ pageId: string, sessionId: string }` | Notify that page disconnected or rejected connection. | +| `wrappedEvent` | `{ pageId: string, sessionId: string, wrappedEvent: string }` | Forward CDP message (JSON string) from page. | #### Page Object @@ -175,8 +175,7 @@ a `disconnect` back to the proxy for that `pageId`. Devices also send a `disconnect` for each session when a page is removed. For targets with `nativePageReloads`, the proxy closes the debugger connection -with `[PAGE_REMOVED]` when it receives a `disconnect` for its session (or for -its page, if `sessionId` is omitted). +with `[PAGE_REMOVED]` when it receives a `disconnect` for its session. ### Connection Semantics diff --git a/packages/dev-middleware/src/inspector-proxy/types.js b/packages/dev-middleware/src/inspector-proxy/types.js index 9a1abe384215..d040ed077d6b 100644 --- a/packages/dev-middleware/src/inspector-proxy/types.js +++ b/packages/dev-middleware/src/inspector-proxy/types.js @@ -58,7 +58,7 @@ export type WrappedEventFromDevice = Readonly<{ payload: Readonly<{ pageId: string, wrappedEvent: string, - sessionId?: string, + sessionId: string, }>, }>; @@ -87,10 +87,10 @@ export type DisconnectRequest = Readonly<{ }>; // Event sent from Device to Inspector Proxy when a debugger session ends or is -// rejected. Legacy devices omit the sessionId. +// rejected. export type DisconnectEventFromDevice = Readonly<{ event: 'disconnect', - payload: Readonly<{pageId: string, sessionId?: string}>, + payload: Readonly<{pageId: string, sessionId: string}>, }>; // Request sent from Inspector Proxy to Device to get a list of pages.