Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(desktop): release IPC listeners and hidden editor roots (#18954)

Innei83e477e2e260
diff --git a/apps/desktop/src/overlay/ScreenCaptureOverlay.tsx b/apps/desktop/src/overlay/ScreenCaptureOverlay.tsx
index 469b3cc51d4..4a1420d4608 100644
--- a/apps/desktop/src/overlay/ScreenCaptureOverlay.tsx
+++ b/apps/desktop/src/overlay/ScreenCaptureOverlay.tsx
@@ -134,10 +134,7 @@ const ScreenCaptureOverlay = memo(() => {
),
);
};
- window.electron?.ipcRenderer?.on?.('overlayCaptureUploadStatus', listener);
- return () => {
- window.electron?.ipcRenderer?.removeListener?.('overlayCaptureUploadStatus', listener);
- };
+ return window.electron?.ipcRenderer?.on?.('overlayCaptureUploadStatus', listener);
}, []);
const previewWindow = useCallback(
diff --git a/eslint.config.mjs b/eslint.config.mjs
index f90cb9e769b..d29b5f88948 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -85,6 +85,12 @@ const useRefLazyInitRestrictedSyntax = [
},
];
+const electronIpcRemoveListenerRestrictedSyntax = {
+ message:
+ 'Do not use removeListener in renderer code. Electron contextBridge does not preserve listener identity across calls; use the disposer returned by ipcRenderer.on().',
+ selector: "CallExpression > MemberExpression.callee[property.name='removeListener']",
+};
+
export default eslint(
{
ignores: [
@@ -360,6 +366,21 @@ export default eslint(
'no-restricted-syntax': ['error', ...useRefLazyInitRestrictedSyntax],
},
},
+ {
+ files: [
+ 'apps/desktop/src/overlay/**/*.{ts,tsx}',
+ 'packages/electron-client-ipc/src/**/*.{ts,tsx}',
+ 'src/**/*.{ts,tsx}',
+ ],
+ ignores: ['src/hooks/usePWAInstall.ts'],
+ rules: {
+ 'no-restricted-syntax': [
+ 'error',
+ ...useRefLazyInitRestrictedSyntax,
+ electronIpcRemoveListenerRestrictedSyntax,
+ ],
+ },
+ },
// MDX files
{
...mdxFlat,
diff --git a/eslint.config.test.mts b/eslint.config.test.mts
deleted file mode 100644
index 8529a8c6fb6..00000000000
--- a/eslint.config.test.mts
+++ /dev/null
@@ -1,235 +0,0 @@
-// @vitest-environment node
-
-import { ESLint } from 'eslint';
-import { describe, expect, it } from 'vitest';
-
-const eslint = new ESLint({ cwd: process.cwd() });
-
-const lintRestrictedImports = async (filePath: string, code: string): Promise<string[]> => {
- const [result] = await eslint.lintText(code, { filePath });
-
- return result.messages
- .filter(({ ruleId }) => ruleId === 'no-restricted-imports')
- .map(({ message }) => message);
-};
-
-const lintRestrictedSyntax = async (filePath: string, code: string): Promise<string[]> => {
- const [result] = await eslint.lintText(code, { filePath });
-
- return result.messages
- .filter(({ ruleId }) => ruleId === 'no-restricted-syntax')
- .map(({ message }) => message);
-};
-
-const forbiddenImports = [
- [
- 'Conversation internal root barrel',
- 'src/features/Conversation/ChatItem/lint-fixture.tsx',
- `import { ChatInput } from '@/features/Conversation';\nvoid ChatInput;`,
- 'Conversation internals must use stable subpaths',
- ],
- [
- 'NavPanel route Sidebar ownership',
- 'src/features/NavPanel/lint-fixture.tsx',
- `import Sidebar from '@/routes/(main)/agent/_layout/Sidebar';\nvoid Sidebar;`,
- 'NavPanel must not own route Sidebar implementations',
- ],
- [
- 'NavPanel route SideBar ownership',
- 'src/features/NavPanel/lint-fixture.tsx',
- `import SideBar from '@/routes/(main)/settings/_layout/SideBar';\nvoid SideBar;`,
- 'NavPanel must not own route Sidebar implementations',
- ],
- [
- 'route Sidebar NavPanel host barrel',
- 'src/routes/(main)/agent/_layout/Sidebar/lint-fixture.tsx',
- `import NavPanel from '@/features/NavPanel';\nvoid NavPanel;`,
- 'Route Sidebars must import NavPanelPortal from its dedicated subpath',
- ],
- [
- 'HomeInbox RunReplyEditor static import',
- 'src/features/HomeInbox/lint-fixture.tsx',
- `import RunReplyEditor from '@/features/AgentTasks/AgentTaskDetail/RunReplyEditor';\nvoid RunReplyEditor;`,
- 'Load RunReplyEditor with import()',
- ],
- [
- 'HomeInbox TopicChatDrawer static import',
- 'src/features/HomeInbox/lint-fixture.tsx',
- `import TopicChatDrawer from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';\nvoid TopicChatDrawer;`,
- 'HomeInbox must not mount TopicChatDrawer',
- ],
- [
- 'HomeInbox DocumentModal implementation import',
- 'src/features/HomeInbox/lint-fixture.tsx',
- `import DocumentModal from '@/features/DocumentModal';\nvoid DocumentModal;`,
- 'imperative DocumentModal loader',
- ],
- [
- 'home cold-path ChatInput static import',
- 'src/features/Home/lint-fixture.tsx',
- `import { ChatInput } from '@/features/ChatInput';\nvoid ChatInput;`,
- 'Home cold-path modules must not statically import ChatInput',
- ],
- [
- 'home cold-path ChatInput subpath import',
- 'src/features/Home/lint-fixture.tsx',
- `import ChatInputDesktop from '@/features/ChatInput/Desktop';\nvoid ChatInputDesktop;`,
- 'Home cold-path modules must not statically import ChatInput',
- ],
- [
- 'home cold-path Conversation root barrel',
- 'src/features/Home/lint-fixture.tsx',
- `import { ChatInput } from '@/features/Conversation';\nvoid ChatInput;`,
- 'Home cold-path modules must use stable Conversation subpaths',
- ],
- [
- 'home input direct EditorInput import',
- 'src/features/Home/InputArea/index.tsx',
- `import EditorInput from './EditorInput';\nvoid EditorInput;`,
- 'load EditorInput through useProgressiveEditor',
- ],
- [
- 'ShareModal implementation bypass',
- 'src/features/PageEditor/lint-fixture.tsx',
- `import openShareModal from '@/features/ShareModal/Modal';\nvoid openShareModal;`,
- 'Import the imperative facade from "@/features/ShareModal"',
- ],
- [
- 'existing UI restriction remains active',
- 'src/features/HomeInbox/lint-fixture.tsx',
- `import { Button } from '@lobehub/ui';\nvoid Button;`,
- 'Import from "@lobehub/ui/base-ui" instead',
- ],
-] as const;
-
-const allowedImports = [
- [
- 'Conversation stable store subpath',
- 'src/features/Conversation/ChatItem/lint-fixture.tsx',
- `import { useConversationStore } from '@/features/Conversation/store';\nvoid useConversationStore;`,
- ],
- [
- 'route Sidebar dedicated Portal subpath',
- 'src/routes/(main)/agent/_layout/Sidebar/lint-fixture.tsx',
- `import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';\nvoid NavPanelPortal;`,
- ],
- [
- 'HomeInbox interaction-triggered editor import',
- 'src/features/HomeInbox/lint-fixture.tsx',
- `void import('@/features/AgentTasks/AgentTaskDetail/RunReplyEditor');`,
- ],
- [
- 'HomeInbox imperative DocumentModal loader',
- 'src/features/HomeInbox/lint-fixture.tsx',
- `import { openDocumentModal } from '@/features/DocumentModal/loader';\nvoid openDocumentModal;`,
- ],
- [
- 'home interaction-triggered ChatInput import',
- 'src/features/Home/lint-fixture.tsx',
- `void import('@/features/ChatInput');`,
- ],
- [
- 'home lightweight ChatInput initial-state utility',
- 'src/features/Home/lint-fixture.tsx',
- `import { initialState } from '@/features/ChatInput/store/initialState';\nvoid initialState;`,
- ],
- [
- 'home lightweight ChatInput context-selection utility',
- 'src/features/Home/lint-fixture.tsx',
- `import { resolveContextSelections } from '@/features/ChatInput/utils/contextSelections';\nvoid resolveContextSelections;`,
- ],
- [
- 'isolated home EditorInput entry',
- 'src/features/Home/InputArea/EditorInput.tsx',
- `import { ChatInput } from '@/features/ChatInput';\nvoid ChatInput;`,
- ],
- [
- 'ShareModal imperative facade',
- 'src/features/PageEditor/lint-fixture.tsx',
- `import { openShareModal } from '@/features/ShareModal';\nvoid openShareModal;`,
- ],
-] as const;
-
-describe('performance import boundaries', () => {
- it.each(forbiddenImports)('rejects %s', async (_name, filePath, code, message) => {
- await expect(lintRestrictedImports(filePath, code)).resolves.toEqual([
- expect.stringContaining(message),
- ]);
- });
-
- it.each(allowedImports)('allows %s', async (_name, filePath, code) => {
- await expect(lintRestrictedImports(filePath, code)).resolves.toEqual([]);
- });
-});
-
-const useRefLazyInitFixture = 'src/hooks/useRef-lazy-init-lint-fixture.tsx';
-
-const forbiddenUseRefInits = [
- [
- 'useRef(function call)',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(getPlatform()); return r; };`,
- ],
- [
- 'useRef(new Map)',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(new Map()); return r; };`,
- ],
- [
- 'useRef(new Set) with type args',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef<Set<string>>(new Set()); return r; };`,
- ],
- [
- 'useRef(Date.now())',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(Date.now()); return r; };`,
- ],
- [
- 'useRef(Symbol())',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(Symbol('x')); return r; };`,
- ],
- [
- 'React.useRef(new Map)',
- `import React from 'react';\nexport const C = () => { const r = React.useRef(new Map()); return r; };`,
- ],
- [
- 'useRef(useSingleton(...))',
- `import { useRef } from 'react';\nimport { useSingleton } from '@/hooks/useSingleton';\nexport const C = () => { const r = useRef(useSingleton(() => new Map())); return r; };`,
- ],
-] as const;
-
-const allowedUseRefInits = [
- [
- 'useRef(null)',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(null); return r; };`,
- ],
- [
- 'useRef(false)',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(false); return r; };`,
- ],
- [
- 'useRef(identifier)',
- `import { useRef } from 'react';\nexport const C = (v: string) => { const r = useRef(v); return r; };`,
- ],
- [
- 'useRef(arrow function)',
- `import { useRef } from 'react';\nexport const C = () => { const r = useRef(() => {}); return r; };`,
- ],
- [
- 'useSingleton alone',
- `import { useSingleton } from '@/hooks/useSingleton';\nexport const C = () => useSingleton(() => new Map());`,
- ],
- [
- 'useSingleton mutable box',
- `import { useSingleton } from '@/hooks/useSingleton';\nexport const C = () => { const r = useSingleton(() => ({ current: new Map() })); r.current = new Map(); return r; };`,
- ],
-] as const;
-
-describe('useRef lazy-init boundary', () => {
- it.each(forbiddenUseRefInits)('rejects %s', async (_name, code) => {
- await expect(lintRestrictedSyntax(useRefLazyInitFixture, code)).resolves.toEqual([
- expect.stringContaining('useSingleton'),
- ]);
- });
-
- it.each(allowedUseRefInits)('allows %s', async (_name, code) => {
- await expect(lintRestrictedSyntax(useRefLazyInitFixture, code)).resolves.toEqual([]);
- });
-});
diff --git a/packages/electron-client-ipc/src/useWatchBroadcast.test.ts b/packages/electron-client-ipc/src/useWatchBroadcast.test.ts
new file mode 100644
index 00000000000..a5dd5b94854
--- /dev/null
+++ b/packages/electron-client-ipc/src/useWatchBroadcast.test.ts
@@ -0,0 +1,36 @@
+// @vitest-environment happy-dom
+
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useWatchBroadcast } from './useWatchBroadcast';
+
+describe('useWatchBroadcast', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('uses the disposer returned by the preload bridge', () => {
+ const handler = vi.fn();
+ const legacyRemoveListener = vi.fn();
+ const unsubscribe = vi.fn();
+ const on = vi.fn(
+ (_event: string, _listener: (event: unknown, data: { locale: string }) => void) =>
+ unsubscribe,
+ );
+
+ vi.stubGlobal('window', {
+ electron: { ipcRenderer: { on, removeListener: legacyRemoveListener } },
+ });
+
+ const { unmount } = renderHook(() => useWatchBroadcast('localeChanged', handler));
+ const listener = on.mock.calls[0]?.[1];
+
+ listener?.(undefined, { locale: 'zh-CN' });
+ expect(handler).toHaveBeenCalledWith({ locale: 'zh-CN' });
+
+ unmount();
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ expect(legacyRemoveListener).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/electron-client-ipc/src/useWatchBroadcast.ts b/packages/electron-client-ipc/src/useWatchBroadcast.ts
index 5d9c31fae99..4b73659e3bb 100644
--- a/packages/electron-client-ipc/src/useWatchBroadcast.ts
+++ b/packages/electron-client-ipc/src/useWatchBroadcast.ts
@@ -6,8 +6,7 @@ import type { MainBroadcastEventKey, MainBroadcastParams } from './events';
interface ElectronAPI {
ipcRenderer: {
- on: (event: MainBroadcastEventKey, listener: (e: any, data: any) => void) => void;
- removeListener: (event: MainBroadcastEventKey, listener: (e: any, data: any) => void) => void;
+ on: (event: MainBroadcastEventKey, listener: (e: any, data: any) => void) => () => void;
};
}
@@ -34,10 +33,6 @@ export const useWatchBroadcast = <T extends MainBroadcastEventKey>(
handlerRef.current(data);
};
- window.electron.ipcRenderer.on(event, listener);
-
- return () => {
- window.electron.ipcRenderer.removeListener(event, listener);
- };
+ return window.electron.ipcRenderer.on(event, listener);
}, [event]);
};
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index 737079ef200..31458a6fdf7 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -1,12 +1,13 @@
import { useEditor } from '@lobehub/editor/react';
-import { type ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { memo, useRef } from 'react';
import ReasoningConfigLoader from './ReasoningConfigLoader';
import { createStore, Provider } from './store';
import { DEFAULT_CHAT_INPUT_FEATURE } from './store/initialState';
-import { type StoreUpdaterProps } from './StoreUpdater';
+import type { StoreUpdaterProps } from './StoreUpdater';
import StoreUpdater from './StoreUpdater';
+import { useEditorRootLifecycle } from './useEditorRootLifecycle';
interface ChatInputProviderProps extends StoreUpdaterProps {
children: ReactNode;
@@ -38,6 +39,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
}) => {
const editor = useEditor();
const slashMenuRef = useRef<HTMLDivElement>(null);
+ useEditorRootLifecycle(editor);
return (
<Provider
diff --git a/src/features/ChatInput/useEditorRootLifecycle.test.ts b/src/features/ChatInput/useEditorRootLifecycle.test.ts
new file mode 100644
index 00000000000..9ba40b430b3
--- /dev/null
+++ b/src/features/ChatInput/useEditorRootLifecycle.test.ts
@@ -0,0 +1,163 @@
+// @vitest-environment happy-dom
+
+import type { IEditor } from '@lobehub/editor';
+import { getKernelFromEditorConfig } from '@lobehub/editor';
+import { Editor, useEditor } from '@lobehub/editor/react';
+import { render, waitFor } from '@testing-library/react';
+import { Activity, createElement, type Ref } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useEditorRootLifecycle } from './useEditorRootLifecycle';
+
+const Probe = ({ editor, rootRef }: { editor: IEditor; rootRef: Ref<HTMLDivElement> }) => {
+ useEditorRootLifecycle(editor);
+ return createElement('div', { ref: rootRef });
+};
+
+describe('useEditorRootLifecycle', () => {
+ it('restores a hidden root to its owning editor and destroys it only after unmount', async () => {
+ let ownerRoot: HTMLElement | null = null;
+ let replacementRoot: HTMLElement | null = document.createElement('div');
+ const destroy = vi.fn();
+ const ownerSetRootElement = vi.fn((root: HTMLElement | null) => {
+ ownerRoot = root;
+ });
+ const ownerLexicalEditor = {
+ getRootElement: vi.fn(() => ownerRoot),
+ setRootElement: ownerSetRootElement,
+ };
+ const replacementSetRootElement = vi.fn((root: HTMLElement | null) => {
+ replacementRoot = root;
+ });
+ const replacementLexicalEditor = {
+ getRootElement: vi.fn(() => replacementRoot),
+ setRootElement: replacementSetRootElement,
+ };
+ const editor = {
+ destroy,
+ getLexicalEditor: vi
+ .fn()
+ .mockReturnValueOnce(ownerLexicalEditor)
+ .mockReturnValue(replacementLexicalEditor),
+ } as unknown as IEditor;
+ const rootRef = (root: HTMLDivElement | null) => {
+ if (root) ownerRoot = root;
+ };
+ const tree = (mode: 'hidden' | 'visible') =>
+ createElement(Activity, { children: createElement(Probe, { editor, rootRef }), mode });
+
+ const { rerender, unmount } = render(tree('visible'));
+ const element = ownerRoot;
+
+ rerender(tree('hidden'));
+ expect(ownerSetRootElement).toHaveBeenLastCalledWith(null);
+ expect(destroy).not.toHaveBeenCalled();
+
+ rerender(tree('visible'));
+ expect(ownerSetRootElement).toHaveBeenLastCalledWith(element);
+ expect(replacementSetRootElement).not.toHaveBeenCalled();
+ expect(editor.getLexicalEditor).toHaveBeenCalledOnce();
+
+ rerender(tree('hidden'));
+ unmount();
+ expect(ownerSetRootElement).toHaveBeenLastCalledWith(null);
+ await waitFor(() => expect(destroy).toHaveBeenCalledOnce());
+ });
+});
+
+const isRegistered = (editor: IEditor) => {
+ const theme = (editor.getLexicalEditor() as any)?._config?.theme;
+ return !!theme && getKernelFromEditorConfig({ theme } as any) === (editor as any);
+};
+
+const rootOf = (editor: IEditor) => editor.getLexicalEditor()!.getRootElement();
+
+const renderRealEditor = ({ lifecycle }: { lifecycle: boolean }) => {
+ let captured!: IEditor;
+ const Host = () => {
+ const editor = useEditor();
+ captured = editor;
+ useEditorRootLifecycle(lifecycle ? editor : ({ getLexicalEditor: () => null } as IEditor));
+ return createElement(Editor, { content: '', editor, type: 'text' });
+ };
+ const tree = (mode: 'hidden' | 'visible') =>
+ createElement(Activity, { children: createElement(Host), mode });
+ return { ...render(tree('visible')), editor: () => captured, tree };
+};
+
+describe('useEditorRootLifecycle with a real editor', () => {
+ it('leaks the kernel into the global registry when the lifecycle is not applied', async () => {
+ const { editor, unmount } = renderRealEditor({ lifecycle: false });
+ await waitFor(() => expect(rootOf(editor())).toBeTruthy());
+
+ unmount();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(isRegistered(editor())).toBe(true);
+ });
+
+ it('destroys the kernel on a direct visible unmount', async () => {
+ const { editor, unmount } = renderRealEditor({ lifecycle: true });
+ await waitFor(() => expect(rootOf(editor())).toBeTruthy());
+
+ unmount();
+ await waitFor(() => expect(isRegistered(editor())).toBe(false));
+ });
+
+ it('detaches the root but keeps the kernel while hidden', async () => {
+ const { editor, rerender, tree } = renderRealEditor({ lifecycle: true });
+ await waitFor(() => expect(rootOf(editor())).toBeTruthy());
+ const root = rootOf(editor());
+
+ rerender(tree('hidden'));
+ expect(rootOf(editor())).toBeNull();
+ expect(root!.isConnected).toBe(true);
+ expect(isRegistered(editor())).toBe(true);
+ });
+
+ it('restores the same root to the same kernel when revealed', async () => {
+ const { editor, rerender, tree } = renderRealEditor({ lifecycle: true });
+ await waitFor(() => expect(rootOf(editor())).toBeTruthy());
+ const root = rootOf(editor());
+ const lexicalEditor = editor().getLexicalEditor();
+
+ rerender(tree('hidden'));
+ rerender(tree('visible'));
+ expect(rootOf(editor())).toBe(root);
+ expect(editor().getLexicalEditor()).toBe(lexicalEditor);
+ expect(isRegistered(editor())).toBe(true);
+ });
+
+ it('destroys the kernel when a hidden tree unmounts', async () => {
+ const { editor, rerender, tree, unmount } = renderRealEditor({ lifecycle: true });
+ await waitFor(() => expect(rootOf(editor())).toBeTruthy());
+
+ rerender(tree('hidden'));
+ unmount();
+ await waitFor(() => expect(isRegistered(editor())).toBe(false));
+ });
+
+ it('destroys the kernel when the root is detached by a ref cleanup before the effect', async () => {
+ let root: HTMLElement | null = null;
+ const destroy = vi.fn();
+ const lexicalEditor = {
+ getRootElement: () => root,
+ setRootElement: (next: HTMLElement | null) => {
+ root = next;
+ },
+ };
+ const editor = { destroy, getLexicalEditor: () => lexicalEditor } as unknown as IEditor;
+ const Host = () => {
+ useEditorRootLifecycle(editor);
+ return createElement('div', {
+ ref: (node: HTMLElement | null) => {
+ lexicalEditor.setRootElement(node);
+ return () => lexicalEditor.setRootElement(null);
+ },
+ });
+ };
+
+ const { unmount } = render(createElement(Host));
+ unmount();
+ await waitFor(() => expect(destroy).toHaveBeenCalledOnce());
+ });
+});
diff --git a/src/features/ChatInput/useEditorRootLifecycle.ts b/src/features/ChatInput/useEditorRootLifecycle.ts
new file mode 100644
index 00000000000..f241a125b44
--- /dev/null
+++ b/src/features/ChatInput/useEditorRootLifecycle.ts
@@ -0,0 +1,56 @@
+import type { IEditor } from '@lobehub/editor';
+import { useEffect, useRef } from 'react';
+
+/**
+ * React Activity disconnects effects while preserving hidden DOM. Detach the
+ * Lexical root while inactive, then reconnect the same element when visible.
+ */
+export const useEditorRootLifecycle = (editor: IEditor) => {
+ const disconnectObserverRef = useRef<MutationObserver | null>(null);
+ const destroyedEditorRef = useRef<IEditor | null>(null);
+ const rootRef = useRef<HTMLElement | null>(null);
+ const inactiveEditorRef = useRef<{
+ lexicalEditor: NonNullable<ReturnType<IEditor['getLexicalEditor']>>;
+ root: HTMLElement;
+ } | null>(null);
+
+ useEffect(() => {
+ disconnectObserverRef.current?.disconnect();
+ disconnectObserverRef.current = null;
+
+ const inactiveEditor = inactiveEditorRef.current;
+ const lexicalEditor = inactiveEditor?.lexicalEditor ?? editor.getLexicalEditor();
+ if (!lexicalEditor) return;
+
+ if (inactiveEditor) {
+ lexicalEditor.setRootElement(inactiveEditor.root);
+ inactiveEditorRef.current = null;
+ }
+ rootRef.current = lexicalEditor.getRootElement();
+
+ return () => {
+ // The root is read from our own ref as well, because a future editor
+ // release may detach it from a ref cleanup, which React runs before this
+ // passive cleanup — leaving getRootElement() already null.
+ const root = lexicalEditor.getRootElement() ?? rootRef.current;
+ lexicalEditor.setRootElement(null);
+ rootRef.current = null;
+
+ if (!root) return;
+ inactiveEditorRef.current = { lexicalEditor, root };
+
+ const destroyWhenDisconnected = () => {
+ if (root.isConnected || destroyedEditorRef.current === editor) return;
+ destroyedEditorRef.current = editor;
+ observer.disconnect();
+ if (disconnectObserverRef.current === observer) disconnectObserverRef.current = null;
+ inactiveEditorRef.current = null;
+ editor.destroy();
+ };
+ const observer = new MutationObserver(destroyWhenDisconnected);
+ observer.observe(root.ownerDocument, { childList: true, subtree: true });
+ disconnectObserverRef.current = observer;
+ queueMicrotask(destroyWhenDisconnected);
+ };
+ }, [editor]);
+};
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 2b38d0ac37e..d45a4253ffa 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -145,10 +145,12 @@ function setupIpcCapture() {
ipcRenderer: {
on: vi.fn((channel: string, handler: (...args: any[]) => void) => {
listeners.set(channel, handler);
+ return () => {
+ if (listeners.get(channel) === handler) listeners.delete(channel);
+ };
}),
- removeListener: vi.fn((channel: string, handler: (...args: any[]) => void) => {
- if (listeners.get(channel) === handler) listeners.delete(channel);
- }),
+ // A separately bridged callback does not preserve the listener proxy identity.
+ removeListener: vi.fn(),
},
},
};
@@ -662,6 +664,12 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
return { get, store };
}
+ it('releases all IPC subscriptions after a run settles', async () => {
+ await runWithEvents([ccInit(), ccResult()]);
+
+ expect([...ipc.getListeners().keys()]).toEqual([]);
+ });
+
describe('cancellation coordination', () => {
/**
* @example “Send now” awaits the renderer cancellation hook before dispatching a replacement.
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index feb5785d38a..9e9b4f4a39e 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -325,14 +325,14 @@ const subscribeBroadcasts = (
if (data.sessionId === sessionId) callbacks.onError(data.error);
};
- ipc.on('heteroAgentEvent' as any, onStreamEvent);
- ipc.on('heteroAgentSessionComplete' as any, onComplete);
- ipc.on('heteroAgentSessionError' as any, onError);
+ const unsubscribeStreamEvent = ipc.on('heteroAgentEvent' as any, onStreamEvent);
+ const unsubscribeComplete = ipc.on('heteroAgentSessionComplete' as any, onComplete);
+ const unsubscribeError = ipc.on('heteroAgentSessionError' as any, onError);
return () => {
- ipc.removeListener('heteroAgentEvent' as any, onStreamEvent);
- ipc.removeListener('heteroAgentSessionComplete' as any, onComplete);
- ipc.removeListener('heteroAgentSessionError' as any, onError);
+ unsubscribeStreamEvent();
+ unsubscribeComplete();
+ unsubscribeError();
};
};