π€― 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(topic): restore project topic creation from agent subroutes (#16176)
AmAzing-c9a83a7ff315
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsxnew file mode 100644index 00000000000..5b48cb93c14--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx@@ -0,0 +1,224 @@+/**+ * @vitest-environment happy-dom+ */+import { fireEvent, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import GroupItem from './GroupItem';++const commitAgentDefaultMock = vi.hoisted(() => vi.fn());+const switchTopicMock = vi.hoisted(() => vi.fn());+const routerPushMock = vi.hoisted(() => vi.fn());+const routeParamsMock = vi.hoisted(() => ({ aid: 'agent-1' as string | undefined }));+const agentStoreStateMock = vi.hoisted(() => ({ activeAgentId: 'agent-1' as string | undefined }));+const activeWorkspaceSlugMock = vi.hoisted(() => ({ value: 'lobehub' as string | null }));++vi.mock('react-router', () => ({+ useParams: () => routeParamsMock,+}));++vi.mock('@lobehub/ui', () => ({+ AccordionItem: ({+ action,+ children,+ title,+ }: {+ action?: ReactNode;+ children?: ReactNode;+ title?: ReactNode;+ }) => (+ <section>+ <div>+ {title}+ {action}+ </div>+ {children}+ </section>+ ),+ ActionIcon: ({+ onClick,+ title,+ }: {+ onClick?: (event: { stopPropagation: () => void }) => void;+ title?: string;+ }) => (+ <button+ aria-label={title}+ type="button"+ onClick={() => onClick?.({ stopPropagation: vi.fn() })}+ />+ ),+ Center: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Icon: () => <span />,+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++vi.mock('antd-style', () => ({+ createStaticStyles: () => ({+ addTopicAction: 'addTopicAction',+ statusBadge: 'statusBadge',+ statusBadgeError: 'statusBadgeError',+ statusBadgeLoading: 'statusBadgeLoading',+ statusBadgeWaiting: 'statusBadgeWaiting',+ unreadDot: 'unreadDot',+ unreadRipple: 'unreadRipple',+ unreadWrapper: 'unreadWrapper',+ }),+ cssVar: {+ colorError: '#f00',+ colorInfo: '#00f',+ colorTextSecondary: '#666',+ colorTextTertiary: '#999',+ colorWarning: '#fa0',+ },+ cx: (...classes: Array<string | undefined>) => classes.filter(Boolean).join(' '),+ keyframes: () => 'keyframes',+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { directory?: string }) =>+ options?.directory ? `${key}:${options.directory}` : key,+ }),+}));++vi.mock('@/components/RingLoading', () => ({+ default: () => <span />,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ useActiveWorkspaceSlug: () => activeWorkspaceSlugMock.value,+}));++vi.mock('@/const/url', () => ({+ SESSION_CHAT_URL: (agentId: string) => `/agent/${agentId}`,+}));++vi.mock('@/const/version', () => ({ isDesktop: true }));++vi.mock('@/features/ChatInput/ControlBar/useCommitWorkingDirectory', () => ({+ useCommitWorkingDirectory: () => ({+ commitAgentDefault: commitAgentDefaultMock,+ }),+}));++vi.mock('@/helpers/executionTarget', () => ({+ resolveExecutionTarget: () => 'device',+}));++vi.mock('@/hooks/useQueryRoute', () => ({+ useQueryRoute: () => ({+ push: routerPushMock,+ }),+}));++vi.mock('@/libs/router/navigation', () => ({+ usePathname: () => '/lobehub/agent/agent-1/profile',+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: { activeAgentId?: string }) => unknown) =>+ selector(agentStoreStateMock),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => () => ({ boundDeviceId: 'device-1' }),+ isAgentHeterogeneousById: () => () => true,+ },+}));++vi.mock('@/store/chat', () => {+ const useChatStore = (selector: (state: { topicLoadingIds: string[] }) => unknown) =>+ selector({ topicLoadingIds: [] });+ useChatStore.getState = () => ({ switchTopic: switchTopicMock });+ return { useChatStore };+});++vi.mock('@/store/chat/selectors', () => ({+ operationSelectors: {+ unreadCompletedCountForTopics: () => () => 0,+ },+}));++vi.mock('../../List/Item', () => ({+ default: ({ title }: { title: string }) => <div>{title}</div>,+}));++describe('Project topic group item', () => {+ beforeEach(() => {+ commitAgentDefaultMock.mockReset();+ switchTopicMock.mockReset();+ routerPushMock.mockReset();+ routeParamsMock.aid = 'agent-1';+ agentStoreStateMock.activeAgentId = 'agent-1';+ activeWorkspaceSlugMock.value = 'lobehub';+ });++ it('navigates to a new chat topic after committing the project directory', async () => {+ commitAgentDefaultMock.mockResolvedValue(undefined);++ render(+ <GroupItem+ expanded+ activeTopicId={undefined}+ group={{+ children: [],+ id: 'project:/Users/me/project',+ title: 'project',+ }}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopicInProject:project' }));++ expect(commitAgentDefaultMock).toHaveBeenCalledWith('/Users/me/project');+ await expect.poll(() => routerPushMock.mock.calls.length).toBe(1);+ expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });+ expect(routerPushMock).toHaveBeenCalledWith('/agent/agent-1');+ });++ it('preserves the detected route prefix when adding a project topic without an active workspace slug', async () => {+ activeWorkspaceSlugMock.value = null;+ commitAgentDefaultMock.mockResolvedValue(undefined);++ render(+ <GroupItem+ expanded+ group={{+ children: [],+ id: 'project:/Users/me/project',+ title: 'project',+ }}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopicInProject:project' }));++ await expect.poll(() => routerPushMock.mock.calls.length).toBe(1);+ expect(routerPushMock).toHaveBeenCalledWith('/lobehub/agent/agent-1');+ });++ it('falls back to the pathname agent id when route params and store state are unavailable', () => {+ routeParamsMock.aid = undefined;+ agentStoreStateMock.activeAgentId = undefined;++ render(+ <GroupItem+ expanded+ group={{+ children: [],+ id: 'project:/Users/me/project',+ title: 'project',+ }}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopicInProject:project' }));++ expect(commitAgentDefaultMock).toHaveBeenCalledWith('/Users/me/project');+ });+});diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsxindex 16cd6cb47e2..d803503c84b 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx@@ -10,16 +10,22 @@ import {} from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useParams } from 'react-router';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import RingLoadingIcon from '@/components/RingLoading';+import { SESSION_CHAT_URL } from '@/const/url';import { isDesktop } from '@/const/version';import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { useQueryRoute } from '@/hooks/useQueryRoute';+import { usePathname } from '@/libs/router/navigation';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';+import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../../utils/agentPathname';import TopicItem from '../../List/Item';import { type GroupItemComponentProps } from '../GroupedAccordion';import {@@ -212,20 +218,44 @@ const GroupItem = memo<GroupItemComponentProps>();const agentId = useAgentStore((s) => s.activeAgentId);- const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId ?? ''));+ const { aid: routeAgentId } = useParams<{ aid?: string }>();+ const pathname = usePathname();+ const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);+ const targetAgentId = routeAgentId ?? agentRoute?.agentId ?? agentId;+ const currentAgentId = targetAgentId ?? agentId;+ const router = useQueryRoute();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();+ const agencyConfig = useAgentStore(+ agentByIdSelectors.getAgencyConfigById(currentAgentId ?? ''),+ );const isHeterogeneous = useAgentStore((s) =>- agentId ? agentByIdSelectors.isAgentHeterogeneousById(agentId)(s) : false,+ currentAgentId ? agentByIdSelectors.isAgentHeterogeneousById(currentAgentId)(s) : false,);- const { commitAgentDefault } = useCommitWorkingDirectory(agentId ?? '');+ const { commitAgentDefault } = useCommitWorkingDirectory(currentAgentId ?? '');const handleAddTopic = useCallback(async () => {- if (!workingDirectory || !agentId) return;+ if (!workingDirectory || !currentAgentId || !targetAgentId) return;// Write the agent's per-device default so the new topic inherits this// directory at creation time β the same high-precedence slot the picker// uses, not the legacy per-agent fallback that gets shadowed by it.await commitAgentDefault(workingDirectory);useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });- }, [workingDirectory, agentId, commitAgentDefault]);+ router.push(+ buildPrefixedAgentRoutePath(+ SESSION_CHAT_URL(targetAgentId),+ agentRoute,+ activeWorkspaceSlug,+ ),+ );+ }, [+ workingDirectory,+ currentAgentId,+ targetAgentId,+ commitAgentDefault,+ router,+ agentRoute,+ activeWorkspaceSlug,+ ]);// Web can add a topic in a directory too when the agent targets a bound// device β the write goes to `workingDirByDevice`, no Electron dependency.diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsxindex b3de20a80d9..a627bb0ff29 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx@@ -115,6 +115,44 @@ describe('useTopicNavigation', () => {expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);});+ it('switches topics in place on an exact topic route', async () => {+ pathnameMock.mockReturnValue('/agent/agent-1/topic-1');+ chatStoreStateMock.activeTopicId = 'topic-1';+ focusTopicPopupMock.mockResolvedValue(false);++ const { result } = renderHook(() => useTopicNavigation());++ expect(result.current.isInTopicContextRoute).toBe(true);+ expect(result.current.isInAgentSubRoute).toBe(false);++ await act(async () => {+ await result.current.navigateToTopic('topic-2');+ });++ expect(pushMock).not.toHaveBeenCalled();+ expect(switchTopicMock).toHaveBeenCalledWith('topic-2');+ expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);+ });++ it('routes to the next topic from a topic child route instead of leaving the URL on the child route', async () => {+ pathnameMock.mockReturnValue('/agent/agent-1/topic-1/page');+ chatStoreStateMock.activeTopicId = 'topic-1';+ focusTopicPopupMock.mockResolvedValue(false);++ const { result } = renderHook(() => useTopicNavigation());++ expect(result.current.isInTopicContextRoute).toBe(true);+ expect(result.current.isInAgentSubRoute).toBe(true);++ await act(async () => {+ await result.current.navigateToTopic('topic-2');+ });++ expect(pushMock).toHaveBeenCalledWith('/agent/agent-1/topic-2');+ expect(switchTopicMock).not.toHaveBeenCalled();+ expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);+ });+it('still routes back to chat from a profile sub-route even when activeTopicId is cached', async () => {// regression: cached activeTopicId should not make profile look like a topic routepathnameMock.mockReturnValue('/agent/agent-1/profile');@@ -150,4 +188,21 @@ describe('useTopicNavigation', () => {expect(switchTopicMock).not.toHaveBeenCalled();expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);});++ it('preserves a detected route prefix when routing from a prefixed profile path without an active workspace slug', async () => {+ pathnameMock.mockReturnValue('/lobehub/agent/agent-1/profile');+ focusTopicPopupMock.mockResolvedValue(false);++ const { result } = renderHook(() => useTopicNavigation());++ expect(result.current.isInAgentSubRoute).toBe(true);++ await act(async () => {+ await result.current.navigateToTopic('topic-prefixed');+ });++ expect(pushMock).toHaveBeenCalledWith('/lobehub/agent/agent-1/topic-prefixed');+ expect(switchTopicMock).not.toHaveBeenCalled();+ expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);+ });});diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.tsindex 43a058a5249..11013619d7e 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts@@ -1,15 +1,16 @@-import { useCallback } from 'react';+import { useCallback, useMemo } from 'react';import { useParams } from 'react-router';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';-import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useQueryRoute } from '@/hooks/useQueryRoute';import { usePathname } from '@/libs/router/navigation';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';+import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../utils/agentPathname';+/*** Hook to handle topic navigation with automatic route detection* If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first@@ -20,58 +21,40 @@ interface NavigateToTopicOptions {export const useTopicNavigation = () => {const pathname = usePathname();+ const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);const params = useParams<{ aid?: string; topicId?: string }>();const [activeAgentId, activeTopicId] = useChatStore((s) => [s.activeAgentId, s.activeTopicId]);const router = useQueryRoute();const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);const switchTopic = useChatStore((s) => s.switchTopic);const activeWorkspaceSlug = useActiveWorkspaceSlug();- const routeAgentId = params.aid ?? activeAgentId;+ const routeAgentId = params.aid ?? agentRoute?.agentId ?? activeAgentId;// URL is the source of truth. Sidebar mounts at `/agent/:aid` so `params.topicId`// is undefined here β fall back to parsing pathname directly so consumers can compare// their item id against the URL's topic id without waiting for store hydration.const urlTopicId = params.topicId;const routeTopicId = params.topicId ?? activeTopicId ?? undefined;- const topicBasePath =- routeAgentId && routeTopicId- ? buildWorkspaceAwarePath(- SESSION_CHAT_TOPIC_URL(routeAgentId, routeTopicId),- activeWorkspaceSlug,- )- : undefined;-- const urlTopicBasePath =- routeAgentId && params.topicId- ? buildWorkspaceAwarePath(- SESSION_CHAT_TOPIC_URL(routeAgentId, params.topicId),- activeWorkspaceSlug,- )- : undefined;const focusTopicPopup = useFocusTopicPopup({ agentId: activeAgentId });const isInTopicContextRoute = useCallback(() => {- if (!topicBasePath) return false;+ if (!routeAgentId || !routeTopicId || agentRoute?.agentId !== routeAgentId) return false;- return (- pathname === topicBasePath ||- pathname === `${topicBasePath}/` ||- pathname.startsWith(`${topicBasePath}/`)- );- }, [pathname, topicBasePath]);+ return agentRoute.segmentsAfterAgent[0] === routeTopicId;+ }, [agentRoute, routeAgentId, routeTopicId]);const isInAgentSubRoute = useCallback(() => {if (!routeAgentId) return false;- const agentBasePath =- urlTopicBasePath ??- buildWorkspaceAwarePath(SESSION_CHAT_URL(routeAgentId), activeWorkspaceSlug);+ if (agentRoute?.agentId !== routeAgentId) return false;++ const { segmentsAfterAgent } = agentRoute;+ if (segmentsAfterAgent.length === 0) return false;++ const isExactTopicRoute =+ routeTopicId && segmentsAfterAgent.length === 1 && segmentsAfterAgent[0] === routeTopicId;- // If pathname has more segments after /agent/:aid (or the active topic), it's a sub-route- return (- pathname.startsWith(agentBasePath) &&- pathname !== agentBasePath &&- pathname !== `${agentBasePath}/`- );- }, [activeWorkspaceSlug, pathname, routeAgentId, urlTopicBasePath]);+ // If pathname has more segments after /agent/:aid (or the active topic), it's a sub-route.+ return !isExactTopicRoute;+ }, [agentRoute, routeAgentId, routeTopicId]);const navigateToTopic = useCallback(async (topicId?: string, options?: NavigateToTopicOptions) => {@@ -84,9 +67,10 @@ export const useTopicNavigation = () => {const basePath = topicId? SESSION_CHAT_TOPIC_URL(routeAgentId, topicId): SESSION_CHAT_URL(routeAgentId);+ const targetPath = buildPrefixedAgentRoutePath(basePath, agentRoute, activeWorkspaceSlug);// Include topicId in URL when navigating from sub-route- router.push(basePath);+ router.push(targetPath);toggleConfig(false);return;}@@ -94,7 +78,16 @@ export const useTopicNavigation = () => {switchTopic(topicId);toggleConfig(false);},- [focusTopicPopup, isInAgentSubRoute, routeAgentId, router, switchTopic, toggleConfig],+ [+ activeWorkspaceSlug,+ agentRoute,+ focusTopicPopup,+ isInAgentSubRoute,+ routeAgentId,+ router,+ switchTopic,+ toggleConfig,+ ],);return {diff --git a/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.test.ts b/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.test.tsnew file mode 100644index 00000000000..352bc4ffab6--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { buildPrefixedAgentRoutePath, parseAgentPathname } from './agentPathname';++describe('agentPathname', () => {+ it('parses an agent route without a prefix', () => {+ expect(parseAgentPathname('/agent/agent-1/topic-1')).toEqual({+ agentId: 'agent-1',+ prefix: '',+ segmentsAfterAgent: ['topic-1'],+ });+ });++ it('parses workspace and proxy prefixes before the agent segment', () => {+ expect(parseAgentPathname('/team/agent/agent-1/profile')).toEqual({+ agentId: 'agent-1',+ prefix: '/team',+ segmentsAfterAgent: ['profile'],+ });++ expect(parseAgentPathname('/_dangerous_local_dev_proxy/agent/agent-1/profile')).toEqual({+ agentId: 'agent-1',+ prefix: '/_dangerous_local_dev_proxy',+ segmentsAfterAgent: ['profile'],+ });+ });++ it('ignores paths without an agent id', () => {+ expect(parseAgentPathname('/settings/profile')).toBeUndefined();+ expect(parseAgentPathname('/team/agent')).toBeUndefined();+ });++ it('preserves a detected prefix only when workspace navigation cannot restore it', () => {+ const route = parseAgentPathname('/team/agent/agent-1/profile');++ expect(buildPrefixedAgentRoutePath('/agent/agent-1/topic-1', route, null)).toBe(+ '/team/agent/agent-1/topic-1',+ );+ expect(buildPrefixedAgentRoutePath('/agent/agent-1/topic-1', route, 'team')).toBe(+ '/agent/agent-1/topic-1',+ );+ });+});diff --git a/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.ts b/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.tsnew file mode 100644index 00000000000..f2191d4371d--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.ts@@ -0,0 +1,34 @@+export interface AgentPathnameInfo {+ agentId: string;+ prefix: string;+ segmentsAfterAgent: string[];+}++// TODO(agent-route): migrate Header/Nav and useThreadNavigation to this parser+// after this scoped bugfix lands, then remove the remaining substring checks.+export const parseAgentPathname = (pathname: string): AgentPathnameInfo | undefined => {+ const [pathOnly] = pathname.split(/[?#]/);+ const segments = pathOnly.split('/').filter(Boolean);+ const agentSegmentIndex = segments.indexOf('agent');++ if (agentSegmentIndex < 0) return;++ const agentId = segments[agentSegmentIndex + 1];+ if (!agentId) return;++ return {+ agentId,+ prefix: agentSegmentIndex > 0 ? `/${segments.slice(0, agentSegmentIndex).join('/')}` : '',+ segmentsAfterAgent: segments.slice(agentSegmentIndex + 2),+ };+};++export const buildPrefixedAgentRoutePath = (+ targetPath: string,+ route: AgentPathnameInfo | undefined,+ activeWorkspaceSlug: string | null,+) => {+ if (!route?.prefix || activeWorkspaceSlug) return targetPath;++ return `${route.prefix}${targetPath}`;+};