🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf: reduce idle rendering and defer cold tab routers (#19347)
Innei8642e9b94781
diff --git a/src/features/Electron/TabHost/TabHost.test.ts b/src/features/Electron/TabHost/TabHost.test.tsindex 5a4b90a3fe8..9851ecbc1ae 100644--- a/src/features/Electron/TabHost/TabHost.test.ts+++ b/src/features/Electron/TabHost/TabHost.test.ts@@ -100,6 +100,26 @@ afterEach(() => {});describe('TabHost', () => {+ it('creates only the visible router when restoring many persisted tabs', async () => {+ setStore(+ Array.from({ length: 14 }, (_, i) => ({+ id: `t${i}`,+ lastVisited: i,+ url: `/item/t${i}`,+ })),+ 't0',+ );+ renderHost();+ expect(await screen.findByTestId('param-t0')).toBeVisible();+ expect(created.map(({ url }) => url)).toEqual(['/item/t0']);+ act(() => useElectronStore.setState({ activeTabId: 't1' }));+ expect(await screen.findByTestId('param-t1')).toBeVisible();+ expect(created.map(({ url }) => url)).toEqual(['/item/t0', '/item/t1']);+ act(() => useElectronStore.setState({ activeTabId: 't0' }));+ expect(screen.getByTestId('param-t0')).toBeVisible();+ expect(created).toHaveLength(2);+ });+it('mounts per-tab routers inside an outer data router without tripping the nested-Router invariant', async () => {setStore([@@ -122,6 +142,8 @@ describe('TabHost', () => {render(React.createElement(RouterProvider, { router: outerRouter }));expect(await screen.findByTestId('param-a')).toHaveTextContent('a');+ expect(screen.queryByTestId('param-b')).not.toBeInTheDocument();+ act(() => useElectronStore.setState({ activeTabId: 'b' }));expect(await screen.findByTestId('param-b')).toHaveTextContent('b');});@@ -137,6 +159,8 @@ describe('TabHost', () => {renderHost();expect(await screen.findByTestId('param-a')).toHaveTextContent('a');+ expect(screen.queryByTestId('param-b')).not.toBeInTheDocument();+ act(() => useElectronStore.setState({ activeTabId: 'b' }));expect(await screen.findByTestId('param-b')).toHaveTextContent('b');});@@ -152,7 +176,10 @@ describe('TabHost', () => {renderHost();const slotA = (await screen.findByTestId('param-a')).parentElement!;+ expect(screen.queryByTestId('param-b')).not.toBeInTheDocument();+ act(() => useElectronStore.setState({ activeTabId: 'b' }));const slotB = (await screen.findByTestId('param-b')).parentElement!;+ act(() => useElectronStore.setState({ activeTabId: 'a' }));expect(slotA.style.display).toBe('');expect(slotB.style.display).toBe('none');@@ -224,7 +251,7 @@ describe('TabHost', () => {renderHost();expect(await screen.findByTestId('param-a')).toBeVisible();- expect(screen.getByTestId('param-b').parentElement).toHaveStyle({ display: 'none' });+ expect(screen.queryByTestId('param-b')).not.toBeInTheDocument();await waitFor(() => expect(useElectronStore.getState().splitView).toBeNull());});@@ -239,7 +266,10 @@ describe('TabHost', () => {setStore(baseTabs, 't0');renderHost();- await screen.findByTestId(`param-${oldest.id}`);+ for (const tab of baseTabs) {+ act(() => useElectronStore.setState({ activeTabId: tab.id }));+ await screen.findByTestId(`param-${tab.id}`);+ }expect(created).toHaveLength(MAX_LIVE_TAB_ROUTERS);const withEvictor: TabItem[] = [@@ -298,6 +328,10 @@ describe('TabHost', () => {act(() => {useElectronStore.setState({ activeTabId: 'f0', tabs: evicted });});+ for (const tab of fillers.slice(1, MAX_LIVE_TAB_ROUTERS)) {+ act(() => useElectronStore.setState({ activeTabId: tab.id }));+ await screen.findByTestId(`param-${tab.id}`);+ }const targetEntry = created.find((entry) => entry.url === '/agent/orig')!;await vi.waitFor(() => expect(targetEntry.dispose).toHaveBeenCalled());@@ -322,13 +356,17 @@ describe('TabHost', () => {url: `/item/f${index}`,}));- // The newest filler is active; `target` is hidden but live. `createTestRouter`+ // Visit the target and fillers so `target` is hidden but live. `createTestRouter`// mounts no reporter, mirroring the real hidden tab whose reporter effect is// torn down.- setStore([target, ...fillers], fillers.at(-1)!.id);+ setStore([target, ...fillers], target.id);renderHost();await screen.findByTestId('param-target');+ for (const tab of fillers) {+ act(() => useElectronStore.setState({ activeTabId: tab.id }));+ await screen.findByTestId(`param-${tab.id}`);+ }const targetRouter = created.find((entry) => entry.url === '/item/target')!.router;await act(async () => {@@ -340,7 +378,7 @@ describe('TabHost', () => {'/item/target',);- // A newly active sixth tab pushes the oldest (`target`) out of the live set.+ // A newly active tab pushes the oldest (`target`) out of the live set.const withEvictor: TabItem[] = [...useElectronStore.getState().tabs,{ id: 'evictor', lastVisited: 100, url: '/item/evictor' },@@ -381,6 +419,8 @@ describe('TabHost', () => {render(React.createElement(TabHost, { createRouter: createScopedRouter }));+ act(() => useElectronStore.setState({ activeTabId: 'b' }));+ act(() => useElectronStore.setState({ activeTabId: 'a' }));await vi.waitFor(() => {expect(getTabRouter('a')).toBeDefined();expect(getTabRouter('b')).toBeDefined();@@ -422,7 +462,9 @@ describe('TabHost', () => {render(React.createElement(TabHost, { createRouter: createReporterRouter }));+ act(() => useElectronStore.setState({ activeTabId: 'b' }));await screen.findByTestId('param-b');+ act(() => useElectronStore.setState({ activeTabId: 'a' }));const hiddenRouter = created.find((entry) => entry.url === '/agent/b')!.router;await act(async () => {diff --git a/src/features/Electron/TabHost/TabHost.tsx b/src/features/Electron/TabHost/TabHost.tsxindex 488f96fc4b4..bb4d97df1d0 100644--- a/src/features/Electron/TabHost/TabHost.tsx+++ b/src/features/Electron/TabHost/TabHost.tsx@@ -155,7 +155,14 @@ const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {}, [closeSplitView, isPreferenceInit, splitView, splitViewEnabled]);const liveIds = useMemo(- () => resolveLiveTabIds(tabs, activeTabId, MAX_LIVE_TAB_ROUTERS, visibleTabIds),+ () =>+ resolveLiveTabIds(+ // Persisted tabs are cold until first shown; only retain already-created routers.+ tabs.filter((tab) => visibleTabIds.includes(tab.id) || getTabRouter(tab.id)),+ activeTabId,+ MAX_LIVE_TAB_ROUTERS,+ visibleTabIds,+ ),[tabs, activeTabId, visibleTabIds],);diff --git a/src/features/NavPanel/index.test.tsx b/src/features/NavPanel/index.test.tsxindex 85768c5cf27..91ca2e1e354 100644--- a/src/features/NavPanel/index.test.tsx+++ b/src/features/NavPanel/index.test.tsx@@ -1,12 +1,18 @@-import { render, screen, waitFor } from '@testing-library/react';+import { act, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import NavPanel from './index';import { NavPanelPortal } from './NavPanelPortal';-import { clearNavPanelRegistry } from './registry';+import {+ clearNavPanelRegistry,+ registerNavPanelContent,+ unregisterNavPanelContent,+} from './registry';import NavPanelShell from './Shell';+const panelRender = vi.fn();+let pathname = '/lobe-team/settings/general';interface WorkspaceMock {@@ -37,11 +43,14 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({}));vi.mock('./components/NavPanelDraggable', () => ({- NavPanelDraggable: ({ activeContent }: NavPanelDraggableMockProps) => (- <div data-nav-key={activeContent.key} data-testid="nav-panel">- {activeContent.node}- </div>- ),+ NavPanelDraggable: ({ activeContent }: NavPanelDraggableMockProps) => {+ panelRender();+ return (+ <div data-nav-key={activeContent.key} data-testid="nav-panel">+ {activeContent.node}+ </div>+ );+ },}));vi.mock('@/features/HomeSidebar/Content', () => ({@@ -54,6 +63,27 @@ describe('NavPanel', () => {clearNavPanelRegistry();});+ it.each([false, true])(+ 'ignores unrelated registrations with active content present: %s',+ (registered) => {+ pathname = '/tasks';+ const owner = Symbol('home');+ if (registered) registerNavPanelContent('home', owner, <div>Original</div>);+ render(<NavPanel />);+ const before = panelRender.mock.calls.length;+ const otherOwner = Symbol('discover');++ act(() => registerNavPanelContent('discover', otherOwner, <div>Discover</div>));+ act(() => unregisterNavPanelContent('discover', otherOwner));+ expect(panelRender).toHaveBeenCalledTimes(before);++ act(() => registerNavPanelContent('home', owner, <div>Updated</div>));+ expect(screen.getByText('Updated')).toBeInTheDocument();+ act(() => unregisterNavPanelContent('home', owner));+ expect(screen.getByTestId('nav-sidebar-skeleton')).toBeInTheDocument();+ },+ );+it('selects the route-owned entry instead of a concurrently registered Home entry', async () => {render(<>diff --git a/src/features/NavPanel/index.tsx b/src/features/NavPanel/index.tsxindex 3f443b69223..a16d9dc1fda 100644--- a/src/features/NavPanel/index.tsx+++ b/src/features/NavPanel/index.tsx@@ -18,12 +18,12 @@ const NavPanelFallback = memo<{ navKey: string }>(({ navKey }) => (const NavPanel = memo(() => {const activeNavKey = useActiveNavKey();- const registry = useSyncExternalStore(+ const getActiveContent = () => getNavPanelRegistrySnapshot().get(activeNavKey);+ const registeredContent = useSyncExternalStore(subscribeNavPanelRegistry,- getNavPanelRegistrySnapshot,- getNavPanelRegistrySnapshot,+ getActiveContent,+ getActiveContent,);- const registeredContent = registry.get(activeNavKey);const activeContent = registeredContent? { key: activeNavKey, node: registeredContent.node }: { key: `pending:${activeNavKey}`, node: <NavPanelFallback navKey={activeNavKey} /> };diff --git a/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx b/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsxindex 87270c62c23..e7fe6df97e0 100644--- a/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx+++ b/src/routes/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx@@ -8,6 +8,8 @@ import * as THREE from 'three';import { type QueryTagsResult } from '@/database/models/userMemory';import UserAvatar from '@/features/User/UserAvatar';+import { retainActiveConnections } from './retainActiveConnections';+// Configuration constantsconst CONFIG = {// Connection line count ratio (actual count = tag count * ratio)@@ -267,7 +269,8 @@ const ConnectionLine = memo<ConnectionLineProps>(},);-const CenterAvatar = () => {+// Connection animation updates must not rerender the DOM avatar mounted through Html.+const CenterAvatar = memo(() => {return (<Htmlcenter@@ -280,7 +283,7 @@ const CenterAvatar = () => {<UserAvatar shape={'circle'} size={80} /></Html>);-};+});interface CloudProps {radius?: number;@@ -411,7 +414,7 @@ const Cloud = memo<CloudProps>(({ tags, radius = 20 }) => {setConnections((prev) => {// Filter out expired connections- const active = prev.filter((conn) => time - conn.birthTime < conn.duration);+ const active = retainActiveConnections(prev, time);// If there are not enough connections, randomly add new onesconst needed = connectionCount - active.length;diff --git a/src/routes/(main)/memory/(home)/features/RoleTagCloud/retainActiveConnections.test.ts b/src/routes/(main)/memory/(home)/features/RoleTagCloud/retainActiveConnections.test.tsnew file mode 100644index 00000000000..32ab09e131a--- /dev/null+++ b/src/routes/(main)/memory/(home)/features/RoleTagCloud/retainActiveConnections.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { retainActiveConnections } from './retainActiveConnections';++describe('retainActiveConnections', () => {+ it('keeps idle ticks referentially stable, including an empty cloud', () => {+ const connections = [{ birthTime: 1, duration: 2 }];+ expect(retainActiveConnections(connections, 2)).toBe(connections);+ const empty: typeof connections = [];+ expect(retainActiveConnections(empty, 10)).toBe(empty);+ });++ it('expires connections at their deadline without replacing survivors or mutating state', () => {+ const expired = { birthTime: 1, duration: 2 };+ const survivor = { birthTime: 2, duration: 4 };+ const connections = [expired, survivor];+ const active = retainActiveConnections(connections, 3);+ expect(active).toEqual([survivor]);+ expect(active[0]).toBe(survivor);+ expect(connections).toEqual([expired, survivor]);+ expect(retainActiveConnections(active, 6)).toEqual([]);+ });+});diff --git a/src/routes/(main)/memory/(home)/features/RoleTagCloud/retainActiveConnections.ts b/src/routes/(main)/memory/(home)/features/RoleTagCloud/retainActiveConnections.tsnew file mode 100644index 00000000000..35f3d1093bc--- /dev/null+++ b/src/routes/(main)/memory/(home)/features/RoleTagCloud/retainActiveConnections.ts@@ -0,0 +1,9 @@+export const retainActiveConnections = <T extends { birthTime: number; duration: number }>(+ connections: T[],+ time: number,+): T[] => {+ const active = connections.filter(+ (connection) => time - connection.birthTime < connection.duration,+ );+ return active.length === connections.length ? connections : active;+};