From 7cd6a964bf8e35024ac6d0811de5a7911a0a2f6d Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:22:15 -0700 Subject: [PATCH 1/6] fix: dedupe Flipper bootstrap when multiple devtools plugins mount concurrently Multiple web devtools plugins each called startFlipperConnection() independently, racing js-flipper's flipperClient.start()/addPlugin() under the same hardcoded plugin id. The second addPlugin() call silently overwrote the first's registration, so one plugin's onConnect never fired and its requests hung until Flipper timed out. Introduce a module-level bootstrap promise so start()/addPlugin() run exactly once regardless of how many callers race the bootstrap, and share the message-listener registry across all callers so every plugin instance receives messages once the single connection is live. --- .../plugin/react/src/useCommunicationLayer.ts | 47 ++++++++++++------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/devtools/plugin/react/src/useCommunicationLayer.ts b/devtools/plugin/react/src/useCommunicationLayer.ts index 4742a50..38d5a2a 100644 --- a/devtools/plugin/react/src/useCommunicationLayer.ts +++ b/devtools/plugin/react/src/useCommunicationLayer.ts @@ -18,23 +18,27 @@ type CommunicationLayerMethods = Pick< type Callbacks = IntoArrays; +type FlipperListener = ( + message: TransactionMetadata & MessengerEvent, +) => void; + // keep track of the Flipper connection between React renders let flipperConnection: FlipperPluginConnection | null = null; -/** Adds a Flipper client and starts the connection */ -export const startFlipperConnection = ( - setLayerCallbacks: ( - value: React.SetStateAction>, - ) => void, -): void => { - const listeners: Array< - ( - message: TransactionMetadata & MessengerEvent, - ) => void - > = []; - - if (!flipperConnection) { - flipperClient +// shared across every startFlipperConnection() caller so a plugin instance that +// registers before or after the connection is established still receives messages +const flipperListeners = new Set(); + +// module-level bootstrap mutex: js-flipper's own start()/addPlugin() are not +// safe to call more than once (see FlipperClient internals) - every caller must +// await this SAME promise rather than issuing its own start()/addPlugin() call, +// or the second registration silently overwrites the first under the shared +// "player-ui-devtools" plugin id and that instance's connection never resolves +let flipperBootstrapPromise: Promise | null = null; + +const ensureFlipperConnectionStarted = (): Promise => { + if (!flipperBootstrapPromise) { + flipperBootstrapPromise = flipperClient .start("player-ui-devtools") .then(() => { flipperClient.addPlugin({ @@ -45,7 +49,7 @@ export const startFlipperConnection = ( flipperConnection = conn; conn.receive("message::flipper", (message) => { - listeners.forEach((listener) => listener(message)); + flipperListeners.forEach((listener) => listener(message)); }); }, onDisconnect() { @@ -59,6 +63,17 @@ export const startFlipperConnection = ( }); } + return flipperBootstrapPromise; +}; + +/** Adds a Flipper client and starts the connection */ +export const startFlipperConnection = ( + setLayerCallbacks: ( + value: React.SetStateAction>, + ) => void, +): void => { + void ensureFlipperConnectionStarted(); + const sendMessage: CommunicationLayerMethods["sendMessage"] = async ( message, ) => { @@ -66,7 +81,7 @@ export const startFlipperConnection = ( }; const addListener: CommunicationLayerMethods["addListener"] = (listener) => { - listeners.push(listener); + flipperListeners.add(listener); }; setLayerCallbacks((current) => ({ From a4636074e3bd30330c322607363544adbe7b2665 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:22:28 -0700 Subject: [PATCH 2/6] test: add regression coverage for concurrent Flipper bootstrap dedup Mocks js-flipper to assert start()/addPlugin() are each invoked exactly once no matter how many startFlipperConnection() callers race the bootstrap, and that every caller's addListener wires to the same shared connection once it comes online. --- .../__tests__/useCommunicationLayer.test.ts | 114 ++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts diff --git a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts new file mode 100644 index 0000000..a675f93 --- /dev/null +++ b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import type { FlipperPluginConnection } from "js-flipper"; + +type FakePlugin = { + getId: () => string; + onConnect: (conn: FlipperPluginConnection) => void; + onDisconnect: () => void; +}; + +const start = vi.fn(); +const addPlugin = vi.fn(); + +vi.mock("js-flipper", () => ({ + flipperClient: { + start: (...args: unknown[]) => start(...args), + addPlugin: (plugin: FakePlugin) => addPlugin(plugin), + }, +})); + +/** Fake FlipperPluginConnection driving the registered plugin's onConnect/receive. */ +function fakeConnection(): { + connection: FlipperPluginConnection; + emit: (message: unknown) => void; +} { + let receiveHandler: ((message: unknown) => void) | undefined; + const connection = { + send: vi.fn(), + receive: vi.fn((_event: string, handler: (message: unknown) => void) => { + receiveHandler = handler; + }), + } as unknown as FlipperPluginConnection; + + return { + connection, + emit: (message: unknown) => receiveHandler?.(message), + }; +} + +describe("startFlipperConnection", () => { + beforeEach(() => { + vi.resetModules(); + start.mockReset(); + addPlugin.mockReset(); + }); + + it("calls flipperClient.start and addPlugin exactly once no matter how many concurrent callers race the bootstrap", async () => { + // mimics the real timing hazard: start() resolves asynchronously, so a second + // caller can invoke startFlipperConnection() before the first bootstrap settles + let resolveStart: () => void; + start.mockReturnValue( + new Promise((resolve) => { + resolveStart = resolve; + }), + ); + + const { startFlipperConnection } = await import("../useCommunicationLayer"); + + startFlipperConnection(vi.fn()); + startFlipperConnection(vi.fn()); + startFlipperConnection(vi.fn()); + + expect(start).toHaveBeenCalledTimes(1); + + resolveStart!(); + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + + // a caller arriving after the bootstrap already resolved must not restart it + startFlipperConnection(vi.fn()); + expect(start).toHaveBeenCalledTimes(1); + expect(addPlugin).toHaveBeenCalledTimes(1); + }); + + it("wires every caller's addListener to the single shared connection, regardless of bootstrap order", async () => { + start.mockResolvedValue(undefined); + + const { startFlipperConnection } = await import("../useCommunicationLayer"); + + const firstListeners: unknown[] = []; + const secondListeners: unknown[] = []; + + startFlipperConnection((updater) => { + const result = updater({ + sendMessage: [], + addListener: [], + removeListener: [], + }); + result.addListener.forEach((add) => + add((message) => firstListeners.push(message)), + ); + }); + + startFlipperConnection((updater) => { + const result = updater({ + sendMessage: [], + addListener: [], + removeListener: [], + }); + result.addListener.forEach((add) => + add((message) => secondListeners.push(message)), + ); + }); + + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + + const { emit, connection } = fakeConnection(); + const registeredPlugin = addPlugin.mock.calls[0][0] as FakePlugin; + registeredPlugin.onConnect(connection); + + emit({ payload: "hello" }); + + expect(firstListeners).toEqual([{ payload: "hello" }]); + expect(secondListeners).toEqual([{ payload: "hello" }]); + }); +}); From 04219ae73d956e86f8268faeef77942e56bcbeeb Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 18:42:27 -0700 Subject: [PATCH 3/6] fix: reset Flipper bootstrap mutex on start() failure and disconnect Code review on the concurrent-bootstrap fix found the mutex could get permanently poisoned: a rejected start() or a genuine Flipper disconnect left flipperBootstrapPromise settled forever, so no later caller could ever retry the bootstrap. Reset it to null in both the start().catch() handler and onDisconnect() so a future call re-runs start()/addPlugin() from scratch. Also wire up removeListener to actually delete the callback from the shared flipperListeners Set - previously it was a no-op, so every unmounted Player instance leaked a stale closure into the module-level Set forever. Adds regression tests for all three behaviors: retry after a rejected start(), reconnect after onDisconnect, and removeListener actually detaching a listener. --- .../__tests__/useCommunicationLayer.test.ts | 91 +++++++++++++++++++ .../plugin/react/src/useCommunicationLayer.ts | 15 ++- 2 files changed, 105 insertions(+), 1 deletion(-) diff --git a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts index a675f93..7fc7620 100644 --- a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts +++ b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts @@ -111,4 +111,95 @@ describe("startFlipperConnection", () => { expect(firstListeners).toEqual([{ payload: "hello" }]); expect(secondListeners).toEqual([{ payload: "hello" }]); }); + + it("retries the bootstrap on a later call after flipperClient.start() rejects", async () => { + start.mockRejectedValueOnce(new Error("boom")); + + const { startFlipperConnection } = await import("../useCommunicationLayer"); + + startFlipperConnection(vi.fn()); + + await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(1)); + // let the rejection's .catch() handler run and reset the mutex + await vi.waitFor(() => { + // addPlugin must never have been called for the failed attempt + expect(addPlugin).not.toHaveBeenCalled(); + }); + + start.mockResolvedValueOnce(undefined); + + startFlipperConnection(vi.fn()); + + await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2)); + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + }); + + it("re-bootstraps after onDisconnect fires, allowing reconnection", async () => { + start.mockResolvedValue(undefined); + + const { startFlipperConnection } = await import("../useCommunicationLayer"); + + startFlipperConnection(vi.fn()); + + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + + const registeredPlugin = addPlugin.mock.calls[0][0] as FakePlugin; + const { connection } = fakeConnection(); + registeredPlugin.onConnect(connection); + + // simulate Flipper desktop closing / the device connection dropping + registeredPlugin.onDisconnect(); + + // a later call must re-run the full start()/addPlugin() bootstrap + startFlipperConnection(vi.fn()); + + await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2)); + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(2)); + }); + + it("removeListener stops a listener from receiving further messages", async () => { + start.mockResolvedValue(undefined); + + const { startFlipperConnection } = await import("../useCommunicationLayer"); + + const firstListeners: unknown[] = []; + const secondListeners: unknown[] = []; + let removeFirst: (() => void) | undefined; + + startFlipperConnection((updater) => { + const result = updater({ + sendMessage: [], + addListener: [], + removeListener: [], + }); + const listener = (message: unknown) => firstListeners.push(message); + result.addListener.forEach((add) => add(listener)); + removeFirst = () => + result.removeListener.forEach((remove) => remove(listener)); + }); + + startFlipperConnection((updater) => { + const result = updater({ + sendMessage: [], + addListener: [], + removeListener: [], + }); + result.addListener.forEach((add) => + add((message) => secondListeners.push(message)), + ); + }); + + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + + const { emit, connection } = fakeConnection(); + const registeredPlugin = addPlugin.mock.calls[0][0] as FakePlugin; + registeredPlugin.onConnect(connection); + + removeFirst?.(); + + emit({ payload: "hello" }); + + expect(firstListeners).toEqual([]); + expect(secondListeners).toEqual([{ payload: "hello" }]); + }); }); diff --git a/devtools/plugin/react/src/useCommunicationLayer.ts b/devtools/plugin/react/src/useCommunicationLayer.ts index 38d5a2a..42f95e7 100644 --- a/devtools/plugin/react/src/useCommunicationLayer.ts +++ b/devtools/plugin/react/src/useCommunicationLayer.ts @@ -55,11 +55,18 @@ const ensureFlipperConnectionStarted = (): Promise => { onDisconnect() { console.log("Flipper client disconnected"); flipperConnection = null; + // allow a future call to re-run start()/addPlugin() so the plugin + // can reconnect after Flipper desktop closes/reopens or the + // device connection drops + flipperBootstrapPromise = null; }, }); }) .catch((error) => { console.error("Failed to start Flipper client", error); + // reset the mutex so a future call retries the bootstrap from + // scratch instead of being permanently poisoned by this failure + flipperBootstrapPromise = null; }); } @@ -84,10 +91,16 @@ export const startFlipperConnection = ( flipperListeners.add(listener); }; + const removeListener: CommunicationLayerMethods["removeListener"] = ( + listener, + ) => { + flipperListeners.delete(listener); + }; + setLayerCallbacks((current) => ({ sendMessage: [...current.sendMessage, sendMessage], addListener: [...current.addListener, addListener], - removeListener: current.removeListener, + removeListener: [...current.removeListener, removeListener], })); }; From 143e58770c2e2d616624036131ac849cb108919e Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Fri, 11 Sep 2026 21:46:55 -0700 Subject: [PATCH 4/6] test: cover reconnect when js-flipper start() short-circuits on an open socket js-flipper's real FlipperClient.start() is `if (this.ws) { return; }` - after the most common disconnect path (Flipper desktop sending a plugin-level deinit) the websocket itself never closes, so every start() call after the first no-ops rather than doing fresh connect work. Verified directly against the installed js-flipper@0.273.0 source (node_modules/.pnpm/js-flipper@0.273.0/.../lib/client.js): start()'s early return still leaves a Promise that resolves, and the existing bootstrap chain (start().then(() => addPlugin(...))) already re-invokes addPlugin() unconditionally on every retry regardless of what start() did internally - addPlugin() is what re-registers the plugin object into FlipperClient's plugins Map, which is the actual reconnect mechanism. No production code change was needed: the mutex reset in onDisconnect (fdda3af) already produces a correct re-registration here. This test makes that guarantee explicit and regression-proof by modeling start()'s real no-op shape instead of a full fresh-connect mock. --- .../__tests__/useCommunicationLayer.test.ts | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts index 7fc7620..e4b741a 100644 --- a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts +++ b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts @@ -157,6 +157,43 @@ describe("startFlipperConnection", () => { await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(2)); }); + it("re-registers the plugin via addPlugin() after onDisconnect even when start() no-ops because the websocket never dropped", async () => { + // js-flipper's real FlipperClient.start() is `if (this.ws) { return; }` - + // the most common disconnect (Flipper desktop sending a plugin-level + // "deinit") never tears down the websocket, so start() short-circuits on + // every call after the first and does no reconnect work of its own. The + // bootstrap must not rely on start() to do anything on retry - it only + // needs to resolve so addPlugin() runs again and re-registers a fresh + // plugin object under the shared id. + start.mockImplementation(() => Promise.resolve()); + + const { startFlipperConnection } = await import("../useCommunicationLayer"); + + startFlipperConnection(vi.fn()); + + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + + const firstPlugin = addPlugin.mock.calls[0][0] as FakePlugin; + const { connection } = fakeConnection(); + firstPlugin.onConnect(connection); + + // Flipper desktop sends "deinit" for this plugin id; the underlying ws + // stays open, so a subsequent start() call will short-circuit. + firstPlugin.onDisconnect(); + + startFlipperConnection(vi.fn()); + + await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2)); + // addPlugin must fire again even though start() did no reconnect work, + // otherwise the stale plugin object (closed over the disconnected + // state) stays registered and the plugin never comes back online. + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(2)); + + const secondPlugin = addPlugin.mock.calls[1][0] as FakePlugin; + expect(secondPlugin.getId()).toBe(firstPlugin.getId()); + expect(secondPlugin).not.toBe(firstPlugin); + }); + it("removeListener stops a listener from receiving further messages", async () => { start.mockResolvedValue(undefined); From 3d2e3e0536ec0fc3fcdf14c41a7db88df9476f98 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Tue, 22 Sep 2026 17:46:41 -0700 Subject: [PATCH 5/6] fix: dedupe Flipper bootstrap across duplicated module copies via globalThis Consumers can bundle multiple Player/plugin versions in the same app, each carrying its own copy of useCommunicationLayer.ts (and potentially its own js-flipper version). The previous module-level mutex only deduped concurrent callers within a single JS module instance - it did nothing to stop two duplicated bundles from each calling flipperClient.start()/addPlugin() independently, reintroducing the original race under a different trigger. Move the shared state onto a Symbol.for-keyed globalThis slot so every copy of the module, regardless of bundle or js-flipper version, awaits the same bootstrap and reads/writes the same communication proxy - mirroring the Android adaptor's pattern of sharing one plugin-wrapper instance rather than the raw client or connection. The global promise never rejects (it's purely a mutex); bootstrap failure is surfaced as a `status: "failed"` field on the resolved proxy so a caller that never checks it still gets a safe no-op instead of an unhandled rejection. --- .../__tests__/useCommunicationLayer.test.ts | 70 +++++++- .../plugin/react/src/useCommunicationLayer.ts | 153 ++++++++++++------ 2 files changed, 171 insertions(+), 52 deletions(-) diff --git a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts index e4b741a..367a705 100644 --- a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts +++ b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts @@ -36,11 +36,17 @@ function fakeConnection(): { }; } +const FLIPPER_PROXY_KEY = Symbol.for("player-ui-devtools/flipper-proxy"); + describe("startFlipperConnection", () => { beforeEach(() => { vi.resetModules(); start.mockReset(); addPlugin.mockReset(); + // the bootstrap mutex now lives on globalThis (by design - it must + // survive module duplication across bundles), so vi.resetModules() + // alone no longer isolates tests from each other + delete (globalThis as Record)[FLIPPER_PROXY_KEY]; }); it("calls flipperClient.start and addPlugin exactly once no matter how many concurrent callers race the bootstrap", async () => { @@ -115,7 +121,14 @@ describe("startFlipperConnection", () => { it("retries the bootstrap on a later call after flipperClient.start() rejects", async () => { start.mockRejectedValueOnce(new Error("boom")); - const { startFlipperConnection } = await import("../useCommunicationLayer"); + const { startFlipperConnection, ensureFlipperConnectionStarted } = + await import("../useCommunicationLayer"); + + // capture the first (failing) bootstrap promise before it settles and + // resets the global mutex - calling ensureFlipperConnectionStarted() + // again after the reset would kick off a brand-new bootstrap attempt + // instead of inspecting this one + const firstBootstrap = ensureFlipperConnectionStarted(); startFlipperConnection(vi.fn()); @@ -126,6 +139,13 @@ describe("startFlipperConnection", () => { expect(addPlugin).not.toHaveBeenCalled(); }); + // the shared promise must never reject - failure is surfaced as data so + // a caller that never checks `status` still gets a safe no-op proxy + // instead of an unhandled rejection + await expect(firstBootstrap).resolves.toMatchObject({ + status: "failed", + }); + start.mockResolvedValueOnce(undefined); startFlipperConnection(vi.fn()); @@ -234,9 +254,57 @@ describe("startFlipperConnection", () => { removeFirst?.(); + // addListener/removeListener are now proxied through the shared + // bootstrap promise, so they settle on a microtask rather than + // synchronously - flush pending microtasks before emitting + await Promise.resolve(); + await Promise.resolve(); + emit({ payload: "hello" }); expect(firstListeners).toEqual([]); expect(secondListeners).toEqual([{ payload: "hello" }]); }); + + it("dedupes the bootstrap across duplicated copies of this module, not just concurrent callers within one copy", async () => { + // Consumers can bundle multiple Player/plugin versions in the same app, + // each carrying its own copy of useCommunicationLayer.ts (and potentially + // its own js-flipper version). vi.resetModules() + a fresh dynamic + // import() simulates that: each import() below is a distinct module + // registry entry, standing in for a separate bundle, while globalThis - + // shared across all realms in the same window - is what the mutex must + // live on for this test to pass. + let resolveStart: () => void; + start.mockReturnValue( + new Promise((resolve) => { + resolveStart = resolve; + }), + ); + + const firstBundle = await import("../useCommunicationLayer"); + + // the top-level vi.mock("js-flipper", ...) above is hoisted and + // automatically reapplies to the next fresh import after resetModules() + vi.resetModules(); + const secondBundle = await import("../useCommunicationLayer"); + + expect(secondBundle.startFlipperConnection).not.toBe( + firstBundle.startFlipperConnection, + ); + + firstBundle.startFlipperConnection(vi.fn()); + secondBundle.startFlipperConnection(vi.fn()); + + // only the bundle that wins the race against the shared global mutex + // may ever call flipperClient.start()/addPlugin() - the second bundle's + // own (possibly differently-versioned) flipperClient must never be + // invoked independently + expect(start).toHaveBeenCalledTimes(1); + + resolveStart!(); + await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); + + expect(start).toHaveBeenCalledTimes(1); + expect(addPlugin).toHaveBeenCalledTimes(1); + }); }); diff --git a/devtools/plugin/react/src/useCommunicationLayer.ts b/devtools/plugin/react/src/useCommunicationLayer.ts index 42f95e7..b21d56c 100644 --- a/devtools/plugin/react/src/useCommunicationLayer.ts +++ b/devtools/plugin/react/src/useCommunicationLayer.ts @@ -22,79 +22,130 @@ type FlipperListener = ( message: TransactionMetadata & MessengerEvent, ) => void; -// keep track of the Flipper connection between React renders -let flipperConnection: FlipperPluginConnection | null = null; - -// shared across every startFlipperConnection() caller so a plugin instance that -// registers before or after the connection is established still receives messages -const flipperListeners = new Set(); - -// module-level bootstrap mutex: js-flipper's own start()/addPlugin() are not -// safe to call more than once (see FlipperClient internals) - every caller must -// await this SAME promise rather than issuing its own start()/addPlugin() call, -// or the second registration silently overwrites the first under the shared -// "player-ui-devtools" plugin id and that instance's connection never resolves -let flipperBootstrapPromise: Promise | null = null; - -const ensureFlipperConnectionStarted = (): Promise => { - if (!flipperBootstrapPromise) { - flipperBootstrapPromise = flipperClient - .start("player-ui-devtools") - .then(() => { - flipperClient.addPlugin({ - getId() { - return "player-ui-devtools"; - }, - onConnect(conn) { - flipperConnection = conn; - - conn.receive("message::flipper", (message) => { - flipperListeners.forEach((listener) => listener(message)); - }); - }, - onDisconnect() { - console.log("Flipper client disconnected"); - flipperConnection = null; - // allow a future call to re-run start()/addPlugin() so the plugin - // can reconnect after Flipper desktop closes/reopens or the - // device connection drops - flipperBootstrapPromise = null; - }, - }); - }) - .catch((error) => { - console.error("Failed to start Flipper client", error); - // reset the mutex so a future call retries the bootstrap from - // scratch instead of being permanently poisoned by this failure - flipperBootstrapPromise = null; +/** + * The single communication proxy shared by every startFlipperConnection() + * caller in this JS realm - analogous to Android's PlayerDevtoolsFlipperPlugin, + * which every AndroidDevtoolsPlugin instance looks up and multiplexes over + * rather than each owning its own FlipperClient registration. + * + * `status` surfaces bootstrap failure as inspectable data rather than a + * promise rejection, so a caller that never checks it still gets a safe + * no-op proxy instead of an unhandled rejection. + */ +type FlipperCommunicationProxy = { + status: "connected" | "failed"; + sendMessage: ( + ...args: Parameters + ) => void; + addListener: (listener: FlipperListener) => void; + removeListener: (listener: FlipperListener) => void; +}; + +// Consumers may bundle multiple Player/plugin versions in the same app, each +// with its own copy of this module (and potentially its own js-flipper +// version) - a module-level mutex only dedupes within a single JS module +// instance, not across duplicated bundles sharing the same window. Keying off +// globalThis via Symbol.for gives every copy, regardless of bundle or +// js-flipper version, the same mutex/proxy so only the first copy to run ever +// calls flipperClient.start()/addPlugin(); every later copy just awaits the +// same promise and reads/writes the same shared proxy. +const FLIPPER_PROXY_KEY = Symbol.for("player-ui-devtools/flipper-proxy"); + +type GlobalWithFlipperProxy = typeof globalThis & { + [FLIPPER_PROXY_KEY]?: Promise; +}; + +const createFlipperProxy = (): Promise => { + const listeners = new Set(); + let connection: FlipperPluginConnection | null = null; + + const proxy: FlipperCommunicationProxy = { + status: "connected", + sendMessage: (message) => { + connection?.send("message::plugin", message); + }, + addListener: (listener) => { + listeners.add(listener); + }, + removeListener: (listener) => { + listeners.delete(listener); + }, + }; + + return flipperClient + .start("player-ui-devtools") + .then(() => { + flipperClient.addPlugin({ + getId() { + return "player-ui-devtools"; + }, + onConnect(conn) { + connection = conn; + + conn.receive("message::flipper", (message) => { + listeners.forEach((listener) => listener(message)); + }); + }, + onDisconnect() { + console.log("Flipper client disconnected"); + connection = null; + // allow a future call to re-run start()/addPlugin() so the plugin + // can reconnect after Flipper desktop closes/reopens or the + // device connection drops + delete (globalThis as GlobalWithFlipperProxy)[FLIPPER_PROXY_KEY]; + }, }); - } - return flipperBootstrapPromise; + return proxy; + }) + .catch((error) => { + console.error("Failed to start Flipper client", error); + // reset the mutex so a future call retries the bootstrap from scratch + // instead of being permanently poisoned by this failure - the shared + // promise itself never rejects, so a caller that doesn't check + // `status` still gets a safe no-op proxy rather than an unhandled + // rejection + delete (globalThis as GlobalWithFlipperProxy)[FLIPPER_PROXY_KEY]; + + return { ...proxy, status: "failed" as const }; + }); }; +/** + * Exported for tests: lets a caller await (and inspect the `status` of) the + * same shared bootstrap that startFlipperConnection() fires-and-forgets. + */ +export const ensureFlipperConnectionStarted = + (): Promise => { + const globalWithProxy = globalThis as GlobalWithFlipperProxy; + + globalWithProxy[FLIPPER_PROXY_KEY] ??= createFlipperProxy(); + + return globalWithProxy[FLIPPER_PROXY_KEY]; + }; + /** Adds a Flipper client and starts the connection */ export const startFlipperConnection = ( setLayerCallbacks: ( value: React.SetStateAction>, ) => void, ): void => { - void ensureFlipperConnectionStarted(); + const proxyPromise = ensureFlipperConnectionStarted(); const sendMessage: CommunicationLayerMethods["sendMessage"] = async ( message, ) => { - flipperConnection?.send("message::plugin", message); + (await proxyPromise).sendMessage(message); }; const addListener: CommunicationLayerMethods["addListener"] = (listener) => { - flipperListeners.add(listener); + void proxyPromise.then((proxy) => proxy.addListener(listener)); }; const removeListener: CommunicationLayerMethods["removeListener"] = ( listener, ) => { - flipperListeners.delete(listener); + void proxyPromise.then((proxy) => proxy.removeListener(listener)); }; setLayerCallbacks((current) => ({ From de6349f3863c2d2ada6f5d627a8a01a7cbb8f8c3 Mon Sep 17 00:00:00 2001 From: Jeremiah Zucker Date: Tue, 22 Sep 2026 17:55:58 -0700 Subject: [PATCH 6/6] fix: don't reset the shared Flipper proxy on disconnect js-flipper's disconnectPlugin() only drops the connection from FlipperClient's internal Map - it never removes the plugin from the plugins registry. A later "init" message from Flipper desktop looks the plugin back up and calls onConnect() again on the SAME registered object, so reconnection never requires a new addPlugin() call. Resetting the global proxy slot on every onDisconnect (inherited from the pre-globalThis version of this fix) was therefore both unnecessary and newly harmful: it discarded the shared listeners Set on every transient disconnect, forcing every mounted plugin instance to lose its listener registration and re-run the full bootstrap. onDisconnect now just clears the proxy's internal connection reference so sendMessage no-ops while disconnected, leaving the shared proxy and listeners intact for the next onConnect(). Also trims comments across both files down to what isn't obvious from the code itself. --- .../__tests__/useCommunicationLayer.test.ts | 106 +++++------------- .../plugin/react/src/useCommunicationLayer.ts | 41 ++----- 2 files changed, 41 insertions(+), 106 deletions(-) diff --git a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts index 367a705..d48a70e 100644 --- a/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts +++ b/devtools/plugin/react/src/__tests__/useCommunicationLayer.test.ts @@ -43,15 +43,11 @@ describe("startFlipperConnection", () => { vi.resetModules(); start.mockReset(); addPlugin.mockReset(); - // the bootstrap mutex now lives on globalThis (by design - it must - // survive module duplication across bundles), so vi.resetModules() - // alone no longer isolates tests from each other + // globalThis mutex survives resetModules(), so clear it manually too delete (globalThis as Record)[FLIPPER_PROXY_KEY]; }); it("calls flipperClient.start and addPlugin exactly once no matter how many concurrent callers race the bootstrap", async () => { - // mimics the real timing hazard: start() resolves asynchronously, so a second - // caller can invoke startFlipperConnection() before the first bootstrap settles let resolveStart: () => void; start.mockReturnValue( new Promise((resolve) => { @@ -124,24 +120,17 @@ describe("startFlipperConnection", () => { const { startFlipperConnection, ensureFlipperConnectionStarted } = await import("../useCommunicationLayer"); - // capture the first (failing) bootstrap promise before it settles and - // resets the global mutex - calling ensureFlipperConnectionStarted() - // again after the reset would kick off a brand-new bootstrap attempt - // instead of inspecting this one + // capture before it settles - re-calling after reset would restart the bootstrap const firstBootstrap = ensureFlipperConnectionStarted(); startFlipperConnection(vi.fn()); await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(1)); - // let the rejection's .catch() handler run and reset the mutex await vi.waitFor(() => { - // addPlugin must never have been called for the failed attempt expect(addPlugin).not.toHaveBeenCalled(); }); - // the shared promise must never reject - failure is surfaced as data so - // a caller that never checks `status` still gets a safe no-op proxy - // instead of an unhandled rejection + // must resolve, not reject, so an unchecked caller never sees an unhandled rejection await expect(firstBootstrap).resolves.toMatchObject({ status: "failed", }); @@ -154,64 +143,42 @@ describe("startFlipperConnection", () => { await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); }); - it("re-bootstraps after onDisconnect fires, allowing reconnection", async () => { + it("reconnects via a second onConnect() on the same registered plugin, without re-running start()/addPlugin()", async () => { + // js-flipper never removes the plugin from its registry on disconnect, + // so reconnect is just another onConnect() call on the same plugin. start.mockResolvedValue(undefined); const { startFlipperConnection } = await import("../useCommunicationLayer"); - startFlipperConnection(vi.fn()); + const messages: unknown[] = []; + startFlipperConnection((updater) => { + const result = updater({ + sendMessage: [], + addListener: [], + removeListener: [], + }); + result.addListener.forEach((add) => + add((message) => messages.push(message)), + ); + }); await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); const registeredPlugin = addPlugin.mock.calls[0][0] as FakePlugin; - const { connection } = fakeConnection(); - registeredPlugin.onConnect(connection); + const first = fakeConnection(); + registeredPlugin.onConnect(first.connection); - // simulate Flipper desktop closing / the device connection dropping registeredPlugin.onDisconnect(); - // a later call must re-run the full start()/addPlugin() bootstrap - startFlipperConnection(vi.fn()); - - await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2)); - await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(2)); - }); - - it("re-registers the plugin via addPlugin() after onDisconnect even when start() no-ops because the websocket never dropped", async () => { - // js-flipper's real FlipperClient.start() is `if (this.ws) { return; }` - - // the most common disconnect (Flipper desktop sending a plugin-level - // "deinit") never tears down the websocket, so start() short-circuits on - // every call after the first and does no reconnect work of its own. The - // bootstrap must not rely on start() to do anything on retry - it only - // needs to resolve so addPlugin() runs again and re-registers a fresh - // plugin object under the shared id. - start.mockImplementation(() => Promise.resolve()); - - const { startFlipperConnection } = await import("../useCommunicationLayer"); - - startFlipperConnection(vi.fn()); - - await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(1)); - - const firstPlugin = addPlugin.mock.calls[0][0] as FakePlugin; - const { connection } = fakeConnection(); - firstPlugin.onConnect(connection); + const second = fakeConnection(); + registeredPlugin.onConnect(second.connection); - // Flipper desktop sends "deinit" for this plugin id; the underlying ws - // stays open, so a subsequent start() call will short-circuit. - firstPlugin.onDisconnect(); - - startFlipperConnection(vi.fn()); + expect(start).toHaveBeenCalledTimes(1); + expect(addPlugin).toHaveBeenCalledTimes(1); - await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2)); - // addPlugin must fire again even though start() did no reconnect work, - // otherwise the stale plugin object (closed over the disconnected - // state) stays registered and the plugin never comes back online. - await vi.waitFor(() => expect(addPlugin).toHaveBeenCalledTimes(2)); - - const secondPlugin = addPlugin.mock.calls[1][0] as FakePlugin; - expect(secondPlugin.getId()).toBe(firstPlugin.getId()); - expect(secondPlugin).not.toBe(firstPlugin); + // listener registered before the disconnect must survive it + second.emit({ payload: "hello" }); + expect(messages).toEqual([{ payload: "hello" }]); }); it("removeListener stops a listener from receiving further messages", async () => { @@ -254,9 +221,7 @@ describe("startFlipperConnection", () => { removeFirst?.(); - // addListener/removeListener are now proxied through the shared - // bootstrap promise, so they settle on a microtask rather than - // synchronously - flush pending microtasks before emitting + // addListener/removeListener resolve on a microtask now, not synchronously await Promise.resolve(); await Promise.resolve(); @@ -267,13 +232,9 @@ describe("startFlipperConnection", () => { }); it("dedupes the bootstrap across duplicated copies of this module, not just concurrent callers within one copy", async () => { - // Consumers can bundle multiple Player/plugin versions in the same app, - // each carrying its own copy of useCommunicationLayer.ts (and potentially - // its own js-flipper version). vi.resetModules() + a fresh dynamic - // import() simulates that: each import() below is a distinct module - // registry entry, standing in for a separate bundle, while globalThis - - // shared across all realms in the same window - is what the mutex must - // live on for this test to pass. + // simulates two bundled copies of this module (e.g. two Player plugin + // versions) via resetModules() + fresh import(); globalThis is what + // must dedupe them since each has its own module-local state. let resolveStart: () => void; start.mockReturnValue( new Promise((resolve) => { @@ -283,8 +244,6 @@ describe("startFlipperConnection", () => { const firstBundle = await import("../useCommunicationLayer"); - // the top-level vi.mock("js-flipper", ...) above is hoisted and - // automatically reapplies to the next fresh import after resetModules() vi.resetModules(); const secondBundle = await import("../useCommunicationLayer"); @@ -295,10 +254,7 @@ describe("startFlipperConnection", () => { firstBundle.startFlipperConnection(vi.fn()); secondBundle.startFlipperConnection(vi.fn()); - // only the bundle that wins the race against the shared global mutex - // may ever call flipperClient.start()/addPlugin() - the second bundle's - // own (possibly differently-versioned) flipperClient must never be - // invoked independently + // only the winner of the global mutex race ever calls start()/addPlugin() expect(start).toHaveBeenCalledTimes(1); resolveStart!(); diff --git a/devtools/plugin/react/src/useCommunicationLayer.ts b/devtools/plugin/react/src/useCommunicationLayer.ts index b21d56c..380a83b 100644 --- a/devtools/plugin/react/src/useCommunicationLayer.ts +++ b/devtools/plugin/react/src/useCommunicationLayer.ts @@ -22,16 +22,9 @@ type FlipperListener = ( message: TransactionMetadata & MessengerEvent, ) => void; -/** - * The single communication proxy shared by every startFlipperConnection() - * caller in this JS realm - analogous to Android's PlayerDevtoolsFlipperPlugin, - * which every AndroidDevtoolsPlugin instance looks up and multiplexes over - * rather than each owning its own FlipperClient registration. - * - * `status` surfaces bootstrap failure as inspectable data rather than a - * promise rejection, so a caller that never checks it still gets a safe - * no-op proxy instead of an unhandled rejection. - */ +// Shared across every startFlipperConnection() caller, like Android's +// PlayerDevtoolsFlipperPlugin. `status` surfaces bootstrap failure as data +// instead of a rejection, so an unchecked caller still gets a safe no-op. type FlipperCommunicationProxy = { status: "connected" | "failed"; sendMessage: ( @@ -41,14 +34,8 @@ type FlipperCommunicationProxy = { removeListener: (listener: FlipperListener) => void; }; -// Consumers may bundle multiple Player/plugin versions in the same app, each -// with its own copy of this module (and potentially its own js-flipper -// version) - a module-level mutex only dedupes within a single JS module -// instance, not across duplicated bundles sharing the same window. Keying off -// globalThis via Symbol.for gives every copy, regardless of bundle or -// js-flipper version, the same mutex/proxy so only the first copy to run ever -// calls flipperClient.start()/addPlugin(); every later copy just awaits the -// same promise and reads/writes the same shared proxy. +// globalThis-keyed so duplicated bundles (multiple Player/plugin versions, +// each with their own copy of this module/js-flipper) share one mutex. const FLIPPER_PROXY_KEY = Symbol.for("player-ui-devtools/flipper-proxy"); type GlobalWithFlipperProxy = typeof globalThis & { @@ -89,10 +76,9 @@ const createFlipperProxy = (): Promise => { onDisconnect() { console.log("Flipper client disconnected"); connection = null; - // allow a future call to re-run start()/addPlugin() so the plugin - // can reconnect after Flipper desktop closes/reopens or the - // device connection drops - delete (globalThis as GlobalWithFlipperProxy)[FLIPPER_PROXY_KEY]; + // js-flipper reconnects by calling onConnect() again on this same + // plugin object - no addPlugin() re-run needed, so don't reset + // the global proxy (that would drop the shared listeners). }, }); @@ -100,21 +86,14 @@ const createFlipperProxy = (): Promise => { }) .catch((error) => { console.error("Failed to start Flipper client", error); - // reset the mutex so a future call retries the bootstrap from scratch - // instead of being permanently poisoned by this failure - the shared - // promise itself never rejects, so a caller that doesn't check - // `status` still gets a safe no-op proxy rather than an unhandled - // rejection + // reset the mutex so a later call retries instead of staying poisoned delete (globalThis as GlobalWithFlipperProxy)[FLIPPER_PROXY_KEY]; return { ...proxy, status: "failed" as const }; }); }; -/** - * Exported for tests: lets a caller await (and inspect the `status` of) the - * same shared bootstrap that startFlipperConnection() fires-and-forgets. - */ +/** Exported for tests to await/inspect the shared bootstrap's `status`. */ export const ensureFlipperConnectionStarted = (): Promise => { const globalWithProxy = globalThis as GlobalWithFlipperProxy;