π€― 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
β»οΈ refactor(permission): serve resource access and collaborators from replicas (#20858)
Arvin Xu1010b76675f1
diff --git a/src/features/PagePermission/index.tsx b/src/features/PagePermission/index.tsxindex 2777696f0bf..c47b2ba2ada 100644--- a/src/features/PagePermission/index.tsx+++ b/src/features/PagePermission/index.tsx@@ -5,8 +5,7 @@ import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';import ResourceAccessPage from '@/features/ResourcePermission/ResourceAccessPage';-import { useClientDataSWR } from '@/libs/swr';-import { documentService } from '@/services/document';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';/*** Member Permissions for one page/document β the Agent-style standalone page.@@ -17,9 +16,10 @@ import { documentService } from '@/services/document';const PagePermission = memo(() => {const { t } = useTranslation('setting');const { id } = useParams<{ id: string }>();- const { data } = useClientDataSWR(id ? ['page-permission-title', id] : null, () =>- documentService.getDocumentById(id!),- );+ // The page detail replica: the title paints from the page list or the+ // persisted detail row and revalidates in the background.+ pageActions.useFetchPageDetail(id);+ const title = usePageStore((s) => pageSelectors.getDocumentById(id)(s)?.title || undefined);if (!id) return null;@@ -28,7 +28,7 @@ const PagePermission = memo(() => {redirectPath={`/page/${id}`}resourceHomePath={`/page/${id}`}resourceId={id}- resourceName={data?.title}+ resourceName={title}resourceType={'document'}copy={{generalAccessDesc: t('permission.page.documentGeneralAccessDesc'),diff --git a/src/features/ResourcePermission/ResourceAccessPage.tsx b/src/features/ResourcePermission/ResourceAccessPage.tsxindex 8d8db59cf74..a38b7c61409 100644--- a/src/features/ResourcePermission/ResourceAccessPage.tsx+++ b/src/features/ResourcePermission/ResourceAccessPage.tsx@@ -92,10 +92,8 @@ const ResourceAccessPage = memo<ResourceAccessPageProps>(const { t } = useTranslation('setting');const navigate = useWorkspaceAwareNavigate();const activeWorkspaceSlug = useActiveWorkspaceSlug();- const { data, error, isLoading, mutate, setAccessLevel, updating } = useResourcePermission(- resourceType,- resourceId,- );+ const { data, error, isConfirmed, isLoading, mutate, setAccessLevel, updating } =+ useResourcePermission(resourceType, resourceId);const isPrivate = data?.visibility === 'private';const accessOptions = useAccessLevelOptions({@@ -107,9 +105,9 @@ const ResourceAccessPage = memo<ResourceAccessPageProps>(// Managing member access is a manager-only surface, like Agent's page: a// non-manager (or a private resource that is not the caller's) gets a- // reason toast and lands back where they came from.- const isDenied =- (!!error && isForbiddenError(error)) || (!isLoading && !!data && !data.canManage);+ // reason toast and lands back where they came from. A persisted record may+ // predate a grant, so only a record re-fetched this session redirects.+ const isDenied = (!!error && isForbiddenError(error)) || (isConfirmed && !data?.canManage);useEffect(() => {if (!isDenied) return;toast.error(t('permission.noManagePermission'));diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsxindex 082fd678a2e..0b18327f9c5 100644--- a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx@@ -2,14 +2,18 @@ import { render, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { ResourceGeneralAccess } from '@/services/resourcePermission';+import ResourceConfigAccessGate from './ResourceConfigAccessGate';const mocks = vi.hoisted(() => ({+ access: undefined as Partial<ResourceGeneralAccess> | undefined,+ accessError: undefined as unknown,accessResolved: true,canEditContent: true,canEditResource: false,- canManageResource: false,navigate: vi.fn(),+ retryAccess: vi.fn(),toastInfo: vi.fn(),}));@@ -20,15 +24,17 @@ vi.mock('@lobehub/ui', async (importOriginal) => ({vi.mock('@/components/AsyncBoundary', () => ({default: ({children,+ error,isLoading,loading,}: {children: ReactNode;+ error?: unknown;isLoading: boolean;loading: ReactNode;- }) => (isLoading ? loading : children),+ }) => (error ? <div>Access error</div> : isLoading ? loading : children),}));-vi.mock('@/components/Skeleton/Surface', () => ({ default: () => null }));+vi.mock('@/components/Skeleton/Surface', () => ({ default: () => <div>Skeleton</div> }));vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({useWorkspaceAwareNavigate: () => mocks.navigate,}));@@ -37,12 +43,11 @@ vi.mock('@/hooks/usePermission', () => ({}));vi.mock('./useResourceAccess', () => ({useResourceAccess: () => ({- accessError: undefined,+ access: mocks.access,+ accessError: mocks.accessError,canEditResource: mocks.canEditResource,- canManageResource: mocks.canManageResource,isAccessResolved: mocks.accessResolved,- isLoading: false,- retryAccess: vi.fn(),+ retryAccess: mocks.retryAccess,}),}));@@ -66,9 +71,10 @@ const renderGate = (describe('ResourceConfigAccessGate', () => {beforeEach(() => {vi.clearAllMocks();+ mocks.access = { accessLevel: 'use', canManage: false };+ mocks.accessError = undefined;mocks.canEditContent = true;mocks.canEditResource = false;- mocks.canManageResource = false;mocks.accessResolved = true;});@@ -124,10 +130,81 @@ describe('ResourceConfigAccessGate', () => {});it('uses the surface-specific loading state while access is resolving', () => {+ mocks.access = undefined;mocks.accessResolved = false;const { getByText } = renderGate('agent', <div>Profile loading</div>);expect(getByText('Profile loading')).toBeInTheDocument();+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ it('opens the config page from the record on screen without waiting for the server', () => {+ // A persisted grant that this session has not re-fetched yet.+ mocks.access = { accessLevel: 'edit', canManage: false };+ mocks.canEditResource = true;++ const { getByText, queryByText } = renderGate();++ expect(getByText('Agent config')).toBeInTheDocument();+ expect(queryByText('Skeleton')).toBeNull();+ });++ it('opens the share page from a persisted management grant', () => {+ mocks.access = { accessLevel: 'view', canManage: true };+ mocks.canEditResource = true;++ const { getByText } = renderGate('agent', undefined, 'manage');++ expect(getByText('Agent config')).toBeInTheDocument();+ });++ it('returns a chat-only caller to chat from the record on screen, without a skeleton', () => {+ // A persisted use-only record: decided on the first render.+ const { queryByText } = renderGate();++ expect(queryByText('Skeleton')).toBeNull();+ expect(queryByText('Agent config')).toBeNull();+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1', { replace: true });+ });++ it('redirects when a revalidation withdraws the grant on screen', () => {+ mocks.access = { accessLevel: 'edit', canManage: false };+ mocks.canEditResource = true;+ const { getByText, queryByText, rerender } = renderGate();+ expect(getByText('Agent config')).toBeInTheDocument();++ mocks.access = { accessLevel: 'use', canManage: false };+ mocks.canEditResource = false;+ rerender(+ <ResourceConfigAccessGate+ redirectPath="/agent/agent-1"+ resourceId="agent-1"+ resourceType="agent"+ >+ <div>Agent config</div>+ </ResourceConfigAccessGate>,+ );++ expect(queryByText('Agent config')).toBeNull();+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1', { replace: true });+ });++ it('redirects once the server denies access with no record left', () => {+ mocks.access = undefined;++ renderGate();++ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1', { replace: true });+ });++ it('shows the error page when the first load fails with nothing to render', () => {+ mocks.access = undefined;+ mocks.accessResolved = false;+ mocks.accessError = new Error('offline');++ const { getByText } = renderGate();++ expect(getByText('Access error')).toBeInTheDocument();});});diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.tsxindex 76195bd31ae..dabfb02a6cf 100644--- a/src/features/ResourcePermission/ResourceConfigAccessGate.tsx+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.tsx@@ -24,34 +24,38 @@ const ResourceConfigAccessGate = memo<ResourceConfigAccessGateProps>(({ children, loading, redirectPath, requiredAccess = 'edit', resourceId, resourceType }) => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();- const hasRedirected = useRef(false);+ // Router reuses this gate across resources (`/agent/A/profile` β+ // `/agent/B/profile`), so the lifecycle below is per resource, not per mount.+ const resourceKey = `${resourceType}:${resourceId}`;+ const hasRedirected = useRef<string | null>(null);const { allowed: canEditContent } = usePermission('edit_own_content');- const {- accessError,- canEditResource,- canManageResource,- isAccessResolved,- isLoading,- retryAccess,- } = useResourceAccess(resourceType, resourceId);+ const { access, accessError, canEditResource, isAccessResolved, retryAccess } =+ useResourceAccess(resourceType, resourceId);- const accessReady = !!resourceId && isAccessResolved && !isLoading;+ // Decide from the access record on screen, persisted or fresh: a reload+ // opens the config page (or returns a chat-only caller to chat) at once+ // while the record revalidates. A grant the server has since withdrawn is+ // still rejected on every write, and the revalidation then redirects; a+ // denial that has since been lifted only costs one bounce, because the+ // chat page re-syncs the record. Management counts the record's grant too;+ // the page's own destructive controls wait for a confirmed one. Without a+ // record (personal mode, or a denial) it follows the edit check.+ const canManage = access?.canManage ?? canEditResource;+ const accessReady = !!resourceId && isAccessResolved;const canConfigure =- accessReady &&- canEditContent &&- (requiredAccess === 'manage' ? canManageResource : canEditResource);+ accessReady && canEditContent && (requiredAccess === 'manage' ? canManage : canEditResource);+ const isBlocked = accessReady && !canConfigure;useEffect(() => {- if (!accessReady || accessError || canConfigure || hasRedirected.current) return;+ if (!isBlocked || hasRedirected.current === resourceKey) return;- hasRedirected.current = true;+ hasRedirected.current = resourceKey;// Name the actual reason: a workspace role that cannot configure Agents at// all reads very differently from holding use-only access on this one// resource, and conflating them made authors think their own Agent had// rejected them.const isRoleRestricted = !canEditContent;- const isManagementRestricted =- requiredAccess === 'manage' && canEditResource && !canManageResource;+ const isManagementRestricted = requiredAccess === 'manage' && canEditResource && !canManage;const messageKey =resourceType === 'agent'? isRoleRestricted@@ -65,29 +69,33 @@ const ResourceConfigAccessGate = memo<ResourceConfigAccessGateProps>(toast.info(t(messageKey));navigate(redirectPath, { replace: true });}, [- accessError,- accessReady,- canConfigure,canEditContent,canEditResource,- canManageResource,+ canManage,+ isBlocked,navigate,redirectPath,requiredAccess,+ resourceKey,resourceType,t,]);+ // Skeleton only while there is no record to decide from; a failed first+ // load shows the error page with Retry. A blocked caller is redirected by+ // the effect above, so nothing renders for that frame.+ const fallback = loading ?? <SurfaceSkeleton variant={'form'} />;+return (<AsyncBoundarydata={accessReady ? true : undefined}- error={accessError}+ error={accessReady ? undefined : accessError}errorVariant={'page'}isLoading={!accessReady && !accessError}- loading={loading ?? <SurfaceSkeleton variant={'form'} />}+ loading={fallback}onRetry={() => void retryAccess()}>- {canConfigure ? children : (loading ?? <SurfaceSkeleton variant={'form'} />)}+ {canConfigure ? children : null}</AsyncBoundary>);},diff --git a/src/features/ResourcePermission/accessLoader.ts b/src/features/ResourcePermission/accessLoader.tsnew file mode 100644index 00000000000..539a1afe8fa--- /dev/null+++ b/src/features/ResourcePermission/accessLoader.ts@@ -0,0 +1,25 @@+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import type { PermissionResourceType } from '@/services/resourcePermission';+import { resourcePermissionActions } from '@/store/resourcePermission';++/**+ * Route loader body: seed the persisted access record of the route's resource.+ *+ * Route loaders run before React commits the route, the only point where this+ * async IndexedDB read can land before `ResourceConfigAccessGate` renders. A+ * resource with no persisted record (first visit, personal mode) is a harmless+ * miss, and the gate then waits for the server as before.+ */+export const preHydrateResourceAccess = async (+ resourceType: PermissionResourceType,+ resourceId: string | undefined,+): Promise<null> => {+ if (resourceId) {+ await settleWithin(+ resourcePermissionActions.preHydrateAccess({ resourceId, resourceType }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );+ }++ return null;+};diff --git a/src/features/ResourcePermission/useAgentManagementAccess.test.tsx b/src/features/ResourcePermission/useAgentManagementAccess.test.tsxindex 445860378f5..bb839326379 100644--- a/src/features/ResourcePermission/useAgentManagementAccess.test.tsx+++ b/src/features/ResourcePermission/useAgentManagementAccess.test.tsx@@ -8,8 +8,8 @@ const testState = vi.hoisted(() => ({{ visibility?: 'private' | 'public'; workspaceId?: string | null } | undefined,permission: {canManageResource: false,+ isAccessConfirmed: true,isAccessResolved: true,- isLoading: false,},}));@@ -33,8 +33,8 @@ describe('useAgentManagementAccess', () => {beforeEach(() => {testState.agent = undefined;testState.permission.canManageResource = false;+ testState.permission.isAccessConfirmed = true;testState.permission.isAccessResolved = true;- testState.permission.isLoading = false;});it('fails closed while the Agent identity is loading', () => {@@ -67,4 +67,13 @@ describe('useAgentManagementAccess', () => {expect(result.current).toEqual({ canManageAgent: true, isAccessLoading: false });});++ it('waits for a server answer before publishing from a persisted record', () => {+ testState.agent = { visibility: 'public', workspaceId: 'workspace-1' };+ testState.permission.isAccessConfirmed = false;++ const { result } = renderHook(() => useAgentManagementAccess('agent-1'));++ expect(result.current).toEqual({ canManageAgent: false, isAccessLoading: true });+ });});diff --git a/src/features/ResourcePermission/useAgentManagementAccess.ts b/src/features/ResourcePermission/useAgentManagementAccess.tsindex 814c10bab55..107aaea0d4e 100644--- a/src/features/ResourcePermission/useAgentManagementAccess.ts+++ b/src/features/ResourcePermission/useAgentManagementAccess.ts@@ -23,7 +23,7 @@ export const useAgentManagementAccess = (agentId?: string) => {const isAgentLoading = !!agentId && !agent;const isPublicWorkspaceAgent = !!agent?.workspaceId && agent.visibility !== 'private';const { allowed: canEditContent } = usePermission('edit_own_content');- const { canManageResource, isAccessResolved, isLoading } = useResourceAccess(+ const { canManageResource, isAccessConfirmed, isAccessResolved } = useResourceAccess('agent',isPublicWorkspaceAgent ? agentId : undefined,);@@ -31,8 +31,10 @@ export const useAgentManagementAccess = (agentId?: string) => {const canManageAgent =!isAgentLoading &&(!isPublicWorkspaceAgent || (isAccessResolved && canEditContent && canManageResource));+ // A persisted record may predate a downgrade: the manager-vs-member answer+ // published below waits for this session's server answer.const isAccessLoading =- isAgentLoading || (isPublicWorkspaceAgent && (isLoading || !isAccessResolved));+ isAgentLoading || (isPublicWorkspaceAgent && (!isAccessResolved || !isAccessConfirmed));// Publish every resolved answer for the runtime resolvers (store actions// can't run this hook) so send/regenerate route with the samediff --git a/src/features/ResourcePermission/useResourceAccess.test.tsx b/src/features/ResourcePermission/useResourceAccess.test.tsxindex 7906446ae13..e5ddf70daf4 100644--- a/src/features/ResourcePermission/useResourceAccess.test.tsx+++ b/src/features/ResourcePermission/useResourceAccess.test.tsx@@ -1,12 +1,13 @@import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { cacheScope } from '@/libs/replica';import type { ResourceGeneralAccess } from '@/services/resourcePermission';+import { resourcePermissionActions, useResourcePermissionStore } from '@/store/resourcePermission';import { useResourceAccess } from './useResourceAccess';const testState = vi.hoisted(() => ({- data: undefined as ResourceGeneralAccess | undefined,hasActiveWorkspace: true,}));@@ -15,28 +16,36 @@ vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({}));vi.mock('@/libs/swr', () => ({- useClientDataSWR: () => ({- data: testState.data,- error: undefined,- isLoading: false,- mutate: vi.fn(),- }),+ mutate: vi.fn(async () => undefined),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),}));+const KEY = 'agent:agent-1';++const record = (overrides: Partial<ResourceGeneralAccess>): ResourceGeneralAccess => ({+ accessLevel: 'view',+ canManage: false,+ creatorId: 'creator',+ generalAccess: 'viewer',+ visibility: 'public',+ ...overrides,+});++/** Seed the record on screen; `check` is what the server answered this session. */+const seed = (data: ResourceGeneralAccess | undefined, check?: 'confirmed' | 'denied') =>+ useResourcePermissionStore.setState({+ accessMap: data ? { [KEY]: data } : {},+ accessSessionMap: check ? { [`${cacheScope.get()}|${KEY}`]: check } : {},+ });+describe('useResourceAccess', () => {beforeEach(() => {- testState.data = undefined;+ resourcePermissionActions.reset();testState.hasActiveWorkspace = true;});it('does not apply view-only Member Permissions to an Agent author or admin', () => {- testState.data = {- accessLevel: 'view',- canManage: true,- creatorId: 'creator',- generalAccess: 'viewer',- visibility: 'public',- };+ seed(record({ canManage: true }), 'confirmed');const { result } = renderHook(() => useResourceAccess('agent', 'agent-1'));@@ -48,13 +57,7 @@ describe('useResourceAccess', () => {});it('still applies view-only Member Permissions to an ordinary member', () => {- testState.data = {- accessLevel: 'view',- canManage: false,- creatorId: 'creator',- generalAccess: 'viewer',- visibility: 'public',- };+ seed(record({ canManage: false }), 'confirmed');const { result } = renderHook(() => useResourceAccess('agent', 'agent-1'));@@ -64,4 +67,62 @@ describe('useResourceAccess', () => {canUseResource: false,});});++ it('resolves edit/use from a persisted record before the server answers', () => {+ seed(record({ accessLevel: 'edit', canManage: true, generalAccess: 'editor' }));++ const { result } = renderHook(() => useResourceAccess('agent', 'agent-1'));++ expect(result.current).toMatchObject({+ canEditResource: true,+ canUseResource: true,+ isAccessResolved: true,+ isLoading: false,+ });+ // Management stays fail-closed until this session re-fetches the record.+ expect(result.current.canManageResource).toBe(false);+ expect(result.current.isAccessConfirmed).toBe(false);+ });++ it('fails every check closed once the server denies access this session', () => {+ seed(undefined, 'denied');++ const { result } = renderHook(() => useResourceAccess('agent', 'agent-1'));++ expect(result.current).toMatchObject({+ access: undefined,+ canEditResource: false,+ canManageResource: false,+ canUseResource: false,+ isAccessConfirmed: true,+ isAccessResolved: true,+ isLoading: false,+ });+ });++ it('stays permissive and loading while there is no record yet', () => {+ const { result } = renderHook(() => useResourceAccess('agent', 'agent-1'));++ expect(result.current).toMatchObject({+ canEditResource: true,+ canManageResource: false,+ canUseResource: true,+ isAccessResolved: false,+ isLoading: true,+ });+ });++ it('keeps full access in personal mode', () => {+ testState.hasActiveWorkspace = false;++ const { result } = renderHook(() => useResourceAccess('agent', 'agent-1'));++ expect(result.current).toMatchObject({+ canEditResource: true,+ canManageResource: true,+ canUseResource: true,+ isAccessResolved: true,+ isLoading: false,+ });+ });});diff --git a/src/features/ResourcePermission/useResourceAccess.ts b/src/features/ResourcePermission/useResourceAccess.tsindex 169cb6f4e71..e1717465e71 100644--- a/src/features/ResourcePermission/useResourceAccess.ts+++ b/src/features/ResourcePermission/useResourceAccess.ts@@ -1,19 +1,27 @@import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';-import { useClientDataSWR } from '@/libs/swr';+import { cacheScope } from '@/libs/replica';import type { PermissionResourceType } from '@/services/resourcePermission';-import { resourcePermissionService } from '@/services/resourcePermission';--// Same SWR key as useResourcePermission so both hooks share one fetch/cache entry.-const FETCH_RESOURCE_PERMISSION_KEY = 'resource-permission';+import {+ resourcePermissionActions,+ resourcePermissionSelectors,+ useResourcePermissionStore,+} from '@/store/resourcePermission';/*** Read-side derivation of the workspace General-access level for a resource.*+ * The record is a replica: after a reload, edit/use checks resolve from the+ * last confirmed value on the first frame while it revalidates, so config+ * pages, menus and composer controls do not wait for the network. The server+ * still checks every write.+ ** Edit/use checks stay permissive while workspace access is loading so chat* input does not flash disabled. A server-confirmed creator/admin (`canManage`)* bypasses the public resource's Member Permissions. Management checks are- * deliberately fail-closed: destructive/ownership controls must not appear- * until that access is confirmed. Personal mode keeps full access.+ * deliberately fail-closed: a persisted grant may predate a downgrade, so+ * destructive/ownership controls wait until this session has re-fetched it+ * (`isAccessConfirmed`). A denial answered this session fails every check+ * closed. Personal mode keeps full access.*/export const useResourceAccess = (resourceType: PermissionResourceType,@@ -21,19 +29,32 @@ export const useResourceAccess = () => {const hasActiveWorkspace = useHasActiveWorkspace();const enabled = hasActiveWorkspace && !!resourceId;+ const ref = enabled ? { resourceId: resourceId!, resourceType } : null;- const { data, error, isLoading, mutate } = useClientDataSWR(- enabled ? [FETCH_RESOURCE_PERMISSION_KEY, resourceType, resourceId] : null,- () => resourcePermissionService.getGeneralAccess(resourceType, resourceId!),+ const scope = cacheScope.use();+ const { error, revalidate } = resourcePermissionActions.useFetchAccess(ref);+ const data = useResourcePermissionStore(resourcePermissionSelectors.access(ref));+ const sessionCheck = useResourcePermissionStore(+ resourcePermissionSelectors.sessionCheck(ref, scope),);+ const isDenied = enabled && sessionCheck === 'denied';+ // The server answered this session β a grant re-fetched, or a denial.+ const isAccessConfirmed = !enabled || isDenied || (!!data && sessionCheck === 'confirmed');+return {+ /** The record on screen (persisted or fresh); `undefined` until one exists. */+ access: enabled && !isDenied ? data : undefined,accessError: error,- canEditResource: !enabled || !data ? true : data.canManage || data.accessLevel === 'edit',- canManageResource: !enabled || data?.canManage === true,- canUseResource: !enabled || !data ? true : data.canManage || data.accessLevel !== 'view',- isAccessResolved: !enabled || !!data,- isLoading,- retryAccess: mutate,+ canEditResource:+ !enabled || (!isDenied && (!data ? true : data.canManage || data.accessLevel === 'edit')),+ canManageResource: !enabled || (!isDenied && isAccessConfirmed && data?.canManage === true),+ canUseResource:+ !enabled || (!isDenied && (!data ? true : data.canManage || data.accessLevel !== 'view')),+ isAccessConfirmed,+ isAccessResolved: !enabled || isDenied || !!data,+ /** First load only: a persisted record is not "loading". */+ isLoading: enabled && !data && !isDenied && !error,+ retryAccess: revalidate,};};diff --git a/src/features/ResourcePermission/useResourceCollaborators.test.ts b/src/features/ResourcePermission/useResourceCollaborators.test.tsindex fe32da8eb73..74cea653fec 100644--- a/src/features/ResourcePermission/useResourceCollaborators.test.ts+++ b/src/features/ResourcePermission/useResourceCollaborators.test.ts@@ -1,6 +1,8 @@import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { resourcePermissionActions, useResourcePermissionStore } from '@/store/resourcePermission';+import { useResourceCollaborators } from './useResourceCollaborators';const serviceMocks = vi.hoisted(() => ({@@ -9,12 +11,6 @@ const serviceMocks = vi.hoisted(() => ({removeCollaborator: vi.fn(),}));-const swrState = vi.hoisted(() => ({- data: undefined as unknown,- keys: [] as unknown[],- mutate: vi.fn(),-}));-vi.mock('@lobehub/ui', async (importOriginal) => ({...(await importOriginal<object>()),...(await import('~base-ui-stubs')).baseUiStubs,@@ -25,28 +21,49 @@ vi.mock('@/services/resourcePermission', () => ({}));vi.mock('@/libs/swr', () => ({- useClientDataSWR: (key: unknown) => {- swrState.keys.push(key);- return { data: swrState.data, error: undefined, isLoading: false, mutate: swrState.mutate };- },+ mutate: vi.fn(async () => undefined),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),}));+/** The replica sync queries registered for the collaborator list. */+const syncKeys = async () => {+ const { useClientDataSWR } = await import('@/libs/swr');+ return vi+ .mocked(useClientDataSWR)+ .mock.calls.map(([key]) => key)+ .filter((key) => Array.isArray(key) && key[1] === 'resourceCollaborators');+};++const KEY = 'knowledgeBase:kb-1';+const list = () => useResourcePermissionStore.getState().collaboratorsMap[KEY];+const seed = (rows: { userId: string }[]) =>+ useResourcePermissionStore.setState({ collaboratorsMap: { [KEY]: rows as any } });+describe('useResourceCollaborators', () => {beforeEach(() => {vi.clearAllMocks();- swrState.data = undefined;- swrState.keys = [];+ resourcePermissionActions.reset();});- it('does not fetch without a resource id or when disabled', () => {+ it('does not fetch without a resource id or when disabled', async () => {renderHook(() => useResourceCollaborators('knowledgeBase', undefined));renderHook(() => useResourceCollaborators('knowledgeBase', 'kb-1', { enabled: false }));- expect(swrState.keys).toEqual([null, null]);+ expect(await syncKeys()).toHaveLength(0);});- it('adds collaborators then revalidates', async () => {+ it('paints a list fetched earlier this session without a loading state', () => {+ seed([{ userId: 'member-1' }]);++ const { result } = renderHook(() => useResourceCollaborators('knowledgeBase', 'kb-1'));++ expect(result.current.collaborators).toEqual([{ userId: 'member-1' }]);+ expect(result.current.isLoading).toBe(false);+ });++ it('adds collaborators then re-fetches the list', async () => {serviceMocks.addCollaborators.mockResolvedValue(undefined);+ serviceMocks.listCollaborators.mockResolvedValue([{ userId: 'member-1' }]);const { result } = renderHook(() => useResourceCollaborators('knowledgeBase', 'kb-1'));await act(async () => {@@ -59,7 +76,8 @@ describe('useResourceCollaborators', () => {['member-1'],'edit',);- expect(swrState.mutate).toHaveBeenCalled();+ expect(serviceMocks.listCollaborators).toHaveBeenCalledWith('knowledgeBase', 'kb-1');+ expect(list()).toEqual([{ userId: 'member-1' }]);});it('reports a failed add so the caller can keep the picker open', async () => {@@ -87,25 +105,39 @@ describe('useResourceCollaborators', () => {});it('removes optimistically: the row is dropped before the request settles', async () => {- swrState.data = [{ userId: 'member-1' }, { userId: 'member-2' }];- serviceMocks.removeCollaborator.mockResolvedValue(undefined);+ seed([{ userId: 'member-1' }, { userId: 'member-2' }]);+ let settle!: () => void;+ serviceMocks.removeCollaborator.mockReturnValue(+ new Promise<void>((resolve) => {+ settle = resolve;+ }),+ );+ serviceMocks.listCollaborators.mockResolvedValue([{ userId: 'member-2' }]);const { result } = renderHook(() => useResourceCollaborators('knowledgeBase', 'kb-1'));+ let pending!: Promise<void>;+ act(() => {+ pending = result.current.removeCollaborator('member-1');+ });++ expect(list()).toEqual([{ userId: 'member-2' }]);+await act(async () => {- await result.current.removeCollaborator('member-1');+ settle();+ await pending;});- expect(swrState.mutate).toHaveBeenNthCalledWith(1, [{ userId: 'member-2' }], false);expect(serviceMocks.removeCollaborator).toHaveBeenCalledWith('knowledgeBase','kb-1','member-1',);+ expect(list()).toEqual([{ userId: 'member-2' }]);});it('rolls a failed removal back and surfaces it as a toast instead of throwing', async () => {const { toast } = await import('@lobehub/ui');- swrState.data = [{ userId: 'member-1' }];+ seed([{ userId: 'member-1' }]);serviceMocks.removeCollaborator.mockRejectedValue(new Error('FORBIDDEN'));const { result } = renderHook(() => useResourceCollaborators('knowledgeBase', 'kb-1'));@@ -113,9 +145,7 @@ describe('useResourceCollaborators', () => {await result.current.removeCollaborator('member-1');});- // optimistic drop, then rollback to the pre-removal list- expect(swrState.mutate).toHaveBeenNthCalledWith(1, [], false);- expect(swrState.mutate).toHaveBeenLastCalledWith([{ userId: 'member-1' }], false);+ expect(list()).toEqual([{ userId: 'member-1' }]);expect(vi.mocked(toast.error)).toHaveBeenCalled();expect(result.current.mutating).toBe(false);});diff --git a/src/features/ResourcePermission/useResourceCollaborators.ts b/src/features/ResourcePermission/useResourceCollaborators.tsindex d1009831a08..fea8f2807f6 100644--- a/src/features/ResourcePermission/useResourceCollaborators.ts+++ b/src/features/ResourcePermission/useResourceCollaborators.ts@@ -2,16 +2,18 @@ import { toast } from '@lobehub/ui';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useClientDataSWR } from '@/libs/swr';import type { PermissionResourceType, ResourceAccessLevel } from '@/services/resourcePermission';-import { resourcePermissionService } from '@/services/resourcePermission';--const FETCH_RESOURCE_COLLABORATORS_KEY = 'resource-collaborators';+import {+ resourcePermissionActions,+ resourcePermissionSelectors,+ useResourcePermissionStore,+} from '@/store/resourcePermission';/*** The collaborator grants of one resource, with add/remove handlers for the* Permission page. Only fetch when the caller manages the resource β the- * server rejects everyone else.+ * server rejects everyone else. The list is memory-only: it holds what this+ * session fetched, never a persisted roster from before a lost grant.*/export const useResourceCollaborators = (resourceType: PermissionResourceType,@@ -23,24 +25,22 @@ export const useResourceCollaborators = (const [mutating, setMutating] = useState(false);- const { data, error, isLoading, mutate } = useClientDataSWR(- resourceId && enabled ? [FETCH_RESOURCE_COLLABORATORS_KEY, resourceType, resourceId] : null,- () => resourcePermissionService.listCollaborators(resourceType, resourceId!),- );+ const ref = resourceId && enabled ? { resourceId, resourceType } : null;+ const { error, revalidate } = resourcePermissionActions.useFetchCollaborators(ref);+ const data = useResourcePermissionStore(resourcePermissionSelectors.collaborators(ref));/**- * Run a mutation and refresh the list, reporting whether it succeeded. The- * failure is surfaced as a toast here, but the boolean still matters: a- * caller that dismisses a surface on completion must branch on it, or a- * rejected mutation reads exactly like a successful one and takes the- * user's unsaved input down with it.+ * Run a mutation, reporting whether it succeeded. The failure is surfaced as+ * a toast here, but the boolean still matters: a caller that dismisses a+ * surface on completion must branch on it, or a rejected mutation reads+ * exactly like a successful one and takes the user's unsaved input down+ * with it.*/const run = useCallback(async (action: () => Promise<void>): Promise<boolean> => {setMutating(true);try {await action();- await mutate();return true;} catch (e) {console.error('[ResourceCollaborators]', e);@@ -50,14 +50,18 @@ export const useResourceCollaborators = (setMutating(false);}},- [mutate, t],+ [t],);const addCollaborators = useCallback((userIds: string[], accessLevel: ResourceAccessLevel): Promise<boolean> => {if (!resourceId || userIds.length === 0) return Promise.resolve(false);return run(() =>- resourcePermissionService.addCollaborators(resourceType, resourceId, userIds, accessLevel),+ resourcePermissionActions.addCollaborators(+ { resourceId, resourceType },+ userIds,+ accessLevel,+ ),);},[run, resourceType, resourceId],@@ -71,32 +75,20 @@ export const useResourceCollaborators = (const removeCollaborator = useCallback(async (userId: string) => {if (!resourceId) return;- const previous = data;- setMutating(true);- await mutate(- (previous ?? []).filter((item) => item.userId !== userId),- false,+ await run(() =>+ resourcePermissionActions.removeCollaborator({ resourceId, resourceType }, userId),);- try {- await resourcePermissionService.removeCollaborator(resourceType, resourceId, userId);- await mutate();- } catch (e) {- await mutate(previous, false);- console.error('[ResourceCollaborators]', e);- toast.error((e as Error)?.message || t('permission.updateError'));- } finally {- setMutating(false);- }},- [data, mutate, t, resourceType, resourceId],+ [run, resourceType, resourceId],);return {addCollaborators,collaborators: data,error,- isLoading,- mutate,+ /** First load only: a list already fetched this session is not "loading". */+ isLoading: !!ref && !data && !error,+ mutate: revalidate,mutating,removeCollaborator,};diff --git a/src/features/ResourcePermission/useResourcePermission.ts b/src/features/ResourcePermission/useResourcePermission.tsindex 5fc74ec8b80..d906e607710 100644--- a/src/features/ResourcePermission/useResourcePermission.ts+++ b/src/features/ResourcePermission/useResourcePermission.ts@@ -2,15 +2,18 @@ import { toast } from '@lobehub/ui';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useClientDataSWR } from '@/libs/swr';+import { cacheScope } from '@/libs/replica';import type { PermissionResourceType, ResourceAccessLevel } from '@/services/resourcePermission';-import { resourcePermissionService } from '@/services/resourcePermission';--const FETCH_RESOURCE_PERMISSION_KEY = 'resource-permission';+import {+ resourcePermissionActions,+ resourcePermissionSelectors,+ useResourcePermissionStore,+} from '@/store/resourcePermission';/*** State + handlers of the Permission panel: publicity and the workspace- * General-access level (Notion-style Share).+ * General-access level (Notion-style Share). Reads the same access replica as+ * `useResourceAccess`, so a reload paints the last confirmed level at once.*/export const useResourcePermission = (resourceType: PermissionResourceType,@@ -20,54 +23,39 @@ export const useResourcePermission = (const [updating, setUpdating] = useState(false);- const { data, error, isLoading, mutate } = useClientDataSWR(- resourceId ? [FETCH_RESOURCE_PERMISSION_KEY, resourceType, resourceId] : null,- () => resourcePermissionService.getGeneralAccess(resourceType, resourceId!),+ const ref = resourceId ? { resourceId, resourceType } : null;+ const scope = cacheScope.use();+ const { error, revalidate } = resourcePermissionActions.useFetchAccess(ref);+ const data = useResourcePermissionStore(resourcePermissionSelectors.access(ref));+ const sessionCheck = useResourcePermissionStore(+ resourcePermissionSelectors.sessionCheck(ref, scope),);- const run = useCallback(- async (- action: () => Promise<Awaited<ReturnType<typeof resourcePermissionService.getGeneralAccess>>>,- optimisticData: Awaited<ReturnType<typeof resourcePermissionService.getGeneralAccess>>,- ) => {- const previousData = data;+ const setAccessLevel = useCallback(+ async (accessLevel: ResourceAccessLevel) => {+ if (!data || !resourceId) return;setUpdating(true);- await mutate(optimisticData, false);try {- const result = await action();- await mutate(result, false);+ await resourcePermissionActions.setAccessLevel({ resourceId, resourceType }, accessLevel);} catch (e) {- await mutate(previousData, false);console.error('[ResourcePermission]', e);toast.error((e as Error)?.message || t('permission.updateError'));} finally {setUpdating(false);}},- [data, mutate, t],- );-- const setAccessLevel = useCallback(- (accessLevel: ResourceAccessLevel) => {- if (!data) return;- return run(- () => resourcePermissionService.setAccessLevel(resourceType, resourceId!, accessLevel),- {- ...data,- accessLevel,- generalAccess: accessLevel === 'edit' ? 'editor' : 'viewer',- },- );- },- [data, run, resourceType, resourceId],+ [data, resourceId, resourceType, t],);return {data,error,- isLoading,+ /** The server answered this record during this session (not only a persisted copy). */+ isConfirmed: !!data && sessionCheck === 'confirmed',+ /** First load only: a persisted record is not "loading". */+ isLoading: !!ref && !data && !error,/** Re-fetch β used by the Permission page to retry a failed load. */- mutate,+ mutate: revalidate,setAccessLevel,updating,};diff --git a/src/routes/(main)/page/pageListLoader.ts b/src/routes/(main)/page/pageListLoader.tsindex 0e8c32c1736..17fa5cf784d 100644--- a/src/routes/(main)/page/pageListLoader.ts+++ b/src/routes/(main)/page/pageListLoader.ts@@ -1,11 +1,18 @@+import type { LoaderFunctionArgs } from 'react-router';++import { preHydrateResourceAccess } from '@/features/ResourcePermission/accessLoader';import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';import { pageActions } from '@/store/page';// Route loaders run before React commits the route: the only point where the// persisted page list (an async read) can land before the sidebar paints its-// loading skeleton.-export const pageListLoader = async (): Promise<null> => {- await settleWithin(pageActions.preHydrate(), PRE_PAINT_HYDRATE_TIMEOUT);+// loading skeleton. A page route also seeds the page's persisted access record,+// which the editor and the Permission page decide from.+export const pageListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {+ await Promise.all([+ settleWithin(pageActions.preHydrate(), PRE_PAINT_HYDRATE_TIMEOUT),+ preHydrateResourceAccess('document', params.id),+ ]);return null;};diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 3943ce50aa4..324f5c51a56 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -18,7 +18,7 @@ import {SquarePlay,Video,} from 'lucide-react';-import { createElement, isValidElement, type ReactElement, type ReactNode, Suspense } from 'react';+import { createElement, type ReactElement } from 'react';import type { RouteObject } from 'react-router';import {@@ -26,7 +26,6 @@ import {BusinessDesktopRoutesWithoutMainLayout,BusinessResourceRoutes,} from '@/business/client/BusinessDesktopRoutes';-import BrandTextLoading from '@/components/Loading/BrandTextLoading';import AppsSkeleton from '@/components/Skeleton/Apps';import CommunityHomeSkeleton from '@/components/Skeleton/CommunityHome';import CommunityListSkeleton from '@/components/Skeleton/CommunityList';@@ -37,7 +36,6 @@ import { delayed } from '@/components/Skeleton/Delayed';import GenerationSkeleton from '@/components/Skeleton/Generation';import MemorySkeleton from '@/components/Skeleton/Memory';import ResourceHomeSkeleton from '@/components/Skeleton/ResourceHome';-import RouteSegmentSkeleton from '@/components/Skeleton/RouteSegment';import ProviderSettingsSkeleton, {ProviderDetailSkeleton,} from '@/components/Skeleton/Settings/Provider';@@ -88,7 +86,9 @@ import { identitiesListLoader } from '@/spa/router/identitiesListLoader';import { libraryTreeLoader } from '@/spa/router/libraryTreeLoader';import { pageListLoader } from '@/spa/router/pageListLoader';import { preferenceListLoader } from '@/spa/router/preferenceListLoader';+import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';+import { withSegmentFallback } from '@/spa/router/withSegmentFallback';import { SettingsTabs } from '@/store/global/initialState';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';@@ -385,6 +385,8 @@ export const sharedMainAreaChildren: RouteObject[] = [{ preloadId: 'agent' },),errorElement: <ErrorBoundary />,+ // Seed the persisted access record before the config gates decide.+ loader: agentAccessLoader,path: ':aid',},],@@ -433,6 +435,7 @@ export const sharedMainAreaChildren: RouteObject[] = [{ preloadId: 'group' },),errorElement: <ErrorBoundary />,+ loader: agentGroupAccessLoader,path: ':gid',},],@@ -1808,47 +1811,6 @@ export interface SharedDesktopRouteOptions {* Builds the common Web/Electron top-level route tree. Platform entry files* supply only the root children, runtime-only routes, and onboarding route.*/-/**- * Swap the default brand-loading fallback for a structural segment skeleton.- *- * `dynamicElement` / `dynamicLayout` wrap every route element in their own- * `Suspense`, and that boundary is always nearer the suspending component than- * any outlet-level one β so a fallback set on the main layout's outlet never- * fires for route content, and the 100+ call sites would otherwise each need- * the option. Explicit route fallbacks are preserved so a route can render the- * nearest segment skeleton instead. Rewriting only defaults here keeps the main- * area consistent without touching routes outside it (mobile still wants the- * full-page brand loading, since its nav bar is inside the same boundary as its- * outlet).- */-export const withSegmentFallback = (routes: RouteObject[]): RouteObject[] =>- routes.map((route) => {- const suspenseElement =- isValidElement(route.element) && route.element.type === Suspense- ? (route.element as ReactElement<{ fallback: ReactNode }>)- : undefined;- const fallback = suspenseElement?.props.fallback;- const element =- suspenseElement && isValidElement(fallback) && fallback.type === BrandTextLoading- ? // This intentionally couples to `dynamicElement` / `dynamicLayout`- // returning a bare Suspense with BrandTextLoading as their default.- // Explicit segment fallbacks must pass through unchanged.- createElement(Suspense, {- ...suspenseElement.props,- fallback: <RouteSegmentSkeleton />,- key: suspenseElement.key,- })- : route.element;-- // `RouteObject` is a discriminated union of index / non-index routes, and- // spreading loses the discriminant β the copy keeps the original's shape.- return {- ...route,- ...(route.children && { children: withSegmentFallback(route.children) }),- element,- } as RouteObject;- });-export const createSharedDesktopRoutes = ({mainAreaChildren,onboardingRoute,diff --git a/src/spa/router/pageListLoader.ts b/src/spa/router/pageListLoader.tsindex c32e5127f9d..91c58403ec3 100644--- a/src/spa/router/pageListLoader.ts+++ b/src/spa/router/pageListLoader.ts@@ -1,4 +1,6 @@+import type { LoaderFunctionArgs } from 'react-router';+// The route tables sit in the entry chunk's static graph; resolving the real// loader on first use keeps the page store in the page route's lazy chunks.-export const pageListLoader = () =>- import('@/routes/(main)/page/pageListLoader').then((module) => module.pageListLoader());+export const pageListLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/page/pageListLoader').then((module) => module.pageListLoader(args));diff --git a/src/spa/router/pageListLoader.wiring.test.ts b/src/spa/router/pageListLoader.wiring.test.tsindex 6a3c58cbd25..a566d111f0e 100644--- a/src/spa/router/pageListLoader.wiring.test.ts+++ b/src/spa/router/pageListLoader.wiring.test.ts@@ -1,5 +1,5 @@// @vitest-environment happy-dom-import type { RouteObject } from 'react-router';+import type { LoaderFunctionArgs, RouteObject } from 'react-router';import { describe, expect, it, vi } from 'vitest';import { desktopRoutes } from './desktopRouter.config';@@ -33,7 +33,9 @@ describe('page list loader wiring', () => {it('delegates to the real loader on first use', async () => {const { pageListLoader: realLoader } = await import('@/routes/(main)/page/pageListLoader');- await expect(pageListLoader()).resolves.toBeNull();- expect(realLoader).toHaveBeenCalled();+ const args = { params: { id: 'docs_a' } } as unknown as LoaderFunctionArgs;++ await expect(pageListLoader(args)).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalledWith(args);});});diff --git a/src/spa/router/resourceAccessLoader.test.ts b/src/spa/router/resourceAccessLoader.test.tsnew file mode 100644index 00000000000..8ab53a0c715--- /dev/null+++ b/src/spa/router/resourceAccessLoader.test.ts@@ -0,0 +1,22 @@+import type { LoaderFunctionArgs } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { agentAccessLoader, agentGroupAccessLoader } from './resourceAccessLoader';++vi.mock('@/features/ResourcePermission/accessLoader', () => ({+ preHydrateResourceAccess: vi.fn(async () => null),+}));++const args = (params: Record<string, string>) => ({ params }) as unknown as LoaderFunctionArgs;++describe('resource access route loaders', () => {+ it('pre-hydrates the route resource through the real loader', async () => {+ const { preHydrateResourceAccess } = await import('@/features/ResourcePermission/accessLoader');++ await expect(agentAccessLoader(args({ aid: 'agt_1' }))).resolves.toBeNull();+ await expect(agentGroupAccessLoader(args({ gid: 'grp_1' }))).resolves.toBeNull();++ expect(preHydrateResourceAccess).toHaveBeenCalledWith('agent', 'agt_1');+ expect(preHydrateResourceAccess).toHaveBeenCalledWith('agentGroup', 'grp_1');+ });+});diff --git a/src/spa/router/resourceAccessLoader.ts b/src/spa/router/resourceAccessLoader.tsnew file mode 100644index 00000000000..92baa378502--- /dev/null+++ b/src/spa/router/resourceAccessLoader.ts@@ -0,0 +1,16 @@+import type { LoaderFunctionArgs } from 'react-router';++/**+ * Route-table entries for the resource-access pre-paint hydrate.+ *+ * The real loader imports the resource-permission store. The route tables sit in+ * the entry chunk's static graph, so importing it directly would pull the store+ * into the first screen; resolving it on first use keeps it in a lazy chunk.+ */+const loadAccess = () => import('@/features/ResourcePermission/accessLoader');++export const agentAccessLoader = ({ params }: LoaderFunctionArgs) =>+ loadAccess().then((module) => module.preHydrateResourceAccess('agent', params.aid));++export const agentGroupAccessLoader = ({ params }: LoaderFunctionArgs) =>+ loadAccess().then((module) => module.preHydrateResourceAccess('agentGroup', params.gid));diff --git a/src/spa/router/tabRouter.tsx b/src/spa/router/tabRouter.tsxindex b736a8238f2..1fddf1459b6 100644--- a/src/spa/router/tabRouter.tsx+++ b/src/spa/router/tabRouter.tsx@@ -8,7 +8,7 @@ import TabLocationReporter from '@/features/Electron/TabHost/TabLocationReporterimport { ErrorBoundary } from '@/utils/router';import { createMainAreaChildren } from './desktopRouter.config';-import { withSegmentFallback } from './desktopRouter.shared';+import { withSegmentFallback } from './withSegmentFallback';const TabRootLayout = () => (<Suspense fallback={<RouteSegmentSkeleton />}>diff --git a/src/spa/router/withSegmentFallback.tsx b/src/spa/router/withSegmentFallback.tsxnew file mode 100644index 00000000000..26489f6eb0f--- /dev/null+++ b/src/spa/router/withSegmentFallback.tsx@@ -0,0 +1,46 @@+import { createElement, isValidElement, type ReactElement, type ReactNode, Suspense } from 'react';+import type { RouteObject } from 'react-router';++import BrandTextLoading from '@/components/Loading/BrandTextLoading';+import RouteSegmentSkeleton from '@/components/Skeleton/RouteSegment';++/**+ * Swap the default brand-loading fallback for a structural segment skeleton.+ *+ * `dynamicElement` / `dynamicLayout` wrap every route element in their own+ * `Suspense`, and that boundary is always nearer the suspending component than+ * any outlet-level one β so a fallback set on the main layout's outlet never+ * fires for route content, and the 100+ call sites would otherwise each need+ * the option. Explicit route fallbacks are preserved so a route can render the+ * nearest segment skeleton instead. Rewriting only defaults here keeps the main+ * area consistent without touching routes outside it (mobile still wants the+ * full-page brand loading, since its nav bar is inside the same boundary as its+ * outlet).+ */+export const withSegmentFallback = (routes: RouteObject[]): RouteObject[] =>+ routes.map((route) => {+ const suspenseElement =+ isValidElement(route.element) && route.element.type === Suspense+ ? (route.element as ReactElement<{ fallback: ReactNode }>)+ : undefined;+ const fallback = suspenseElement?.props.fallback;+ const element =+ suspenseElement && isValidElement(fallback) && fallback.type === BrandTextLoading+ ? // This intentionally couples to `dynamicElement` / `dynamicLayout`+ // returning a bare Suspense with BrandTextLoading as their default.+ // Explicit segment fallbacks must pass through unchanged.+ createElement(Suspense, {+ ...suspenseElement.props,+ fallback: <RouteSegmentSkeleton />,+ key: suspenseElement.key,+ })+ : route.element;++ // `RouteObject` is a discriminated union of index / non-index routes, and+ // spreading loses the discriminant β the copy keeps the original's shape.+ return {+ ...route,+ ...(route.children && { children: withSegmentFallback(route.children) }),+ element,+ } as RouteObject;+ });diff --git a/src/store/resourcePermission/action.test.ts b/src/store/resourcePermission/action.test.tsnew file mode 100644index 00000000000..3e7267f2b4f--- /dev/null+++ b/src/store/resourcePermission/action.test.ts@@ -0,0 +1,241 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import type { ResourceGeneralAccess } from '@/services/resourcePermission';++import { resourcePermissionActions } from './action';+import { initialState } from './initialState';+import { resourceAccessResource, resourceCollaboratorsResource } from './projection';+import { useResourcePermissionStore } from './store';++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(async () => undefined),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++vi.mock('@/services/resourcePermission', () => ({+ resourcePermissionService: {+ getGeneralAccess: vi.fn(),+ setAccessLevel: vi.fn(),+ },+}));++const { resourcePermissionService } = await import('@/services/resourcePermission');++const REF = { resourceId: 'agent-1', resourceType: 'agent' } as const;+const KEY = 'agent:agent-1';++const record = (overrides: Partial<ResourceGeneralAccess> = {}): ResourceGeneralAccess => ({+ accessLevel: 'use',+ canManage: false,+ creatorId: 'creator',+ generalAccess: 'viewer',+ visibility: 'public',+ ...overrides,+});++const state = () => useResourcePermissionStore.getState();++/**+ * Mount the access sync and play the request SWR would run: the fetcher, then+ * the success / error callback the slice installed.+ */+const mountAccessSync = async () => {+ renderHook(() => resourcePermissionActions.useFetchAccess(REF));+ const { useClientDataSWR } = await import('@/libs/swr');+ const call = vi+ .mocked(useClientDataSWR)+ .mock.calls.findLast(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === 'resourceAccess',+ );+ const [, fetcher, config] = call as unknown as [+ unknown,+ () => Promise<unknown>,+ { onError: (error: unknown) => void; onSuccess: (data: unknown) => void },+ ];+ return { config, fetcher };+};+const syncAccess = async () => {+ const { config, fetcher } = await mountAccessSync();+ try {+ config.onSuccess(await fetcher());+ } catch (error) {+ config.onError(error);+ }+};+const sessionCheck = () => state().accessSessionMap[`${cacheScope.get()}|${KEY}`];++describe('resourcePermissionActions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // State only: `reset()` also clears the replicas, which (scope not yet+ // persistable here) would block later hydrates in this scope.+ useResourcePermissionStore.setState(initialState);+ });++ it('keys the access replica per resource type and id, with a bounded persisted set', () => {+ expect(resourceAccessResource.key(REF)).toBe(KEY);+ expect(resourceAccessResource.persisted).toBe(true);+ });++ it('never persists the manager-only collaborator roster', async () => {+ // A stored roster would paint for a former manager before the server's 403.+ expect(resourceCollaboratorsResource.persisted).toBe(false);+ expect(resourceCollaboratorsResource.storage).toBeUndefined();++ renderHook(() => resourcePermissionActions.useFetchCollaborators(REF));++ expect(state().collaboratorsMap[KEY]).toBeUndefined();+ expect(state().collaboratorsReplica.entries[KEY]?.source).not.toBe('storage');+ });++ it('discards an access read still in flight when the user-data stores reset', async () => {+ // A Desktop server switch that resolves to the same scope string: the old+ // server's answer must not repopulate the store or confirm a manage grant.+ let answer!: (value: ResourceGeneralAccess) => void;+ vi.mocked(resourcePermissionService.getGeneralAccess).mockReturnValue(+ new Promise((resolve) => {+ answer = resolve;+ }),+ );+ const { config, fetcher } = await mountAccessSync();+ const pending = fetcher();++ // Let the reset's row purge land, so later hydrates in this scope still run.+ const canPersist = vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ resourcePermissionActions.reset();+ canPersist.mockRestore();+ answer(record({ canManage: true }));+ config.onSuccess(await pending);++ expect(state().accessMap[KEY]).toBeUndefined();+ expect(sessionCheck()).toBeUndefined();+ });++ it('applies a server answer and confirms it for this session', async () => {+ vi.mocked(resourcePermissionService.getGeneralAccess).mockResolvedValue(+ record({ canManage: true }),+ );++ await syncAccess();++ expect(resourcePermissionService.getGeneralAccess).toHaveBeenCalledWith('agent', 'agent-1');+ expect(state().accessMap[KEY]?.canManage).toBe(true);+ expect(sessionCheck()).toBe('confirmed');+ });++ it('drops the record on screen and marks it denied when the server refuses access', async () => {+ useResourcePermissionStore.setState({ accessMap: { [KEY]: record({ canManage: true }) } });+ vi.mocked(resourcePermissionService.getGeneralAccess).mockRejectedValue({+ data: { code: 'FORBIDDEN' },+ });++ await syncAccess();++ expect(sessionCheck()).toBe('denied');+ expect(state().accessMap[KEY]).toBeUndefined();+ });++ it('keeps the record through a transport failure', async () => {+ useResourcePermissionStore.setState({ accessMap: { [KEY]: record() } });+ vi.mocked(resourcePermissionService.getGeneralAccess).mockRejectedValue(new Error('offline'));++ await syncAccess();++ expect(sessionCheck()).toBeUndefined();+ expect(state().accessMap[KEY]).toEqual(record());+ });++ it('updates the access level optimistically and lands the server answer', async () => {+ useResourcePermissionStore.setState({ accessMap: { [KEY]: record({ canManage: true }) } });+ let settle!: (value: ResourceGeneralAccess) => void;+ vi.mocked(resourcePermissionService.setAccessLevel).mockReturnValue(+ new Promise((resolve) => {+ settle = resolve;+ }),+ );++ const pending = resourcePermissionActions.setAccessLevel(REF, 'edit');++ expect(state().accessMap[KEY]).toMatchObject({ accessLevel: 'edit', generalAccess: 'editor' });++ settle(record({ accessLevel: 'edit', canManage: true, generalAccess: 'editor' }));+ await pending;++ expect(state().accessMap[KEY]).toMatchObject({ accessLevel: 'edit', canManage: true });+ expect(sessionCheck()).toBe('confirmed');+ });++ it('rolls a rejected access-level change back', async () => {+ useResourcePermissionStore.setState({ accessMap: { [KEY]: record({ canManage: true }) } });+ vi.mocked(resourcePermissionService.setAccessLevel).mockRejectedValue(new Error('nope'));++ await expect(resourcePermissionActions.setAccessLevel(REF, 'edit')).rejects.toThrow('nope');++ expect(state().accessMap[KEY]).toMatchObject({ accessLevel: 'use', generalAccess: 'viewer' });+ });++ it('withdraws a stale manage grant when the server refuses a management write', async () => {+ // Confirmed manager this session, demoted before the write.+ vi.mocked(resourcePermissionService.getGeneralAccess).mockResolvedValueOnce(+ record({ canManage: true }),+ );+ await syncAccess();+ expect(sessionCheck()).toBe('confirmed');++ let answer!: (value: ResourceGeneralAccess) => void;+ vi.mocked(resourcePermissionService.getGeneralAccess).mockReturnValueOnce(+ new Promise((resolve) => {+ answer = resolve;+ }),+ );+ vi.mocked(resourcePermissionService.setAccessLevel).mockRejectedValue({+ data: { code: 'FORBIDDEN' },+ });++ await expect(resourcePermissionActions.setAccessLevel(REF, 'edit')).rejects.toEqual({+ data: { code: 'FORBIDDEN' },+ });++ // Manage controls close before the re-fetch answers.+ expect(sessionCheck()).toBeUndefined();+ expect(resourcePermissionService.getGeneralAccess).toHaveBeenCalledTimes(2);++ answer(record({ canManage: false }));+ await vi.waitFor(() => expect(state().accessMap[KEY]?.canManage).toBe(false));+ expect(sessionCheck()).toBe('confirmed');+ });++ it('keeps the confirmation through a management write that failed in transport', async () => {+ vi.mocked(resourcePermissionService.getGeneralAccess).mockResolvedValueOnce(+ record({ canManage: true }),+ );+ await syncAccess();+ vi.mocked(resourcePermissionService.setAccessLevel).mockRejectedValue(new Error('offline'));++ await expect(resourcePermissionActions.setAccessLevel(REF, 'edit')).rejects.toThrow('offline');++ expect(sessionCheck()).toBe('confirmed');+ expect(resourcePermissionService.getGeneralAccess).toHaveBeenCalledTimes(1);+ });++ it('seeds the persisted record before anything mounts', async () => {+ const get = vi.spyOn(resourceAccessResource.storage!, 'get').mockResolvedValue({+ data: record({ accessLevel: 'edit', generalAccess: 'editor' }),+ updatedAt: 1,+ });++ // Another resource: the engine keeps a denied key's removal for the session.+ const ref = { resourceId: 'agent-2', resourceType: 'agent' } as const;++ await expect(resourcePermissionActions.preHydrateAccess(ref)).resolves.toBe(true);++ expect(get).toHaveBeenCalledWith(expect.objectContaining({ queryKey: 'agent:agent-2' }));+ expect(state().accessMap['agent:agent-2']).toMatchObject({ accessLevel: 'edit' });+ expect(state().accessReplica.entries['agent:agent-2']?.source).toBe('storage');+ // A persisted record is not this session's server answer.+ expect(state().accessSessionMap).toEqual({});+ get.mockRestore();+ });+});diff --git a/src/store/resourcePermission/action.ts b/src/store/resourcePermission/action.tsnew file mode 100644index 00000000000..f41c61ad908--- /dev/null+++ b/src/store/resourcePermission/action.ts@@ -0,0 +1,217 @@+import { cacheScope, createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';+import type {+ ResourceAccessLevel,+ ResourceCollaborator,+ ResourceGeneralAccess,+} from '@/services/resourcePermission';+import { resourcePermissionService } from '@/services/resourcePermission';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';+import { isTrpcErrorCode } from '@/utils/trpcError';++import {+ initialState,+ type ResourceAccessCheck,+ type ResourcePermissionState,+} from './initialState';+import {+ resourceAccessResource,+ resourceCollaboratorsResource,+ resourceKey,+ type ResourceRef,+} from './projection';+import { accessSessionKey } from './selectors';+import { useResourcePermissionStore } from './store';++const n = setNamespace('resourcePermission');++type Setter = StoreSetter<ResourcePermissionState>;++/**+ * Failures that are the server's answer rather than a transport fault: the+ * resource went private, left the workspace, or the caller lost access.+ */+export const isAccessDenialError = (error: unknown): boolean =>+ isTrpcErrorCode(error, 'NOT_FOUND') ||+ isTrpcErrorCode(error, 'FORBIDDEN') ||+ isTrpcErrorCode(error, 'UNAUTHORIZED');++export class ResourcePermissionActionImpl {+ readonly #access;+ readonly #collaborators;+ readonly #set: Setter;++ constructor(set: Setter, get: () => ResourcePermissionState) {+ this.#set = set;++ this.#access = createReplicaSlice(resourceAccessResource, {+ actionPrefix: 'resourceAccess',+ effects: {+ // Every server answer, unchanged ones included, re-confirms the record+ // for this session β that is what management checks wait for.+ onApplied: (_data, _params, { key, scope }) => this.#markAccess(scope, key, 'confirmed'),+ onError: (error, _params, { key, scope }) => {+ if (key === undefined || !isAccessDenialError(error)) return;+ // The persisted grant no longer holds: drop it so neither this view+ // nor a reload acts on it, and fail every check closed.+ this.#markAccess(scope, key, 'denied');+ void this.#access.remove(key, scope);+ },+ },+ fetcher: ({ resourceId, resourceType }) =>+ resourcePermissionService.getGeneralAccess(resourceType, resourceId),+ get,+ set,+ stateKey: 'accessReplica',+ view: recordLens<ResourcePermissionState, ResourceGeneralAccess>('accessMap'),+ });++ this.#collaborators = createReplicaSlice(resourceCollaboratorsResource, {+ actionPrefix: 'resourceCollaborators',+ effects: {+ onError: (error, _params, { key, scope }) => {+ // Only managers may list grants; a caller who lost that must not+ // keep (or reload) the list they saw before.+ if (key !== undefined && isAccessDenialError(error)) {+ void this.#collaborators.remove(key, scope);+ }+ },+ },+ fetcher: ({ resourceId, resourceType }) =>+ resourcePermissionService.listCollaborators(resourceType, resourceId),+ get,+ set,+ stateKey: 'collaboratorsReplica',+ view: recordLens<ResourcePermissionState, ResourceCollaborator[]>('collaboratorsMap'),+ });+ }++ #markAccess = (scope: string, key: string, check: ResourceAccessCheck): void => {+ this.#set(+ (s) => ({+ accessSessionMap: { ...s.accessSessionMap, [accessSessionKey(scope, key)]: check },+ }),+ false,+ n('markAccess', { check, key }),+ );+ };++ /**+ * A management write the server refused proves this session's `confirmed`+ * manage grant is stale (the caller was demoted after the access read).+ * Withdraw the confirmation so manage controls close at once, drop the+ * manager-only roster, and re-fetch the record β `fresh`, so a read that+ * started before the demotion cannot land and re-confirm the old grant.+ */+ #onManagementRefused = (ref: ResourceRef, scope: string, error: unknown): void => {+ if (!isAccessDenialError(error) || cacheScope.get() !== scope) return;+ const key = resourceKey(ref);+ const sessionKey = accessSessionKey(scope, key);+ this.#set(+ (s) => {+ if (s.accessSessionMap[sessionKey] !== 'confirmed') return s;+ const { [sessionKey]: _, ...accessSessionMap } = s.accessSessionMap;+ return { accessSessionMap };+ },+ false,+ n('withdrawAccess', { key }),+ );+ void this.#collaborators.remove(key, scope);+ this.#access.fetch(ref, { fresh: true, scope }).catch(() => {});+ };++ /** Run a management write, reacting to a refusal before rethrowing it. */+ #manage = async <T>(ref: ResourceRef, write: () => Promise<T>): Promise<T> => {+ const scope = cacheScope.get();+ try {+ return await write();+ } catch (error) {+ this.#onManagementRefused(ref, scope, error);+ throw error;+ }+ };++ useFetchAccess = (ref: ResourceRef | null): ReplicaSyncResult => this.#access.useSync(ref);++ /**+ * Seed the persisted access record before a route commits (see the route+ * loaders in `@/features/ResourcePermission/accessLoader`), so a config page+ * decides from it on the first frame instead of after `useSync` hydrates.+ */+ preHydrateAccess = (ref: ResourceRef): Promise<boolean> => {+ const scope = cacheScope.get();+ // The slot may still hold the previous identity's rows; drop them before seeding.+ this.#access.ensureScope(scope);+ return this.#access.hydrate(ref, scope);+ };++ useFetchCollaborators = (ref: ResourceRef | null): ReplicaSyncResult =>+ this.#collaborators.useSync(ref);++ setAccessLevel = async (ref: ResourceRef, accessLevel: ResourceAccessLevel): Promise<void> => {+ const scope = cacheScope.get();+ const key = resourceKey(ref);+ await this.#manage(ref, () =>+ this.#access.optimistic(+ key,+ (data) => ({+ ...data,+ accessLevel,+ generalAccess: accessLevel === 'edit' ? 'editor' : 'viewer',+ }),+ () =>+ resourcePermissionService.setAccessLevel(ref.resourceType, ref.resourceId, accessLevel),+ { confirm: (result) => () => result },+ ),+ );+ // The write's response is a server answer too.+ if (cacheScope.get() === scope) this.#markAccess(scope, key, 'confirmed');+ };++ addCollaborators = async (+ ref: ResourceRef,+ userIds: string[],+ accessLevel: ResourceAccessLevel,+ ): Promise<void> => {+ await this.#manage(ref, () =>+ resourcePermissionService.addCollaborators(+ ref.resourceType,+ ref.resourceId,+ userIds,+ accessLevel,+ ),+ );+ await this.#collaborators.fetch(ref, { fresh: true });+ };++ /**+ * The row disappears immediately and comes back if the server rejects the+ * revocation (the caller surfaces the error).+ */+ removeCollaborator = async (ref: ResourceRef, userId: string): Promise<void> => {+ await this.#manage(ref, () =>+ this.#collaborators.optimistic(+ resourceKey(ref),+ (list) => list.filter((item) => item.userId !== userId),+ () =>+ resourcePermissionService.removeCollaborator(ref.resourceType, ref.resourceId, userId),+ ),+ );+ await this.#collaborators.fetch(ref, { fresh: true });+ };++ reset = (): void => {+ // `clear()` advances each replica's clear generation, so a read still in+ // flight from the previous data context (e.g. a Desktop server switch that+ // resolves to the same scope string) is discarded instead of repopulating+ // the maps and re-confirming a manage grant. It also drops this scope's+ // persisted access rows, which that context wrote.+ void this.#access.clear();+ void this.#collaborators.clear();+ this.#set(initialState, false, n('reset'));+ };+}++const { getState, setState } = useResourcePermissionStore;++export const resourcePermissionActions = new ResourcePermissionActionImpl(setState, getState);diff --git a/src/store/resourcePermission/index.ts b/src/store/resourcePermission/index.tsnew file mode 100644index 00000000000..35af29b83fc--- /dev/null+++ b/src/store/resourcePermission/index.ts@@ -0,0 +1,4 @@+export { isAccessDenialError, resourcePermissionActions } from './action';+export type { ResourceRef } from './projection';+export { resourcePermissionSelectors } from './selectors';+export { useResourcePermissionStore } from './store';diff --git a/src/store/resourcePermission/initialState.ts b/src/store/resourcePermission/initialState.tsnew file mode 100644index 00000000000..f087a90ee8a--- /dev/null+++ b/src/store/resourcePermission/initialState.ts@@ -0,0 +1,30 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type { ResourceCollaborator, ResourceGeneralAccess } from '@/services/resourcePermission';++/**+ * What the server last answered for an access record during this page+ * session, keyed by `${scope}|${resourceKey}`. A hydrated record has no entry:+ * it may predate a downgrade, so it vouches for nothing that needs a fresh+ * answer (management controls, redirects).+ */+export type ResourceAccessCheck = 'confirmed' | 'denied';++export interface ResourcePermissionState {+ /** General-access record per `resourceKey` (replica view). */+ accessMap: Record<string, ResourceGeneralAccess>;+ /** Local-first bookkeeping for `accessMap`. */+ accessReplica: ReplicaState<ResourceGeneralAccess>;+ accessSessionMap: Record<string, ResourceAccessCheck>;+ /** Collaborator grants per `resourceKey` (replica view). */+ collaboratorsMap: Record<string, ResourceCollaborator[]>;+ /** Local-first bookkeeping for `collaboratorsMap`. */+ collaboratorsReplica: ReplicaState<ResourceCollaborator[]>;+}++export const initialState: ResourcePermissionState = {+ accessMap: {},+ accessReplica: createReplicaState(),+ accessSessionMap: {},+ collaboratorsMap: {},+ collaboratorsReplica: createReplicaState(),+};diff --git a/src/store/resourcePermission/projection.ts b/src/store/resourcePermission/projection.tsnew file mode 100644index 00000000000..83e96fbe381--- /dev/null+++ b/src/store/resourcePermission/projection.ts@@ -0,0 +1,47 @@+import { defineReplica } from '@/libs/replica';+import type {+ PermissionResourceType,+ ResourceCollaborator,+ ResourceGeneralAccess,+} from '@/services/resourcePermission';++export interface ResourceRef {+ resourceId: string;+ resourceType: PermissionResourceType;+}++/** Entry key of one resource in every resource-permission replica. */+export const resourceKey = ({ resourceId, resourceType }: ResourceRef): string =>+ `${resourceType}:${resourceId}`;++/**+ * The caller's workspace General-access record of one resource. Persisted so a+ * reload renders the last confirmed access (config pages, sidebar menus,+ * composer controls) without waiting for the network; the server still checks+ * every write, and management stays fail-closed until this session re-confirms+ * the record (see `resourceAccessSelectors.isConfirmed`).+ *+ * A record is a few scalar fields, but one is kept per agent / group / page the+ * user opens, so the persisted rows are capped.+ */+export const resourceAccessResource = defineReplica<ResourceRef, ResourceGeneralAccess>({+ key: resourceKey,+ name: 'resourceAccess',+ persist: { maxEntries: 200 },+ storage: 'indexedDB',+ version: 1,+});++/**+ * The collaborator grants of one resource, read by its managers on the+ * Permission page. Memory-only (`storage: 'memory'`): the roster carries other+ * members' names, avatars and emails, and only a current manager may see it. A+ * persisted copy would paint for a former manager on revisit before the server+ * answered 403, so the list only ever holds what this session fetched.+ */+export const resourceCollaboratorsResource = defineReplica<ResourceRef, ResourceCollaborator[]>({+ key: resourceKey,+ name: 'resourceCollaborators',+ storage: 'memory',+ version: 1,+});diff --git a/src/store/resourcePermission/selectors.ts b/src/store/resourcePermission/selectors.tsnew file mode 100644index 00000000000..79ef1926865--- /dev/null+++ b/src/store/resourcePermission/selectors.ts@@ -0,0 +1,21 @@+import type { ResourcePermissionState } from './initialState';+import { resourceKey, type ResourceRef } from './projection';++/** `accessSessionMap` key: the same resource is a separate answer per identity scope. */+export const accessSessionKey = (scope: string, key: string): string => `${scope}|${key}`;++const access = (ref: ResourceRef | null) => (s: ResourcePermissionState) =>+ ref ? s.accessMap[resourceKey(ref)] : undefined;++/** What the server answered for this record during this session, if anything. */+const sessionCheck = (ref: ResourceRef | null, scope: string) => (s: ResourcePermissionState) =>+ ref ? s.accessSessionMap[accessSessionKey(scope, resourceKey(ref))] : undefined;++const collaborators = (ref: ResourceRef | null) => (s: ResourcePermissionState) =>+ ref ? s.collaboratorsMap[resourceKey(ref)] : undefined;++export const resourcePermissionSelectors = {+ access,+ collaborators,+ sessionCheck,+};diff --git a/src/store/resourcePermission/store.ts b/src/store/resourcePermission/store.tsnew file mode 100644index 00000000000..c6c8b01c2f0--- /dev/null+++ b/src/store/resourcePermission/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { initialState, type ResourcePermissionState } from './initialState';++const devtools = createDevtools('resourcePermission');++export const useResourcePermissionStore = createWithEqualityFn<ResourcePermissionState>()(+ devtools(() => initialState),+ shallow,+);++expose('resourcePermission', useResourcePermissionStore);diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.tsindex d1791dad141..f7f4e94cfa8 100644--- a/src/store/utils/userDataStores.test.ts+++ b/src/store/utils/userDataStores.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const resetGatewayMuxRegistry = vi.hoisted(() => vi.fn());const storeResets = vi.hoisted(() => [] as Array<() => void>);const pageReset = vi.hoisted(() => vi.fn());+const resourcePermissionReset = vi.hoisted(() => vi.fn());const sandboxReset = vi.hoisted(() => vi.fn());const fakeStore = vi.hoisted(() => () => ({getState: () => {@@ -29,6 +30,9 @@ vi.mock('@/store/library', () => ({ useKnowledgeBaseStore: fakeStore() }));vi.mock('@/store/mention', () => ({ useMentionStore: fakeStore() }));vi.mock('@/store/notebook', () => ({ useNotebookStore: fakeStore() }));vi.mock('@/store/page', () => ({ pageActions: { reset: pageReset } }));+vi.mock('@/store/resourcePermission', () => ({+ resourcePermissionActions: { reset: resourcePermissionReset },+}));vi.mock('@/store/sandbox', () => ({ sandboxActions: { reset: sandboxReset } }));vi.mock('@/store/session', () => ({ useSessionStore: fakeStore() }));vi.mock('@/store/task', () => ({ useTaskStore: fakeStore() }));@@ -42,6 +46,7 @@ describe('stores.reset', () => {resetGatewayMuxRegistry.mockClear();storeResets.length = 0;pageReset.mockClear();+ resourcePermissionReset.mockClear();sandboxReset.mockClear();});@@ -55,6 +60,9 @@ describe('stores.reset', () => {expect(resetGatewayMuxRegistry).toHaveBeenCalledTimes(1);expect(storeResets).toHaveLength(18);expect(pageReset).toHaveBeenCalledTimes(1);+ // Confirmed manage grants and the memory-only collaborator roster must not+ // outlive the data context, even when the next one reuses the scope string.+ expect(resourcePermissionReset).toHaveBeenCalledTimes(1);expect(sandboxReset).toHaveBeenCalledTimes(1);for (const reset of storeResets) expect(reset).toHaveBeenCalledTimes(1);expect(order[0]).toBe('mux');diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.tsindex b9aa3488693..512c596cab0 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -16,6 +16,7 @@ import { useMentionStore } from '@/store/mention';import { useNotebookStore } from '@/store/notebook';import { pageActions } from '@/store/page';import { projectFileActions } from '@/store/projectFile';+import { resourcePermissionActions } from '@/store/resourcePermission';import { sandboxActions } from '@/store/sandbox';import { useSessionStore } from '@/store/session';import { useTaskStore } from '@/store/task';@@ -54,6 +55,7 @@ const resetableActions: ResetableStore[] = [agentDocumentActions,pageActions,projectFileActions,+ resourcePermissionActions,sandboxActions,];