🤯 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(home): isolate recents by workspace (#16411)
Arvin Xuf3f4d1da458c
diff --git a/src/hooks/useInitRecents.ts b/src/hooks/useInitRecents.tsindex be68c62e074..7dd66b25728 100644--- a/src/hooks/useInitRecents.ts+++ b/src/hooks/useInitRecents.ts@@ -1,3 +1,4 @@+import { useCacheScope } from '@/libs/swr/useCacheScope';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useHomeStore } from '@/store/home';@@ -7,9 +8,10 @@ import { authSelectors } from '@/store/user/selectors';export const useInitRecents = () => {const useFetchRecents = useHomeStore((s) => s.useFetchRecents);const isLogin = useUserStore(authSelectors.isLogin);+ const scope = useCacheScope();const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);- const { isValidating, data, ...rest } = useFetchRecents(isLogin, recentPageSize);+ const { isValidating, data, ...rest } = useFetchRecents(isLogin, recentPageSize, scope);return {...rest,diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsnew file mode 100644index 00000000000..01ea15b3156--- /dev/null+++ b/src/libs/swr/keys.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { recentKeys } from './keys';++describe('recentKeys', () => {+ it('keys the Home recent list by identity cache scope', () => {+ expect(recentKeys.list(true, 10, 'user-1:workspace-1')).toEqual([+ 'recent:list',+ true,+ 10,+ 'user-1:workspace-1',+ ]);+ });++ it('keeps users isolated in the same workspace', () => {+ expect(recentKeys.list(true, 10, 'user-1:workspace-1')).not.toEqual(+ recentKeys.list(true, 10, 'user-2:workspace-1'),+ );+ });++ it('keeps workspaces isolated for the same user', () => {+ expect(recentKeys.allDrawer(true, 'user-1:workspace-1')).not.toEqual(+ recentKeys.allDrawer(true, 'user-1:workspace-2'),+ );+ });+});diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 8d7dc384b74..0c295755c42 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -134,10 +134,19 @@ export const threadKeys = {// ---- recent -------------------------------------------------------------export const recentKeys = {- /** Home "all recents" drawer list, keyed by open state. */- allDrawer: def('recent:allDrawer', (open: boolean) => ['recent:allDrawer', open]),- /** Home recents list, keyed by login + limit. */- list: def('recent:list', (isLogin: boolean, limit: number) => ['recent:list', isLogin, limit]),+ /** Home "all recents" drawer list, keyed by open state and identity scope. */+ allDrawer: def('recent:allDrawer', (open: boolean, scope: string) => [+ 'recent:allDrawer',+ open,+ scope,+ ]),+ /** Home recents list, keyed by login + limit + identity scope. */+ list: def('recent:list', (isLogin: boolean, limit: number, scope: string) => [+ 'recent:list',+ isLogin,+ limit,+ scope,+ ]),};// ---- task ---------------------------------------------------------------diff --git a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsxindex 65b2c863473..eee6b52121d 100644--- a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx+++ b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx@@ -11,6 +11,7 @@ import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useClientDataSWR } from '@/libs/swr';import { recentKeys } from '@/libs/swr/keys';+import { useCacheScope } from '@/libs/swr/useCacheScope';import { recentService } from '@/services/recent';import RecentListItem from './Item';@@ -23,9 +24,10 @@ interface AllRecentsDrawerProps {const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {const { t } = useTranslation('common');const [searchKeyword, setSearchKeyword] = useState('');+ const scope = useCacheScope();const { data: recents, isLoading } = useClientDataSWR(- open ? recentKeys.allDrawer(open) : null,+ open ? recentKeys.allDrawer(open, scope) : null,() => recentService.getAll(50),);diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.tsnew file mode 100644index 00000000000..d7b26f48e36--- /dev/null+++ b/src/store/home/slices/recent/action.test.ts@@ -0,0 +1,165 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import * as swr from '@/libs/swr';+import { recentKeys } from '@/libs/swr/keys';+import * as cacheScope from '@/libs/swr/useCacheScope';+import { type RecentItem } from '@/server/routers/lambda/recent';+import { useHomeStore } from '@/store/home';+import { initialRecentState } from '@/store/home/slices/recent/initialState';++const item = (id: string, title: string): RecentItem => ({ id, title }) as unknown as RecentItem;++/**+ * Render `useFetchRecents` with `useClientDataSWRWithSync` stubbed so we can grab+ * the `onData` sync callback and drive the scope guard directly.+ */+const captureOnData = (scope: string) => {+ let onData: ((data: RecentItem[]) => void) | undefined;+ vi.spyOn(swr, 'useClientDataSWRWithSync').mockImplementation(((+ _key: unknown,+ _fetcher: unknown,+ opts: any,+ ) => {+ onData = opts?.onData;+ return { data: undefined, isValidating: false, mutate: vi.fn() };+ }) as any);++ renderHook(() => useHomeStore.getState().useFetchRecents(true, 10, scope));+ return () => onData;+};++beforeEach(() => {+ useHomeStore.setState({ ...initialRecentState });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('RecentActionImpl', () => {+ describe('useFetchRecents onData scope guard', () => {+ it('applies data for the matching scope and tags recentsScope', () => {+ vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');+ const getOnData = captureOnData('user-1:ws-A');++ act(() => getOnData()!([item('a', 'A')]));++ const state = useHomeStore.getState();+ expect(state.recents).toEqual([item('a', 'A')]);+ expect(state.isRecentsInit).toBe(true);+ expect(state.recentsScope).toBe('user-1:ws-A');+ });++ it('ignores data whose scope no longer matches the active cache scope', () => {+ // active scope moved to ws-A, but this callback belongs to the stale ws-B key+ vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');+ const getOnData = captureOnData('user-1:ws-B');++ act(() => getOnData()!([item('stale', 'STALE')]));++ const state = useHomeStore.getState();+ expect(state.recents).toEqual([]);+ expect(state.isRecentsInit).toBe(false);+ expect(state.recentsScope).toBeNull();+ });++ it('keeps data isolated across users in the same workspace', () => {+ useHomeStore.setState({+ isRecentsInit: true,+ recents: [item('u1', 'user1 item')],+ recentsScope: 'user-1:ws-A',+ });+ // now signed in as user-2 in the same workspace+ vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-2:ws-A');+ const getOnData = captureOnData('user-2:ws-A');++ act(() => getOnData()!([item('u2', 'user2 item')]));++ const state = useHomeStore.getState();+ expect(state.recents).toEqual([item('u2', 'user2 item')]);+ expect(state.recentsScope).toBe('user-2:ws-A');+ });++ it('skips redundant set when init, same scope and equal data', () => {+ useHomeStore.setState({+ isRecentsInit: true,+ recents: [item('a', 'A')],+ recentsScope: 'user-1:ws-A',+ });+ vi.spyOn(cacheScope, 'getCacheScope').mockReturnValue('user-1:ws-A');+ const getOnData = captureOnData('user-1:ws-A');++ // an early return means no set() runs, so the state object keeps its identity+ const before = useHomeStore.getState();+ act(() => getOnData()!([item('a', 'A')]));++ expect(useHomeStore.getState()).toBe(before);+ });+ });++ describe('updateRecentTitle', () => {+ it('renames in the store mirror and patches the scoped SWR caches', () => {+ useHomeStore.setState({ recents: [item('a', 'old'), item('b', 'keep')] });+ const mutateSpy = vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as any);++ act(() => {+ useHomeStore.getState().updateRecentTitle('a', 'new');+ });++ expect(useHomeStore.getState().recents).toEqual([item('a', 'new'), item('b', 'keep')]);+ // both the list and the drawer SWR caches get a non-revalidating patch+ expect(mutateSpy).toHaveBeenCalledTimes(2);+ expect(mutateSpy).toHaveBeenCalledWith(expect.any(Function), expect.any(Function), {+ revalidate: false,+ });+ });++ it('SWR cache updater matches keys by root and renames the target item only', () => {+ useHomeStore.setState({ recents: [] });+ let updater: (items?: RecentItem[]) => RecentItem[] | undefined = () => undefined;+ const matchers: Array<(key: unknown) => boolean> = [];+ vi.spyOn(swr, 'mutate').mockImplementation(((match: any, fn: any) => {+ matchers.push(match);+ updater = fn;+ return Promise.resolve(undefined);+ }) as any);++ act(() => {+ useHomeStore.getState().updateRecentTitle('a', 'new');+ });++ expect(matchers[0](recentKeys.list(true, 10, 's'))).toBe(true);+ expect(matchers[0](['other:key'])).toBe(false);+ expect(updater([item('a', 'old'), item('b', 'keep')])).toEqual([+ item('a', 'new'),+ item('b', 'keep'),+ ]);+ expect(updater(undefined)).toBeUndefined();+ });+ });++ describe('refreshRecents', () => {+ it('revalidates both the list and the drawer SWR caches', async () => {+ const mutateSpy = vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as any);++ await act(async () => {+ await useHomeStore.getState().refreshRecents();+ });++ expect(mutateSpy).toHaveBeenCalledTimes(2);+ const matcher = mutateSpy.mock.calls[0][0] as (key: unknown) => boolean;+ expect(matcher(recentKeys.list(true, 10, 's'))).toBe(true);+ });+ });++ describe('drawer visibility', () => {+ it('opens and closes the all-recents drawer', () => {+ act(() => useHomeStore.getState().openAllRecentsDrawer());+ expect(useHomeStore.getState().allRecentsDrawerOpen).toBe(true);++ act(() => useHomeStore.getState().closeAllRecentsDrawer());+ expect(useHomeStore.getState().allRecentsDrawerOpen).toBe(false);+ });+ });+});diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsindex 71dbe1a5cdc..51c6f6d9e59 100644--- a/src/store/home/slices/recent/action.ts+++ b/src/store/home/slices/recent/action.ts@@ -3,6 +3,7 @@ import { type SWRResponse } from 'swr';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';import { recentKeys } from '@/libs/swr/keys';+import { getCacheScope } from '@/libs/swr/useCacheScope';import { type RecentItem } from '@/server/routers/lambda/recent';import { recentService } from '@/services/recent';import { type HomeStore } from '@/store/home/store';@@ -17,6 +18,9 @@ const n = setNamespace('recent');// tab is backgrounded.const RECENTS_REFRESH_INTERVAL = 10_000;+const updateRecentTitleInList = (id: string, title: string) => (items?: RecentItem[]) =>+ items?.map((item) => (item.id === id ? { ...item, title } : item));+type Setter = StoreSetter<HomeStore>;export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>new RecentActionImpl(set, get, _api);@@ -42,6 +46,18 @@ export class RecentActionImpl {updateRecentTitle = (id: string, title: string): void => {const recents = this.#get().recents.map((item) => (item.id === id ? { ...item, title } : item));this.#set({ recents }, false, n('updateRecentTitle'));++ const updater = updateRecentTitleInList(id, title);+ void Promise.all([+ mutate((key: unknown) => Array.isArray(key) && key[0] === recentKeys.list.root, updater, {+ revalidate: false,+ }),+ mutate(+ (key: unknown) => Array.isArray(key) && key[0] === recentKeys.allDrawer.root,+ updater,+ { revalidate: false },+ ),+ ]);};refreshRecents = async (): Promise<void> => {@@ -54,15 +70,26 @@ export class RecentActionImpl {useFetchRecents = (isLogin: boolean | undefined,limit: number = 10,+ scope: string,): SWRResponse<RecentItem[]> => {return useClientDataSWRWithSync<RecentItem[]>(- isLogin === true ? recentKeys.list(isLogin, limit) : null,+ isLogin === true ? recentKeys.list(isLogin, limit, scope) : null,async () => recentService.getAll(limit + 1),{onData: (data) => {- if (this.#get().isRecentsInit && isEqual(this.#get().recents, data)) return;+ if (getCacheScope() !== scope) return;++ const state = this.#get();++ if (state.isRecentsInit && state.recentsScope === scope && isEqual(state.recents, data)) {+ return;+ }- this.#set({ isRecentsInit: true, recents: data }, false, n('useFetchRecents/onData'));+ this.#set(+ { isRecentsInit: true, recents: data, recentsScope: scope },+ false,+ n('useFetchRecents/onData'),+ );},refreshInterval: RECENTS_REFRESH_INTERVAL,},diff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.tsindex 83b9e529134..196fdb0ccbe 100644--- a/src/store/home/slices/recent/initialState.ts+++ b/src/store/home/slices/recent/initialState.ts@@ -4,10 +4,12 @@ export interface RecentState {allRecentsDrawerOpen: boolean;isRecentsInit: boolean;recents: RecentItem[];+ recentsScope: string | null;}export const initialRecentState: RecentState = {allRecentsDrawerOpen: false,isRecentsInit: false,recents: [],+ recentsScope: null,};