🤯 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(workspace): leave workspace scope on every personal root route (#21265)
Neko7ed2fedbdca9
diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 31144abafe2..6b26353a135 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -28,6 +28,10 @@"notFound.check": "Please check if your URL is correct.","notFound.desc": "We couldn't find the page you were looking for.","notFound.title": "Entered Unknown Territory?",+ "otherScope.desc": "It belongs to {{name}}, not the space you are in now.",+ "otherScope.personal": "your personal space",+ "otherScope.switch": "Switch to {{name}}",+ "otherScope.title": "This is in another space","pluginSettings.desc": "Complete the following configuration to start using this skill","pluginSettings.title": "{{name}} Skill Settings","response.400": "Sorry, the server does not understand your request. Please make sure your request parameters are correct.",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex 9a1607e6956..a5abf40f9da 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -28,6 +28,10 @@"notFound.check": "请检查 URL 是否正确","notFound.desc": "未找到你访问的页面","notFound.title": "页面不存在",+ "otherScope.desc": "它属于「{{name}}」,不在当前空间。",+ "otherScope.personal": "个人空间",+ "otherScope.switch": "切换到「{{name}}」",+ "otherScope.title": "该内容在另一个空间","pluginSettings.desc": "请完成以下配置,即可启用该技能","pluginSettings.title": "{{name}} 技能配置","response.400": "请求参数有误,请检查后重试",diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex bcb29ff44de..2bd7609af23 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -2,6 +2,10 @@ export default {'asyncState.desc': 'Something went wrong while loading. Please try again.','asyncState.metricLabel': 'Failed to load','asyncState.title': 'Failed to load',+ 'otherScope.desc': 'It belongs to {{name}}, not the space you are in now.',+ 'otherScope.personal': 'your personal space',+ 'otherScope.switch': 'Switch to {{name}}',+ 'otherScope.title': 'This is in another space','chatRequestBlocked.contactSupport': 'Contact support','chatRequestBlocked.description':'This request was blocked by our security checks. If you think this is a mistake, contact support to restore access.',diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 8706b72128d..4e746c032b7 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -317,16 +317,21 @@ export const lambdaClient = createTRPCClient<LambdaRouter>({* not currently in — e.g. sharing a personal device into a chosen workspace* from the personal settings page — pin the workspace header per client* instead. The override runs after the business headers merge, so it wins.+ * `null` pins the personal scope: the workspace header is dropped even while a+ * workspace is active.*/-export const createWorkspaceLambdaClient = (workspaceId: string) => {+export const createWorkspaceLambdaClient = (workspaceId: string | null) => {const scopedLinkOptions = {...linkOptions,- headers: async () => ({- ...(await linkOptions.headers()),+ headers: async () => {+ const headers = (await linkOptions.headers()) as Record<string, string>;// Same contract as the cloud business headers slot / the server's// `WORKSPACE_ID_HEADER` (src/app/(backend)/webapi/_utils/workspace.ts).- 'X-Workspace-Id': workspaceId,- }),+ if (workspaceId) return { ...headers, 'X-Workspace-Id': workspaceId };++ const { 'X-Workspace-Id': _, ...personal } = headers;+ return personal;+ },};return createTRPCClient<LambdaRouter>({links: [diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsxindex 3f540ad6dad..759b7bc375e 100644--- a/src/features/AgentGoals/GoalDetailPage.test.tsx+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx@@ -9,35 +9,53 @@ import { WorkspaceSidePanelProvider } from '@/features/RightPanel/WorkspaceSidePimport GoalDetailPage from './GoalDetailPage';-const mocks = vi.hoisted(() => ({ canEdit: true, hasSupervision: true, showPortal: false }));+const mocks = vi.hoisted(() => ({+ canEdit: true,+ graphError: undefined as unknown,+ hasSnapshot: true,+ hasSupervision: true,+ recovery: { pending: false } as { pending: boolean },+ showPortal: false,+}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('@/store/goal', () => ({goalSelectors: {- goalGraph: () => () => ({- goal: {- agentId: 'agt_manager',- config: mocks.hasSupervision- ? { manager: true, managerState: { topicId: 'tpc_manager' } }- : {},- id: 'goal_1',- projectId: null,- requirement: 'Reach 1,100 followers',- status: 'review',- title: 'Ship it',- },- nodes: [],- }),+ goalGraph: () => () =>+ mocks.hasSnapshot+ ? {+ goal: {+ agentId: 'agt_manager',+ config: mocks.hasSupervision+ ? { manager: true, managerState: { topicId: 'tpc_manager' } }+ : {},+ id: 'goal_1',+ projectId: null,+ requirement: 'Reach 1,100 followers',+ status: 'review',+ title: 'Ship it',+ },+ nodes: [],+ }+ : undefined,},useGoalStore: (selector: (s: any) => unknown) =>selector({pauseGoal: vi.fn(),resumeGoal: vi.fn(),- useFetchGoalGraph: () => ({ error: undefined, isLoading: false, mutate: vi.fn() }),+ useFetchGoalGraph: () => ({ error: mocks.graphError, isLoading: false, mutate: vi.fn() }),}),}));+vi.mock('@/features/Workspace/useLocateInOtherScope', () => ({+ useOtherScopeRecovery: () => mocks.recovery,+}));++vi.mock('@/components/Skeleton/GoalDetail', () => ({+ default: () => <div data-testid="goal-detail-skeleton" />,+}));+vi.mock('@/store/serverConfig', () => ({useServerConfigStore: (selector: (s: any) => unknown) => selector({ featureFlags: {} }),}));@@ -182,7 +200,10 @@ vi.mock('./GoalSupervision', () => ({describe('GoalDetailPage', () => {beforeEach(() => {mocks.canEdit = true;+ mocks.graphError = undefined;+ mocks.hasSnapshot = true;mocks.hasSupervision = true;+ mocks.recovery = { pending: false };mocks.showPortal = false;});@@ -314,4 +335,16 @@ describe('GoalDetailPage', () => {expect(screen.getByTestId('goal-portal-content')).toBeInTheDocument();});++ // A 404 may only mean the goal lives in another of the user's spaces; while+ // those are probed the page keeps its loading frame instead of going blank.+ it('keeps the page skeleton while another space is being probed', () => {+ mocks.hasSnapshot = false;+ mocks.graphError = { data: { code: 'NOT_FOUND', httpStatus: 404 } };+ mocks.recovery = { pending: true };++ render(<GoalDetailPage goalId={'goal_1'} />);++ expect(screen.getByTestId('goal-detail-skeleton')).toBeTruthy();+ });});diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 25f5d32389f..1a96ef1c5af 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -7,7 +7,6 @@ import { useTranslation } from 'react-i18next';import { Link } from 'react-router';import NotFound from '@/components/404';-import AsyncError from '@/components/AsyncError';import ConversationSkeleton from '@/components/Skeleton/Conversation/List';import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';import AgentBreadcrumb from '@/features/AgentBreadcrumb';@@ -18,6 +17,8 @@ import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';import RightPanel from '@/features/RightPanel';import { useWorkspaceSidePanel } from '@/features/RightPanel/WorkspaceSidePanel';import WideScreenContainer from '@/features/WideScreenContainer';+import OtherScopeAsyncError from '@/features/Workspace/OtherScopeAsyncError';+import { type ScopedLambdaClient } from '@/features/Workspace/useLocateInOtherScope';import { usePermission } from '@/hooks/usePermission';import { useResourceManageable } from '@/hooks/useResourceManageable';import { useChatStore } from '@/store/chat';@@ -56,6 +57,10 @@ const styles = createStaticStyles(({ css }) => ({`,}));+/** A goal 404s outside its own scope; reading it through another scope tells where it lives. */+const probeGoalGraph = (client: ScopedLambdaClient, id: string, signal: AbortSignal) =>+ client.goal.graph.query({ id }, { context: { showNotification: false }, signal });+interface GoalDetailPageProps {/** Absent for a goal with no responsible agent — e.g. one created from a project. */agentId?: string;@@ -157,7 +162,19 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {// page (or switching goals) must not leak it into the conversation surface.useEffect(() => () => clearPortalStack(), [clearPortalStack, goalId]);- if (error && !snapshot) return <AsyncError error={error} variant={'page'} onRetry={mutate} />;+ if (error && !snapshot)+ return (+ <OtherScopeAsyncError+ error={error}+ pendingFallback={<GoalDetailSkeleton />}+ resourceKey={`goal:${goalId}`}+ variant={'page'}+ probe={(client: ScopedLambdaClient, signal: AbortSignal) =>+ probeGoalGraph(client, goalId, signal)+ }+ onRetry={mutate}+ />+ );if (!snapshot)return isLoading ? (<GoalDetailSkeleton />diff --git a/src/features/Electron/titlebar/TabBar/scope.ts b/src/features/Electron/titlebar/TabBar/scope.tsindex 8af53c19dd7..182b969ef52 100644--- a/src/features/Electron/titlebar/TabBar/scope.ts+++ b/src/features/Electron/titlebar/TabBar/scope.ts@@ -1,3 +1,5 @@+import { parseRootSegment, RESERVED_ROOT_SEGMENTS } from '@/features/Workspace/rootSegments';+import { normalizeTabUrl } from './url';export type TabScope =@@ -14,47 +16,14 @@ export interface ScopedTabTarget {url: string;}-const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;--// Every top-level segment mounted in `sharedMainAreaChildren` (mirrored under-// `/:workspaceSlug`) plus the personal-only roots. Anything missing here is-// treated as a workspace slug, so a route like `/project/...` would spawn a-// phantom `workspace:project` tab bucket.-const PERSONAL_TOP_LEVEL_SEGMENTS = new Set([- 'agent',- 'agents',- 'apps',- 'community',- 'desktop-onboarding',- 'devtools',- 'eval',- 'goal',- 'group',- 'image',- 'invite',- 'me',- 'memory',- 'onboarding',- 'page',- 'project',- 'projects',- '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];+ const firstSegment = parseRootSegment(pathname);- if (!firstSegment || PERSONAL_TOP_LEVEL_SEGMENTS.has(firstSegment)) return PERSONAL_TAB_SCOPE;+ // Any root that is not a workspace slug opens in the personal bucket.+ if (!firstSegment || RESERVED_ROOT_SEGMENTS.has(firstSegment)) return PERSONAL_TAB_SCOPE;return { slug: firstSegment, type: 'workspace' };};diff --git a/src/features/Workspace/OtherScopeAsyncError.tsx b/src/features/Workspace/OtherScopeAsyncError.tsxnew file mode 100644index 00000000000..a0a52cc65b1--- /dev/null+++ b/src/features/Workspace/OtherScopeAsyncError.tsx@@ -0,0 +1,59 @@+'use client';++import { Button, Icon } from '@lobehub/ui';+import { ArrowLeftRightIcon } from 'lucide-react';+import { memo, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError, { type AsyncErrorProps } from '@/components/AsyncError';++import { type ScopeProbe, useOtherScopeRecovery } from './useLocateInOtherScope';+import { useWorkspaceAwareNavigate } from './useWorkspaceAwareNavigate';++export interface OtherScopeAsyncErrorProps extends AsyncErrorProps {+ /** Shown while the other scopes are probed, so the page never goes blank. */+ pendingFallback: ReactNode;+ /** Re-read the resource through a client pinned to another scope; reject when not visible. */+ probe: ScopeProbe;+ /** Stable identity of the resource being probed, e.g. `goal:<id>`. */+ resourceKey: string;+}++/**+ * `AsyncError` for a scoped detail page. When the read 404s because the+ * resource belongs to another of the user's spaces (personal ⇄ workspace), it+ * says so and offers to switch there, instead of a bare "Failed to load".+ */+const OtherScopeAsyncError = memo<OtherScopeAsyncErrorProps>(+ ({ pendingFallback, probe, resourceKey, ...props }) => {+ const { t } = useTranslation('error');+ const navigate = useWorkspaceAwareNavigate();+ const { pending, scope, targetPath } = useOtherScopeRecovery(props.error, resourceKey, probe);++ if (pending) return pendingFallback;+ if (!scope || !targetPath) return <AsyncError {...props} />;++ const name = scope.id ? (scope.name ?? scope.slug) : t('otherScope.personal');++ return (+ <AsyncError+ {...props}+ description={t('otherScope.desc', { name })}+ title={t('otherScope.title')}+ action={+ <Button+ icon={<Icon icon={ArrowLeftRightIcon} />}+ type={'primary'}+ onClick={() => navigate(targetPath, { escape: true })}+ >+ {t('otherScope.switch', { name })}+ </Button>+ }+ />+ );+ },+);++OtherScopeAsyncError.displayName = 'OtherScopeAsyncError';++export default OtherScopeAsyncError;diff --git a/src/features/Workspace/rootSegments.test.ts b/src/features/Workspace/rootSegments.test.tsnew file mode 100644index 00000000000..e2e82fe125c--- /dev/null+++ b/src/features/Workspace/rootSegments.test.ts@@ -0,0 +1,89 @@+import type { RouteObject } from 'react-router';+import { describe, expect, it } from 'vitest';++import { desktopRoutes as webRoutes } from '@/spa/router/desktopRouter.config';+import {+ desktopRoutes as electronRoutes,+ mainAreaMetaRoutes as electronMainAreaRoutes,+} from '@/spa/router/desktopRouter.config.desktop';+import { mobileRoutes } from '@/spa/router/mobileRouter.config';++import {+ OFF_TABLE_ROOT_SEGMENTS,+ parseRootSegment,+ RESERVED_ROOT_SEGMENTS,+ WORKSPACE_MIRRORED_ROOT_SEGMENTS,+} from './rootSegments';+import { isWorkspaceSlugCandidatePath } from './useWorkspaceUrlSync';++const NON_LITERAL = new Set([':workspaceSlug', '*']);++/** First literal segment of every route, descending through pathless layouts and `/`. */+const collectRootSegments = (routes: RouteObject[] = [], out = new Set<string>()) => {+ for (const route of routes) {+ if (route.index) continue;+ const path = route.path?.replace(/^\//, '') ?? '';+ if (!path) {+ collectRootSegments(route.children, out);+ continue;+ }+ const first = path.split('/')[0];+ if (!NON_LITERAL.has(first)) out.add(first);+ }+ return out;+};++const findWorkspaceRoutes = (routes: RouteObject[] = []): RouteObject[] =>+ routes.flatMap((route) => {+ if (route.path === ':workspaceSlug') return route.children ?? [];+ const path = route.path?.replace(/^\//, '') ?? '';+ return path ? [] : findWorkspaceRoutes(route.children);+ });++const routeTables = [webRoutes, electronRoutes, electronMainAreaRoutes, mobileRoutes];++const rootSegments = new Set(routeTables.flatMap((routes) => [...collectRootSegments(routes)]));+const mirroredSegments = new Set(+ routeTables.flatMap((routes) => [...collectRootSegments(findWorkspaceRoutes(routes))]),+);++describe('root route segments', () => {+ it('reserves every root of the route tables', () => {+ const missing = [...rootSegments].filter((s) => !RESERVED_ROOT_SEGMENTS.has(s));+ expect(missing, `Add to RESERVED_ROOT_SEGMENTS: ${missing.join(', ')}`).toEqual([]);+ });++ it('reserves nothing the route tables lack, beyond the off-table roots', () => {+ const stale = [...RESERVED_ROOT_SEGMENTS].filter(+ (s) => !rootSegments.has(s) && !mirroredSegments.has(s) && !OFF_TABLE_ROOT_SEGMENTS.has(s),+ );+ expect(stale, `Not a root route anymore: ${stale.join(', ')}`).toEqual([]);+ });++ it('lists exactly the roots mirrored under /:workspaceSlug', () => {+ expect([...WORKSPACE_MIRRORED_ROOT_SEGMENTS].sort()).toEqual([...mirroredSegments].sort());+ });++ it('parses the first segment of a path', () => {+ expect(parseRootSegment('/goal/g1?x=1')).toBe('goal');+ expect(parseRootSegment('/airi')).toBe('airi');+ expect(parseRootSegment('/')).toBeNull();+ });+});++describe('isWorkspaceSlugCandidatePath', () => {+ it.each([+ '/goal/goal_MkfdMJaxDdRp',+ '/agent/agt_1/goal/goal_1',+ '/task/task_1',+ '/project/proj_1',+ '/acceptance/acc_1',+ '/dashboard',+ ])('treats %s as personal, not as a workspace slug', (path) => {+ expect(isWorkspaceSlugCandidatePath(path)).toBe(false);+ });++ it('treats an unknown root as a slug candidate', () => {+ expect(isWorkspaceSlugCandidatePath('/r1018-team/goal/goal_1')).toBe(true);+ });+});diff --git a/src/features/Workspace/rootSegments.ts b/src/features/Workspace/rootSegments.tsnew file mode 100644index 00000000000..f4baa26391e--- /dev/null+++ b/src/features/Workspace/rootSegments.ts@@ -0,0 +1,67 @@+/**+ * First path segments that share the URL namespace with `/:workspaceSlug`.+ *+ * `rootSegments.test.ts` derives both sets from the Web, Electron and mobile+ * route tables and fails when a root route is added without updating them.+ * A root missing here is read as a workspace slug: in-app navigation to it+ * keeps the previous workspace scope and its requests 404 (`/goal/:id` did).+ */++/**+ * Roots mirrored under `/:workspaceSlug/...` (children of the workspace route).+ * A few, like `billing`, exist only there.+ */+export const WORKSPACE_MIRRORED_ROOT_SEGMENTS: ReadonlySet<string> = new Set([+ 'agent',+ 'agents',+ 'billing',+ 'community',+ 'dashboard',+ 'eval',+ 'goal',+ 'goals',+ 'group',+ 'image',+ 'memory',+ 'page',+ 'project',+ 'projects',+ 'resource',+ 'settings',+ 'task',+ 'tasks',+ 'video',+]);++/**+ * Roots outside the SPA route table: Next.js pages, the share micro-app, Cloud+ * business routes, and the retired `/verify` that persisted tabs may still hold.+ */+export const OFF_TABLE_ROOT_SEGMENTS: ReadonlySet<string> = new Set([+ 'a',+ 'devtools',+ 'embed',+ 'invite',+ 'share',+ 'subscription',+ 'verify',+ 'waitlist',+]);++/** Every root that is never a workspace slug. */+export const RESERVED_ROOT_SEGMENTS: ReadonlySet<string> = new Set([+ ...WORKSPACE_MIRRORED_ROOT_SEGMENTS,+ ...OFF_TABLE_ROOT_SEGMENTS,+ // Personal-only roots in the SPA route table.+ 'acceptance',+ 'apps',+ 'desktop-onboarding',+ 'me',+ 'onboarding',+ 'verify-im',+]);++const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;++export const parseRootSegment = (pathname: string): string | null =>+ FIRST_SEGMENT_REGEX.exec(pathname)?.[1] ?? null;diff --git a/src/features/Workspace/useLocateInOtherScope.test.ts b/src/features/Workspace/useLocateInOtherScope.test.tsnew file mode 100644index 00000000000..601b0eb96cc--- /dev/null+++ b/src/features/Workspace/useLocateInOtherScope.test.ts@@ -0,0 +1,198 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { MemoryRouter } from 'react-router';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ buildOtherScopePath,+ probeScopes,+ SCOPE_PROBE_CONCURRENCY,+ SCOPE_PROBE_TIMEOUT_MS,+ useOtherScopeRecovery,+} from './useLocateInOtherScope';++const mocks = vi.hoisted(() => ({+ activeId: null as string | null,+ activeSlug: null as string | null,+ clients: [] as Array<string | null>,+ workspaces: [] as Array<{ id: string; name: string; slug: string }>,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => mocks.activeId,+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ useActiveWorkspaceSlug: () => mocks.activeSlug,+}));+vi.mock('@/business/client/hooks/useWorkspaces', () => ({+ useWorkspaces: () => mocks.workspaces,+}));+vi.mock('@/libs/trpc/client', () => ({+ createWorkspaceLambdaClient: (id: string | null) => {+ mocks.clients.push(id);+ return { scope: id };+ },+}));++const notFound = { data: { code: 'NOT_FOUND', httpStatus: 404 }, message: 'Goal not found' };+const TEAM = { id: 'ws_team', name: 'Project AIRI', slug: 'airi' };++/** The probe succeeds only through the client of `home` (null = personal). */+const probeLivingIn = (home: string | null) => async (client: any, _signal: AbortSignal) => {+ if (client.scope !== home) throw notFound;+};++const renderAt = (path: string, home: string | null, error: unknown = notFound) =>+ renderHook(() => useOtherScopeRecovery(error, `goal:${path}`, probeLivingIn(home)), {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(+ SWRConfig,+ { value: { provider: () => new Map() } },+ createElement(MemoryRouter, { initialEntries: [path] }, children),+ ),+ });++beforeEach(() => {+ mocks.activeId = null;+ mocks.activeSlug = null;+ mocks.clients = [];+ mocks.workspaces = [TEAM];+});++describe('buildOtherScopePath', () => {+ it('drops the active slug when the target is personal', () => {+ expect(buildOtherScopePath('/airi/goal/g1', 'airi', {})).toBe('/goal/g1');+ expect(buildOtherScopePath('/airi/agent/a1/goal/g1', 'airi', {})).toBe('/agent/a1/goal/g1');+ });++ it('adds the target slug to a personal path', () => {+ expect(buildOtherScopePath('/goal/g1', null, { slug: 'airi' })).toBe('/airi/goal/g1');+ });++ it('swaps one workspace slug for another', () => {+ expect(buildOtherScopePath('/airi/goal/g1', 'airi', { slug: 'other' })).toBe('/other/goal/g1');+ });++ it('keeps a personal path that only starts with the active slug text', () => {+ expect(buildOtherScopePath('/airing/goal/g1', 'airi', {})).toBe('/airing/goal/g1');+ });+});++describe('useOtherScopeRecovery', () => {+ it('finds a personal goal opened in a team scope and targets the personal route', async () => {+ mocks.activeId = TEAM.id;+ mocks.activeSlug = TEAM.slug;++ const { result } = renderAt('/airi/goal/g1', null);++ expect(result.current.pending).toBe(true);+ await waitFor(() => expect(result.current.scope).toEqual({ id: null }));+ expect(result.current.targetPath).toBe('/goal/g1');+ expect(mocks.clients).toEqual([null]);+ });++ it('finds a team goal opened in the personal scope and targets the team route', async () => {+ const { result } = renderAt('/goal/g1', TEAM.id);++ await waitFor(() => expect(result.current.scope?.id).toBe(TEAM.id));+ expect(result.current.targetPath).toBe('/airi/goal/g1');+ });++ it('settles without a scope when no other scope has the goal', async () => {+ const { result } = renderAt('/goal/g1', 'ws_nowhere');++ await waitFor(() => expect(result.current.pending).toBe(false));+ expect(result.current.scope).toBeUndefined();+ });++ it('does not probe other scopes for errors other than 404', () => {+ const { result } = renderAt('/goal/g1', TEAM.id, { data: { httpStatus: 500 } });++ expect(result.current).toEqual({ pending: false });+ expect(mocks.clients).toEqual([]);+ });++ it('does not probe when the user has no other scope', () => {+ mocks.workspaces = [];++ const { result } = renderAt('/goal/g1', TEAM.id);++ expect(result.current).toEqual({ pending: false });+ expect(mocks.clients).toEqual([]);+ });+});++describe('probeScopes', () => {+ const scopes = [+ { id: null },+ ...Array.from({ length: 8 }, (_, i) => ({ id: `ws_${i}`, slug: `ws-${i}` })),+ ];++ /** A probe that settles only when the test says so, recording every call. */+ const controlledProbe = () => {+ const calls: Array<{ id: string | null; signal: AbortSignal; settle: (ok: boolean) => void }> =+ [];+ const probe = (client: any, signal: AbortSignal) =>+ new Promise<void>((resolve, reject) => {+ calls.push({+ id: client.scope,+ settle: (ok) => (ok ? resolve() : reject(notFound)),+ signal,+ });+ });+ return { calls, probe };+ };++ it('keeps at most SCOPE_PROBE_CONCURRENCY probes in flight, personal first', async () => {+ const { calls, probe } = controlledProbe();+ const result = probeScopes(scopes, probe);++ await waitFor(() => expect(calls).toHaveLength(SCOPE_PROBE_CONCURRENCY));+ expect(calls.map((c) => c.id)).toEqual([null, 'ws_0', 'ws_1']);++ // A miss frees one slot for the next candidate, never more.+ calls[0].settle(false);+ await waitFor(() => expect(calls).toHaveLength(SCOPE_PROBE_CONCURRENCY + 1));+ expect(calls[3].id).toBe('ws_2');++ // The first hit aborts the probes still in flight and starts no more.+ calls[2].settle(true);+ await expect(result).resolves.toEqual(scopes[2]);+ expect(calls).toHaveLength(SCOPE_PROBE_CONCURRENCY + 1);+ expect(calls[1].signal.aborted).toBe(true);+ expect(calls[3].signal.aborted).toBe(true);+ });++ it('resolves null after every candidate misses', async () => {+ const probe = vi.fn(async () => {+ throw notFound;+ });++ await expect(probeScopes(scopes, probe)).resolves.toBeNull();+ expect(probe).toHaveBeenCalledTimes(scopes.length);+ });++ describe('when a probe never settles', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('treats the check as not found after SCOPE_PROBE_TIMEOUT_MS and aborts the probes', async () => {+ const { calls, probe } = controlledProbe();+ let result: unknown = 'pending';+ void probeScopes(scopes, probe).then((scope) => (result = scope));++ await vi.advanceTimersByTimeAsync(SCOPE_PROBE_TIMEOUT_MS - 1);+ expect(result).toBe('pending');+ expect(calls).toHaveLength(SCOPE_PROBE_CONCURRENCY);++ await vi.advanceTimersByTimeAsync(1);+ expect(result).toBeNull();+ expect(calls.every((c) => c.signal.aborted)).toBe(true);+ expect(calls).toHaveLength(SCOPE_PROBE_CONCURRENCY);+ });+ });+});diff --git a/src/features/Workspace/useLocateInOtherScope.ts b/src/features/Workspace/useLocateInOtherScope.tsnew file mode 100644index 00000000000..8313a0fd442--- /dev/null+++ b/src/features/Workspace/useLocateInOtherScope.ts@@ -0,0 +1,167 @@+'use client';++import { useMemo } from 'react';+import { useLocation } from 'react-router';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import { useClientDataSWR } from '@/libs/swr';+import { normalizeAsyncError } from '@/libs/swr/normalizeError';+import { createWorkspaceLambdaClient } from '@/libs/trpc/client';++export type ScopedLambdaClient = ReturnType<typeof createWorkspaceLambdaClient>;++/** A scope the user can switch to: personal (`id: null`) or one of their workspaces. */+export interface OtherScope {+ id: string | null;+ name?: string;+ slug?: string;+}++/**+ * Rewrite `pathname` (which may carry the active workspace's slug) into the+ * same route under `target`: `/{slug}/goal/x` ⇄ `/goal/x`.+ */+export const buildOtherScopePath = (+ pathname: string,+ activeSlug: string | null | undefined,+ target: Pick<OtherScope, 'slug'>,+): string => {+ const isPrefixed =+ !!activeSlug && (pathname === `/${activeSlug}` || pathname.startsWith(`/${activeSlug}/`));+ const bare = isPrefixed ? pathname.slice(activeSlug!.length + 1) || '/' : pathname;++ if (!target.slug) return bare;+ return bare === '/' ? `/${target.slug}` : `/${target.slug}${bare}`;+};++/**+ * Reads the resource through a client pinned to one candidate scope and+ * rejects when it is not visible there. Pass `signal` on to the request so a+ * probe that is no longer needed can be cancelled.+ */+export type ScopeProbe = (client: ScopedLambdaClient, signal: AbortSignal) => Promise<unknown>;++/** Probes in flight at once. A user in many workspaces must not fan out one read per workspace. */+export const SCOPE_PROBE_CONCURRENCY = 3;++/**+ * Deadline for the whole cross-scope check. A probe that never settles must not+ * hold the page on its loading frame: past this, the check counts as "not+ * found" and the page falls back to the original error and its Retry.+ */+export const SCOPE_PROBE_TIMEOUT_MS = 10_000;++/**+ * Find the first candidate scope `probe` succeeds in. Candidates start in order+ * (personal first) with at most {@link SCOPE_PROBE_CONCURRENCY} in flight; the+ * first success aborts the rest and starts no more. Resolves `null` when every+ * candidate misses or {@link SCOPE_PROBE_TIMEOUT_MS} passes first.+ */+export const probeScopes = (candidates: OtherScope[], probe: ScopeProbe) =>+ new Promise<OtherScope | null>((resolve) => {+ const controller = new AbortController();+ let settled = false;+ let inFlight = 0;+ let next = 0;++ const settle = (scope: OtherScope | null) => {+ if (settled) return;+ settled = true;+ clearTimeout(deadline);+ controller.abort();+ resolve(scope);+ };+ const deadline = setTimeout(() => settle(null), SCOPE_PROBE_TIMEOUT_MS);++ const launch = () => {+ while (!settled && inFlight < SCOPE_PROBE_CONCURRENCY && next < candidates.length) {+ const scope = candidates[next++];+ inFlight++;+ Promise.resolve()+ .then(() => probe(createWorkspaceLambdaClient(scope.id), controller.signal))+ .then(+ () => settle(scope),+ // Not visible in this scope (or aborted); the next candidate takes the slot.+ () => {},+ )+ .finally(() => {+ inFlight--;+ if (settled) return;+ if (next >= candidates.length && inFlight === 0) settle(null);+ else launch();+ });+ }+ };++ if (candidates.length === 0) settle(null);+ else launch();+ });++/**+ * After a read 404s in the active scope, find which of the user's OTHER scopes+ * (personal or another workspace) the resource lives in, so the page can offer+ * a switch instead of a dead "Failed to load". Rows are scoped server-side by+ * the `X-Workspace-Id` header, so the same id legitimately 404s in every scope+ * but its own.+ *+ * `probe` must reject when the resource is not visible through the given+ * client. Pass a `null` key to skip (e.g. the error is not a 404).+ */+export const useLocateInOtherScope = (key: string | null, probe: ScopeProbe) => {+ const activeId = useActiveWorkspaceId();+ const workspaces = useWorkspaces();++ const candidates = useMemo<OtherScope[]>(+ () => [+ ...(activeId ? [{ id: null }] : []),+ ...workspaces+ .filter((ws) => ws.id !== activeId && !ws.lockedOut)+ .map((ws) => ({ id: ws.id, name: ws.name, slug: ws.slug })),+ ],+ [activeId, workspaces],+ );++ return useClientDataSWR<OtherScope | null>(+ key && candidates.length > 0+ ? ['locateInOtherScope', key, candidates.map((c) => c.id ?? 'personal').join(',')]+ : null,+ () => probeScopes(candidates, probe),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );+};++export interface OtherScopeRecovery {+ /** Still probing; show a loading frame rather than flash the generic error. */+ pending: boolean;+ /** The scope that holds the resource, when one was found. */+ scope?: OtherScope;+ /** The current route rewritten into `scope`, query string kept. */+ targetPath?: string;+}++/**+ * Turns a detail page's read `error` into a way out: on a 404, locate the+ * resource in the user's other scopes and build the same route there.+ */+export const useOtherScopeRecovery = (+ error: unknown,+ key: string,+ probe: ScopeProbe,+): OtherScopeRecovery => {+ const { pathname, search } = useLocation();+ const activeSlug = useActiveWorkspaceSlug();++ const isNotFound = normalizeAsyncError(error).status === 404;+ const { data: scope, isLoading } = useLocateInOtherScope(isNotFound ? key : null, probe);++ if (isNotFound && isLoading) return { pending: true };+ if (!scope) return { pending: false };++ return {+ pending: false,+ scope,+ targetPath: buildOtherScopePath(pathname, activeSlug, scope) + search,+ };+};diff --git a/src/features/Workspace/useWorkspaceUrlSync.ts b/src/features/Workspace/useWorkspaceUrlSync.tsindex 0e4b0a0b3ae..64ca362f07f 100644--- a/src/features/Workspace/useWorkspaceUrlSync.ts+++ b/src/features/Workspace/useWorkspaceUrlSync.ts@@ -7,48 +7,9 @@ import { useIsWorkspaceLoading } from '@/business/client/hooks/useIsWorkspaceLoaimport { useSilentSwitchWorkspace } from '@/business/client/hooks/useSwitchWorkspace';import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import { parseRootSegment, RESERVED_ROOT_SEGMENTS } from './rootSegments';import { useWorkspaceSyncPathname } from './useWorkspaceSyncPathname';-/**- * Top-level route segments that share the namespace with `:workspaceSlug`.- * Anything starting with one of these is NOT a workspace slug — even if the- * first segment happens to resemble one.- *- * Kept in sync with `sharedMainAreaChildren` (paths) + the personal-only list- * in router configs. If you add a new root path segment, add it here too.- */-const RESERVED_FIRST_SEGMENTS = new Set([- // Shared (mirrored under /:workspaceSlug too):- 'agent',- 'group',- 'community',- 'memory',- 'page',- 'projects',- 'resource',- 'image',- 'video',- 'eval',- 'tasks',- 'task',- // Personal-only:- 'a',- 'apps',- 'settings',- 'onboarding',- 'me',- 'share',- 'devtools',- 'desktop-onboarding',-]);--const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;--const parseFirstSegment = (pathname: string): string | null => {- const match = pathname.match(FIRST_SEGMENT_REGEX);- return match ? match[1] : null;-};-/*** Whether `pathname`'s first segment could be an (as-yet-unresolved) workspace* slug — i.e. it's present and not one of the reserved root segments.@@ -60,8 +21,8 @@ const parseFirstSegment = (pathname: string): string | null => {* the background.*/export const isWorkspaceSlugCandidatePath = (pathname: string): boolean => {- const first = parseFirstSegment(pathname);- return !!first && !RESERVED_FIRST_SEGMENTS.has(first);+ const first = parseRootSegment(pathname);+ return !!first && !RESERVED_ROOT_SEGMENTS.has(first);};/**@@ -93,9 +54,9 @@ export const useWorkspaceUrlSync = (): void => {// store to "personal" on first paint of a `/{slug}` URL.if (isLoading) return;- const first = parseFirstSegment(pathname);+ const first = parseRootSegment(pathname);- if (first && !RESERVED_FIRST_SEGMENTS.has(first)) {+ if (first && !RESERVED_ROOT_SEGMENTS.has(first)) {const ws = workspaces.find((w) => w.slug === first);if (ws) {if (activeId !== ws.id) void switchWorkspace(ws.id);diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.tsindex 0b5014ccc21..2003c23ed56 100644--- a/src/features/Workspace/workspaceAwarePath.ts+++ b/src/features/Workspace/workspaceAwarePath.ts@@ -1,5 +1,7 @@import type { NavigateOptions } from 'react-router';+import { parseRootSegment, WORKSPACE_MIRRORED_ROOT_SEGMENTS } from './rootSegments';+export interface WorkspaceAwareNavigateOptions extends NavigateOptions {/** When true, navigate to the literal `to` path without applying the workspace prefix. */escape?: boolean;@@ -75,32 +77,6 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set([]);const SETTINGS_PREFIX_REGEX = /^\/settings\/([^/?#]+)/;-const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;--const WORKSPACE_MIRRORED_FIRST_SEGMENTS = new Set([- 'agent',- 'agents',- 'community',- 'eval',- // Top-level goal detail lives beside task/tasks in the shared main area.- 'goal',- 'group',- 'image',- 'memory',- 'page',- 'project',- 'projects',- 'resource',- 'settings',- 'task',- 'tasks',- 'video',-]);--const parseFirstSegment = (pathname: string): string | null => {- const match = pathname.match(FIRST_SEGMENT_REGEX);- return match ? match[1] : null;-};/*** Returns `true` for `/settings/<tab>` where `<tab>` is NOT in@@ -136,8 +112,8 @@ export const buildWorkspaceAwarePath = (if (isPersonalSettingsPath(to)) return to;if (to === `/${activeSlug}` || to.startsWith(`/${activeSlug}/`)) return to;- const firstSegment = parseFirstSegment(to);- if (firstSegment && !WORKSPACE_MIRRORED_FIRST_SEGMENTS.has(firstSegment)) return to;+ const firstSegment = parseRootSegment(to);+ if (firstSegment && !WORKSPACE_MIRRORED_ROOT_SEGMENTS.has(firstSegment)) return to;return `/${activeSlug}${to}`;};