π€― 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
π fix(desktop): bind sidebar router hooks to the active tab router (#17773)
Innei9d45f1fac090
diff --git a/eslint.config.mjs b/eslint.config.mjsindex bf1081a886a..120c10b70e5 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -16,6 +16,34 @@ const performanceRestrictedImportPaths = [},];+// On desktop the shell β every NavPanelPortal sidebar, the titlebar, the command+// menu β renders as a sibling of TabHost, so React context binds these hooks to+// the frozen root router while page content lives in per-tab memory routers.+// A write then lands on a router no page reads and a read resolves the boot url,+// silently and only on desktop. `Link` stays allowed: the convention is a real+// href plus an onClick that preventDefaults into the navigation facade.+const shellRouterRestrictedPaths = [+ {+ importNames: [+ 'useLocation',+ 'useMatch',+ 'useMatches',+ 'useNavigate',+ 'useParams',+ 'useSearchParams',+ ],+ message:+ 'Shell trees render outside the per-tab router. Read with useActiveLocation / useActiveRouteParams and navigate with useWorkspaceAwareNavigate. There is no active-tab twin for useSearchParams: express the write as a facade navigation, or move the url state into the route tree that owns it.',+ name: 'react-router',+ },+ {+ importNames: ['useQueryParam', 'useQueryState'],+ message:+ 'useQueryState wraps useSearchParams, so it binds to the frozen root router here. Move the url state into the route tree that owns it, or write through the navigation facade.',+ name: '@/hooks/useQueryParam',+ },+];+const createRestrictedImportRule = ({ paths = [], patterns } = {}) => ['error',{@@ -107,6 +135,7 @@ export default eslint(files: ['src/features/NavPanel/**/*.{ts,tsx}'],rules: {'no-restricted-imports': createRestrictedImportRule({+ paths: shellRouterRestrictedPaths,patterns: [{group: [@@ -137,10 +166,31 @@ export default eslint('Route Sidebars must import NavPanelPortal from its dedicated subpath instead of the NavPanel host barrel.',name: '@/features/NavPanel',},+ ...shellRouterRestrictedPaths,],}),},},+ {+ // Sidebar/titlebar/command-menu trees the desktop shell renders outside TabHost.+ // GenerationLayout is split deliberately: Body and Header are portal'd into the+ // sidebar, while the layout root stays in the route tree and owns the url sync.+ files: [+ 'src/features/AgentSidebar/**/*.{ts,tsx}',+ 'src/features/CommandMenu/**/*.{ts,tsx}',+ 'src/features/Electron/titlebar/**/*.{ts,tsx}',+ 'src/features/HomeSidebar/**/*.{ts,tsx}',+ 'src/features/Pages/PageLayout/Sidebar.{ts,tsx}',+ 'src/features/WorkspaceSetting/SideBar/**/*.{ts,tsx}',+ 'src/routes/(main)/(create)/features/GenerationLayout/Body/**/*.{ts,tsx}',+ 'src/routes/(main)/(create)/features/GenerationLayout/Header/**/*.{ts,tsx}',+ ],+ rules: {+ 'no-restricted-imports': createRestrictedImportRule({+ paths: shellRouterRestrictedPaths,+ }),+ },+ },{files: ['src/features/HomeInbox/**/*.{ts,tsx}'],rules: {diff --git a/src/features/AgentTasks/shared/taskDetailPath.ts b/src/features/AgentTasks/shared/taskDetailPath.tsindex 41fedbd1bf2..52f4f5f370b 100644--- a/src/features/AgentTasks/shared/taskDetailPath.ts+++ b/src/features/AgentTasks/shared/taskDetailPath.ts@@ -1,13 +1,13 @@import { useCallback } from 'react';-import { useParams } from 'react-router';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';export const taskDetailPath = (taskId: string, agentId?: string) =>agentId ? `/agent/${agentId}/task/${taskId}` : `/task/${taskId}`;export const useTaskDetailPath = () => {- const { aid } = useParams<{ aid?: string }>();+ const { aid } = useActiveRouteParams<{ aid?: string }>();return useCallback((taskId: string, agentId?: string) => taskDetailPath(taskId, agentId ?? aid),diff --git a/src/features/Generation/TopicUrlSync.tsx b/src/features/Generation/TopicUrlSync.tsxnew file mode 100644index 00000000000..8cdd6839e34--- /dev/null+++ b/src/features/Generation/TopicUrlSync.tsx@@ -0,0 +1,11 @@+'use client';++import { type TopicUrlSyncStore, useTopicUrlSync } from './useTopicUrlSync';++const TopicUrlSync = ({ useStore }: { useStore: TopicUrlSyncStore }) => {+ useTopicUrlSync(useStore);++ return null;+};++export default TopicUrlSync;diff --git a/src/features/Generation/index.ts b/src/features/Generation/index.tsnew file mode 100644index 00000000000..d235937da9e--- /dev/null+++ b/src/features/Generation/index.ts@@ -0,0 +1,2 @@+export { default as TopicUrlSync } from './TopicUrlSync';+export { type TopicUrlSyncStore, useTopicUrlSync } from './useTopicUrlSync';diff --git a/src/features/Generation/useTopicUrlSync.test.ts b/src/features/Generation/useTopicUrlSync.test.tsnew file mode 100644index 00000000000..cc1dea51ed0--- /dev/null+++ b/src/features/Generation/useTopicUrlSync.test.ts@@ -0,0 +1,79 @@+import { act, cleanup, renderHook, screen } from '@testing-library/react';+import React, { type PropsWithChildren } from 'react';+import { MemoryRouter, UNSAFE_LocationContext, useLocation } from 'react-router';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { create } from 'zustand';++import { useTopicUrlSync } from './useTopicUrlSync';++const useTopicStore = create<{ activeGenerationTopicId: string | null }>(() => ({+ activeGenerationTopicId: null,+}));++const probe = (testId: string) => () =>+ React.createElement('div', { 'data-testid': testId }, useLocation().search);++const PageProbe = probe('page-search');+const ShellProbe = probe('shell-search');++// Mirrors the desktop shell: `NavPanelShell` β which renders every portal'd+// sidebar β is a sibling of `TabHost` under the frozen root router, and each tab+// resets LocationContext so its own router mounts as a root.+const desktopWrapper =+ (tabEntry: string) =>+ ({ children }: PropsWithChildren) =>+ React.createElement(+ MemoryRouter,+ { initialEntries: ['/'] },+ React.createElement(ShellProbe),+ React.createElement(+ UNSAFE_LocationContext,+ { value: null as never },+ React.createElement(+ MemoryRouter,+ { initialEntries: [tabEntry] },+ React.createElement(PageProbe),+ children,+ ),+ ),+ );++const renderSync = (tabEntry: string) =>+ renderHook(() => useTopicUrlSync(useTopicStore), { wrapper: desktopWrapper(tabEntry) });++beforeEach(() => {+ useTopicStore.setState({ activeGenerationTopicId: null });+});++afterEach(() => {+ cleanup();+});++describe('useTopicUrlSync', () => {+ it('writes the active topic into the router the page reads, not the shell router', async () => {+ renderSync('/image');++ await act(async () => {+ useTopicStore.setState({ activeGenerationTopicId: 'topic-1' });+ });++ expect(screen.getByTestId('page-search').textContent).toBe('?topic=topic-1');+ expect(screen.getByTestId('shell-search').textContent).toBe('');+ });++ it('seeds the store from the page url on mount', () => {+ renderSync('/image?topic=topic-9');++ expect(useTopicStore.getState().activeGenerationTopicId).toBe('topic-9');+ });++ it('clears the topic param when the topic is reset', async () => {+ renderSync('/image?topic=topic-9');++ await act(async () => {+ useTopicStore.setState({ activeGenerationTopicId: null });+ });++ expect(screen.getByTestId('page-search').textContent).toBe('');+ });+});diff --git a/src/routes/(main)/(create)/features/GenerationLayout/Body/List/TopicUrlSync.tsx b/src/features/Generation/useTopicUrlSync.tssimilarity index 63%rename from src/routes/(main)/(create)/features/GenerationLayout/Body/List/TopicUrlSync.tsxrename to src/features/Generation/useTopicUrlSync.tsindex 63725ab5960..27c5c38523e 100644--- a/src/routes/(main)/(create)/features/GenerationLayout/Body/List/TopicUrlSync.tsx+++ b/src/features/Generation/useTopicUrlSync.ts@@ -4,18 +4,25 @@ import { useLayoutEffect } from 'react';import { useQueryState } from '@/hooks/useQueryParam';-import { useGenerationTopicContext } from './StoreContext';+export interface TopicUrlSyncStore {+ getState: () => { activeGenerationTopicId: string | null };+ setState: (partial: { activeGenerationTopicId: string | null }) => void;+ subscribe: (listener: (state: { activeGenerationTopicId: string | null }) => void) => () => void;+}/*** Bidirectional sync between URL 'topic' param and store's activeGenerationTopicId.*+ * Must run inside the route tree, never in a portal'd sidebar: on Electron the+ * sidebar is rendered by `NavPanel`, which lives outside `TabHost` and is bound+ * to the frozen root router. Writing there lands the param in a different router+ * than the generation page reads, so the workspace never opens after generating.+ ** Uses two useLayoutEffect hooks to ensure URL β store sync runs before* the store β URL subscription is set up, preventing stale store values* from overwriting the URL on remount.*/-const TopicUrlSync = () => {- const { useStore } = useGenerationTopicContext();-+export const useTopicUrlSync = (useStore: TopicUrlSyncStore) => {const [topic, setTopic] = useQueryState('topic', { history: 'replace', throttleMs: 500 });// URL β store: runs first to ensure store matches URL before subscription@@ -37,8 +44,4 @@ const TopicUrlSync = () => {unsubscribeTopic();};}, [setTopic, useStore]);-- return null;};--export default TopicUrlSync;diff --git a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.ts b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.tsnew file mode 100644index 00000000000..32f831543ef--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.desktop.test.ts@@ -0,0 +1,118 @@+import { act, cleanup, renderHook, screen } from '@testing-library/react';+import React, { type PropsWithChildren } from 'react';+import { createMemoryRouter, MemoryRouter, useLocation } from 'react-router';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Resolve the desktop twins of both facades. The web twins are plain+// `useLocation` / `useNavigate`, under which the pre-fix `useSearchParams` and+// the fixed facade call behave identically β only the desktop twins can tell+// them apart, because only they dispatch to the active tab's own router.+vi.mock('@/hooks/useActiveLocation', async () => await import('@/hooks/useActiveLocation.desktop'));+vi.mock(+ '@/features/Workspace/useWorkspaceAwareNavigate',+ async () => await import('@/features/Workspace/useWorkspaceAwareNavigate.desktop'),+);+// The desktop navigate twin forwards absolute string paths to `appNavigate`,+// which must also resolve to its desktop twin β the web one drives a global+// navigate ref that no test registers, so it would silently do nothing.+vi.mock(+ '@/features/Electron/navigation/appNavigate',+ async () => await import('@/features/Electron/navigation/appNavigate.desktop'),+);++const { getOrCreateTabRouter, getTabRouter, resetTabRouterManager } =+ await import('@/features/Electron/TabHost/tabRouterManager');+const { useElectronStore } = await import('@/store/electron');+const { useFileItemClick } = await import('./useFileItemClick');++const TAB_ID = 'tab-1';+const TAB_URL = '/resource/library/kb_1?view=grid';++const createRouter = (url: string) =>+ createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] }) as any;++const ShellProbe = () =>+ React.createElement('div', { 'data-testid': 'shell-search' }, useLocation().search);++// The library sidebar is portal'd into the shell, which on desktop is a sibling+// of TabHost β so the hook renders under the shell router while the page it+// drives lives in the tab router.+const shellWrapper = ({ children }: PropsWithChildren) =>+ React.createElement(+ MemoryRouter,+ { initialEntries: ['/'] },+ React.createElement(ShellProbe),+ children,+ );++const renderFileClick = (options: Parameters<typeof useFileItemClick>[0]) =>+ renderHook(() => useFileItemClick(options), { wrapper: shellWrapper });++beforeEach(() => {+ resetTabRouterManager();+ useElectronStore.setState({+ activeTabId: TAB_ID,+ tabs: [{ id: TAB_ID, lastVisited: 0, url: TAB_URL }],+ });+ getOrCreateTabRouter(TAB_ID, TAB_URL, createRouter);+});++afterEach(() => {+ cleanup();+ resetTabRouterManager();+ useElectronStore.setState({ activeTabId: null, tabs: [] });+});++describe('useFileItemClick (desktop shell)', () => {+ it('writes ?file= to the active tab router, not the shell router', async () => {+ const { result } = renderFileClick({+ id: 'file_1',+ isFolder: false,+ isPage: false,+ libraryId: 'kb_1',+ });++ await act(async () => {+ result.current();+ });++ expect(getTabRouter(TAB_ID)!.state.location.search).toBe('?view=grid&file=file_1');+ expect(screen.getByTestId('shell-search').textContent).toBe('');+ });++ it('preserves the tab url view preferences when selecting a page', async () => {+ const { result } = renderFileClick({+ id: 'page_1',+ isFolder: false,+ isPage: true,+ libraryId: 'kb_1',+ });++ await act(async () => {+ result.current();+ });++ const search = new URLSearchParams(getTabRouter(TAB_ID)!.state.location.search);+ expect(search.get('file')).toBe('page_1');+ expect(search.get('view')).toBe('grid');+ });++ it('drops the file param and keeps the tab router when entering a folder', async () => {+ const { result } = renderFileClick({+ id: 'folder_1',+ isFolder: true,+ libraryId: 'kb_1',+ isPage: false,+ slug: 'folder-slug',+ });++ await act(async () => {+ result.current();+ });++ const { pathname, search } = getTabRouter(TAB_ID)!.state.location;+ expect(pathname).toBe('/resource/library/kb_1/folder-slug');+ expect(new URLSearchParams(search).has('file')).toBe(false);+ expect(screen.getByTestId('shell-search').textContent).toBe('');+ });+});diff --git a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.tsindex b699dc89322..2f46b5fc73f 100644--- a/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts+++ b/src/features/ResourceManager/components/Explorer/hooks/useFileItemClick.ts@@ -1,7 +1,7 @@import { useCallback } from 'react';-import { useSearchParams } from 'react-router';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';export interface UseFileItemClickOptions {@@ -25,18 +25,27 @@ export const useFileItemClick = ({onOpen,}: UseFileItemClickOptions) => {const navigate = useWorkspaceAwareNavigate();- const [searchParams, setSearchParams] = useSearchParams();+ // Read/write the URL through the active-tab facade rather than+ // `useSearchParams`: this hook also runs in the library sidebar, which Electron+ // portals into the shell's frozen root router.+ const { search } = useActiveLocation();const setMode = useResourceManagerStore((s) => s.setMode);const setCurrentViewItemId = useResourceManagerStore((s) => s.setCurrentViewItemId);const handleClick = useCallback(() => {+ const selectFile = () => {+ const newParams = new URLSearchParams(search);+ newParams.set('file', id);+ navigate({ search: `?${newParams.toString()}` }, { replace: true });+ };+if (isFolder) {// Navigate to folder using slug-based routing (Google Drive style)const folderSlug = slug || id;if (libraryId) {// Preserve existing query parameters (view and sort preferences)- const newParams = new URLSearchParams(searchParams);+ const newParams = new URLSearchParams(search);// Remove 'file' parameter when navigating to foldernewParams.delete('file');@@ -49,27 +58,13 @@ export const useFileItemClick = ({setCurrentViewItemId(id);setMode('page');// Update URL query parameter for shareable links- setSearchParams(- (prev) => {- const newParams = new URLSearchParams(prev);- newParams.set('file', id);- return newParams;- },- { replace: true },- );+ selectFile();} else {// Set mode to editor for regular filessetCurrentViewItemId(id);setMode('editor');// Update URL query parameter for shareable links- setSearchParams(- (prev) => {- const newParams = new URLSearchParams(prev);- newParams.set('file', id);- return newParams;- },- { replace: true },- );+ selectFile();// Call onOpen if provided for backwards compatibilityonOpen?.(id);}@@ -80,8 +75,7 @@ export const useFileItemClick = ({libraryId,isPage,navigate,- searchParams,- setSearchParams,+ search,setMode,setCurrentViewItemId,onOpen,diff --git a/src/routes/(main)/(create)/features/GenerationLayout/Body/List/index.tsx b/src/routes/(main)/(create)/features/GenerationLayout/Body/List/index.tsxindex 879ee44a3b0..68a9fd41c3b 100644--- a/src/routes/(main)/(create)/features/GenerationLayout/Body/List/index.tsx+++ b/src/routes/(main)/(create)/features/GenerationLayout/Body/List/index.tsx@@ -13,7 +13,6 @@ import type { GenerationLayoutCommonProps } from '../../types';import GridSkeletonList from './SkeletonList';import { GenerationTopicStoreProvider } from './StoreContext';import TopicList from './TopicList';-import TopicUrlSync from './TopicUrlSync';const List = memo<Pick<GenerationLayoutCommonProps, 'namespace' | 'useStore' | 'viewModeStatusKey'> & {@@ -34,7 +33,6 @@ const List = memo<<GenerationTopicStoreProvider value={{ namespace, useStore: useStore as any }}><Flexbox gap={4} paddingBlock={1}><TopicList viewMode={viewMode} visibility={visibility} />- <TopicUrlSync /></Flexbox></GenerationTopicStoreProvider>);diff --git a/src/routes/(main)/(create)/features/GenerationLayout/index.tsx b/src/routes/(main)/(create)/features/GenerationLayout/index.tsxindex 225e3c9ed57..b2a5399ce66 100644--- a/src/routes/(main)/(create)/features/GenerationLayout/index.tsx+++ b/src/routes/(main)/(create)/features/GenerationLayout/index.tsx@@ -4,6 +4,8 @@ import { Flexbox } from '@lobehub/ui';import type { FC, ReactNode } from 'react';import { Outlet } from 'react-router';+import { TopicUrlSync, type TopicUrlSyncStore } from '@/features/Generation';+import { styles } from './style';export interface GenerationLayoutProps {@@ -11,14 +13,21 @@ export interface GenerationLayoutProps {extra?: ReactNode;/** Sidebar wrapped in a NavPanelPortal by the caller (namespace-specific). */sidebar: ReactNode;+ /**+ * Namespace store driving the URL β activeGenerationTopicId sync. The sync+ * lives here rather than in the sidebar because on Electron the sidebar is+ * portal'd into the shell, which is bound to the frozen root router.+ */+ useStore: TopicUrlSyncStore;}-const GenerationLayout: FC<GenerationLayoutProps> = ({ extra, sidebar }) => (+const GenerationLayout: FC<GenerationLayoutProps> = ({ extra, sidebar, useStore }) => (<>{sidebar}<Flexbox className={styles.mainContainer} flex={1} height={'100%'}><Outlet /></Flexbox>+ <TopicUrlSync useStore={useStore} />{extra}</>);diff --git a/src/routes/(main)/(create)/image/_layout/index.tsx b/src/routes/(main)/(create)/image/_layout/index.tsxindex 2d7f87171c2..c77605c5d91 100644--- a/src/routes/(main)/(create)/image/_layout/index.tsx+++ b/src/routes/(main)/(create)/image/_layout/index.tsx@@ -1,10 +1,13 @@'use client';import GenerationLayout from '@/routes/(main)/(create)/features/GenerationLayout';+import { useImageStore } from '@/store/image';import RegisterHotkeys from './RegisterHotkeys';import Sidebar from './Sidebar';-const ImageLayout = () => <GenerationLayout extra={<RegisterHotkeys />} sidebar={<Sidebar />} />;+const ImageLayout = () => (+ <GenerationLayout extra={<RegisterHotkeys />} sidebar={<Sidebar />} useStore={useImageStore} />+);export default ImageLayout;diff --git a/src/routes/(main)/(create)/video/_layout/index.tsx b/src/routes/(main)/(create)/video/_layout/index.tsxindex 28191dfbcff..6c9e7bbda12 100644--- a/src/routes/(main)/(create)/video/_layout/index.tsx+++ b/src/routes/(main)/(create)/video/_layout/index.tsx@@ -1,9 +1,10 @@'use client';import GenerationLayout from '@/routes/(main)/(create)/features/GenerationLayout';+import { useVideoStore } from '@/store/video';import Sidebar from './Sidebar';-const VideoLayout = () => <GenerationLayout sidebar={<Sidebar />} />;+const VideoLayout = () => <GenerationLayout sidebar={<Sidebar />} useStore={useVideoStore} />;export default VideoLayout;diff --git a/src/routes/(main)/group/features/GroupAvatar.tsx b/src/routes/(main)/group/features/GroupAvatar.tsxindex c95d55a4de7..0660fabf313 100644--- a/src/routes/(main)/group/features/GroupAvatar.tsx+++ b/src/routes/(main)/group/features/GroupAvatar.tsx@@ -2,9 +2,9 @@import isEqual from 'fast-deep-equal';import { memo } from 'react';-import { useParams } from 'react-router';import AgentGroupAvatar from '@/features/AgentGroupAvatar';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { useAgentGroupStore } from '@/store/agentGroup';import { agentGroupSelectors } from '@/store/agentGroup/selectors';@@ -12,7 +12,7 @@ import { agentGroupSelectors } from '@/store/agentGroup/selectors';* Connected AgentGroupAvatar that reads from agentGroup store*/const CurrentAgentGroupAvatar = memo<{ size?: number }>(({ size = 28 }) => {- const { gid } = useParams<{ gid: string }>();+ const { gid } = useActiveRouteParams<{ gid: string }>();const groupMeta = useAgentGroupStore((s) => agentGroupSelectors.getGroupMeta(gid ?? '')(s),isEqual,diff --git a/src/routes/(main)/resource/features/hooks/useFolderPath.ts b/src/routes/(main)/resource/features/hooks/useFolderPath.tsindex b40bf404eea..e8546b1ab80 100644--- a/src/routes/(main)/resource/features/hooks/useFolderPath.ts+++ b/src/routes/(main)/resource/features/hooks/useFolderPath.ts@@ -1,4 +1,5 @@-import { useLocation, useParams } from 'react-router';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';/*** Hook to extract folder slug from URL@@ -10,8 +11,10 @@ import { useLocation, useParams } from 'react-router';* - /knowledge -> { knowledgeBaseId: null, currentFolderSlug: null, isInKnowledgeBase: false }*/export const useFolderPath = () => {- const params = useParams<{ id: string; slug?: string }>();- const location = useLocation();+ // Active-tab variants, not the raw router hooks: `LibraryHierarchy` renders in+ // the sidebar, which Electron portals into the shell's frozen root router.+ const params = useActiveRouteParams<{ id: string; slug?: string }>();+ const location = useActiveLocation();// Extract knowledge base ID from paramsconst knowledgeBaseId = params.id || null;