π€― 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: cache task template recommendations (#15993)
YuTengjing04b8d214b984
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.tsnew file mode 100644index 00000000000..e2c13eb92dc--- /dev/null+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts@@ -0,0 +1,144 @@+/**+ * @vitest-environment happy-dom+ */+import { describe, expect, it } from 'vitest';++import { taskTemplateKeys } from '@/libs/swr/keys';++import {+ resolveDailyBriefRecommendationDisplayMode,+ resolveDailyBriefRecommendationRequest,+} from './useDailyBriefRecommendationsUI';++describe('resolveDailyBriefRecommendationRequest', () => {+ it('keeps the cache key available while interests are still initializing', () => {+ const loading = resolveDailyBriefRecommendationRequest({+ interestKeys: null,+ isLogin: true,+ locale: 'zh-CN',+ recommendationCount: 3,+ refreshSeed: '',+ });+ const ready = resolveDailyBriefRecommendationRequest({+ interestKeys: ['ai'],+ isLogin: true,+ locale: 'zh-CN',+ recommendationCount: 3,+ refreshSeed: '',+ });++ expect(loading.key).toEqual(ready.key);+ expect(loading.shouldFetch).toBe(false);+ expect(ready.shouldFetch).toBe(true);+ });++ it('does not include interests in the persisted recommendation cache key', () => {+ const ai = resolveDailyBriefRecommendationRequest({+ interestKeys: ['ai'],+ isLogin: true,+ locale: 'zh-CN',+ recommendationCount: 3,+ refreshSeed: 'seed',+ });+ const research = resolveDailyBriefRecommendationRequest({+ interestKeys: ['research'],+ isLogin: true,+ locale: 'zh-CN',+ recommendationCount: 3,+ refreshSeed: 'seed',+ });++ expect(ai.key).toEqual(research.key);+ expect(ai.key).toEqual(taskTemplateKeys.listDailyRecommend('seed', 3, 'zh-CN'));+ });++ it('keeps refresh seed, count, and locale in the cache key', () => {+ expect(+ resolveDailyBriefRecommendationRequest({+ interestKeys: [],+ isLogin: true,+ locale: 'zh-CN',+ recommendationCount: 3,+ refreshSeed: 'seed-a',+ }).key,+ ).not.toEqual(+ resolveDailyBriefRecommendationRequest({+ interestKeys: [],+ isLogin: true,+ locale: 'en-US',+ recommendationCount: 6,+ refreshSeed: 'seed-b',+ }).key,+ );+ });++ it('disables the cache key before login', () => {+ expect(+ resolveDailyBriefRecommendationRequest({+ interestKeys: [],+ isLogin: false,+ locale: 'zh-CN',+ recommendationCount: 3,+ refreshSeed: '',+ }),+ ).toEqual({ key: null, shouldFetch: false });+ });+});++describe('resolveDailyBriefRecommendationDisplayMode', () => {+ it('keeps cached cards visible while interests are still initializing', () => {+ expect(+ resolveDailyBriefRecommendationDisplayMode({+ canFetchRecommendations: false,+ hasRecommendationKey: true,+ hasTemplates: true,+ isInit: false,+ isLoading: false,+ isValidating: false,+ isWaitingForInterestsFetch: false,+ }),+ ).toBe('cards');+ });++ it('keeps skeleton visible while the first ready-interest fetch is pending', () => {+ expect(+ resolveDailyBriefRecommendationDisplayMode({+ canFetchRecommendations: true,+ hasRecommendationKey: true,+ hasTemplates: false,+ isInit: true,+ isLoading: false,+ isValidating: true,+ isWaitingForInterestsFetch: false,+ }),+ ).toBe('skeleton');+ });++ it('keeps skeleton visible before the first ready-interest fetch starts', () => {+ expect(+ resolveDailyBriefRecommendationDisplayMode({+ canFetchRecommendations: true,+ hasRecommendationKey: true,+ hasTemplates: false,+ isInit: true,+ isLoading: false,+ isValidating: false,+ isWaitingForInterestsFetch: true,+ }),+ ).toBe('skeleton');+ });++ it('hides an initialized empty recommendation result only when idle', () => {+ expect(+ resolveDailyBriefRecommendationDisplayMode({+ canFetchRecommendations: true,+ hasRecommendationKey: true,+ hasTemplates: false,+ isInit: true,+ isLoading: false,+ isValidating: false,+ isWaitingForInterestsFetch: false,+ }),+ ).toBe('hidden');+ });+});diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.tsindex 513f18c2a61..88160193bf9 100644--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts@@ -3,7 +3,7 @@ import { TASK_TEMPLATE_RECOMMEND_COUNT } from '@lobechat/const';import { createNanoId } from '@lobechat/utils';import { useSessionStorageState } from 'ahooks';import { App } from 'antd';-import { useCallback, useMemo } from 'react';+import { useCallback, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';@@ -35,6 +35,65 @@ interface UseDailyBriefRecommendationsUIOptions {count?: number;}+interface ResolveDailyBriefRecommendationRequestParams {+ interestKeys: string[] | null;+ isLogin: boolean | undefined;+ locale: string;+ recommendationCount: number;+ refreshSeed?: string;+}++export const resolveDailyBriefRecommendationRequest = ({+ interestKeys,+ isLogin,+ locale,+ recommendationCount,+ refreshSeed,+}: ResolveDailyBriefRecommendationRequestParams) => {+ const enabled = isLogin === true;++ return {+ key: enabled+ ? taskTemplateKeys.listDailyRecommend(refreshSeed ?? '', recommendationCount, locale)+ : null,+ shouldFetch: enabled && interestKeys !== null,+ };+};++interface ResolveDailyBriefRecommendationDisplayModeParams {+ canFetchRecommendations: boolean;+ hasRecommendationKey: boolean;+ hasTemplates: boolean;+ isInit: boolean;+ isLoading: boolean;+ isValidating: boolean;+ isWaitingForInterestsFetch: boolean;+}++export const resolveDailyBriefRecommendationDisplayMode = ({+ canFetchRecommendations,+ hasRecommendationKey,+ hasTemplates,+ isInit,+ isLoading,+ isValidating,+ isWaitingForInterestsFetch,+}: ResolveDailyBriefRecommendationDisplayModeParams): DailyBriefRecommendationsUIState['mode'] => {+ if (!hasRecommendationKey) return 'hidden';+ if (hasTemplates) return 'cards';+ if (+ !isInit ||+ isLoading ||+ isValidating ||+ !canFetchRecommendations ||+ isWaitingForInterestsFetch+ ) {+ return 'skeleton';+ }++ return 'hidden';+};+export function useDailyBriefRecommendationsUI(options: UseDailyBriefRecommendationsUIOptions = {},): DailyBriefRecommendationsUIState {@@ -50,24 +109,58 @@ export function useDailyBriefRecommendationsUI(const isInit = useBriefStore(briefListSelectors.isBriefsInit);const interestKeys = useResolvedInterestKeys();- const swrKey = interestKeys ? [...interestKeys].sort().join(',') : '';- const swrEnabled = isLogin && interestKeys !== null;const [refreshSeed, setRefreshSeed] = useSessionStorageState<string>(REFRESH_SEED_STORAGE_KEY, {defaultValue: '',});-- const { data, isLoading, mutate } = useSWR(- swrEnabled- ? taskTemplateKeys.listDailyRecommend(swrKey, refreshSeed, recommendationCount, locale)- : null,- async () =>- taskTemplateService.listDailyRecommend(interestKeys ?? [], {- count: recommendationCount,+ const recommendationRequest = useMemo(+ () =>+ resolveDailyBriefRecommendationRequest({+ interestKeys,+ isLogin,locale,- refreshSeed: refreshSeed || undefined,+ recommendationCount,+ refreshSeed,}),- { revalidateOnFocus: false, revalidateOnReconnect: false },+ [interestKeys, isLogin, locale, recommendationCount, refreshSeed],+ );+ const canFetchRecommendations = recommendationRequest.shouldFetch && interestKeys !== null;+ const recommendationFetcher = canFetchRecommendations+ ? async () =>+ taskTemplateService.listDailyRecommend(interestKeys, {+ count: recommendationCount,+ locale,+ refreshSeed: refreshSeed || undefined,+ })+ : null;++ const { data, isLoading, isValidating, mutate } = useSWR(+ recommendationRequest.key,+ recommendationFetcher,+ {+ keepPreviousData: true,+ revalidateIfStale: canFetchRecommendations,+ revalidateOnFocus: false,+ revalidateOnMount: canFetchRecommendations,+ revalidateOnReconnect: false,+ },);+ const waitedForInterestsRef = useRef(false);++ useEffect(() => {+ if (!recommendationRequest.key) {+ waitedForInterestsRef.current = false;+ return;+ }++ if (interestKeys === null) {+ waitedForInterestsRef.current = true;+ return;+ }++ if (!waitedForInterestsRef.current) return;+ waitedForInterestsRef.current = false;+ void mutate();+ }, [interestKeys, mutate, recommendationRequest.key]);const handleRefresh = useCallback(() => {setRefreshSeed(nextRefreshSeed());@@ -120,9 +213,17 @@ export function useDailyBriefRecommendationsUI(useFetchUserComposioConnections(requiredSources.has('composio'));useFetchLobehubSkillConnections(requiredSources.has('lobehub'));- if (!swrEnabled) return { mode: 'hidden' };- if (!isInit || isLoading) return { mode: 'skeleton', skeletonCount: recommendationCount };- if (templates.length === 0) return { mode: 'hidden' };+ const displayMode = resolveDailyBriefRecommendationDisplayMode({+ canFetchRecommendations,+ hasRecommendationKey: Boolean(recommendationRequest.key),+ hasTemplates: templates.length > 0,+ isInit,+ isLoading,+ isValidating,+ isWaitingForInterestsFetch: interestKeys !== null && waitedForInterestsRef.current,+ });+ if (displayMode === 'hidden') return { mode: 'hidden' };+ if (displayMode === 'skeleton') return { mode: 'skeleton', skeletonCount: recommendationCount };return {mode: 'cards',diff --git a/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.ts b/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.tsnew file mode 100644index 00000000000..369e133c89f--- /dev/null+++ b/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.ts@@ -0,0 +1,62 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useUserStore } from '@/store/user';+import type { LobeUser } from '@/types/user';++import { useResolvedInterestKeys } from './useResolvedInterestKeys';++vi.mock('zustand/traditional');++describe('useResolvedInterestKeys', () => {+ it('returns null before auth loads', () => {+ const { result } = renderHook(() => useResolvedInterestKeys());++ expect(result.current).toBeNull();+ });++ it('waits for login user state before exposing empty interests', () => {+ act(() => {+ useUserStore.setState({+ isLoaded: true,+ isSignedIn: true,+ isUserStateInit: false,+ user: { id: 'user-id' } as LobeUser,+ });+ });++ const { result } = renderHook(() => useResolvedInterestKeys());++ expect(result.current).toBeNull();+ });++ it('normalizes interests after login user state initializes', () => {+ act(() => {+ useUserStore.setState({+ isLoaded: true,+ isSignedIn: true,+ isUserStateInit: true,+ user: { id: 'user-id', interests: [' AI ', '', 'Research'] } as LobeUser,+ });+ });++ const { result } = renderHook(() => useResolvedInterestKeys());++ expect(result.current).toEqual(['ai', 'research']);+ });++ it('allows empty interests after login user state initializes', () => {+ act(() => {+ useUserStore.setState({+ isLoaded: true,+ isSignedIn: true,+ isUserStateInit: true,+ user: { id: 'user-id', interests: [] } as LobeUser,+ });+ });++ const { result } = renderHook(() => useResolvedInterestKeys());++ expect(result.current).toEqual([]);+ });+});diff --git a/src/features/RecommendTaskTemplates/useResolvedInterestKeys.ts b/src/features/RecommendTaskTemplates/useResolvedInterestKeys.tsindex 9fbcbcd5c3d..4107dbcf4a5 100644--- a/src/features/RecommendTaskTemplates/useResolvedInterestKeys.ts+++ b/src/features/RecommendTaskTemplates/useResolvedInterestKeys.ts@@ -8,19 +8,22 @@ import { authSelectors } from '@/store/user/slices/auth/selectors';* Predefined interests are stored as canonical INTEREST_AREAS keys. Freeform* entries are lowercased passthroughs β the server treats them as non-matching.*- * Returns `null` while the user store hasn't finished hydrating (`interests`- * is `[]` until then, which would fire an SWR request with empty keys and- * immediately re-fire once the real interests land β wasted round trip).+ * Returns `null` while the login user state hasn't finished initializing+ * (`interests` is `[]` after auth loads but before `useInitUserState` merges+ * profile data, which would create a transient empty-interest SWR key).** Callers should keep SWR disabled while null.*/export const useResolvedInterestKeys = (): string[] | null => {const isUserLoaded = useUserStore(authSelectors.isLoaded);+ const isLogin = useUserStore(authSelectors.isLogin);+ const isUserStateInit = useUserStore((s) => s.isUserStateInit);const userInterests = useUserStore(userProfileSelectors.interests);return useMemo(() => {if (!isUserLoaded) return null;+ if (isLogin && !isUserStateInit) return null;return userInterests.map((raw) => raw.trim().toLocaleLowerCase()).filter(Boolean);- }, [isUserLoaded, userInterests]);+ }, [isLogin, isUserLoaded, isUserStateInit, userInterests]);};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex d6ee386a2c4..9c5437a4ee4 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -548,10 +548,10 @@ export const chatToolKeys = {};// =========================================================================-// UI-layer keys (features / routes / components). Same rule as above: every-// prefix below is deliberately kept OUT of `CACHE_TIERS` (memory-only). Names-// avoid colliding with cached prefixes β e.g. share/topicInfo is `share:` not-// `topic:`, portal header is `portal:` not `document:`.+// UI-layer keys (features / routes / components). Prefixes below stay+// memory-only unless explicitly listed in `CACHE_TIERS`. Names avoid colliding+// with cached prefixes β e.g. share/topicInfo is `share:` not `topic:`, portal+// header is `portal:` not `document:`.// =========================================================================// ---- stats (settings/stats + user header counts) ------------------------@@ -732,16 +732,15 @@ export const topicActionKeys = {openNewOrSave: def('topicAction:openNewOrSave', () => ['topicAction:openNewOrSave']),};-// ---- misc remaining domains (memory-only; off CACHE_TIERS) --------------+// ---- misc remaining domains ---------------------------------------------export const homeKeys = {dailyBrief: def('home:dailyBrief', (userId: string) => ['home:dailyBrief', userId]),};export const taskTemplateKeys = {listDailyRecommend: def('taskTemplate:listDailyRecommend',- (interestsKey: string, refreshSeed: unknown, recommendationCount: number, locale: string) => [+ (refreshSeed: unknown, recommendationCount: number, locale: string) => ['taskTemplate:listDailyRecommend',- interestsKey,refreshSeed,recommendationCount,locale,diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex 49e0e9a0df3..11169a1da2e 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -75,6 +75,24 @@ describe('createCacheProvider β tiering', () => {expect(keys).not.toContain('random');});+ it('persists task-template recommendation keys in the local tier', async () => {+ const scope = { value: 's1' };+ const { provider } = buildProvider(scope, {+ idbPatterns: [...CACHE_TIERS.idb],+ localPatterns: [...CACHE_TIERS.local],+ });+ const map = provider();+ const key = 'taskTemplate:listDailyRecommend:ai,,3,zh-CN';++ map.set(key, { data: [{ id: 1, title: 'Daily brief' }] });++ await until(() => localStorage.getItem(getScopedCacheKey('s1')) !== null);++ const stored = JSON.parse(localStorage.getItem(getScopedCacheKey('s1'))!);+ expect(stored.map(([k]: [string]) => k)).toContain(key);+ expect(await localDataCache.entriesByScope('s1')).toEqual([]);+ });+it('routes idb-tier keys to IndexedDB and reloads them on a fresh provider', async () => {const scope = { value: 's1' };const { provider } = buildProvider(scope);@@ -193,6 +211,7 @@ describe('createCacheProvider β tiering', () => {expect(CACHE_TIERS.idb).toContain('message:');expect(CACHE_TIERS.idb).toContain('topic:');expect(CACHE_TIERS.local).toContain('recent:list');+ expect(CACHE_TIERS.local).toContain('taskTemplate:');});});diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex 47c8d184ee6..e13e47c200e 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -440,6 +440,7 @@ export const CACHE_TIERS = {'fetchRecentResources','fetchRecentPages','group:list',+ 'taskTemplate:', // home task-template recommendations],} as const;diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.tsindex d02572d07b4..80135050a82 100644--- a/src/store/user/slices/common/action.test.ts+++ b/src/store/user/slices/common/action.test.ts@@ -1,7 +1,9 @@import { act, renderHook, waitFor } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DEFAULT_PREFERENCE } from '@/const/user';+import type * as SWRLib from '@/libs/swr';+import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';import { userService } from '@/services/user';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';@@ -9,8 +11,23 @@ import { type GlobalServerConfig } from '@/types/serverConfig';import { type UserInitializationState, type UserPreference } from '@/types/user';import { withSWR } from '~test-utils';+import { isTaskTemplateRecommendationKey } from './action';++const swrMocks = vi.hoisted(() => ({+ mutate: vi.fn(),+}));+vi.mock('zustand/traditional');+vi.mock('@/libs/swr', async (importOriginal) => {+ const actual = await importOriginal<typeof SWRLib>();++ return {+ ...actual,+ mutate: swrMocks.mutate,+ };+});+vi.mock('swr', async (importOriginal) => {const modules = await importOriginal();return {@@ -19,11 +36,25 @@ vi.mock('swr', async (importOriginal) => {};});+beforeEach(() => {+ swrMocks.mutate.mockReset();+ swrMocks.mutate.mockResolvedValue(undefined);+});+afterEach(() => {vi.restoreAllMocks();});describe('createCommonSlice', () => {+ describe('isTaskTemplateRecommendationKey', () => {+ it('matches every daily recommendation cache variant', () => {+ expect(+ isTaskTemplateRecommendationKey(taskTemplateKeys.listDailyRecommend('seed', 3, 'zh-CN')),+ ).toBe(true);+ expect(isTaskTemplateRecommendationKey(userKeys.initState())).toBe(false);+ });+ });+describe('updateAvatar', () => {it('should update avatar', async () => {const { result } = renderHook(() => useUserStore());@@ -69,6 +100,30 @@ describe('createCommonSlice', () => {expect(updateSpy).toHaveBeenCalledWith(['new']);});++ it('does not fail the interest update when recommendation cache invalidation fails', async () => {+ act(() => {+ useUserStore.setState({ user: { id: 'u1', interests: ['old'] } as any });+ });++ const cacheError = new Error('cache failed');+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(userService, 'updateInterests').mockResolvedValue(undefined as any);+ swrMocks.mutate.mockImplementation((key) => {+ if (key === isTaskTemplateRecommendationKey) return Promise.reject(cacheError);++ return Promise.resolve(undefined);+ });++ await expect(useUserStore.getState().updateInterests(['new'])).resolves.toBeUndefined();+ await waitFor(() => {+ expect(consoleSpy).toHaveBeenCalledWith(+ '[taskTemplate:recommendationCache:invalidate]',+ cacheError,+ );+ });+ expect(useUserStore.getState().user?.interests).toEqual(['new']);+ });});describe('useInitUserState', () => {diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.tsindex 53498005b13..9f6895997d9 100644--- a/src/store/user/slices/common/action.ts+++ b/src/store/user/slices/common/action.ts@@ -7,7 +7,7 @@ import { type PartialDeep } from 'type-fest';import { DEFAULT_PREFERENCE } from '@/const/user';import { mutate, useOnlyFetchOnceSWR } from '@/libs/swr';-import { userKeys } from '@/libs/swr/keys';+import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';import { userService } from '@/services/user';import { type StoreSetter } from '@/store/types';import { type UserStore } from '@/store/user';@@ -29,6 +29,9 @@ type Setter = StoreSetter<UserStore>;export const createCommonSlice = (set: Setter, get: () => UserStore, _api?: unknown) =>new CommonActionImpl(set, get, _api);+export const isTaskTemplateRecommendationKey = (key: unknown): boolean =>+ Array.isArray(key) && key[0] === taskTemplateKeys.listDailyRecommend.root;+export class CommonActionImpl {readonly #get: () => UserStore;readonly #set: Setter;@@ -59,6 +62,9 @@ export class CommonActionImpl {this.#set({ user: { ...previousUser, interests } }, false, n('updateInterests/optimistic'));}await userService.updateInterests(interests);+ void mutate(isTaskTemplateRecommendationKey).catch((error) => {+ console.error('[taskTemplate:recommendationCache:invalidate]', error);+ });await this.#get().refreshUserState();};