🤯 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): preserve workspace scope in tab navigation (#16184)
Inneicc61139b3a39
diff --git a/src/features/AgentDocumentPage/routeMeta.ts b/src/features/AgentDocumentPage/routeMeta.tsindex 422bb3b7092..11180ed9f2e 100644--- a/src/features/AgentDocumentPage/routeMeta.ts+++ b/src/features/AgentDocumentPage/routeMeta.ts@@ -1,5 +1,6 @@import { FileTextIcon } from 'lucide-react';+import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';import { useClientDataSWR } from '@/libs/swr';import { portalKeys } from '@/libs/swr/keys';import { documentService } from '@/services/document';@@ -10,6 +11,7 @@ export const agentDocumentRouteMeta = routeMeta({icon: FileTextIcon,titleKey: 'navigation.document',useDynamicMeta: (params): DynamicRouteMeta => {+ const routeWorkspaceId = useRouteWorkspaceId(params);const documentId = params.docId ? getIdFromIdentifier(params.docId, 'docs') : '';// Deduped against the Document Header's SWR fetch (same key), so this adds// no extra request — it just surfaces the title into the breadcrumb.@@ -17,7 +19,8 @@ export const agentDocumentRouteMeta = routeMeta({documentId ? portalKeys.documentHeader(documentId) : null,() => documentService.getDocumentById(documentId),);+ const document = matchesRouteWorkspace(data?.workspaceId, routeWorkspaceId) ? data : undefined;- return { title: data?.filename || data?.title || undefined };+ return { title: document?.filename || document?.title || undefined };},});diff --git a/src/features/AgentTasks/routeMeta.ts b/src/features/AgentTasks/routeMeta.tsindex 92d52977e2c..c0fc491b594 100644--- a/src/features/AgentTasks/routeMeta.ts+++ b/src/features/AgentTasks/routeMeta.ts@@ -1,5 +1,6 @@import { ListTodoIcon } from 'lucide-react';+import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';@@ -13,7 +14,11 @@ export const taskRouteMeta = routeMeta({icon: ListTodoIcon,titleKey: 'navigation.task',useDynamicMeta: (params): DynamicRouteMeta => {- const detail = useTaskStore(taskDetailSelectors.taskDetailById(params.taskId ?? ''));+ const routeWorkspaceId = useRouteWorkspaceId(params);+ const detail = useTaskStore((s) => {+ const item = taskDetailSelectors.taskDetailById(params.taskId ?? '')(s);+ return matchesRouteWorkspace(item?.workspaceId, routeWorkspaceId) ? item : undefined;+ });return {title: detail?.name || undefined,diff --git a/src/features/Electron/navigation/tabNavigation.test.ts b/src/features/Electron/navigation/tabNavigation.test.tsnew file mode 100644index 00000000000..30552e93cd2--- /dev/null+++ b/src/features/Electron/navigation/tabNavigation.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';+import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';++import { resolveTabNavigationAction } from './tabNavigation';++const tab = (id: string, url: string): TabItem => ({+ id,+ lastVisited: 1,+ scope: resolveTabScope(url),+ url,+});++describe('resolveTabNavigationAction', () => {+ it('opens a new tab when navigation crosses from personal to workspace scope', () => {+ expect(+ resolveTabNavigationAction({+ activeTabId: 'personal',+ currentUrl: '/acme/agent/workspace-agent',+ tabs: [tab('personal', '/agent/personal-agent')],+ }),+ ).toEqual({ type: 'add', url: '/acme/agent/workspace-agent' });+ });++ it('opens a new tab when navigation crosses from workspace to personal scope', () => {+ expect(+ resolveTabNavigationAction({+ activeTabId: 'workspace',+ currentUrl: '/agent/personal-agent',+ tabs: [tab('workspace', '/acme/agent/workspace-agent')],+ }),+ ).toEqual({ type: 'add', url: '/agent/personal-agent' });+ });++ it('updates the active tab for same-scope navigation', () => {+ expect(+ resolveTabNavigationAction({+ activeTabId: 'workspace',+ currentUrl: '/acme/group/g1',+ tabs: [tab('workspace', '/acme/agent/a1')],+ }),+ ).toEqual({ id: 'workspace', type: 'update', url: '/acme/group/g1' });+ });++ it('activates an existing tab with the same scoped target', () => {+ expect(+ resolveTabNavigationAction({+ activeTabId: 'personal',+ currentUrl: '/acme/agent/a1?b=2&a=1',+ tabs: [tab('personal', '/agent/a1'), tab('workspace', '/acme/agent/a1?a=1&b=2')],+ }),+ ).toEqual({ id: 'workspace', type: 'activate' });+ });+});diff --git a/src/features/Electron/navigation/tabNavigation.ts b/src/features/Electron/navigation/tabNavigation.tsnew file mode 100644index 00000000000..fe4ba29133a--- /dev/null+++ b/src/features/Electron/navigation/tabNavigation.ts@@ -0,0 +1,56 @@+import {+ isSameTabScope,+ isSameTabTarget,+ normalizeTabScope,+ resolveTabScope,+} from '@/features/Electron/titlebar/TabBar/scope';+import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';++export type TabNavigationAction =+ | {+ type: 'activate';+ id: string;+ }+ | {+ type: 'add';+ url: string;+ }+ | {+ type: 'none';+ }+ | {+ id: string;+ type: 'update';+ url: string;+ };++interface ResolveTabNavigationActionInput {+ activeTabId: string | null;+ currentUrl: string;+ tabs: TabItem[];+}++export const resolveTabNavigationAction = ({+ activeTabId,+ currentUrl,+ tabs,+}: ResolveTabNavigationActionInput): TabNavigationAction => {+ const currentScope = resolveTabScope(currentUrl);+ const activeTab = activeTabId ? tabs.find((t) => t.id === activeTabId) : null;++ if (activeTab && isSameTabTarget(activeTab, currentUrl, currentScope)) {+ return activeTab.url === currentUrl+ ? { type: 'none' }+ : { id: activeTab.id, type: 'update', url: currentUrl };+ }++ const existing = tabs.find((t) => isSameTabTarget(t, currentUrl, currentScope));+ if (existing) return { id: existing.id, type: 'activate' };++ if (!activeTab) return { type: 'add', url: currentUrl };++ const activeScope = normalizeTabScope(activeTab.scope, activeTab.url);+ if (!isSameTabScope(activeScope, currentScope)) return { type: 'add', url: currentUrl };++ return { id: activeTab.id, type: 'update', url: currentUrl };+};diff --git a/src/features/Electron/navigation/useNavigationHistory.ts b/src/features/Electron/navigation/useNavigationHistory.tsindex 0d9f8683478..bd369c1e975 100644--- a/src/features/Electron/navigation/useNavigationHistory.ts+++ b/src/features/Electron/navigation/useNavigationHistory.ts@@ -40,14 +40,14 @@ export const useNavigationHistory = () => {if (!canGoBackFn()) return;const targetEntry = storeGoBack();- if (targetEntry) navigate(targetEntry.url);+ if (targetEntry) navigate(targetEntry.url, { escape: true });}, [canGoBackFn, storeGoBack, navigate]);const goForward = useCallback(() => {if (!canGoForwardFn()) return;const targetEntry = storeGoForward();- if (targetEntry) navigate(targetEntry.url);+ if (targetEntry) navigate(targetEntry.url, { escape: true });}, [canGoForwardFn, storeGoForward, navigate]);useEffect(() => {diff --git a/src/features/Electron/navigation/useTabNavigation.ts b/src/features/Electron/navigation/useTabNavigation.tsindex 397444dfb47..bb7620ee78d 100644--- a/src/features/Electron/navigation/useTabNavigation.ts+++ b/src/features/Electron/navigation/useTabNavigation.ts@@ -3,9 +3,11 @@import { useEffect, useRef } from 'react';import { useLocation } from 'react-router';-import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';+import { isSameTabTarget } from '@/features/Electron/titlebar/TabBar/scope';import { useElectronStore } from '@/store/electron';+import { resolveTabNavigationAction } from './tabNavigation';+export const useTabNavigation = () => {const location = useLocation();@@ -33,29 +35,22 @@ export const useTabNavigation = () => {if (prevLocationRef.current === currentUrl) return;prevLocationRef.current = currentUrl;- const normalized = normalizeTabUrl(currentUrl);const { tabs, activeTabId } = useElectronStore.getState();+ const action = resolveTabNavigationAction({ activeTabId, currentUrl, tabs });- const activeTab = activeTabId ? tabs.find((t) => t.id === activeTabId) : null;- if (activeTab && normalizeTabUrl(activeTab.url) === normalized) {- // Keep the active tab's url in sync (e.g. query/hash variations that- // normalize the same) without re-activating.- if (activeTab.url !== currentUrl) updateTab(activeTab.id, currentUrl);- return;- }-- const existing = tabs.find((t) => normalizeTabUrl(t.url) === normalized);- if (existing) {- activateTab(existing.id);- return;- }-- if (activeTab) {- updateTab(activeTab.id, currentUrl);- } else {- // First launch (or stale activeTabId): make the current page visible as a tab,- // so the tab bar and its "+" entry are always discoverable.- addTab(currentUrl);+ switch (action.type) {+ case 'activate': {+ activateTab(action.id);+ break;+ }+ case 'add': {+ addTab(action.url);+ break;+ }+ case 'update': {+ updateTab(action.id, action.url);+ break;+ }}}, [location.pathname, location.search, activateTab, addTab, updateTab]);@@ -66,7 +61,7 @@ export const useTabNavigation = () => {if (!activeTabId) return;const activeTab = tabs.find((t) => t.id === activeTabId);if (!activeTab) return;- if (normalizeTabUrl(activeTab.url) !== normalizeTabUrl(currentRouteMetaUrl)) return;+ if (!isSameTabTarget(activeTab, currentRouteMetaUrl)) return;updateTabCache(activeTabId, currentRouteMeta);}, [currentRouteMeta, currentRouteMetaUrl, updateTabCache]);diff --git a/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx b/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsxindex b6e44dddc29..dab9942b24e 100644--- a/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx+++ b/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx@@ -11,7 +11,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useElectronStore } from '@/store/electron';import { type ResolvedTab } from '../TabBar/hooks/useResolvedTabs';-import { normalizeTabUrl } from '../TabBar/url';+import { isSameTabTarget } from '../TabBar/scope';import { useStyles } from './styles';interface PageItemProps {@@ -30,11 +30,11 @@ const PageItem = memo<PageItemProps>(({ item, isPinned, onClose }) => {const unpinPage = useElectronStore((s) => s.unpinPage);const { meta, tab } = item;- const currentId = normalizeTabUrl(location.pathname + location.search);- const isActive = tab.id === currentId;+ const currentUrl = location.pathname + location.search;+ const isActive = isSameTabTarget(tab, currentUrl);const handleClick = () => {- navigate(tab.url);+ navigate(tab.url, { escape: true });onClose();};diff --git a/src/features/Electron/titlebar/RecentlyViewed/storage.ts b/src/features/Electron/titlebar/RecentlyViewed/storage.tsindex 78c7b8a191a..275e1caf395 100644--- a/src/features/Electron/titlebar/RecentlyViewed/storage.ts+++ b/src/features/Electron/titlebar/RecentlyViewed/storage.ts@@ -1,3 +1,4 @@+import { normalizeTabScope } from '../TabBar/scope';import { type TabItem } from '../TabBar/types';export const PINNED_PAGES_STORAGE_KEY = 'lobechat:desktop:pinned-pages:v3';@@ -9,6 +10,17 @@ const isTabItem = (item: unknown): item is TabItem =>typeof (item as TabItem).url === 'string' &&typeof (item as TabItem).lastVisited === 'number';+const reviveTabItem = (item: unknown): TabItem | null => {+ if (!isTabItem(item)) return null;++ return {+ ...item,+ scope: normalizeTabScope((item as Partial<TabItem>).scope, item.url),+ };+};++const isRevivedTabItem = (item: TabItem | null): item is TabItem => !!item;+export const getPinnedPages = (): TabItem[] => {if (typeof window === 'undefined') return [];@@ -19,7 +31,7 @@ export const getPinnedPages = (): TabItem[] => {const parsed = JSON.parse(data);if (!Array.isArray(parsed)) return [];- return parsed.filter(isTabItem);+ return parsed.map(reviveTabItem).filter(isRevivedTabItem);} catch {return [];}diff --git a/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx b/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsxindex 01886e36dc8..ff3ea91290f 100644--- a/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx+++ b/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx@@ -5,11 +5,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { type DynamicRouteMeta, type RouteMeta } from '@/spa/router/routeMeta';+import { resolveTabScope } from './scope';import TabCacheBridges from './TabCacheBridges';import { type TabItem } from './types';const mocks = vi.hoisted(() => {- const tabs: { current: { id: string; lastVisited: number; url: string }[] } = { current: [] };+ const tabs: { current: TabItem[] } = { current: [] };return {getTabs: () => tabs.current,@@ -18,7 +19,7 @@ const mocks = vi.hoisted(() => {tabs.current = [];mocks.routes.current = next;},- setTabs: (next: { id: string; lastVisited: number; url: string }[]) => {+ setTabs: (next: TabItem[]) => {tabs.current = next;},updateTabCache: vi.fn<(id: string, cached: DynamicRouteMeta) => void>(),@@ -43,7 +44,7 @@ vi.mock('@/store/electron', () => ({const dynamicSource: Record<string, DynamicRouteMeta> = {};const resolveTopicMeta = (params: Record<string, string | undefined>): DynamicRouteMeta => {- const key = params.topicId ?? '';+ const key = [params.workspaceSlug ?? 'personal', params.topicId ?? params.topic ?? ''].join(':');return dynamicSource[key] ?? {};};@@ -68,7 +69,12 @@ const buildRoutes = (): RouteObject[] => [},];-const tab = (url: string): TabItem => ({ id: url, lastVisited: 1, url });+const tab = (url: string): TabItem => ({+ id: url,+ lastVisited: 1,+ scope: resolveTabScope(url),+ url,+});describe('TabCacheBridges', () => {afterEach(() => {@@ -82,8 +88,8 @@ describe('TabCacheBridges', () => {it('pushes dynamic meta into each tab cache, including inactive tabs', async () => {mocks.routes.current = buildRoutes();mocks.setTabs([tab('/agent/a1/topic-A'), tab('/agent/a1/topic-B')]);- dynamicSource['topic-A'] = { title: 'Topic A' };- dynamicSource['topic-B'] = { title: 'Topic B' };+ dynamicSource['personal:topic-A'] = { title: 'Topic A' };+ dynamicSource['personal:topic-B'] = { title: 'Topic B' };render(<TabCacheBridges />);@@ -99,6 +105,36 @@ describe('TabCacheBridges', () => {});});+ it('resolves dynamic meta from each tab url scope and query params', async () => {+ mocks.routes.current = [+ {+ children: [+ {+ children: [{ handle: { meta: agentMeta }, path: 'agent/:aid' }],+ path: ':workspaceSlug',+ },+ ],+ path: '/',+ },+ ];+ mocks.setTabs([tab('/acme/agent/a1?topic=topic-A'), tab('/beta/agent/a1?topic=topic-A')]);+ dynamicSource['acme:topic-A'] = { title: 'Acme Topic' };+ dynamicSource['beta:topic-A'] = { title: 'Beta Topic' };++ render(<TabCacheBridges />);++ await waitFor(() => {+ expect(mocks.updateTabCache).toHaveBeenCalledWith(+ '/acme/agent/a1?topic=topic-A',+ expect.objectContaining({ title: 'Acme Topic' }),+ );+ expect(mocks.updateTabCache).toHaveBeenCalledWith(+ '/beta/agent/a1?topic=topic-A',+ expect.objectContaining({ title: 'Beta Topic' }),+ );+ });+ });+it('skips tabs whose route has no useDynamicMeta', async () => {mocks.routes.current = buildRoutes();mocks.setTabs([tab('/settings')]);diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsxindex 0368c0446cc..3f429b0f8b9 100644--- a/src/features/Electron/titlebar/TabBar/index.tsx+++ b/src/features/Electron/titlebar/TabBar/index.tsx@@ -17,8 +17,10 @@ import { cx } from 'antd-style';import { Plus } from 'lucide-react';import { startTransition, useCallback, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import { useLocation } from 'react-router';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useRegisterDesktopTabHotkeys } from '@/hooks/useHotkeys/desktopTabScope';import { usePermission } from '@/hooks/usePermission';import { electronSystemService } from '@/services/electron/system';@@ -26,6 +28,7 @@ import { useElectronStore } from '@/store/electron';import { electronStylish } from '@/styles/electron';import { useResolvedTabs } from './hooks/useResolvedTabs';+import { resolveTabScope } from './scope';import { useStyles } from './styles';import TabItem from './TabItem';@@ -40,6 +43,7 @@ const restrictToHorizontalAxis: Modifier = ({ transform }) => ({ ...transform, yconst TabBar = () => {const styles = useStyles;const navigate = useWorkspaceAwareNavigate();+ const location = useLocation();useRegisterDesktopTabHotkeys();const { t } = useTranslation('electron');const { allowed: canCreate, reason } = usePermission('create_content');@@ -61,6 +65,12 @@ const TabBar = () => {);const tabIds = useMemo(() => tabs.map((tab) => tab.tab.id), [tabs]);+ const newTabUrl = useMemo(() => {+ const scope = resolveTabScope(location.pathname + location.search);+ const activeSlug = scope.type === 'workspace' ? scope.slug : null;++ return buildWorkspaceAwarePath(NEW_TAB_URL, activeSlug);+ }, [location.pathname, location.search]);const handleDragEnd = useCallback((event: DragEndEvent) => {@@ -79,7 +89,7 @@ const TabBar = () => {const handleActivate = useCallback((id: string, url: string) => {activateTab(id);- startTransition(() => navigate(url));+ startTransition(() => navigate(url, { escape: true }));},[activateTab, navigate],);@@ -88,7 +98,7 @@ const TabBar = () => {const { activeTabId: newActiveId, tabs: newTabs } = useElectronStore.getState();if (newActiveId) {const target = newTabs.find((tab) => tab.id === newActiveId);- if (target) navigate(target.url);+ if (target) navigate(target.url, { escape: true });} else {navigate('/');}@@ -102,7 +112,7 @@ const TabBar = () => {startTransition(() => {if (isActive && nextActiveId) {const nextTab = tabs.find((tab) => tab.tab.id === nextActiveId);- if (nextTab) navigate(nextTab.tab.url);+ if (nextTab) navigate(nextTab.tab.url, { escape: true });}if (!nextActiveId) {@@ -118,7 +128,7 @@ const TabBar = () => {closeOtherTabs(id);startTransition(() => {const target = tabs.find((tab) => tab.tab.id === id);- if (target) navigate(target.tab.url);+ if (target) navigate(target.tab.url, { escape: true });});},[closeOtherTabs, tabs, navigate],@@ -177,9 +187,9 @@ const TabBar = () => {if (!canCreate) return;// Always open a fresh Home tab, even if a Home tab already exists.- addNewTab(NEW_TAB_URL);- startTransition(() => navigate(NEW_TAB_URL));- }, [canCreate, addNewTab, navigate]);+ addNewTab(newTabUrl);+ startTransition(() => navigate(newTabUrl, { escape: true }));+ }, [canCreate, addNewTab, navigate, newTabUrl]);useWatchBroadcast('createNewTab', () => {handleNewTab();diff --git a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.ts b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.tsindex 57a8501710a..972c21562a3 100644--- a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.ts+++ b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.test.ts@@ -2,6 +2,7 @@ import { MessageSquare } from 'lucide-react';import { type RouteObject } from 'react-router';import { describe, expect, it } from 'vitest';+import { mergeSearchParams } from '@/features/RouteMeta/params';import { type RouteMeta } from '@/spa/router/routeMeta';import {@@ -40,6 +41,21 @@ describe('matchRouteMeta', () => {const result = matchRouteMeta(fixtureRoutes, '/nonexistent/path');expect(result.static).toEqual({});});++ it('merges search params into route params', () => {+ const result = matchRouteMeta(fixtureRoutes, '/agent/abc?topic=tpc_1');+ expect(result.params.aid).toBe('abc');+ expect(result.params.topic).toBe('tpc_1');+ });+});++describe('mergeSearchParams', () => {+ it('keeps path params when search params use the same key', () => {+ expect(mergeSearchParams({ aid: 'path-agent' }, '?aid=query-agent&topic=t1')).toEqual({+ aid: 'path-agent',+ topic: 't1',+ });+ });});describe('guardedMergeCache', () => {diff --git a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.ts b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.tsindex 23cccb92d10..e95d34bdcd5 100644--- a/src/features/Electron/titlebar/TabBar/resolveRouteMeta.ts+++ b/src/features/Electron/titlebar/TabBar/resolveRouteMeta.ts@@ -1,22 +1,24 @@import { Circle } from 'lucide-react';import { matchRoutes, type RouteObject } from 'react-router';+import { mergeSearchParams } from '@/features/RouteMeta/params';import {type DynamicRouteMeta,getRouteMetaFromHandle,type RouteMeta,+ type RouteMetaParams,type StaticRouteMeta,} from '@/spa/router/routeMeta';export interface MatchedRouteMeta {meta?: RouteMeta;- params: Record<string, string | undefined>;+ params: RouteMetaParams;static: StaticRouteMeta;}export const matchRouteMeta = (routes: RouteObject[], url: string): MatchedRouteMeta => {const matches = matchRoutes(routes, url) ?? [];- const params = matches.at(-1)?.params ?? {};+ const params = mergeSearchParams(matches.at(-1)?.params ?? {}, url);for (let i = matches.length - 1; i >= 0; i -= 1) {const meta = getRouteMetaFromHandle(matches[i].route.handle);diff --git a/src/features/Electron/titlebar/TabBar/resolveTab.test.ts b/src/features/Electron/titlebar/TabBar/resolveTab.test.tsindex 1a0985244b2..bfb0fa669c6 100644--- a/src/features/Electron/titlebar/TabBar/resolveTab.test.ts+++ b/src/features/Electron/titlebar/TabBar/resolveTab.test.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';import { type RouteMeta } from '@/spa/router/routeMeta';import { resolveTab } from './hooks/useResolvedTabs';+import { resolveTabScope } from './scope';import { type TabItem } from './types';const agentMeta: RouteMeta = { icon: MessageSquare, titleKey: 'navigation.chat' };@@ -22,6 +23,7 @@ const tab = (url: string, cached?: TabItem['cached']): TabItem => ({cached,id: url,lastVisited: 1,+ scope: resolveTabScope(url),url,});diff --git a/src/features/Electron/titlebar/TabBar/scope.test.ts b/src/features/Electron/titlebar/TabBar/scope.test.tsnew file mode 100644index 00000000000..750f7b62dea--- /dev/null+++ b/src/features/Electron/titlebar/TabBar/scope.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { isSameTabTarget, normalizeTabScope, resolveTabScope, tabTargetId } from './scope';++describe('desktop tab scope', () => {+ it('marks known top-level desktop routes as personal scope', () => {+ expect(resolveTabScope('/agent/personal-agent')).toEqual({ type: 'personal' });+ expect(resolveTabScope('/fleet')).toEqual({ type: 'personal' });+ expect(resolveTabScope('/settings/profile')).toEqual({ type: 'personal' });+ expect(resolveTabScope('/verify/run_1')).toEqual({ type: 'personal' });+ expect(resolveTabScope('/invite/abc')).toEqual({ type: 'personal' });+ });++ it('uses the first segment as workspace scope for workspace-prefixed URLs', () => {+ expect(resolveTabScope('/acme/agent/workspace-agent')).toEqual({+ slug: 'acme',+ type: 'workspace',+ });+ expect(resolveTabScope('/acme')).toEqual({ slug: 'acme', type: 'workspace' });+ });++ it('normalizes missing persisted scope from the item URL', () => {+ expect(normalizeTabScope(undefined, '/beta/group/g1')).toEqual({+ slug: 'beta',+ type: 'workspace',+ });+ });++ it('requires both normalized URL and scope to match', () => {+ expect(+ isSameTabTarget({ scope: { type: 'personal' }, url: '/agent/a?b=2&a=1' }, '/agent/a?a=1&b=2'),+ ).toBe(true);++ expect(+ isSameTabTarget(+ { scope: { slug: 'acme', type: 'workspace' }, url: '/acme/agent/a' },+ '/beta/agent/a',+ ),+ ).toBe(false);+ });++ it('keeps the historical recent/pinned id as the normalized URL', () => {+ expect(tabTargetId('/acme/agent/a?b=2&a=1')).toBe('/acme/agent/a?a=1&b=2');+ });+});diff --git a/src/features/Electron/titlebar/TabBar/scope.ts b/src/features/Electron/titlebar/TabBar/scope.tsnew file mode 100644index 00000000000..1e941005aae--- /dev/null+++ b/src/features/Electron/titlebar/TabBar/scope.ts@@ -0,0 +1,84 @@+import { normalizeTabUrl } from './url';++export type TabScope =+ | {+ type: 'personal';+ }+ | {+ slug: string;+ type: 'workspace';+ };++export interface ScopedTabTarget {+ scope?: TabScope;+ url: string;+}++const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;++const PERSONAL_TOP_LEVEL_SEGMENTS = new Set([+ 'agent',+ 'community',+ 'desktop-onboarding',+ 'devtools',+ 'eval',+ 'fleet',+ 'group',+ 'image',+ 'invite',+ 'me',+ 'memory',+ 'onboarding',+ 'page',+ 'resource',+ 'settings',+ 'share',+ 'task',+ 'tasks',+ 'verify',+ 'verify-im',+ 'video',+]);++export const PERSONAL_TAB_SCOPE: TabScope = { type: 'personal' };++export const resolveTabScope = (url: string): TabScope => {+ const [pathname = '/'] = url.split(/[?#]/);+ const firstSegment = FIRST_SEGMENT_REGEX.exec(pathname)?.[1];++ if (!firstSegment || PERSONAL_TOP_LEVEL_SEGMENTS.has(firstSegment)) return PERSONAL_TAB_SCOPE;++ return { slug: firstSegment, type: 'workspace' };+};++export const normalizeTabScope = (scope: unknown, url: string): TabScope => {+ if (!scope || typeof scope !== 'object') return resolveTabScope(url);++ const typedScope = scope as Partial<TabScope>;+ if (typedScope.type === 'personal') return PERSONAL_TAB_SCOPE;+ if (+ typedScope.type === 'workspace' &&+ 'slug' in typedScope &&+ typeof typedScope.slug === 'string' &&+ typedScope.slug.length > 0+ ) {+ return { slug: typedScope.slug, type: 'workspace' };+ }++ return resolveTabScope(url);+};++export const isSameTabScope = (a: TabScope, b: TabScope): boolean => {+ if (a.type !== b.type) return false;+ return a.type === 'personal' || a.slug === (b as Extract<TabScope, { type: 'workspace' }>).slug;+};++export const isSameTabTarget = (+ target: ScopedTabTarget,+ url: string,+ scope: TabScope = resolveTabScope(url),+): boolean =>+ normalizeTabUrl(target.url) === normalizeTabUrl(url) &&+ isSameTabScope(normalizeTabScope(target.scope, target.url), scope);++export const tabTargetId = (url: string): string => normalizeTabUrl(url);diff --git a/src/features/Electron/titlebar/TabBar/storage.test.ts b/src/features/Electron/titlebar/TabBar/storage.test.tsindex 0c3466274e2..b101af718a0 100644--- a/src/features/Electron/titlebar/TabBar/storage.test.ts+++ b/src/features/Electron/titlebar/TabBar/storage.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { resolveTabScope } from './scope';import {getTabPages,saveTabPages,@@ -21,13 +22,37 @@ describe('TabBar storage', () => {});it('round-trips v2 tab items', () => {- saveTabPages([{ id: '/agent/abc', lastVisited: 1, url: '/agent/abc' }], '/agent/abc');+ saveTabPages(+ [+ {+ id: '/agent/abc',+ lastVisited: 1,+ scope: resolveTabScope('/agent/abc'),+ url: '/agent/abc',+ },+ ],+ '/agent/abc',+ );const loaded = getTabPages();expect(loaded.tabs).toHaveLength(1);expect(loaded.tabs[0].url).toBe('/agent/abc');+ expect(loaded.tabs[0].scope).toEqual({ type: 'personal' });expect(loaded.activeTabId).toBe('/agent/abc');});+ it('revives old v2 tab items without persisted scope', () => {+ window.localStorage.setItem(+ TAB_PAGES_STORAGE_KEY,+ JSON.stringify({+ activeTabId: '/acme/agent/abc',+ tabs: [{ id: '/acme/agent/abc', lastVisited: 1, url: '/acme/agent/abc' }],+ }),+ );++ const loaded = getTabPages();+ expect(loaded.tabs[0].scope).toEqual({ slug: 'acme', type: 'workspace' });+ });+describe('v1 -> v2 migration', () => {it('reconstructs urls from old type + params', () => {window.localStorage.setItem(@@ -60,6 +85,11 @@ describe('TabBar storage', () => {const migrated = getTabPages();expect(migrated.tabs.map((t) => t.url)).toEqual(['/agent/abc', '/agent/abc/tpc_1', '/']);+ expect(migrated.tabs.map((t) => t.scope)).toEqual([+ { type: 'personal' },+ { type: 'personal' },+ { type: 'personal' },+ ]);expect(migrated.activeTabId).toBe('/agent/abc');expect(migrated.tabs[0].cached).toEqual({ avatar: 'a.png', title: 'Claude' });});@@ -110,6 +140,7 @@ describe('TabBar storage', () => {const loaded = getTabPages();expect(loaded.tabs).toHaveLength(1);expect(loaded.tabs[0].url).toBe('/page/p1');+ expect(loaded.tabs[0].scope).toEqual({ type: 'personal' });});});});diff --git a/src/features/Electron/titlebar/TabBar/storage.ts b/src/features/Electron/titlebar/TabBar/storage.tsindex b5a2e9de055..6fb0fd37278 100644--- a/src/features/Electron/titlebar/TabBar/storage.ts+++ b/src/features/Electron/titlebar/TabBar/storage.ts@@ -1,5 +1,6 @@import { type DynamicRouteMeta } from '@/spa/router/routeMeta';+import { normalizeTabScope } from './scope';import { type TabItem } from './types';import { normalizeTabUrl } from './url';@@ -20,6 +21,17 @@ const isTabItem = (item: unknown): item is TabItem =>typeof (item as TabItem).url === 'string' &&typeof (item as TabItem).lastVisited === 'number';+const reviveTabItem = (item: unknown): TabItem | null => {+ if (!isTabItem(item)) return null;++ return {+ ...item,+ scope: normalizeTabScope((item as Partial<TabItem>).scope, item.url),+ };+};++const isRevivedTabItem = (item: TabItem | null): item is TabItem => !!item;+const reconstructUrlFromV1 = (type: unknown, params: unknown): string | null => {if (typeof type !== 'string' || !params || typeof params !== 'object') return null;const p = params as Record<string, string | undefined>;@@ -94,6 +106,7 @@ const migrateV1 = (): TabPagesStorageData => {cached,id,lastVisited: typeof old.lastVisited === 'number' ? old.lastVisited : Date.now(),+ scope: normalizeTabScope(undefined, url),url,visitCount: typeof old.visitCount === 'number' ? old.visitCount : undefined,});@@ -123,7 +136,9 @@ export const getTabPages = (): TabPagesStorageData => {const parsed = JSON.parse(data);if (!parsed || typeof parsed !== 'object') return EMPTY;- const tabs = Array.isArray(parsed.tabs) ? parsed.tabs.filter(isTabItem) : [];+ const tabs = Array.isArray(parsed.tabs)+ ? parsed.tabs.map(reviveTabItem).filter(isRevivedTabItem)+ : [];return {activeTabId: typeof parsed.activeTabId === 'string' ? parsed.activeTabId : null,diff --git a/src/features/Electron/titlebar/TabBar/types.ts b/src/features/Electron/titlebar/TabBar/types.tsindex b2cdd3f41ad..9abf782dde5 100644--- a/src/features/Electron/titlebar/TabBar/types.ts+++ b/src/features/Electron/titlebar/TabBar/types.ts@@ -1,9 +1,12 @@import { type DynamicRouteMeta } from '@/spa/router/routeMeta';+import { type TabScope } from './scope';+export interface TabItem {cached?: DynamicRouteMeta;id: string;lastVisited: number;+ scope: TabScope;url: string;visitCount?: number;}diff --git a/src/features/Electron/titlebar/TabBar/url.test.ts b/src/features/Electron/titlebar/TabBar/url.test.tsindex 86a7b3f99fc..b78b4dabf6b 100644--- a/src/features/Electron/titlebar/TabBar/url.test.ts+++ b/src/features/Electron/titlebar/TabBar/url.test.ts@@ -51,6 +51,30 @@ describe('parseAgentTabContext', () => {});});+ it('parses a workspace agent url', () => {+ expect(parseAgentTabContext('/acme/agent/abc')).toEqual({+ agentId: 'abc',+ topicId: null,+ workspaceSlug: 'acme',+ });+ });++ it('parses a workspace agent topic path url', () => {+ expect(parseAgentTabContext('/acme/agent/abc/tpc_xyz')).toEqual({+ agentId: 'abc',+ topicId: 'tpc_xyz',+ workspaceSlug: 'acme',+ });+ });++ it('parses workspace topic from the search param', () => {+ expect(parseAgentTabContext('/acme/agent/abc?topic=t1')).toEqual({+ agentId: 'abc',+ topicId: 't1',+ workspaceSlug: 'acme',+ });+ });+it('returns null for non-agent urls', () => {expect(parseAgentTabContext('/group/g1')).toBeNull();});diff --git a/src/features/Electron/titlebar/TabBar/url.ts b/src/features/Electron/titlebar/TabBar/url.tsindex c45e1cfa25c..9abae9844ca 100644--- a/src/features/Electron/titlebar/TabBar/url.ts+++ b/src/features/Electron/titlebar/TabBar/url.ts@@ -23,17 +23,39 @@ export const normalizeTabUrl = (url: string): string => {export interface AgentTabContext {agentId: string;topicId: string | null;+ workspaceSlug?: string;}+const WORKSPACE_AGENT_TOPIC_PATH = /^\/([^/]+)\/agent\/([^/]+)\/(tpc_[^/]+)(?:\/|$)/;+const WORKSPACE_AGENT_PATH = /^\/([^/]+)\/agent\/([^/]+)(?:\/|$)/;const AGENT_TOPIC_PATH = /^\/agent\/([^/]+)\/(tpc_[^/]+)(?:\/|$)/;const AGENT_PATH = /^\/agent\/([^/]+)(?:\/|$)/;export const parseAgentTabContext = (url: string): AgentTabContext | null => {const [rawPath = '', rawQuery = ''] = url.split('?');+ const workspaceTopicMatch = rawPath.match(WORKSPACE_AGENT_TOPIC_PATH);+ if (workspaceTopicMatch) {+ return {+ agentId: workspaceTopicMatch[2],+ topicId: workspaceTopicMatch[3],+ workspaceSlug: workspaceTopicMatch[1],+ };+ }+const topicMatch = rawPath.match(AGENT_TOPIC_PATH);if (topicMatch) return { agentId: topicMatch[1], topicId: topicMatch[2] };+ const workspaceAgentMatch = rawPath.match(WORKSPACE_AGENT_PATH);+ if (workspaceAgentMatch) {+ const queryTopic = new URLSearchParams(rawQuery.split('#')[0] ?? '').get('topic');+ return {+ agentId: workspaceAgentMatch[2],+ topicId: queryTopic || null,+ workspaceSlug: workspaceAgentMatch[1],+ };+ }+const agentMatch = rawPath.match(AGENT_PATH);if (!agentMatch) return null;diff --git a/src/features/Fleet/AgentColumn.tsx b/src/features/Fleet/AgentColumn.tsxindex 71f6b7291a9..61102bff817 100644--- a/src/features/Fleet/AgentColumn.tsx+++ b/src/features/Fleet/AgentColumn.tsx@@ -19,6 +19,7 @@ import {import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';import StatusDot from '@/features/AgentTopicManager/StatusDot';import {@@ -29,6 +30,7 @@ import {useConversationStore,} from '@/features/Conversation';import OpStatusTray from '@/features/Conversation/ChatInput/OpStatusTray';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useOperationState } from '@/hooks/useOperationState';import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -351,6 +353,7 @@ const AgentColumn = memo<AgentColumnProps>(({ column, status }) => {const { t } = useTranslation('electron');const meta = useAgentDisplayMeta(column.agentId);const addTab = useElectronStore((s) => s.addTab);+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const context = useMemo(() => toConversationContext(column), [column]);const storedWidth = useFleetStore((s) => s.widths[column.key]);@@ -430,7 +433,8 @@ const AgentColumn = memo<AgentColumnProps>(({ column, status }) => {icon: <Icon icon={MessageSquareIcon} />,key: 'open-in-chat',label: t('fleet.openInChat'),- onClick: () => addTab(buildChatPath(column)),+ onClick: () =>+ addTab(buildWorkspaceAwarePath(buildChatPath(column), activeWorkspaceSlug)),},]}>diff --git a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsxindex 06764fc6091..ef92946afaa 100644--- a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx+++ b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx@@ -20,11 +20,13 @@ import {import { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { openRenameModal } from '@/components/RenameModal';import { SESSION_CHAT_TOPIC_URL } from '@/const/url';import { isDesktop } from '@/const/version';import { openShareModal } from '@/features/ShareModal';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useAppOrigin } from '@/hooks/useAppOrigin';import { usePermission } from '@/hooks/usePermission';import { useChatStore } from '@/store/chat';@@ -54,6 +56,7 @@ export const useDropdownMenu = ({const { message } = App.useApp();const appOrigin = useAppOrigin();const navigate = useWorkspaceAwareNavigate();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const { allowed: canCreateTopic } = usePermission('create_content');const { allowed: canEditTopic } = usePermission('edit_own_content');@@ -155,9 +158,12 @@ export const useDropdownMenu = ({label: t('actions.openInNewTab', { ns: 'topic' }),onClick: () => {if (!agentId) return;- const url = SESSION_CHAT_TOPIC_URL(agentId, topicId);+ const url = buildWorkspaceAwarePath(+ SESSION_CHAT_TOPIC_URL(agentId, topicId),+ activeWorkspaceSlug,+ );addTab(url);- navigate(url);+ navigate(url, { escape: true });onClose();},},@@ -244,6 +250,7 @@ export const useDropdownMenu = ({].filter(Boolean) as MenuProps['items'],[addTab,+ activeWorkspaceSlug,agentId,appOrigin,autoRenameTopicTitle,diff --git a/src/features/Pages/PageLayout/Body/List/Item/index.tsx b/src/features/Pages/PageLayout/Body/List/Item/index.tsxindex faf33939b12..87131006290 100644--- a/src/features/Pages/PageLayout/Body/List/Item/index.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/index.tsx@@ -4,8 +4,10 @@ import { type MouseEvent } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { isDesktop } from '@/const/version';import NavItem from '@/features/NavPanel/components/NavItem';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useElectronStore } from '@/store/electron';import { pageSelectors, usePageStore } from '@/store/page';@@ -28,6 +30,7 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {const selectPage = usePageStore((s) => s.selectPage);const setRenamingPageId = usePageStore((s) => s.setRenamingPageId);const addTab = useElectronStore((s) => s.addTab);+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const active = selectedPageId === pageId;const title = document?.title || t('pageList.untitled');@@ -66,9 +69,9 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {clearTimeout(clickTimerRef.current);clickTimerRef.current = null;}- addTab(`/page/${pageId}`);+ addTab(buildWorkspaceAwarePath(`/page/${pageId}`, activeWorkspaceSlug));selectPage(pageId);- }, [pageId, addTab, selectPage]);+ }, [pageId, activeWorkspaceSlug, addTab, selectPage]);// Icon with emoji supportconst icon = useMemo(() => {diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsxindex dd5bda22b87..ebdcac0758b 100644--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx@@ -6,9 +6,11 @@ import { CopyPlus, PanelTop, Pencil, Trash2 } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { useDocumentTransferMenuItem } from '@/business/client/hooks/useDocumentTransferMenuItem';import { isDesktop } from '@/const/version';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { usePermission } from '@/hooks/usePermission';import { useElectronStore } from '@/store/electron';import { usePageStore } from '@/store/page';@@ -25,6 +27,7 @@ export const useDropdownMenu = ({const { t } = useTranslation(['common', 'file']);const { message } = App.useApp();const navigate = useWorkspaceAwareNavigate();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const { allowed: canCreatePage } = usePermission('create_content');const { allowed: canEditPage } = usePermission('edit_own_content');const addTab = useElectronStore((s) => s.addTab);@@ -73,9 +76,9 @@ export const useDropdownMenu = ({key: 'openInNewTab',label: t('pageList.actions.openInNewTab', { ns: 'file' }),onClick: () => {- const url = `/page/${pageId}`;+ const url = buildWorkspaceAwarePath(`/page/${pageId}`, activeWorkspaceSlug);addTab(url);- navigate(url);+ navigate(url, { escape: true });},},{ type: 'divider' as const },@@ -116,6 +119,7 @@ export const useDropdownMenu = ({handleDelete,canCreatePage,canEditPage,+ activeWorkspaceSlug,pageId,addTab,navigate,diff --git a/src/features/Pages/routeMeta.ts b/src/features/Pages/routeMeta.tsindex 96587722997..d86e689704a 100644--- a/src/features/Pages/routeMeta.ts+++ b/src/features/Pages/routeMeta.ts@@ -1,5 +1,6 @@import { FilePenIcon } from 'lucide-react';+import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';import { usePageStore } from '@/store/page';import { listSelectors } from '@/store/page/slices/list/selectors';@@ -9,8 +10,12 @@ export const pageRouteMeta = routeMeta({icon: FilePenIcon,titleKey: 'navigation.page',useDynamicMeta: (params): DynamicRouteMeta => {+ const routeWorkspaceId = useRouteWorkspaceId(params);const pageId = params.id ? getIdFromIdentifier(params.id, 'docs') : '';- const document = usePageStore(listSelectors.getDocumentById(pageId));+ const document = usePageStore((s) => {+ const item = listSelectors.getDocumentById(pageId)(s);+ return matchesRouteWorkspace(item?.workspaceId, routeWorkspaceId) ? item : undefined;+ });return {title: document?.title || undefined,diff --git a/src/features/RouteMeta/DynamicMetaRunner.tsx b/src/features/RouteMeta/DynamicMetaRunner.tsxindex a451364e566..4c066ad05e6 100644--- a/src/features/RouteMeta/DynamicMetaRunner.tsx+++ b/src/features/RouteMeta/DynamicMetaRunner.tsx@@ -4,13 +4,17 @@ import debug from 'debug';import { memo, useEffect } from 'react';import { SafeBoundary } from '@/components/ErrorBoundary';-import { type DynamicRouteMeta, type RouteMeta } from '@/spa/router/routeMeta';+import {+ type DynamicRouteMeta,+ type RouteMeta,+ type RouteMetaParams,+} from '@/spa/router/routeMeta';const log = debug('lobe-client:route-meta');interface DynamicMetaRunnerProps {onResolve: (meta: DynamicRouteMeta) => void;- params: Record<string, string | undefined>;+ params: RouteMetaParams;useDynamicMeta?: RouteMeta['useDynamicMeta'];}diff --git a/src/features/RouteMeta/RouteMetaBridge.test.tsx b/src/features/RouteMeta/RouteMetaBridge.test.tsxindex c5542c7f3ee..f7ab215a917 100644--- a/src/features/RouteMeta/RouteMetaBridge.test.tsx+++ b/src/features/RouteMeta/RouteMetaBridge.test.tsx@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => {id: string;params: Record<string, string | undefined>;pathname: string;+ search?: string;}const store = {@@ -59,7 +60,8 @@ vi.mock('react-router', async () => {useMatches: () => React.useSyncExternalStore(mocks.subscribe, mocks.getSnapshot),useLocation: () => {const matches = React.useSyncExternalStore(mocks.subscribe, mocks.getSnapshot);- return { pathname: matches.at(-1)?.pathname ?? '/', search: '' };+ const match = matches.at(-1);+ return { pathname: match?.pathname ?? '/', search: match?.search ?? '' };},};});@@ -176,4 +178,38 @@ describe('RouteMetaBridge', () => {if (titleDescriptor) Object.defineProperty(document, 'title', titleDescriptor);}});++ it('passes search params to dynamic route meta', async () => {+ mocks.setMatches([+ {+ data: undefined,+ handle: {+ meta: {+ titleKey: 'navigation.groupChat',+ useDynamicMeta: (params: Record<string, string | undefined>) => ({+ title: `Topic ${params.topic}`,+ }),+ },+ },+ id: 'routes/group',+ params: { gid: 'group-a' },+ pathname: '/group/group-a',+ search: '?topic=t1',+ },+ ]);++ render(<RouteMetaBridge />);++ await waitFor(() => {+ expect(document.title).toBe(`Topic t1 · ${BRANDING_NAME}`);+ expect(mocks.setCurrentRouteMeta).toHaveBeenLastCalledWith(+ {+ avatar: undefined,+ backgroundColor: undefined,+ title: 'Topic t1',+ },+ '/group/group-a?topic=t1',+ );+ });+ });});diff --git a/src/features/RouteMeta/RouteMetaBridge.tsx b/src/features/RouteMeta/RouteMetaBridge.tsxindex 85c200c225b..8fe41b3650a 100644--- a/src/features/RouteMeta/RouteMetaBridge.tsx+++ b/src/features/RouteMeta/RouteMetaBridge.tsx@@ -10,14 +10,16 @@ import {type DynamicRouteMeta,getRouteMetaFromHandle,type RouteMeta,+ type RouteMetaParams,} from '@/spa/router/routeMeta';import { useElectronStore } from '@/store/electron';import DynamicMetaRunner from './DynamicMetaRunner';+import { mergeSearchParams } from './params';interface MatchedRouteMeta {meta: RouteMeta;- params: Record<string, string | undefined>;+ params: RouteMetaParams;routeId: string;}@@ -67,6 +69,10 @@ const RouteMetaBridge = memo(() => {const translate = t as unknown as Translate;const titleKey = matched?.meta.titleKey;+ const routeMetaParams = useMemo(+ () => (matched ? mergeSearchParams(matched.params, location.search) : {}),+ [location.search, matched],+ );// Keep the previously resolved meta while navigating within the same route family// (e.g. switching topics) so the title doesn't briefly fall back to the static label.const currentDynamic = matched && dynamic.routeId === matched.routeId ? dynamic.meta : {};@@ -90,7 +96,7 @@ const RouteMetaBridge = memo(() => {return (<DynamicMetaRunnerkey={matched.routeId}- params={matched.params}+ params={routeMetaParams}useDynamicMeta={matched.meta.useDynamicMeta}onResolve={handleResolve}/>diff --git a/src/features/RouteMeta/params.ts b/src/features/RouteMeta/params.tsnew file mode 100644index 00000000000..72e7f5aeffc--- /dev/null+++ b/src/features/RouteMeta/params.ts@@ -0,0 +1,16 @@+import { type RouteMetaParams } from '@/spa/router/routeMeta';++export const mergeSearchParams = (params: RouteMetaParams, url: string): RouteMetaParams => {+ const [, rawSearch = ''] = url.split('?');+ const search = rawSearch.split('#')[0] ?? '';+ if (!search) return params;++ const next: RouteMetaParams = { ...params };+ const searchParams = new URLSearchParams(search);++ for (const [key, value] of searchParams.entries()) {+ next[key] ??= value;+ }++ return next;+};diff --git a/src/features/RouteMeta/workspaceScope.test.tsx b/src/features/RouteMeta/workspaceScope.test.tsxnew file mode 100644index 00000000000..77bf4ddd4c5--- /dev/null+++ b/src/features/RouteMeta/workspaceScope.test.tsx@@ -0,0 +1,53 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { matchesRouteWorkspace, useRouteWorkspaceId } from './workspaceScope';++const mocks = vi.hoisted(() => ({+ workspaces: [] as Array<{ id: string; slug: string }>,+}));++vi.mock('@/business/client/hooks/useWorkspaces', () => ({+ useWorkspaces: () => mocks.workspaces,+}));++describe('useRouteWorkspaceId', () => {+ it('resolves personal scope when the route has no workspace slug', () => {+ const { result } = renderHook(() => useRouteWorkspaceId({}));+ expect(result.current).toBeNull();+ });++ it('resolves workspace id from the route workspace slug', () => {+ mocks.workspaces = [{ id: 'ws-1', slug: 'acme' }];++ const { result } = renderHook(() => useRouteWorkspaceId({ workspaceSlug: 'acme' }));++ expect(result.current).toBe('ws-1');+ });++ it('returns unresolved scope for an unknown workspace slug', () => {+ mocks.workspaces = [];++ const { result } = renderHook(() => useRouteWorkspaceId({ workspaceSlug: 'acme' }));++ expect(result.current).toBeUndefined();+ });+});++describe('matchesRouteWorkspace', () => {+ it('matches personal items only in personal scope', () => {+ expect(matchesRouteWorkspace(null, null)).toBe(true);+ expect(matchesRouteWorkspace(undefined, null)).toBe(true);+ expect(matchesRouteWorkspace('ws-1', null)).toBe(false);+ });++ it('matches workspace items only by workspace id', () => {+ expect(matchesRouteWorkspace('ws-1', 'ws-1')).toBe(true);+ expect(matchesRouteWorkspace('ws-2', 'ws-1')).toBe(false);+ });++ it('rejects all items while the route workspace is unresolved', () => {+ expect(matchesRouteWorkspace(null, undefined)).toBe(false);+ expect(matchesRouteWorkspace('ws-1', undefined)).toBe(false);+ });+});diff --git a/src/features/RouteMeta/workspaceScope.ts b/src/features/RouteMeta/workspaceScope.tsnew file mode 100644index 00000000000..b804f9f890f--- /dev/null+++ b/src/features/RouteMeta/workspaceScope.ts@@ -0,0 +1,18 @@+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import { type RouteMetaParams } from '@/spa/router/routeMeta';++export type RouteWorkspaceId = string | null | undefined;++export const useRouteWorkspaceId = (params: RouteMetaParams): RouteWorkspaceId => {+ const workspaces = useWorkspaces();+ const workspaceSlug = params.workspaceSlug;++ if (!workspaceSlug) return null;++ return workspaces.find((workspace) => workspace.slug === workspaceSlug)?.id;+};++export const matchesRouteWorkspace = (+ itemWorkspaceId: string | null | undefined,+ routeWorkspaceId: RouteWorkspaceId,+): boolean => routeWorkspaceId !== undefined && (itemWorkspaceId ?? null) === routeWorkspaceId;diff --git a/src/features/Workspace/routeMeta.test.tsx b/src/features/Workspace/routeMeta.test.tsxnew file mode 100644index 00000000000..66cd16e348f--- /dev/null+++ b/src/features/Workspace/routeMeta.test.tsx@@ -0,0 +1,52 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { workspaceHomeRouteMeta } from './routeMeta';++const mocks = vi.hoisted(() => ({+ workspaces: [] as Array<{ avatar?: string | null; id: string; name: string; slug: string }>,+}));++vi.mock('@/business/client/hooks/useWorkspaces', () => ({+ useWorkspaces: () => mocks.workspaces,+}));++describe('workspaceHomeRouteMeta', () => {+ it('uses the workspace avatar and name for the workspace home tab', () => {+ mocks.workspaces = [+ { avatar: 'https://example.com/avatar.png', id: 'ws-1', name: 'Acme', slug: 'acme' },+ ];++ const { result } = renderHook(() =>+ workspaceHomeRouteMeta.useDynamicMeta?.({ workspaceSlug: 'acme' }),+ );++ expect(result.current).toEqual({+ avatar: 'https://example.com/avatar.png',+ title: 'Acme',+ });+ });++ it('uses the workspace name as the avatar placeholder source when no avatar is set', () => {+ mocks.workspaces = [{ avatar: null, id: 'ws-1', name: 'Acme', slug: 'acme' }];++ const { result } = renderHook(() =>+ workspaceHomeRouteMeta.useDynamicMeta?.({ workspaceSlug: 'acme' }),+ );++ expect(result.current).toEqual({+ avatar: 'Acme',+ title: 'Acme',+ });+ });++ it('returns no dynamic meta while the workspace slug is unresolved', () => {+ mocks.workspaces = [];++ const { result } = renderHook(() =>+ workspaceHomeRouteMeta.useDynamicMeta?.({ workspaceSlug: 'acme' }),+ );++ expect(result.current).toEqual({});+ });+});diff --git a/src/features/Workspace/routeMeta.ts b/src/features/Workspace/routeMeta.tsnew file mode 100644index 00000000000..5a428252388--- /dev/null+++ b/src/features/Workspace/routeMeta.ts@@ -0,0 +1,19 @@+'use client';++import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';++export const workspaceHomeRouteMeta = routeMeta({+ titleKey: 'navigation.home',+ useDynamicMeta: (params): DynamicRouteMeta => {+ const workspaces = useWorkspaces();+ const workspace = workspaces.find((item) => item.slug === params.workspaceSlug);++ if (!workspace) return {};++ return {+ avatar: workspace.avatar || workspace.name,+ title: workspace.name,+ };+ },+});diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 5ae291b7fbe..ff98083a851 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -226,9 +226,11 @@ const TopicItem = memo<TopicItemProps>(void navigateToTopic(id, { skipPopupFocus: true });return;}- addTab(SESSION_CHAT_TOPIC_URL(activeAgentId, id));+ addTab(+ buildWorkspaceAwarePath(SESSION_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug),+ );void navigateToTopic(id);- }, [id, activeAgentId, addTab, focusTopicPopup, navigateToTopic]);+ }, [id, activeAgentId, activeWorkspaceSlug, addTab, focusTopicPopup, navigateToTopic]);const { dropdownMenu } = useTopicItemDropdownMenu({fav,diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsxindex 0bca46ade2b..d99d7361744 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx@@ -21,12 +21,14 @@ import {import { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { openRenameModal } from '@/components/RenameModal';import { SESSION_CHAT_TOPIC_URL } from '@/const/url';import { isDesktop } from '@/const/version';import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsModal';import { openShareModal } from '@/features/ShareModal';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useAppOrigin } from '@/hooks/useAppOrigin';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';@@ -50,6 +52,7 @@ export const useTopicItemDropdownMenu = ({const { t } = useTranslation(['topic', 'common']);const { message } = App.useApp();const navigate = useWorkspaceAwareNavigate();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const { allowed: canCreateTopic } = usePermission('create_content');const { allowed: canEditTopic } = usePermission('edit_own_content');@@ -151,9 +154,12 @@ export const useTopicItemDropdownMenu = ({label: t('actions.openInNewTab'),onClick: () => {if (!activeAgentId) return;- const url = SESSION_CHAT_TOPIC_URL(activeAgentId, id);+ const url = buildWorkspaceAwarePath(+ SESSION_CHAT_TOPIC_URL(activeAgentId, id),+ activeWorkspaceSlug,+ );addTab(url);- navigate(url);+ navigate(url, { escape: true });},},{@@ -248,6 +254,7 @@ export const useTopicItemDropdownMenu = ({canCreateTopic,canEditTopic,activeAgentId,+ activeWorkspaceSlug,appOrigin,autoRenameTopicTitle,duplicateTopic,diff --git a/src/routes/(main)/agent/features/routeMeta.ts b/src/routes/(main)/agent/features/routeMeta.tsindex 2cb2d57126e..9ea027e0a53 100644--- a/src/routes/(main)/agent/features/routeMeta.ts+++ b/src/routes/(main)/agent/features/routeMeta.ts@@ -1,26 +1,40 @@import { MessageSquare } from 'lucide-react';+import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';-const useTopicTitle = (topicId: string | undefined): string | undefined =>+const useTopicTitle = (+ agentId: string | undefined,+ topicId: string | undefined,+ routeWorkspaceId: string | null | undefined,+): string | undefined =>useChatStore((s) => {- if (!topicId) return undefined;- for (const data of Object.values(s.topicDataMap)) {- const topic = data.items?.find((item) => item.id === topicId);- if (topic?.title) return topic.title;- }- return undefined;+ if (!agentId || !topicId || routeWorkspaceId === undefined) return undefined;++ const topic = s.topicDataMap[topicMapKey({ agentId })]?.items?.find(+ (item) => item.id === topicId,+ );+ return topic?.title || undefined;});export const agentRouteMeta = routeMeta({icon: MessageSquare,titleKey: 'navigation.chat',useDynamicMeta: (params): DynamicRouteMeta => {- const meta = useAgentStore(agentSelectors.getAgentMetaById(params.aid ?? ''));- const topicTitle = useTopicTitle(params.topicId);+ const routeWorkspaceId = useRouteWorkspaceId(params);+ const meta = useAgentStore((s) => {+ const agentId = params.aid ?? '';+ const agent = s.agentMap[agentId];++ if (!matchesRouteWorkspace(agent?.workspaceId, routeWorkspaceId)) return {};++ return agentSelectors.getAgentMetaById(agentId)(s);+ });+ const topicTitle = useTopicTitle(params.aid, params.topicId ?? params.topic, routeWorkspaceId);const hasMeta = Object.keys(meta).length > 0;const agentTitle = hasMeta ? meta.title : undefined;diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex b4796cd833f..366158a54be 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -13,11 +13,13 @@ import { AnimatePresence, m } from 'motion/react';import { memo, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import DotsLoading from '@/components/DotsLoading';import { isDesktop } from '@/const/version';import { useHasDraft } from '@/features/ChatInput/draftStorage';import NavItem from '@/features/NavPanel/components/NavItem';import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useAgentGroupStore } from '@/store/agentGroup';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';@@ -92,13 +94,14 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, statconst toggleMobileTopic = useGlobalStore((s) => s.toggleMobileTopic);const [activeGroupId, switchTopic] = useAgentGroupStore((s) => [s.activeGroupId, s.switchTopic]);const addTab = useElectronStore((s) => s.addTab);+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const focusTopicPopup = useFocusTopicPopup({ groupId: activeGroupId });// Construct href for cmd+click supportconst href = useMemo(() => {if (!activeGroupId || !id) return undefined;- return `/group/${activeGroupId}?topic=${id}`;- }, [activeGroupId, id]);+ return buildWorkspaceAwarePath(`/group/${activeGroupId}?topic=${id}`, activeWorkspaceSlug);+ }, [activeGroupId, activeWorkspaceSlug, id]);const [editing, isLoading] = useChatStore((s) => [id ? s.topicRenamingId === id : false,@@ -145,10 +148,18 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stattoggleMobileTopic(false);return;}- addTab(`/group/${activeGroupId}?topic=${id}`);+ addTab(buildWorkspaceAwarePath(`/group/${activeGroupId}?topic=${id}`, activeWorkspaceSlug));switchTopic(id);toggleMobileTopic(false);- }, [id, activeGroupId, addTab, focusTopicPopup, switchTopic, toggleMobileTopic]);+ }, [+ id,+ activeGroupId,+ activeWorkspaceSlug,+ addTab,+ focusTopicPopup,+ switchTopic,+ toggleMobileTopic,+ ]);const dropdownMenu = useTopicItemDropdownMenu({id,diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsxindex 108e546d709..c1147eb5a05 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx@@ -18,8 +18,10 @@ import {import { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { isDesktop } from '@/const/version';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useAppOrigin } from '@/hooks/useAppOrigin';import { usePermission } from '@/hooks/usePermission';import { useAgentGroupStore } from '@/store/agentGroup';@@ -41,6 +43,7 @@ export const useTopicItemDropdownMenu = ({const { t } = useTranslation(['topic', 'common']);const { message } = App.useApp();const navigate = useWorkspaceAwareNavigate();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();const { allowed: canCreateTopic } = usePermission('create_content');const { allowed: canEditTopic } = usePermission('edit_own_content');@@ -114,9 +117,12 @@ export const useTopicItemDropdownMenu = ({label: t('actions.openInNewTab'),onClick: () => {if (!activeGroupId) return;- const url = `/group/${activeGroupId}?topic=${id}`;+ const url = buildWorkspaceAwarePath(+ `/group/${activeGroupId}?topic=${id}`,+ activeWorkspaceSlug,+ );addTab(url);- navigate(url);+ navigate(url, { escape: true });},},{@@ -190,6 +196,7 @@ export const useTopicItemDropdownMenu = ({canCreateTopic,canEditTopic,activeGroupId,+ activeWorkspaceSlug,appOrigin,autoRenameTopicTitle,duplicateTopic,diff --git a/src/routes/(main)/group/features/routeMeta.ts b/src/routes/(main)/group/features/routeMeta.tsindex 61b4a8103d2..0c2ce0e24e2 100644--- a/src/routes/(main)/group/features/routeMeta.ts+++ b/src/routes/(main)/group/features/routeMeta.ts@@ -1,28 +1,39 @@import { Users } from 'lucide-react';-import { useSearchParams } from 'react-router';+import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';import { useChatStore } from '@/store/chat';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { useSessionStore } from '@/store/session';import { sessionGroupSelectors } from '@/store/session/slices/sessionGroup/selectors';-const useTopicTitle = (topicId: string | null): string | undefined =>+const getWorkspaceId = (item: unknown): string | null | undefined =>+ (item as { workspaceId?: string | null } | undefined)?.workspaceId;++const useTopicTitle = (+ groupId: string | undefined,+ topicId: string | undefined,+ routeWorkspaceId: string | null | undefined,+): string | undefined =>useChatStore((s) => {- if (!topicId) return undefined;- for (const data of Object.values(s.topicDataMap)) {- const topic = data.items?.find((item) => item.id === topicId);- if (topic?.title) return topic.title;- }- return undefined;+ if (!groupId || !topicId || routeWorkspaceId === undefined) return undefined;++ const topic = s.topicDataMap[topicMapKey({ groupId })]?.items?.find(+ (item) => item.id === topicId,+ );+ return topic?.title || undefined;});export const groupRouteMeta = routeMeta({icon: Users,titleKey: 'navigation.groupChat',useDynamicMeta: (params): DynamicRouteMeta => {- const [searchParams] = useSearchParams();- const group = useSessionStore(sessionGroupSelectors.getGroupById(params.gid ?? ''));- const topicTitle = useTopicTitle(searchParams.get('topic'));+ const routeWorkspaceId = useRouteWorkspaceId(params);+ const group = useSessionStore((s) => {+ const item = sessionGroupSelectors.getGroupById(params.gid ?? '')(s);+ return matchesRouteWorkspace(getWorkspaceId(item), routeWorkspaceId) ? item : undefined;+ });+ const topicTitle = useTopicTitle(params.gid, params.topic, routeWorkspaceId);return {title: topicTitle || group?.name || undefined,diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex 92ea200ae9f..10eb208ca80 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -20,6 +20,7 @@ import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { fleetRouteMeta } from '@/features/Fleet/routeMeta';import { pageRouteMeta } from '@/features/Pages/routeMeta';import { verifyRouteMeta } from '@/features/Verify/routeMeta';+import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';import DesktopOnboarding from '@/routes/(desktop)/desktop-onboarding';// Layouts — sync import (Electron local, no network overhead)import DesktopMainLayout from '@/routes/(main)/_layout';@@ -653,7 +654,7 @@ export const desktopRoutes: RouteObject[] = [children: [// Workspace home — handled by the persistent `DesktopHomeLayout`// (mirrors `/` index). Adding an element renders Home twice.- { index: true },+ { handle: { meta: workspaceHomeRouteMeta }, index: true },...sharedMainAreaChildren,// Workspace settings — `/:slug/settings/*`. Dedicated layout with// its own sidebar (workspace avatar + 6 tabs + back-to-chat), fullydiff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex cacb19c32c0..3ca08dff6e5 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -20,6 +20,7 @@ import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { fleetRouteMeta } from '@/features/Fleet/routeMeta';import { pageRouteMeta } from '@/features/Pages/routeMeta';import { verifyRouteMeta } from '@/features/Verify/routeMeta';+import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';@@ -759,6 +760,7 @@ export const desktopRoutes: RouteObject[] = [// the outer main layout (mirrors how `/` index is empty here). Adding// an element would render Home twice on top of `DesktopHomeLayout`.{+ handle: { meta: workspaceHomeRouteMeta },index: true,},...sharedMainAreaChildren,diff --git a/src/spa/router/routeMeta.ts b/src/spa/router/routeMeta.tsindex 8d1e18c9e8f..90b066e0525 100644--- a/src/spa/router/routeMeta.ts+++ b/src/spa/router/routeMeta.ts@@ -11,8 +11,10 @@ export interface DynamicRouteMeta {title?: string;}+export type RouteMetaParams = Record<string, string | undefined>;+export interface RouteMeta extends StaticRouteMeta {- useDynamicMeta?: (params: Record<string, string | undefined>) => DynamicRouteMeta;+ useDynamicMeta?: (params: RouteMetaParams) => DynamicRouteMeta;}export interface RouteHandle {diff --git a/src/store/electron/actions/__tests__/recentPages.test.ts b/src/store/electron/actions/__tests__/recentPages.test.tsnew file mode 100644index 00000000000..5c6e5ba3cfc--- /dev/null+++ b/src/store/electron/actions/__tests__/recentPages.test.ts@@ -0,0 +1,93 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';+import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';+import { useElectronStore } from '@/store/electron';+import { initialState } from '@/store/electron/initialState';++vi.mock('@/features/Electron/titlebar/TabBar/resolveRouteMeta', () => ({+ guardedMergeCache: (prev: TabItem['cached'], next: TabItem['cached']) => ({ ...prev, ...next }),+}));++const buildTab = (url: string, cached?: TabItem['cached']): TabItem => ({+ cached,+ id: url,+ lastVisited: 1,+ scope: resolveTabScope(url),+ url,+});++describe('recentPages actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ window.localStorage.clear();+ useElectronStore.setState({ ...initialState, pinnedPages: [], recentPages: [] });+ });++ describe('addRecentPage', () => {+ it('keeps personal and workspace URLs as separate recent entries', () => {+ const { result } = renderHook(() => useElectronStore());++ act(() => {+ result.current.addRecentPage('/agent/abc');+ result.current.addRecentPage('/acme/agent/abc');+ });++ expect(result.current.recentPages.map((page) => page.id)).toEqual([+ '/acme/agent/abc',+ '/agent/abc',+ ]);+ expect(result.current.recentPages.map((page) => page.scope)).toEqual([+ { slug: 'acme', type: 'workspace' },+ { type: 'personal' },+ ]);+ });++ it('dedupes only within the same normalized workspace URL', () => {+ const { result } = renderHook(() => useElectronStore());++ act(() => {+ result.current.addRecentPage('/acme/agent/abc?b=2&a=1');+ result.current.addRecentPage('/acme/agent/abc?a=1&b=2');+ });++ expect(result.current.recentPages).toHaveLength(1);+ expect(result.current.recentPages[0].id).toBe('/acme/agent/abc?a=1&b=2');+ expect(result.current.recentPages[0].scope).toEqual({+ slug: 'acme',+ type: 'workspace',+ });+ expect(result.current.recentPages[0].visitCount).toBe(2);+ });+ });++ describe('pinPage', () => {+ it('pins personal and workspace URLs independently', () => {+ const { result } = renderHook(() => useElectronStore());++ act(() => {+ result.current.pinPage(buildTab('/agent/abc'));+ result.current.pinPage(buildTab('/acme/agent/abc'));+ });++ expect(result.current.pinnedPages.map((page) => page.id)).toEqual([+ '/agent/abc',+ '/acme/agent/abc',+ ]);+ });++ it('removes only the matching scoped recent entry when pinning', () => {+ const { result } = renderHook(() => useElectronStore());++ act(() => {+ result.current.addRecentPage('/agent/abc');+ result.current.addRecentPage('/acme/agent/abc');+ result.current.pinPage(buildTab('/acme/agent/abc'));+ });++ expect(result.current.pinnedPages.map((page) => page.id)).toEqual(['/acme/agent/abc']);+ expect(result.current.recentPages.map((page) => page.id)).toEqual(['/agent/abc']);+ });+ });+});diff --git a/src/store/electron/actions/__tests__/tabPages.test.ts b/src/store/electron/actions/__tests__/tabPages.test.tsindex a115d0b7efa..cb044cbbaf0 100644--- a/src/store/electron/actions/__tests__/tabPages.test.ts+++ b/src/store/electron/actions/__tests__/tabPages.test.ts@@ -1,14 +1,31 @@import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';import { useElectronStore } from '@/store/electron';import { initialState } from '@/store/electron/initialState';+vi.mock('@/features/Electron/titlebar/TabBar/resolveRouteMeta', () => ({+ guardedMergeCache: (prev: TabItem['cached'], next: TabItem['cached']) => {+ if (!next) return prev;++ const merged: TabItem['cached'] = { ...prev };+ for (const [key, value] of Object.entries(next)) {+ if (value === undefined) continue;+ if (typeof value === 'string' && value.trim() === '') continue;+ merged[key as keyof NonNullable<TabItem['cached']>] = value;+ }++ return Object.keys(merged ?? {}).length > 0 ? merged : undefined;+ },+}));+const buildTab = (url: string, cached?: TabItem['cached']): TabItem => ({cached,id: url,lastVisited: 1,+ scope: resolveTabScope(url),url,});@@ -33,10 +50,21 @@ describe('tabPages actions', () => {expect(result.current.tabs).toHaveLength(1);expect(result.current.tabs[0].id).toBe(createdId);+ expect(result.current.tabs[0].scope).toEqual({ type: 'personal' });expect(result.current.tabs[0].url).toBe('/agent/abc?b=2&a=1');expect(result.current.activeTabId).toBe(createdId);});+ it('records workspace scope on workspace tabs', () => {+ const { result } = renderHook(() => useElectronStore());++ act(() => {+ result.current.addTab('/acme/agent/abc');+ });++ expect(result.current.tabs[0].scope).toEqual({ slug: 'acme', type: 'workspace' });+ });+it('dedupes tabs that resolve to the same normalized URL', () => {const { result } = renderHook(() => useElectronStore());@@ -94,10 +122,27 @@ describe('tabPages actions', () => {const updatedTab = result.current.tabs[0];expect(updatedTab.id).toBe(agentTab.id);expect(updatedTab.url).toBe('/');+ expect(updatedTab.scope).toEqual({ type: 'personal' });expect(updatedTab.cached).toBeUndefined();expect(result.current.activeTabId).toBe(agentTab.id);});+ it('updates the stored scope when the tab moves into a workspace URL', () => {+ const { result } = renderHook(() => useElectronStore());+ const agentTab = buildTab('/agent/abc', { title: 'Claude Code' });++ act(() => {+ useElectronStore.setState({ activeTabId: agentTab.id, tabs: [agentTab] });+ });++ act(() => {+ result.current.updateTab(agentTab.id, '/acme/agent/abc');+ });++ expect(result.current.tabs[0].scope).toEqual({ slug: 'acme', type: 'workspace' });+ expect(result.current.tabs[0].cached).toBeUndefined();+ });+it('keeps cached data when the normalized URL is unchanged', () => {const { result } = renderHook(() => useElectronStore());const agentTab = buildTab('/agent/abc?a=1', { title: 'Claude Code' });diff --git a/src/store/electron/actions/recentPages.ts b/src/store/electron/actions/recentPages.tsindex da2e398229f..7682af31cf9 100644--- a/src/store/electron/actions/recentPages.ts+++ b/src/store/electron/actions/recentPages.ts@@ -3,8 +3,13 @@ import {savePinnedPages,} from '@/features/Electron/titlebar/RecentlyViewed/storage';import { guardedMergeCache } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';+import {+ isSameTabTarget,+ normalizeTabScope,+ resolveTabScope,+ tabTargetId,+} from '@/features/Electron/titlebar/TabBar/scope';import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';-import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';import { type DynamicRouteMeta } from '@/spa/router/routeMeta';import { type StoreSetter } from '@/store/types';@@ -47,9 +52,10 @@ export class RecentPagesActionImpl {addRecentPage = (url: string, cached?: DynamicRouteMeta): void => {const { pinnedPages, recentPages } = this.#get();- const id = normalizeTabUrl(url);+ const scope = resolveTabScope(url);+ const id = tabTargetId(url);- const pinnedIndex = pinnedPages.findIndex((p) => p.id === id);+ const pinnedIndex = pinnedPages.findIndex((p) => isSameTabTarget(p, url, scope));if (pinnedIndex >= 0) {const merged = guardedMergeCache(pinnedPages[pinnedIndex].cached, cached);if (merged === pinnedPages[pinnedIndex].cached) return;@@ -61,13 +67,14 @@ export class RecentPagesActionImpl {return;}- const existingIndex = recentPages.findIndex((p) => p.id === id);+ const existingIndex = recentPages.findIndex((p) => isSameTabTarget(p, url, scope));const existingEntry = existingIndex >= 0 ? recentPages[existingIndex] : null;const newEntry: TabItem = {cached: guardedMergeCache(existingEntry?.cached, cached),id,lastVisited: Date.now(),+ scope,url,visitCount: (existingEntry?.visitCount || 0) + 1,};@@ -92,29 +99,40 @@ export class RecentPagesActionImpl {const pinned = getPinnedPages();const { recentPages } = this.#get();- const pinnedIds = new Set(pinned.map((p) => p.id));- const filteredRecent = recentPages.filter((p) => !pinnedIds.has(p.id));+ const filteredRecent = recentPages.filter(+ (recentPage) =>+ !pinned.some((pinnedPage) =>+ isSameTabTarget(+ recentPage,+ pinnedPage.url,+ normalizeTabScope(pinnedPage.scope, pinnedPage.url),+ ),+ ),+ );this.#set({ pinnedPages: pinned, recentPages: filteredRecent }, false, 'loadPinnedPages');};pinPage = (page: TabItem): void => {const { pinnedPages, recentPages } = this.#get();- const { id } = page;+ const scope = normalizeTabScope(page.scope, page.url);+ const id = tabTargetId(page.url);- if (pinnedPages.some((p) => p.id === id)) return;+ if (pinnedPages.some((p) => isSameTabTarget(p, page.url, scope))) return;if (pinnedPages.length >= PINNED_PAGES_LIMIT) return;- const existingRecent = recentPages.find((p) => p.id === id);+ const existingRecent = recentPages.find((p) => isSameTabTarget(p, page.url, scope));const newEntry: TabItem = {...page,cached: page.cached ?? existingRecent?.cached,+ id,lastVisited: Date.now(),+ scope,};const newPinned = [...pinnedPages, newEntry];- const newRecent = recentPages.filter((p) => p.id !== id);+ const newRecent = recentPages.filter((p) => !isSameTabTarget(p, page.url, scope));this.#set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'pinPage');savePinnedPages(newPinned);diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.tsindex 06eac7ec67d..24670b9c6f9 100644--- a/src/store/electron/actions/tabPages.ts+++ b/src/store/electron/actions/tabPages.ts@@ -1,6 +1,12 @@import { nanoid } from 'nanoid';import { guardedMergeCache } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';+import {+ isSameTabScope,+ isSameTabTarget,+ normalizeTabScope,+ resolveTabScope,+} from '@/features/Electron/titlebar/TabBar/scope';import { getTabPages, saveTabPages } from '@/features/Electron/titlebar/TabBar/storage';import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';@@ -50,9 +56,9 @@ export class TabPagesActionImpl {};addTab = (url: string, cached?: DynamicRouteMeta, activate = true): string => {- const normalized = normalizeTabUrl(url);+ const scope = resolveTabScope(url);const { tabs } = this.#get();- const existing = tabs.find((t) => normalizeTabUrl(t.url) === normalized);+ const existing = tabs.find((t) => isSameTabTarget(t, url, scope));if (existing) {if (activate) {@@ -62,11 +68,11 @@ export class TabPagesActionImpl {return existing.id;}- return this.#createTab(url, cached, activate);+ return this.#createTab(url, cached, activate, scope);};addNewTab = (url: string, cached?: DynamicRouteMeta): string => {- return this.#createTab(url, cached, true);+ return this.#createTab(url, cached, true, resolveTabScope(url));};getActiveTab = (): TabItem | null => {@@ -156,13 +162,17 @@ export class TabPagesActionImpl {if (index < 0) return id;const prev = tabs[index];- const sameTarget = normalizeTabUrl(url) === normalizeTabUrl(prev.url);+ const scope = resolveTabScope(url);+ const previousScope = normalizeTabScope(prev.scope, prev.url);+ const sameTarget =+ normalizeTabUrl(url) === normalizeTabUrl(prev.url) && isSameTabScope(scope, previousScope);const newTabs = [...tabs];newTabs[index] = {...prev,cached: sameTarget ? prev.cached : undefined,lastVisited: Date.now(),+ scope,url,};@@ -186,13 +196,19 @@ export class TabPagesActionImpl {this.#persist();};- #createTab = (url: string, cached: DynamicRouteMeta | undefined, activate: boolean): string => {+ #createTab = (+ url: string,+ cached: DynamicRouteMeta | undefined,+ activate: boolean,+ scope = resolveTabScope(url),+ ): string => {const { tabs, activeTabId } = this.#get();const id = generateTabId();const newTab: TabItem = {cached,id,lastVisited: Date.now(),+ scope,url,};