π€― 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(agent-builder): persist suggestion chips via tiered SWR cache (#18064)
YuTengjingd633b07a20f5
diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsxindex c5a94aaa012..0d85fad1355 100644--- a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx@@ -1,9 +1,10 @@import { act, renderHook, waitFor } from '@testing-library/react';import type { PropsWithChildren } from 'react';import { createElement } from 'react';-import { SWRConfig } from 'swr';+import { type State, SWRConfig, unstable_serialize } from 'swr';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { swrKeys } from '@/libs/swr/keys';import { aiChatService } from '@/services/aiChat';import { useBuilderSuggestions } from './useBuilderSuggestions';@@ -35,8 +36,8 @@ const baseParams = {targetId: 'target-agent',} satisfies Parameters<typeof useBuilderSuggestions>[0];-const createSWRWrapper = () => {- const value = { provider: () => new Map() };+const createSWRWrapper = (cache: Map<string, State> = new Map()) => {+ const value = { provider: () => cache };return function SWRTestWrapper({ children }: PropsWithChildren) {return createElement(SWRConfig, { value }, children);@@ -111,6 +112,63 @@ describe('useBuilderSuggestions', () => {expect(result.current.suggestions[0]?.title).toBe('second title');});+ // Regression for LOBE-12895: suggestions are persisted via the tiered SWR+ // cache provider. A cache hit (e.g. hydrated from localStorage on a revisit)+ // must render directly without paying another LLM generation.+ it('serves a persisted cache hit without regenerating', async () => {+ const cache = new Map<string, State>();+ const key = unstable_serialize(+ swrKeys.agentBuilder.suggestions(+ baseParams.mode,+ baseParams.builderAgentId,+ baseParams.targetId,+ baseParams.locale,+ ),+ );+ cache.set(key, {+ data: {+ suggestions: [{ prompt: 'cached prompt', title: 'cached title' }],+ tracingId: 'trace-cached',+ },+ });++ const { result } = renderHook((props) => useBuilderSuggestions(props), {+ initialProps: baseParams,+ wrapper: createSWRWrapper(cache),+ });++ await waitFor(() => {+ expect(result.current.suggestions[0]?.title).toBe('cached title');+ });+ await waitForNextTick();++ expect(aiChatService.generateJSON).not.toHaveBeenCalled();+ });++ // Persisted entries are generated in the UI language, so a language switch+ // must miss the cache and regenerate instead of serving old-locale chips.+ it('regenerates when the UI locale changes', async () => {+ vi.mocked(aiChatService.generateJSON)+ .mockResolvedValueOnce(makeEnvelope('first'))+ .mockResolvedValueOnce(makeEnvelope('second'));++ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {+ initialProps: baseParams,+ wrapper: createSWRWrapper(),+ });++ await waitFor(() => {+ expect(result.current.suggestions[0]?.title).toBe('first title');+ });++ rerender({ ...baseParams, locale: 'en-US' });++ await waitFor(() => {+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);+ });+ expect(result.current.suggestions[0]?.title).toBe('second title');+ });+it('regenerates when the edited target changes', async () => {vi.mocked(aiChatService.generateJSON).mockResolvedValueOnce(makeEnvelope('first'))diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.tsindex a0a55b72ed6..c4a433505b7 100644--- a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts@@ -6,7 +6,7 @@ import {type BuilderSuggestionMode,chainBuilderSuggestion,} from '@lobechat/prompts';-import { useCallback, useState } from 'react';+import { useCallback } from 'react';import useSWR from 'swr';import { swrKeys } from '@/libs/swr/keys';@@ -51,21 +51,20 @@ export const useBuilderSuggestions = ({enabled,targetId,}: UseBuilderSuggestionsParams): BuilderSuggestionsResult => {- // Bumping the nonce forces a fresh generation (SWR key change) on manual refresh.- const [nonce, setNonce] = useState(0);const markRegenerated = useBuilderSuggestionFeedbackStore((s) => s.markRegenerated);- // Key on target identity only β the context summary is deliberately kept out of- // the key so config autosaves (which stream in new summaries for the same target)- // don't refetch. Only a target switch or a nonce bump regenerates; the fetcher- // closure reads the current summary, which is always the latest value on the- // render that changes the key.+ // Key on target identity (+ locale, since chips are generated in the UI+ // language) β the context summary is deliberately kept out of the key so+ // config autosaves (which stream in new summaries for the same target) don't+ // refetch. Only a target/locale switch or a manual refresh regenerates; the+ // fetcher closure reads the current summary, which is always the latest value+ // on the render that changes the key.const key =enabled && contextSummary && model && provider- ? swrKeys.agentBuilder.suggestions(mode, builderAgentId, targetId, nonce)+ ? swrKeys.agentBuilder.suggestions(mode, builderAgentId, targetId, locale): null;- const { data, isLoading, error } = useSWR(+ const { data, isLoading, error, mutate } = useSWR(key,async () => {// Read mode/context/agent from the closure: SWR runs the fetcher from the@@ -96,6 +95,11 @@ export const useBuilderSuggestions = ({},{dedupingInterval: 600_000,+ // The key is persisted to the localStorage SWR tier (see `CACHE_TIERS.local`),+ // so a revisit hydrates the last batch synchronously. Without this flag SWR+ // would still revalidate the stale entry on mount, regenerating (and paying+ // an LLM call) on every page load β the exact thing the persistence avoids.+ revalidateIfStale: false,revalidateOnFocus: false,revalidateOnReconnect: false,shouldRetryOnError: false,@@ -104,8 +108,10 @@ export const useBuilderSuggestions = ({const refresh = useCallback(() => {markRegenerated(data?.tracingId);- setNonce((n) => n + 1);- }, [data?.tracingId, markRegenerated]);+ // Clear the current batch (skeleton shows) and re-run the fetcher on the+ // same key, so the fresh batch lands in the persisted cache entry.+ void mutate(undefined, { revalidate: true });+ }, [data?.tracingId, markRegenerated, mutate]);return {error,diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex c4cdb6196c2..41f7b5308bd 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -1,7 +1,7 @@import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';-import { recentKeys, taskKeys } from './keys';+import { agentBuilderKeys, recentKeys, taskKeys } from './keys';import { CACHE_TIERS } from './localStorageProvider';describe('recentKeys', () => {@@ -54,6 +54,21 @@ describe('recentKeys', () => {});});+describe('agentBuilderKeys', () => {+ // Regression: builder suggestion chips were memory-only (no CACHE_TIERS entry),+ // so every page load showed a skeleton and paid a fresh LLM generation. The key+ // must route to a persisted tier so revisits hydrate the last batch instead.+ it('routes the builder suggestions key to a persisted cache tier', () => {+ const serialized = unstable_serialize(+ agentBuilderKeys.suggestions('agentBuilder', 'builder-1', 'target-1', 'zh-CN'),+ );+ const persisted = [...CACHE_TIERS.idb, ...CACHE_TIERS.local].some((pattern) =>+ serialized.includes(pattern),+ );+ expect(persisted).toBe(true);+ });+});+describe('taskKeys', () => {// Regression for sidebar task list cache persists across navigation to skip skeleton: the sidebar task list used a `sidebar:` domain// key that no CACHE_TIERS pattern matched, so it was memory-only and everydiff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 5f1d7c196b4..4904aadbe8e 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -192,18 +192,22 @@ export const agentLabelKeys = {};// ---- agent builder (opening-suggestion chips) ----------------------------// Kept off `CACHE_TIERS` on purpose β these are ephemeral LLM-generated chips.-// `contextSummary` is intentionally NOT part of the key so config autosaves for-// the same target don't refetch; `nonce` bumps on manual refresh.+// Persisted to the localStorage tier (see `CACHE_TIERS.local`) so revisits skip+// the LLM generation instead of paying a skeleton + a generateJSON call every+// page load. `contextSummary` is intentionally NOT part of the key so config+// autosaves for the same target don't refetch; manual refresh revalidates the+// same key in place (see `useBuilderSuggestions`). `locale` IS part of the key:+// chips are generated in the UI language, so a persisted entry must not be+// served after a language switch.export const agentBuilderKeys = {suggestions: def('agentBuilder:suggestions',- (mode: string, builderAgentId: string, targetId: string | undefined, nonce: number) => [+ (mode: string, builderAgentId: string, targetId: string | undefined, locale?: string) => ['agentBuilder:suggestions',mode,builderAgentId,targetId,- nonce,+ locale ?? null,],),};diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.tsindex a78ab8ec28f..b942e2bcd23 100644--- a/src/libs/swr/localStorageProvider.ts+++ b/src/libs/swr/localStorageProvider.ts@@ -501,6 +501,7 @@ export const CACHE_TIERS = {'fetchRecentResources','fetchRecentPages','group:list',+ 'agentBuilder:suggestions', // builder opening-suggestion chips (skip LLM regen on revisit)'taskTemplate:', // home task-template recommendations'modelConfig:', // small remote model config shells used by home starter chips],