Repository: facebook/react
Pull request: fix[react-devtools]: remove all listeners when Agent is shutdown

Based on https://github.com/facebook/react/pull/31049, credits to @EdmondChuiHW.

What is happening here:
1. Once Agent is destroyed, unsubscribe own listeners and bridge listeners.
2. [Browser extension only] Once Agent is destroyed, unsubscribe listeners from BackendManager.
3. [Browser extension only]  I've discovered that `backendManager.js` content script can get injected multiple times by the browser. When Frontend is initializing, it will create Store first, and then execute a content script for bootstraping backend manager. If Frontend was destroyed somewhere between these 2 steps, Backend won't be notified, because it is not initialized yet, so it will not unsubscribe listeners correctly. We might end up duplicating listeners, and the next time Frontend is launched, it will report an issues "Cannot add / remove node ...", because same operations are emitted twice.

To reproduce 3 you can do the following:
1. Click reload-to-profile
2. Right after when both app and Chrome DevTools panel are reloaded, close Chrome DevTools.
3. Open Chrome DevTools again, open Profiler panel and observe "Cannot add / remove node ..." error in the UI.

Changed files:
filename: packages/react-devtools-extensions/src/contentScripts/backendManager.js
patch: @@ -16,6 +16,7 @@ import {COMPACT_VERSION_NAME} from 'react-devtools-extensions/src/utils';
 import {getIsReloadAndProfileSupported} from 'react-devtools-shared/src/utils';
 
 let welcomeHasInitialized = false;
+const requiredBackends = new Set<string>();
 
 function welcome(event: $FlowFixMe) {
   if (
@@ -49,8 +50,6 @@ function welcome(event: $FlowFixMe) {
   setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__);
 }
 
-window.addEventListener('message', welcome);
-
 function setup(hook: ?DevToolsHook) {
   // this should not happen, but Chrome can be weird sometimes
   if (hook == null) {
@@ -71,20 +70,27 @@ function setup(hook: ?DevToolsHook) {
   updateRequiredBackends();
 
   // register renderers that inject themselves later.
-  hook.sub('renderer', ({renderer}) => {
+  const unsubscribeRendererListener = hook.sub('renderer', ({renderer}) => {
     registerRenderer(renderer, hook);
     updateRequiredBackends();
   });
 
   // listen for backend installations.
-  hook.sub('devtools-backend-installed', version => {
-    activateBackend(version, hook);
-    updateRequiredBackends();
+  const unsubscribeBackendInstallationListener = hook.sub(
+    'devtools-backend-installed',
+    version => {
+      activateBackend(version, hook);
+      updateRequiredBackends();
+    },
+  );
+
+  const unsubscribeShutdownListener: () => void = hook.sub('shutdown', () => {
+    unsubscribeRendererListener();
+    unsubscribeBackendInstallationListener();
+    unsubscribeShutdownListener();
   });
 }
 
-const requiredBackends = new Set<string>();
-
 function registerRenderer(renderer: ReactRenderer, hook: DevToolsHook) {
   let version = renderer.reconcilerVersion || renderer.version;
   if (!hasAssignedBackend(version)) {
@@ -139,6 +145,7 @@ function activateBackend(version: string, hook: DevToolsHook) {
     // If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down,
     // and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here.
     hook.emit('shutdown');
+    delete window.__REACT_DEVTOOLS_BACKEND_MANAGER_INJECTED__;
   });
 
   initBackend(hook, agent, window, getIsReloadAndProfileSupported());
@@ -178,3 +185,13 @@ function updateRequiredBackends() {
     '*',
   );
 }
+
+/*
+ * Make sure this is executed only once in case Frontend is reloaded multiple times while Backend is initializing
+ * We can't use `reactDevToolsAgent` field on a global Hook object, because it only cleaned up after both Frontend and Backend initialized
+ */
+if (!window.__REACT_DEVTOOLS_BACKEND_MANAGER_INJECTED__) {
+  window.__REACT_DEVTOOLS_BACKEND_MANAGER_INJECTED__ = true;
+
+  window.addEventListener('message', welcome);
+}

filename: packages/react-devtools-shared/src/backend/agent.js
patch: @@ -750,6 +750,9 @@ export default class Agent extends EventEmitter<{
   shutdown: () => void = () => {
     // Clean up the overlay if visible, and associated events.
     this.emit('shutdown');
+
+    this._bridge.removeAllListeners();
+    this.removeAllListeners();
   };
 
   startProfiling: (recordChangeDescriptions: boolean) => void =

filename: packages/react-devtools-shared/src/backend/fiber/renderer.js
patch: @@ -3473,7 +3473,7 @@ export function attach(
   }
 
   function cleanup() {
-    // We don't patch any methods so there is no cleanup.
+    isProfiling = false;
   }
 
   function rootSupportsProfiling(root: any) {

filename: packages/react-devtools-shared/src/backend/index.js
patch: @@ -80,15 +80,12 @@ export function initBackend(
     });
     hook.reactDevtoolsAgent = null;
   };
-  agent.addListener('shutdown', onAgentShutdown);
-  subs.push(() => {
-    agent.removeListener('shutdown', onAgentShutdown);
-  });
 
+  // Agent's event listeners are cleaned up by Agent in `shutdown` implementation.
+  agent.addListener('shutdown', onAgentShutdown);
   agent.addListener('updateHookSettings', settings => {
     hook.settings = settings;
   });
-
   agent.addListener('getHookSettings', () => {
     if (hook.settings != null) {
       agent.onHookSettings(hook.settings);