Skip to content

🤯 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.

♻️ refactor(task-template,agent-builder): serve recommendations and builder chips from localStorage replicas (#21201)

Arvin Xu33a3f732c763
diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.ts
index 110c31ffe7e..f25a44e251f 100644
--- a/packages/replica/src/zustand/driver.ts
+++ b/packages/replica/src/zustand/driver.ts
@@ -7,6 +7,13 @@ export interface ReplicaSyncSchedule {
dedupingInterval?: number;
/** Skip focus revalidation while the last one is younger than this (ms). */
focusThrottleInterval?: number;
+ /**
+ * Hold every network request (mount, stale, focus, revalidate) while it
+ * returns `true`, for a read whose input outside the sync key is not ready
+ * yet. Unlike `revalidateOnMount: false` it also covers a later key change.
+ * Read on each request, so it may close over a ref.
+ */
+ isPaused?: () => boolean;
/** Poll every N ms while mounted (0 = off); a function decides per tick from the latest data. */
refreshInterval?: number | ((latest: any) => number);
/** Keep polling while the page is hidden. */
@@ -15,6 +22,13 @@ export interface ReplicaSyncSchedule {
refreshWhenOffline?: boolean;
revalidateIfStale?: boolean;
revalidateOnFocus?: boolean;
+ /**
+ * Whether the first mount fetches. `false` leaves the first request to an
+ * explicit `revalidate`, for a read whose input outside the sync key is not
+ * ready yet. SWR only honors it on the first mount: a later key change still
+ * fetches when the new key has no cached data.
+ */
+ revalidateOnMount?: boolean;
revalidateOnReconnect?: boolean;
}
diff --git a/src/features/AgentBuilder/SuggestionChips/projection.ts b/src/features/AgentBuilder/SuggestionChips/projection.ts
new file mode 100644
index 00000000000..74b08712b6e
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/projection.ts
@@ -0,0 +1,75 @@
+import type { BuilderSuggestionItem, BuilderSuggestionMode } from '@lobechat/prompts';
+
+import type { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import { cacheScope, defineReplica } from '@/libs/replica';
+
+export interface BuilderSuggestionParams {
+ /** Builtin builder agent id — drives the model and is recorded as `agentId`. */
+ builderAgentId: string;
+ /** Latest config summary. Not part of the key: autosaves must not regenerate. */
+ contextSummary: string;
+ locale?: string;
+ mode: BuilderSuggestionMode;
+ model: string;
+ provider: string;
+ /** Agent/group being edited. */
+ targetId?: string;
+}
+
+/** One generated batch of opening chips and the tracing row that produced it. */
+export interface BuilderSuggestionBatch {
+ suggestions: BuilderSuggestionItem[];
+ tracingId?: string;
+}
+
+/**
+ * Entry identity: the edited target and the UI language (chips are generated
+ * in it, so a language switch must miss). The context summary, model and
+ * provider stay out, so config autosaves for the same target keep the batch.
+ */
+export const builderSuggestionKey = ({
+ builderAgentId,
+ locale,
+ mode,
+ targetId,
+}: Pick<BuilderSuggestionParams, 'builderAgentId' | 'locale' | 'mode' | 'targetId'>) =>
+ [mode, builderAgentId, targetId ?? '', locale ?? ''].join('\u0000');
+
+/**
+ * Builder opening-suggestion chips. Persisted so a revisit paints the last
+ * batch on the first frame instead of paying a skeleton and an LLM generation
+ * on every page load. Only titles, prompts and the tracing id are kept; one row
+ * per edited target and locale, the least recently used evicted past the cap.
+ *
+ * The name deliberately matches no `CACHE_TIERS` pattern
+ * (`agentBuilder:suggestions`), so the batch is persisted by the replica only.
+ */
+export const builderSuggestionResource = defineReplica<
+ BuilderSuggestionParams,
+ BuilderSuggestionBatch
+>({
+ key: builderSuggestionKey,
+ name: 'agentBuilderSuggestions',
+ persist: { maxEntries: 50 },
+ storage: 'localStorage',
+ version: 1,
+});
+
+/**
+ * The persisted batch of an entry, read synchronously from the replica's own
+ * localStorage row. The replica hydrates asynchronously, after the first paint;
+ * this lets that first frame show the chips instead of a skeleton.
+ */
+export const peekBuilderSuggestions = (
+ params: BuilderSuggestionParams,
+ scope: string,
+): BuilderSuggestionBatch | undefined => {
+ if (!cacheScope.canHydrate?.()) return undefined;
+ const storage = builderSuggestionResource.storage as
+ LocalStorageQueryProjectionStorage<BuilderSuggestionBatch> | undefined;
+ const data = storage?.getSync?.({
+ queryKey: builderSuggestionResource.storageKey(params),
+ scope,
+ })?.data;
+ return Array.isArray(data?.suggestions) ? data : undefined;
+};
diff --git a/src/features/AgentBuilder/SuggestionChips/suggestionStore.ts b/src/features/AgentBuilder/SuggestionChips/suggestionStore.ts
new file mode 100644
index 00000000000..c7e62de1efe
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/suggestionStore.ts
@@ -0,0 +1,121 @@
+import { TRACING_SCENARIOS } from '@lobechat/const';
+import {
+ BUILDER_SUGGESTION_PROMPT_VERSION,
+ BUILDER_SUGGESTION_SCHEMA_NAME,
+ type BuilderSuggestionItem,
+ chainBuilderSuggestion,
+} from '@lobechat/prompts';
+import { RequestTrigger } from '@lobechat/types';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+} from '@/libs/replica';
+import { aiChatService } from '@/services/aiChat';
+import { createDevtools } from '@/store/middleware/createDevtools';
+
+import {
+ type BuilderSuggestionBatch,
+ type BuilderSuggestionParams,
+ builderSuggestionResource,
+} from './projection';
+
+type GenerateEnvelope = {
+ data?: { suggestions?: BuilderSuggestionItem[] } | null;
+ tracingId?: string;
+} | null;
+
+const generateBuilderSuggestions = async ({
+ builderAgentId,
+ contextSummary,
+ locale,
+ mode,
+ model,
+ provider,
+}: BuilderSuggestionParams): Promise<BuilderSuggestionBatch> => {
+ const { messages, schema } = chainBuilderSuggestion({ contextSummary, locale, mode });
+ const envelope = (await aiChatService.generateJSON(
+ {
+ messages,
+ metadata: { trigger: RequestTrigger.BuilderSuggestion },
+ model,
+ provider,
+ schema,
+ tracing: {
+ agentId: builderAgentId,
+ promptVersion: BUILDER_SUGGESTION_PROMPT_VERSION,
+ scenario: TRACING_SCENARIOS.BuilderSuggestion,
+ schemaName: BUILDER_SUGGESTION_SCHEMA_NAME,
+ },
+ },
+ new AbortController(),
+ )) as GenerateEnvelope;
+
+ const suggestions = (envelope?.data?.suggestions ?? [])
+ .filter((s) => s?.title?.trim() && s?.prompt?.trim())
+ .slice(0, 3)
+ .map(({ prompt, title }) => ({ prompt, title }));
+
+ return { suggestions, tracingId: envelope?.tracingId };
+};
+
+export interface BuilderSuggestionStoreState {
+ /**
+ * `builderSuggestionErrorId(scope, key)` → the last generation failure,
+ * cleared by a success. Scoped, so one identity's failure never shows as
+ * another's (the view of a scope switch is cleared, this map is not).
+ */
+ suggestionErrorMap: Record<string, unknown>;
+ /** `builderSuggestionKey(params)` → the last generated batch. */
+ suggestionMap: Record<string, BuilderSuggestionBatch>;
+ suggestionReplica: ReplicaState<BuilderSuggestionBatch>;
+}
+
+export const initialBuilderSuggestionState: BuilderSuggestionStoreState = {
+ suggestionErrorMap: {},
+ suggestionMap: {},
+ suggestionReplica: createReplicaState(),
+};
+
+const devtools = createDevtools('builderSuggestion');
+
+export const builderSuggestionErrorId = (scope: string, key: string) => `${scope}\u0000${key}`;
+
+const setError = (id: string, error: unknown) => {
+ const { suggestionErrorMap } = useBuilderSuggestionStore.getState();
+ if (suggestionErrorMap[id] === error) return;
+ const next = { ...suggestionErrorMap };
+ if (error === undefined) delete next[id];
+ else next[id] = error;
+ useBuilderSuggestionStore.setState({ suggestionErrorMap: next });
+};
+
+export const useBuilderSuggestionStore = createWithEqualityFn<BuilderSuggestionStoreState>()(
+ devtools(() => initialBuilderSuggestionState),
+ shallow,
+);
+
+/**
+ * Generation is an LLM call, so it never runs as a mount-time sync: views
+ * hydrate the persisted batch first and `fetch` only an entry that is still
+ * empty (see `useBuilderSuggestions`).
+ */
+export const builderSuggestionReplica = createReplicaSlice(builderSuggestionResource, {
+ actionPrefix: 'builderSuggestion',
+ effects: {
+ onApplied: (_data, _params, { key, scope }) =>
+ setError(builderSuggestionErrorId(scope, key), undefined),
+ onError: (error, _params, { isActive, key, scope }) => {
+ if (isActive && key) setError(builderSuggestionErrorId(scope, key), error);
+ },
+ },
+ fetcher: generateBuilderSuggestions,
+ get: useBuilderSuggestionStore.getState,
+ set: useBuilderSuggestionStore.setState,
+ stateKey: 'suggestionReplica',
+ view: recordLens<BuilderSuggestionStoreState, BuilderSuggestionBatch>('suggestionMap'),
+});
diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx
index 34b3675104c..b007f1a47bb 100644
--- a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx
+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx
@@ -1,13 +1,18 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { randomUUID } from 'node:crypto';
+
import { RequestTrigger } from '@lobechat/types';
import { act, renderHook, waitFor } from '@testing-library/react';
-import type { PropsWithChildren } from 'react';
-import { createElement } from 'react';
-import { type State, SWRConfig, unstable_serialize } from 'swr';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { swrKeys } from '@/libs/swr/keys';
+import { cacheScope, replicaKeys } from '@/libs/replica';
+import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';
import { aiChatService } from '@/services/aiChat';
+import { builderSuggestionResource } from './projection';
+import { initialBuilderSuggestionState, useBuilderSuggestionStore } from './suggestionStore';
import { useBuilderSuggestions } from './useBuilderSuggestions';
type GenerateJSONResult = Awaited<ReturnType<typeof aiChatService.generateJSON>>;
@@ -37,14 +42,6 @@ const baseParams = {
targetId: 'target-agent',
} satisfies Parameters<typeof useBuilderSuggestions>[0];
-const createSWRWrapper = (cache: Map<string, State> = new Map()) => {
- const value = { provider: () => cache };
-
- return function SWRTestWrapper({ children }: PropsWithChildren) {
- return createElement(SWRConfig, { value }, children);
- };
-};
-
const waitForNextTick = async () => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -58,19 +55,57 @@ const getGeneratedUserContent = (callIndex: number) => {
return String(userMessage?.content ?? '');
};
+const seedPersisted = (scope: string, params: typeof baseParams, title: string) =>
+ builderSuggestionResource.storage!.set(
+ { queryKey: builderSuggestionResource.storageKey(params), scope },
+ {
+ data: { suggestions: [{ prompt: `${title} prompt`, title }], tracingId: `trace-${title}` },
+ updatedAt: 1,
+ },
+ );
+
describe('useBuilderSuggestions', () => {
+ let scope = '';
+
beforeEach(() => {
- vi.restoreAllMocks();
+ scope = `builder-user-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useBuilderSuggestionStore.setState(initialBuilderSuggestionState));
vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue(makeEnvelope('first'));
vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({
ok: true,
} as RecordTracingFeedbackResult);
});
+ afterEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ // The SWR tier persists every key whose serialized form contains a
+ // CACHE_TIERS pattern; the replica must stay the only persisted copy.
+ it('keeps the replica sync key out of the SWR persistence tiers', () => {
+ const serialized = JSON.stringify(
+ replicaKeys.sync(
+ builderSuggestionResource.name,
+ builderSuggestionResource.version,
+ scope,
+ 'key',
+ baseParams,
+ ),
+ );
+
+ expect(builderSuggestionResource.namespace).toBe('replica:agentBuilderSuggestions:v1');
+ expect(
+ [...CACHE_TIERS.idb, ...CACHE_TIERS.local].filter((p) => serialized.includes(p)),
+ ).toEqual([]);
+ });
+
it('tags suggestion requests with the builder suggestion trigger', async () => {
const { result } = renderHook((props) => useBuilderSuggestions(props), {
initialProps: baseParams,
- wrapper: createSWRWrapper(),
});
await waitFor(() => {
@@ -84,7 +119,6 @@ describe('useBuilderSuggestions', () => {
it('does not regenerate when autosave updates context for the same target', async () => {
const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
initialProps: baseParams,
- wrapper: createSWRWrapper(),
});
await waitFor(() => {
@@ -106,7 +140,6 @@ describe('useBuilderSuggestions', () => {
const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
initialProps: baseParams,
- wrapper: createSWRWrapper(),
});
await waitFor(() => {
@@ -118,38 +151,50 @@ describe('useBuilderSuggestions', () => {
act(() => {
result.current.refresh();
});
+ // The discarded batch leaves the screen while the new one generates.
+ expect(result.current.isLoading).toBe(true);
await waitFor(() => {
- expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);
+ expect(result.current.suggestions[0]?.title).toBe('second title');
});
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);
expect(getGeneratedUserContent(1)).toContain('manual refresh context');
- expect(result.current.suggestions[0]?.title).toBe('second title');
- });
-
- // Regression: 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',
- },
+ });
+
+ // Regression: the chips used to be persisted by the SWR localStorage tier.
+ // They are a localStorage replica now: a reload paints the persisted batch and
+ // must not pay another LLM generation for it.
+ it('serves the persisted batch after a reload without regenerating', async () => {
+ const first = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+ await waitFor(() => {
+ expect(first.result.current.suggestions[0]?.title).toBe('first title');
});
+ first.unmount();
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(1);
+
+ // Reload: the memory store starts empty.
+ act(() => useBuilderSuggestionStore.setState(initialBuilderSuggestionState));
+ const { result } = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: { ...baseParams, contextSummary: 'context after reload' },
+ });
+
+ await waitFor(() => {
+ expect(result.current.suggestions[0]?.title).toBe('first title');
+ });
+ expect(result.current.tracingId).toBe('trace-first');
+ await waitForNextTick();
+
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(1);
+ });
+
+ it('paints a persisted row without generating', async () => {
+ await seedPersisted(scope, baseParams, 'cached title');
const { result } = renderHook((props) => useBuilderSuggestions(props), {
initialProps: baseParams,
- wrapper: createSWRWrapper(cache),
});
await waitFor(() => {
@@ -160,6 +205,37 @@ describe('useBuilderSuggestions', () => {
expect(aiChatService.generateJSON).not.toHaveBeenCalled();
});
+ it('switching to a target with a persisted batch paints it without generating', async () => {
+ await seedPersisted(scope, { ...baseParams, targetId: 'target-agent-2' }, 'second target');
+
+ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+ await waitFor(() => {
+ expect(result.current.suggestions[0]?.title).toBe('first title');
+ });
+
+ rerender({ ...baseParams, targetId: 'target-agent-2' });
+
+ await waitFor(() => {
+ expect(result.current.suggestions[0]?.title).toBe('second target');
+ });
+ await waitForNextTick();
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(1);
+ });
+
+ it('never paints another identity’s persisted batch', async () => {
+ await seedPersisted('someone-else:personal', baseParams, 'other title');
+
+ const { result } = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+
+ await waitFor(() => {
+ expect(result.current.suggestions[0]?.title).toBe('first title');
+ });
+ });
+
// 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 () => {
@@ -169,7 +245,6 @@ describe('useBuilderSuggestions', () => {
const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
initialProps: baseParams,
- wrapper: createSWRWrapper(),
});
await waitFor(() => {
@@ -179,9 +254,9 @@ describe('useBuilderSuggestions', () => {
rerender({ ...baseParams, locale: 'en-US' });
await waitFor(() => {
- expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);
+ expect(result.current.suggestions[0]?.title).toBe('second title');
});
- expect(result.current.suggestions[0]?.title).toBe('second title');
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);
});
it('regenerates when the edited target changes', async () => {
@@ -191,7 +266,6 @@ describe('useBuilderSuggestions', () => {
const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
initialProps: baseParams,
- wrapper: createSWRWrapper(),
});
await waitFor(() => {
@@ -210,4 +284,96 @@ describe('useBuilderSuggestions', () => {
expect(getGeneratedUserContent(1)).toContain('new target context');
});
+
+ it('does not retry a failed generation on its own', async () => {
+ vi.mocked(aiChatService.generateJSON).mockRejectedValue(new Error('llm down'));
+
+ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.isLoading).toBe(false);
+ rerender({ ...baseParams, contextSummary: 'autosaved after failure' });
+ await waitForNextTick();
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: refresh hid the rejected batch in memory only (`persist: false`),
+ // so a failed regeneration followed by a reload restored the rejected batch
+ // and skipped generation because the entry looked filled.
+ it('drops a rejected batch from persistence even when its regeneration fails', async () => {
+ const { result, unmount } = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+ await waitFor(() => expect(result.current.suggestions[0]?.title).toBe('first title'));
+ await waitFor(async () => {
+ const row = await builderSuggestionResource.storage!.get({
+ queryKey: builderSuggestionResource.storageKey(baseParams),
+ scope,
+ });
+ expect(row?.data).toBeTruthy();
+ });
+
+ vi.mocked(aiChatService.generateJSON).mockRejectedValue(new Error('llm down'));
+ act(() => result.current.refresh());
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ unmount();
+
+ await waitFor(async () => {
+ const row = await builderSuggestionResource.storage!.get({
+ queryKey: builderSuggestionResource.storageKey(baseParams),
+ scope,
+ });
+ expect(row).toBeUndefined();
+ });
+
+ // Reload: the rejected batch is not restored; the entry generates again.
+ act(() => useBuilderSuggestionStore.setState(initialBuilderSuggestionState));
+ vi.mocked(aiChatService.generateJSON).mockResolvedValue(makeEnvelope('second'));
+ const reloaded = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+ await waitFor(() => expect(reloaded.result.current.suggestions[0]?.title).toBe('second title'));
+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(3);
+ });
+
+ // Regression: hydration started in a passive effect, so a reload with a
+ // persisted batch rendered the skeleton for at least its first frame.
+ it('paints a persisted batch on the very first render', async () => {
+ await seedPersisted(scope, baseParams, 'persisted');
+ const renders: Array<{ isLoading: boolean; title?: string }> = [];
+
+ renderHook(
+ (props) => {
+ const result = useBuilderSuggestions(props);
+ renders.push({ isLoading: result.isLoading, title: result.suggestions[0]?.title });
+ return result;
+ },
+ { initialProps: baseParams },
+ );
+
+ expect(renders[0]).toEqual({ isLoading: false, title: 'persisted' });
+ await waitForNextTick();
+ expect(renders.every((r) => !r.isLoading)).toBe(true);
+ expect(aiChatService.generateJSON).not.toHaveBeenCalled();
+ });
+
+ // Regression: generation errors were keyed by entry only, so identity A's
+ // failure showed as identity B's (not loading) for the same entry key.
+ it('does not carry a generation error over to another identity', async () => {
+ vi.mocked(aiChatService.generateJSON).mockRejectedValue(new Error('llm down'));
+ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {
+ initialProps: baseParams,
+ });
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+
+ vi.mocked(aiChatService.generateJSON).mockImplementation(() => new Promise(() => {}));
+ scope = `builder-user-${randomUUID()}:personal`;
+ rerender({ ...baseParams });
+ await waitForNextTick();
+
+ expect(result.current.error).toBeUndefined();
+ expect(result.current.isLoading).toBe(true);
+ });
});
diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts
index f02798d4d7c..1e7346d68b9 100644
--- a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts
+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts
@@ -1,19 +1,20 @@
-import { TRACING_SCENARIOS } from '@lobechat/const';
-import {
- BUILDER_SUGGESTION_PROMPT_VERSION,
- BUILDER_SUGGESTION_SCHEMA_NAME,
- type BuilderSuggestionItem,
- type BuilderSuggestionMode,
- chainBuilderSuggestion,
-} from '@lobechat/prompts';
-import { RequestTrigger } from '@lobechat/types';
-import { useCallback } from 'react';
-import useSWR from 'swr';
+import { type BuilderSuggestionItem, type BuilderSuggestionMode } from '@lobechat/prompts';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
-import { swrKeys } from '@/libs/swr/keys';
-import { aiChatService } from '@/services/aiChat';
+import { useSingleton } from '@/hooks/useSingleton';
+import { cacheScope } from '@/libs/replica';
import { useBuilderSuggestionFeedbackStore } from './feedbackStore';
+import {
+ builderSuggestionKey,
+ type BuilderSuggestionParams,
+ peekBuilderSuggestions,
+} from './projection';
+import {
+ builderSuggestionErrorId,
+ builderSuggestionReplica,
+ useBuilderSuggestionStore,
+} from './suggestionStore';
interface UseBuilderSuggestionsParams {
/** Builtin builder agent id — drives the model and is recorded as `agentId`. */
@@ -37,10 +38,10 @@ interface BuilderSuggestionsResult {
tracingId?: string;
}
-type GenerateEnvelope = {
- data?: { suggestions?: BuilderSuggestionItem[] } | null;
- tracingId?: string;
-} | null;
+const EMPTY_SUGGESTIONS: BuilderSuggestionItem[] = [];
+
+/** Failures land in `suggestionErrorMap` through the slice effects. */
+const ignore = () => {};
export const useBuilderSuggestions = ({
mode,
@@ -53,73 +54,83 @@ export const useBuilderSuggestions = ({
targetId,
}: UseBuilderSuggestionsParams): BuilderSuggestionsResult => {
const markRegenerated = useBuilderSuggestionFeedbackStore((s) => s.markRegenerated);
+ const scope = cacheScope.use();
- // 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, locale)
- : null;
+ const params = useMemo<BuilderSuggestionParams | null>(
+ () =>
+ enabled && contextSummary && model && provider
+ ? { builderAgentId, contextSummary, locale, mode, model, provider, targetId }
+ : null,
+ [builderAgentId, contextSummary, enabled, locale, mode, model, provider, targetId],
+ );
+ // The entry is keyed on target identity + locale only (see `builderSuggestionKey`):
+ // config autosaves stream in new summaries for the same target and must not
+ // regenerate. A generation reads the latest params through this ref.
+ const key = params ? builderSuggestionKey(params) : undefined;
+ const paramsRef = useRef(params);
+ paramsRef.current = params;
+
+ const stored = useBuilderSuggestionStore((s) => (key ? s.suggestionMap[key] : undefined));
+ // Entries (scope + key) whose async hydration has settled. Until then the
+ // persisted row is read synchronously, so a reload paints the chips on its
+ // first frame instead of a skeleton.
+ const settled = useSingleton(() => new Set<string>());
+ const entryId = key ? `${scope}\u0000${key}` : undefined;
+ const batch =
+ stored ??
+ (params && entryId && !settled.has(entryId)
+ ? peekBuilderSuggestions(params, scope)
+ : undefined);
+ const error = useBuilderSuggestionStore((s) =>
+ key ? s.suggestionErrorMap[builderSuggestionErrorId(scope, key)] : undefined,
+ );
- const { data, isLoading, error, mutate } = useSWR(
- key,
- async () => {
- // Read mode/context/agent from the closure: SWR runs the fetcher from the
- // render that changed the key, so these already hold the latest values.
- const { messages, schema } = chainBuilderSuggestion({ contextSummary, locale, mode });
- const abortController = new AbortController();
- const envelope = (await aiChatService.generateJSON(
- {
- messages,
- metadata: { trigger: RequestTrigger.BuilderSuggestion },
- model,
- provider,
- schema,
- tracing: {
- agentId: builderAgentId,
- promptVersion: BUILDER_SUGGESTION_PROMPT_VERSION,
- scenario: TRACING_SCENARIOS.BuilderSuggestion,
- schemaName: BUILDER_SUGGESTION_SCHEMA_NAME,
- },
- },
- abortController,
- )) as GenerateEnvelope;
+ // Before paint, so a scope switch never shows the previous identity's chips.
+ useLayoutEffect(() => {
+ if (key) builderSuggestionReplica.ensureScope(scope);
+ }, [key, scope]);
- const suggestions = (envelope?.data?.suggestions ?? [])
- .filter((s) => s?.title?.trim() && s?.prompt?.trim())
- .slice(0, 3);
+ // Keep the batch on screen out of the LRU eviction.
+ useEffect(() => (key ? builderSuggestionReplica.retain(key) : undefined), [key]);
- return { suggestions, tracingId: envelope?.tracingId };
- },
- {
- 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,
- },
- );
+ // Paint the persisted batch; generate (an LLM call) only when there is none —
+ // once per scope + entry, so a failure is not retried on every render.
+ const requested = useSingleton(() => new Set<string>());
+ useEffect(() => {
+ const current = paramsRef.current;
+ if (!key || !current) return;
+ let cancelled = false;
+ void builderSuggestionReplica.hydrate(current, scope).then(() => {
+ settled.add(`${scope}\u0000${key}`);
+ if (cancelled || useBuilderSuggestionStore.getState().suggestionMap[key]) return;
+ const entry = `${scope}\u0000${key}`;
+ if (requested.has(entry)) return;
+ requested.add(entry);
+ builderSuggestionReplica.fetch(paramsRef.current ?? current, { scope }).catch(ignore);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [key, scope]);
const refresh = useCallback(() => {
- markRegenerated(data?.tracingId);
- // 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]);
+ const current = paramsRef.current;
+ if (!key || !current) return;
+ markRegenerated(batch?.tracingId);
+ // Drop the rejected batch from memory and its persisted row (skeleton shows),
+ // so a failed regeneration never restores it on the next visit; then
+ // generate a fresh one from the latest context.
+ settled.add(`${scope}\u0000${key}`);
+ builderSuggestionReplica.remove(key, scope);
+ builderSuggestionReplica.fetch(current, { fresh: true, scope }).catch(ignore);
+ }, [batch?.tracingId, key, markRegenerated, scope]);
return {
error,
- isLoading: !!key && isLoading,
+ // Nothing to paint yet: hydrating, or generating.
+ isLoading: !!key && !batch && !error,
refresh,
- suggestions: data?.suggestions ?? [],
- tracingId: data?.tracingId,
+ suggestions: batch?.suggestions ?? EMPTY_SUGGESTIONS,
+ tracingId: batch?.tracingId,
};
};
diff --git a/src/features/RecommendTaskTemplates/const.ts b/src/features/RecommendTaskTemplates/const.ts
new file mode 100644
index 00000000000..29bd2785182
--- /dev/null
+++ b/src/features/RecommendTaskTemplates/const.ts
@@ -0,0 +1,7 @@
+/**
+ * Replica name of the daily recommendations (`dailyRecommendResource`). Kept
+ * dependency-free so the user store can revalidate it by name: importing the
+ * resource there would evaluate `defineReplica` inside the `@/libs/replica` ↔
+ * `@/store/user` import cycle, before the replica module has initialized.
+ */
+export const TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA = 'taskTemplateDailyRecommend';
diff --git a/src/features/RecommendTaskTemplates/projection.ts b/src/features/RecommendTaskTemplates/projection.ts
new file mode 100644
index 00000000000..3c7d7b3d074
--- /dev/null
+++ b/src/features/RecommendTaskTemplates/projection.ts
@@ -0,0 +1,123 @@
+import type {
+ TaskTemplate,
+ TaskTemplateConnector,
+ TaskTemplateConnectorSource,
+} from '@lobechat/const';
+
+import type { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import { cacheScope, defineReplica, replicaKeys } from '@/libs/replica';
+
+import { TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA } from './const';
+import { getProviderMeta } from './providerMeta';
+
+export interface DailyRecommendParams {
+ count: number;
+ /**
+ * Resolved interests, `null` while the user state is still initializing. Not
+ * part of the entry or sync key: the persisted row paints before interests
+ * resolve, and an interest edit refetches through `revalidateReplica`.
+ */
+ interestKeys: string[] | null;
+ locale: string;
+ /** Session refresh seed ('' = the day's default batch). */
+ refreshSeed: string;
+}
+
+export const dailyRecommendKey = ({
+ count,
+ locale,
+ refreshSeed,
+}: Pick<DailyRecommendParams, 'count' | 'locale' | 'refreshSeed'>) =>
+ [refreshSeed, count, locale].join('\u0000');
+
+const isRecord = (value: unknown): value is Record<PropertyKey, unknown> =>
+ typeof value === 'object' && value !== null;
+
+const isTaskTemplateConnectorSource = (value: unknown): value is TaskTemplateConnectorSource =>
+ value === 'composio' || value === 'lobehub';
+
+const isTaskTemplateConnector = (value: unknown): value is TaskTemplateConnector => {
+ if (!isRecord(value)) return false;
+ if (typeof value.identifier !== 'string') return false;
+ if (!isTaskTemplateConnectorSource(value.source)) return false;
+ return (
+ typeof value.required === 'boolean' &&
+ Boolean(getProviderMeta({ identifier: value.identifier, source: value.source }))
+ );
+};
+
+/**
+ * v2.2.6 returned legacy recommendation rows before `connectors` and text fields existed.
+ * Drop legacy rows from version-skewed self-host servers so they cannot crash the home screen.
+ */
+const isTaskTemplateRecommendation = (value: unknown): value is TaskTemplate => {
+ if (!isRecord(value)) return false;
+ return (
+ typeof value.category === 'string' &&
+ Array.isArray(value.connectors) &&
+ value.connectors.every(isTaskTemplateConnector) &&
+ typeof value.cronPattern === 'string' &&
+ typeof value.description === 'string' &&
+ typeof value.id === 'number' &&
+ typeof value.identifier === 'string' &&
+ typeof value.instruction === 'string' &&
+ Array.isArray(value.interests) &&
+ typeof value.title === 'string'
+ );
+};
+
+/** Treat non-array payloads as empty and drop rows the cards cannot render. */
+export const normalizeTaskTemplateRecommendations = (templates: unknown): TaskTemplate[] =>
+ Array.isArray(templates) ? templates.filter(isTaskTemplateRecommendation) : [];
+
+/**
+ * Continues the persisted row shape the SWR key carried as
+ * `taskTemplate:listDailyRecommend:v2` (connectors + text fields). Bump it when
+ * the row shape changes incompatibly; older rows then never hydrate.
+ */
+const DAILY_RECOMMEND_VERSION = 2;
+
+/**
+ * Home / empty-state task-template recommendations, one entry per refresh
+ * seed + count + locale. localStorage so the home cards paint on the first
+ * frame of a reload; every refresh mints a seed, so old rows are evicted past
+ * the cap.
+ *
+ * The name deliberately matches no `CACHE_TIERS` pattern (`taskTemplate:`), so
+ * the replica's SWR sync key is never persisted a second time by the SWR tier.
+ */
+export const dailyRecommendResource = defineReplica<DailyRecommendParams, TaskTemplate[]>({
+ key: dailyRecommendKey,
+ name: TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA,
+ persist: { maxEntries: 10 },
+ storage: 'localStorage',
+ // Interests stay out of the sync key (see `DailyRecommendParams.interestKeys`).
+ syncKey: (params) =>
+ replicaKeys.sync(
+ TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA,
+ DAILY_RECOMMEND_VERSION,
+ cacheScope.get(),
+ dailyRecommendKey(params),
+ { count: params.count, locale: params.locale, refreshSeed: params.refreshSeed },
+ ),
+ version: DAILY_RECOMMEND_VERSION,
+});
+
+/**
+ * The persisted recommendations of an entry, read synchronously from the
+ * replica's own localStorage row. The replica hydrates asynchronously, after
+ * the first paint; this lets that first frame show the cards, not a skeleton.
+ */
+export const peekDailyRecommendations = (
+ params: DailyRecommendParams,
+ scope: string,
+): unknown[] | undefined => {
+ if (!cacheScope.canHydrate?.()) return undefined;
+ const storage = dailyRecommendResource.storage as
+ LocalStorageQueryProjectionStorage<TaskTemplate[]> | undefined;
+ const data = storage?.getSync?.({
+ queryKey: dailyRecommendResource.storageKey(params),
+ scope,
+ })?.data;
+ return Array.isArray(data) ? data : undefined;
+};
diff --git a/src/features/RecommendTaskTemplates/recommendationStore.ts b/src/features/RecommendTaskTemplates/recommendationStore.ts
new file mode 100644
index 00000000000..3861fd6912f
--- /dev/null
+++ b/src/features/RecommendTaskTemplates/recommendationStore.ts
@@ -0,0 +1,90 @@
+import type { TaskTemplate } from '@lobechat/const';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+} from '@/libs/replica';
+import { taskTemplateService } from '@/services/taskTemplate';
+import { createDevtools } from '@/store/middleware/createDevtools';
+
+import {
+ type DailyRecommendParams,
+ dailyRecommendResource,
+ normalizeTaskTemplateRecommendations,
+} from './projection';
+
+export const fetchDailyRecommendations = async ({
+ count,
+ interestKeys,
+ locale,
+ refreshSeed,
+}: DailyRecommendParams): Promise<TaskTemplate[]> => {
+ // The sync only runs once interests resolve (see `useDailyBriefRecommendationsUI`).
+ if (!interestKeys) throw new Error('[taskTemplate:listDailyRecommend] interests not resolved');
+ const result = await taskTemplateService.listDailyRecommend(interestKeys, {
+ count,
+ locale,
+ refreshSeed: refreshSeed || undefined,
+ });
+ return normalizeTaskTemplateRecommendations(result?.data);
+};
+
+export interface TaskTemplateRecommendationStoreState {
+ /**
+ * `dailyRecommendErrorId(scope, key)` → the last read failure, cleared by a
+ * success. Scoped, so one identity's failure never hides another's cards.
+ * Covers reads started outside `useSync` (`slice.fetch`), whose failure the
+ * sync's own `error` never sees.
+ */
+ dailyRecommendErrorMap: Record<string, unknown>;
+ /** `dailyRecommendKey(params)` → the recommended templates. */
+ dailyRecommendMap: Record<string, TaskTemplate[]>;
+ dailyRecommendReplica: ReplicaState<TaskTemplate[]>;
+}
+
+export const initialTaskTemplateRecommendationState: TaskTemplateRecommendationStoreState = {
+ dailyRecommendErrorMap: {},
+ dailyRecommendMap: {},
+ dailyRecommendReplica: createReplicaState(),
+};
+
+const devtools = createDevtools('taskTemplateRecommendation');
+
+export const useTaskTemplateRecommendationStore =
+ createWithEqualityFn<TaskTemplateRecommendationStoreState>()(
+ devtools(() => initialTaskTemplateRecommendationState),
+ shallow,
+ );
+
+export const dailyRecommendErrorId = (scope: string, key: string) => `${scope}\u0000${key}`;
+
+const setError = (id: string, error: unknown) => {
+ const { dailyRecommendErrorMap } = useTaskTemplateRecommendationStore.getState();
+ if (dailyRecommendErrorMap[id] === error) return;
+ const next = { ...dailyRecommendErrorMap };
+ if (error === undefined) delete next[id];
+ else next[id] = error;
+ useTaskTemplateRecommendationStore.setState({ dailyRecommendErrorMap: next });
+};
+
+export const dailyRecommendReplica = createReplicaSlice(dailyRecommendResource, {
+ actionPrefix: 'taskTemplate/dailyRecommend',
+ effects: {
+ onApplied: (_data, _params, { key, scope }) =>
+ setError(dailyRecommendErrorId(scope, key), undefined),
+ onError: (error, _params, { isActive, key, scope }) => {
+ if (isActive && key) setError(dailyRecommendErrorId(scope, key), error);
+ },
+ },
+ fetcher: fetchDailyRecommendations,
+ get: useTaskTemplateRecommendationStore.getState,
+ // A row persisted by an older or corrupted write is not a list: fetch instead.
+ isHydratable: (cached) => Array.isArray(cached),
+ set: useTaskTemplateRecommendationStore.setState,
+ stateKey: 'dailyRecommendReplica',
+ view: recordLens<TaskTemplateRecommendationStoreState, TaskTemplate[]>('dailyRecommendMap'),
+});
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
index d25ef63a8e8..44722851e75 100644
--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
@@ -1,13 +1,24 @@
/**
* @vitest-environment happy-dom
*/
-import type { TaskTemplate } from '@lobechat/const';
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { randomUUID } from 'node:crypto';
-import { TASK_TEMPLATE_RECOMMENDATION_CACHE_VERSION, taskTemplateKeys } from '@/libs/swr/keys';
+import type { TaskTemplate } from '@lobechat/const';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';
import { taskTemplateService } from '@/services/taskTemplate';
+import { dailyRecommendKey, dailyRecommendResource } from './projection';
+import {
+ initialTaskTemplateRecommendationState,
+ useTaskTemplateRecommendationStore,
+} from './recommendationStore';
import {
resolveDailyBriefRecommendationDisplayMode,
resolveDailyBriefRecommendationRequest,
@@ -15,25 +26,23 @@ import {
} from './useDailyBriefRecommendationsUI';
const {
- mockMutate,
+ mockRefreshSeed,
mockSetRefreshSeed,
mockUseFetchBriefs,
mockUseFetchLobehubConnectorConnections,
mockUseFetchUserComposioConnections,
mockUseResolvedInterestKeys,
- mockUseSWR,
} = vi.hoisted(() => ({
- mockMutate: vi.fn(),
+ mockRefreshSeed: { value: '' },
mockSetRefreshSeed: vi.fn(),
mockUseFetchBriefs: vi.fn(),
mockUseFetchLobehubConnectorConnections: vi.fn(),
mockUseFetchUserComposioConnections: vi.fn(),
mockUseResolvedInterestKeys: vi.fn(),
- mockUseSWR: vi.fn(),
}));
vi.mock('ahooks', () => ({
- useSessionStorageState: () => ['', mockSetRefreshSeed],
+ useSessionStorageState: () => [mockRefreshSeed.value, mockSetRefreshSeed],
}));
vi.mock('antd', async (importOriginal) => ({
@@ -50,10 +59,6 @@ vi.mock('react-i18next', () => ({
}),
}));
-vi.mock('swr', () => ({
- default: mockUseSWR,
-}));
-
// The brief feed is a replica now: the hook only needs the feed to hold a
// value for the scope (`briefListMap` has an entry) to leave its skeleton —
// see `briefListSelectors.isBriefsInit`.
@@ -107,7 +112,7 @@ const template = {
} satisfies TaskTemplate;
describe('resolveDailyBriefRecommendationRequest', () => {
- it('keeps the cache key available while interests are still initializing', () => {
+ it('keeps the entry key available while interests are still initializing', () => {
const loading = resolveDailyBriefRecommendationRequest({
interestKeys: null,
isLogin: true,
@@ -123,55 +128,72 @@ describe('resolveDailyBriefRecommendationRequest', () => {
refreshSeed: '',
});
- expect(loading.key).toEqual(ready.key);
+ expect(dailyRecommendKey(loading.params!)).toEqual(dailyRecommendKey(ready.params!));
expect(loading.shouldFetch).toBe(false);
expect(ready.shouldFetch).toBe(true);
});
- it('does not include interests in the persisted recommendation cache key', () => {
+ it('does not include interests in the persisted entry or the sync key', () => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue('user-1:personal');
const ai = resolveDailyBriefRecommendationRequest({
interestKeys: ['ai'],
isLogin: true,
locale: 'zh-CN',
recommendationCount: 3,
refreshSeed: 'seed',
- });
+ }).params!;
const research = resolveDailyBriefRecommendationRequest({
interestKeys: ['research'],
isLogin: true,
locale: 'zh-CN',
recommendationCount: 3,
refreshSeed: 'seed',
- });
+ }).params!;
- expect(ai.key).toEqual(research.key);
- expect(ai.key).toEqual(taskTemplateKeys.listDailyRecommend('seed', 3, 'zh-CN'));
- expect(ai.key?.[0]).toBe(
- `taskTemplate:listDailyRecommend:v${TASK_TEMPLATE_RECOMMENDATION_CACHE_VERSION}`,
+ expect(dailyRecommendResource.storageKey(ai)).toEqual(
+ dailyRecommendResource.storageKey(research),
);
+ expect(dailyRecommendResource.syncKey!(ai)).toEqual(dailyRecommendResource.syncKey!(research));
});
- it('keeps refresh seed, count, and locale in the cache key', () => {
- expect(
- resolveDailyBriefRecommendationRequest({
- interestKeys: [],
- isLogin: true,
+ // The SWR tier persists every key whose serialized form contains a
+ // CACHE_TIERS pattern; the replica must stay the only persisted copy.
+ it('keeps the replica sync key out of the SWR persistence tiers', () => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue('user-1:personal');
+ const serialized = JSON.stringify(
+ dailyRecommendResource.syncKey!({
+ count: 3,
+ interestKeys: ['ai'],
locale: 'zh-CN',
- recommendationCount: 3,
- refreshSeed: 'seed-a',
- }).key,
- ).not.toEqual(
- resolveDailyBriefRecommendationRequest({
- interestKeys: [],
- isLogin: true,
- locale: 'en-US',
- recommendationCount: 6,
- refreshSeed: 'seed-b',
- }).key,
+ refreshSeed: '',
+ }),
);
+
+ expect(dailyRecommendResource.storage).toBeDefined();
+ expect(dailyRecommendResource.namespace).toBe('replica:taskTemplateDailyRecommend:v2');
+ expect(
+ [...CACHE_TIERS.idb, ...CACHE_TIERS.local].filter((p) => serialized.includes(p)),
+ ).toEqual([]);
});
- it('disables the cache key before login', () => {
+ it('keeps refresh seed, count, and locale in the entry key', () => {
+ const key = (locale: string, recommendationCount: number, refreshSeed: string) =>
+ dailyRecommendKey(
+ resolveDailyBriefRecommendationRequest({
+ interestKeys: [],
+ isLogin: true,
+ locale,
+ recommendationCount,
+ refreshSeed,
+ }).params!,
+ );
+
+ expect(key('zh-CN', 3, 'seed-a')).not.toEqual(key('zh-CN', 3, 'seed-b'));
+ expect(key('zh-CN', 3, 'seed-a')).not.toEqual(key('en-US', 3, 'seed-a'));
+ expect(key('zh-CN', 3, 'seed-a')).not.toEqual(key('zh-CN', 6, 'seed-a'));
+ });
+
+ it('disables the read before login', () => {
expect(
resolveDailyBriefRecommendationRequest({
interestKeys: [],
@@ -180,7 +202,7 @@ describe('resolveDailyBriefRecommendationRequest', () => {
recommendationCount: 3,
refreshSeed: '',
}),
- ).toEqual({ key: null, shouldFetch: false });
+ ).toEqual({ params: null, shouldFetch: false });
});
});
@@ -242,38 +264,56 @@ describe('resolveDailyBriefRecommendationDisplayMode', () => {
});
});
+/** A fresh SWR cache per render: what a page reload starts from. */
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** Never-resolving read: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const params = (overrides: { count?: number; refreshSeed?: string } = {}) => ({
+ count: overrides.count ?? 3,
+ interestKeys: ['coding'],
+ locale: 'en-US',
+ refreshSeed: overrides.refreshSeed ?? '',
+});
+
describe('useDailyBriefRecommendationsUI', () => {
+ let scope = '';
+
+ const seed = (data: unknown, overrides?: { count?: number; refreshSeed?: string }) =>
+ dailyRecommendResource.storage!.set(
+ { queryKey: dailyRecommendResource.storageKey(params(overrides)), scope },
+ { data: data as TaskTemplate[], updatedAt: 1 },
+ );
+
beforeEach(() => {
vi.clearAllMocks();
+ scope = `task-template-user-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useTaskTemplateRecommendationStore.setState(initialTaskTemplateRecommendationState));
+ mockRefreshSeed.value = '';
mockUseResolvedInterestKeys.mockReturnValue(['coding']);
- mockUseSWR.mockReturnValue({
- data: { data: [template], success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
- });
- });
-
- it('returns cards when recommendations are loaded and forwards locale/count inputs', async () => {
vi.mocked(taskTemplateService.listDailyRecommend).mockResolvedValue({
data: [template],
success: true,
});
+ });
- const { result } = renderHook(() => useDailyBriefRecommendationsUI({ count: 2 }));
+ afterEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+ });
- expect(result.current).toMatchObject({
- isValidating: false,
- mode: 'cards',
- templates: [template],
+ it('returns cards when recommendations are loaded and forwards locale/count inputs', async () => {
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI({ count: 2 }), {
+ wrapper,
});
- expect(mockUseSWR.mock.calls[0][0]).toEqual(
- taskTemplateKeys.listDailyRecommend('', 2, 'en-US'),
- );
-
- const fetcher = mockUseSWR.mock.calls[0][1];
- await fetcher();
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ expect(result.current).toMatchObject({ templates: [template] });
expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledWith(['coding'], {
count: 2,
locale: 'en-US',
@@ -281,168 +321,558 @@ describe('useDailyBriefRecommendationsUI', () => {
});
});
- it('keeps validating state visible while cached cards remain mounted', () => {
- mockUseSWR.mockReturnValue({
- data: { data: [template], success: true },
- isLoading: false,
- isValidating: true,
- mutate: mockMutate,
- });
+ // Regression: the recommendations were persisted by the SWR localStorage tier
+ // (`taskTemplate:` in CACHE_TIERS). They are a localStorage replica now: a
+ // reload paints the persisted cards before the network answers.
+ it('paints persisted cards on reload while the request is still pending', async () => {
+ await seed([template]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
-
- expect(result.current).toMatchObject({ isValidating: true, mode: 'cards' });
- });
-
- it('drops recommendations that are missing connectors', () => {
- const templateWithoutConnectors = {
- category: 'engineering',
- cronPattern: '0 9 * * *',
- description: 'Description',
- id: 102,
- identifier: 'legacy-daily-engineering',
- instruction: 'Instruction',
- interests: ['coding'],
- title: 'Legacy title',
- } satisfies Omit<TaskTemplate, 'connectors'>;
- mockUseSWR.mockReturnValue({
- data: { data: [templateWithoutConnectors], success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ expect(result.current).toMatchObject({ isValidating: true, templates: [template] });
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1);
+ });
+
+ it('paints persisted cards before interests resolve, then refreshes once they do', async () => {
+ await seed([template]);
+ mockUseResolvedInterestKeys.mockReturnValue(null);
+ const fresh = { ...template, id: 202, title: 'Fresh' };
+ vi.mocked(taskTemplateService.listDailyRecommend).mockResolvedValue({
+ data: [fresh],
+ success: true,
});
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
- expect(result.current).toEqual({ mode: 'hidden' });
- expect(mockUseFetchUserComposioConnections).toHaveBeenCalledWith(false);
- expect(mockUseFetchLobehubConnectorConnections).toHaveBeenCalledWith(false);
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ expect(result.current).toMatchObject({ templates: [template] });
+ expect(taskTemplateService.listDailyRecommend).not.toHaveBeenCalled();
+
+ mockUseResolvedInterestKeys.mockReturnValue(['coding']);
+ rerender();
+
+ await waitFor(() => expect(result.current).toMatchObject({ templates: [fresh] }));
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows the skeleton while nothing is persisted and the first read is pending', async () => {
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1));
+ expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 });
});
- it('drops recommendations with malformed connector entries', () => {
- const templateWithMalformedConnectors = {
- ...template,
- connectors: [null],
- };
- mockUseSWR.mockReturnValue({
- data: { data: [templateWithMalformedConnectors], success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
+ it('persists the fetched cards for the next session', async () => {
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ await waitFor(async () => {
+ const row = await dailyRecommendResource.storage!.get({
+ queryKey: dailyRecommendResource.storageKey(params()),
+ scope,
+ });
+ expect(row?.data).toEqual([template]);
});
+ });
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ it('never paints another identity’s persisted cards', async () => {
+ await dailyRecommendResource.storage!.set(
+ { queryKey: dailyRecommendResource.storageKey(params()), scope: 'someone-else:personal' },
+ { data: [{ ...template, title: 'Other user' }], updatedAt: 1 },
+ );
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
- expect(result.current).toEqual({ mode: 'hidden' });
- expect(mockUseFetchUserComposioConnections).toHaveBeenCalledWith(false);
- expect(mockUseFetchLobehubConnectorConnections).toHaveBeenCalledWith(false);
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1));
+ expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 });
});
- it('drops recommendations with unknown connector identifiers', () => {
- const templateWithUnknownConnector = {
- ...template,
- connectors: [{ identifier: 'nonexistent-x', required: true, source: 'lobehub' }],
- };
- mockUseSWR.mockReturnValue({
- data: { data: [templateWithUnknownConnector], success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
+ it('keeps the previous cards on screen while a refresh seed loads', async () => {
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+ mockRefreshSeed.value = 'next-seed';
+ rerender();
+
+ await waitFor(() =>
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenLastCalledWith(['coding'], {
+ count: 3,
+ locale: 'en-US',
+ refreshSeed: 'next-seed',
+ }),
+ );
+ expect(result.current).toMatchObject({ mode: 'cards', templates: [template] });
+ });
+
+ it('removes a created card and persists the shorter list', async () => {
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ if (result.current.mode !== 'cards') return;
+
+ const { onCreated } = result.current;
+ act(() => onCreated(template.id));
+
+ expect(result.current).toEqual({ mode: 'hidden' });
+ await waitFor(async () => {
+ const row = await dailyRecommendResource.storage!.get({
+ queryKey: dailyRecommendResource.storageKey(params()),
+ scope,
+ });
+ expect(row?.data).toEqual([]);
});
+ });
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ it('rolls a dismissed card back when the server refuses', async () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ let reject!: (error: unknown) => void;
+ vi.mocked(taskTemplateService.dismiss).mockImplementation(
+ () => new Promise((_, rejectPromise) => (reject = rejectPromise)),
+ );
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ if (result.current.mode !== 'cards') return;
+
+ let dismissing: Promise<void> | undefined;
+ const { onDismiss } = result.current;
+ act(() => {
+ dismissing = onDismiss(template.id) as unknown as Promise<void>;
+ });
expect(result.current).toEqual({ mode: 'hidden' });
+
+ await act(async () => {
+ reject(new Error('dismiss failed'));
+ await dismissing;
+ });
+
+ expect(result.current).toMatchObject({ mode: 'cards', templates: [template] });
+ expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:dismiss]', expect.any(Error));
+ });
+
+ it('drops persisted rows the cards cannot render', async () => {
+ await seed([
+ template,
+ null,
+ { ...template, connectors: [null], id: 103 },
+ {
+ ...template,
+ connectors: [{ identifier: 'nonexistent-x', required: true, source: 'lobehub' }],
+ id: 104,
+ },
+ { category: 'engineering', cronPattern: '0 9 * * *', id: 'oss-intel-daily', interests: [] },
+ ]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ expect(result.current).toMatchObject({ templates: [template] });
+ });
+
+ it('treats a non-array response as empty', async () => {
+ vi.mocked(taskTemplateService.listDailyRecommend).mockResolvedValue({
+ data: { ...template },
+ success: true,
+ } as any);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalled());
+ await waitFor(() => expect(result.current).toEqual({ mode: 'hidden' }));
expect(mockUseFetchUserComposioConnections).toHaveBeenCalledWith(false);
expect(mockUseFetchLobehubConnectorConnections).toHaveBeenCalledWith(false);
});
- it('treats non-array recommendation payloads as empty data', () => {
- mockUseSWR.mockReturnValue({
- data: { data: { ...template }, success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
- });
+ it('logs a failed first load and hides instead of rendering an empty state', async () => {
+ const error = new Error('market down');
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(taskTemplateService.listDailyRecommend).mockRejectedValue(error);
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() =>
+ expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:listDailyRecommend]', error),
+ );
expect(result.current).toEqual({ mode: 'hidden' });
- expect(mockUseFetchUserComposioConnections).toHaveBeenCalledWith(false);
- expect(mockUseFetchLobehubConnectorConnections).toHaveBeenCalledWith(false);
});
- it('normalizes cached rows before removing a card', () => {
- mockUseSWR.mockReturnValue({
- data: { data: [template, null], success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
+ it('keeps persisted cards when the background refresh fails', async () => {
+ await seed([template]);
+ const error = new Error('market down');
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(taskTemplateService.listDailyRecommend).mockRejectedValue(error);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+
+ await waitFor(() =>
+ expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:listDailyRecommend]', error),
+ );
+ expect(result.current).toMatchObject({ mode: 'cards', templates: [template] });
+ });
+
+ // Regression: the retained batch was copied into an identity-agnostic ref, so
+ // after a scope switch with the same entry key the previous identity's cards
+ // painted while the new identity's read was pending.
+ it('drops the retained cards when the identity switches', async () => {
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+ scope = `task-template-user-${randomUUID()}:personal`;
+ rerender();
+
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(2));
+ expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 });
+ });
+
+ // Regression: dismiss targeted only the new seed's (still empty) entry, so a
+ // dismiss on the retained cards during a refresh was silently dropped.
+ it('dismisses a retained card while the refresh seed loads', async () => {
+ vi.mocked(taskTemplateService.dismiss).mockResolvedValue(undefined as any);
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+ mockRefreshSeed.value = 'next-seed';
+ rerender();
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(2));
+ if (result.current.mode !== 'cards') throw new Error('expected retained cards');
+
+ const { onDismiss } = result.current;
+ await act(async () => {
+ await onDismiss(template.id);
});
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ expect(taskTemplateService.dismiss).toHaveBeenCalledWith(template.id);
+ expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 });
+ await waitFor(async () => {
+ const row = await dailyRecommendResource.storage!.get({
+ queryKey: dailyRecommendResource.storageKey(params()),
+ scope,
+ });
+ expect(row?.data).toEqual([]);
+ });
+ });
- expect(result.current.mode).toBe('cards');
- if (result.current.mode !== 'cards') return;
+ // Regression: the retained batch was eligible only while `!error`, so a
+ // failed manual refresh dropped the cards and hid the section.
+ it('keeps the retained cards when a refresh seed fails', async () => {
+ const error = new Error('market down');
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ vi.mocked(taskTemplateService.listDailyRecommend).mockRejectedValue(error);
+ mockRefreshSeed.value = 'next-seed';
+ rerender();
- result.current.onCreated(template.id);
+ await waitFor(() =>
+ expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:listDailyRecommend]', error),
+ );
+ expect(result.current).toMatchObject({ mode: 'cards', templates: [template] });
+ });
- const updater = mockMutate.mock.calls[0][0] as (current?: {
- data: unknown;
- success: boolean;
- }) => unknown;
- expect(updater({ data: [template, null], success: true })).toEqual({
- data: [],
+ // The home rail, its visibility probe and the task empty state each mount
+ // this hook: they share one read.
+ it('sends one read for several mounted views', async () => {
+ const { result } = renderHook(
+ () => [
+ useDailyBriefRecommendationsUI(),
+ useDailyBriefRecommendationsUI(),
+ useDailyBriefRecommendationsUI(),
+ ],
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current[0]).toMatchObject({ mode: 'cards' }));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: every mounted view forced its own `revalidate` once the
+ // interests resolved, so N views sent N reads.
+ it('sends one read for several views once interests resolve', async () => {
+ await seed([template]);
+ mockUseResolvedInterestKeys.mockReturnValue(null);
+ const fresh = { ...template, id: 202, title: 'Fresh' };
+ vi.mocked(taskTemplateService.listDailyRecommend).mockResolvedValue({
+ data: [fresh],
success: true,
});
- expect(updater({ data: { ...template }, success: true })).toEqual({
- data: [],
- success: true,
+
+ const { rerender, result } = renderHook(
+ () => [
+ useDailyBriefRecommendationsUI(),
+ useDailyBriefRecommendationsUI(),
+ useDailyBriefRecommendationsUI(),
+ ],
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current[0]).toMatchObject({ templates: [template] }));
+ expect(taskTemplateService.listDailyRecommend).not.toHaveBeenCalled();
+
+ mockUseResolvedInterestKeys.mockReturnValue(['coding']);
+ rerender();
+
+ await waitFor(() => expect(result.current[2]).toMatchObject({ templates: [fresh] }));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: the card actions filtered the raw hydrated row, so a malformed
+ // row next to a valid card threw on `tmpl.id` and the dismiss never reached
+ // the server.
+ it('dismisses a card from a persisted row that also holds malformed entries', async () => {
+ await seed([template, null]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+ vi.mocked(taskTemplateService.dismiss).mockResolvedValue(undefined as any);
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ if (result.current.mode !== 'cards') throw new Error('expected cards');
+
+ const { onDismiss } = result.current;
+ await act(async () => {
+ await onDismiss(template.id);
});
- expect(mockMutate.mock.calls[0][1]).toEqual({ revalidate: false });
- });
-
- it('drops legacy recommendations from pre-Market task-template servers', () => {
- const legacyServerTemplate = {
- category: 'engineering',
- cronPattern: '0 9 * * *',
- id: 'oss-intel-daily',
- interests: ['coding'],
- requiresSkills: [{ provider: 'github', source: 'lobehub' }],
- };
- mockUseSWR.mockReturnValue({
- data: { data: [legacyServerTemplate], success: true },
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
+
+ expect(taskTemplateService.dismiss).toHaveBeenCalledWith(template.id);
+ expect(consoleErrorSpy).not.toHaveBeenCalledWith('[taskTemplate:dismiss]', expect.anything());
+ expect(result.current).not.toMatchObject({ mode: 'cards' });
+ });
+
+ it('removes a created card from a persisted row that also holds malformed entries', async () => {
+ await seed([template, null]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ if (result.current.mode !== 'cards') throw new Error('expected cards');
+
+ const { onCreated } = result.current;
+ expect(() => act(() => onCreated(template.id))).not.toThrow();
+ expect(result.current).not.toMatchObject({ mode: 'cards' });
+ });
+
+ // Regression: `revalidateOnMount: false` only holds the first mount, so an
+ // entry key change (here the refresh seed) before the interests resolved ran
+ // the fetcher, which failed with "interests not resolved".
+ it('holds the read until interests resolve when the entry key changes first', async () => {
+ mockUseResolvedInterestKeys.mockReturnValue(null);
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 }));
+
+ mockRefreshSeed.value = 'next-seed';
+ rerender();
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
});
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ expect(taskTemplateService.listDailyRecommend).not.toHaveBeenCalled();
+ expect(consoleErrorSpy).not.toHaveBeenCalledWith(
+ '[taskTemplate:listDailyRecommend]',
+ expect.anything(),
+ );
+ expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 });
- expect(result.current).toEqual({ mode: 'hidden' });
- expect(mockUseFetchUserComposioConnections).toHaveBeenCalledWith(false);
- expect(mockUseFetchLobehubConnectorConnections).toHaveBeenCalledWith(false);
+ mockUseResolvedInterestKeys.mockReturnValue(['coding']);
+ rerender();
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1);
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledWith(['coding'], {
+ count: 3,
+ locale: 'en-US',
+ refreshSeed: 'next-seed',
+ });
});
- it('logs recommendation request errors instead of treating them as normal empty data', async () => {
+ // Regression: the read started once interests resolve went through
+ // `slice.fetch`, whose failure was only logged, so a failed first load left
+ // the view on its skeleton instead of settling.
+ it('settles a failed first load that started once interests resolved', async () => {
+ mockUseResolvedInterestKeys.mockReturnValue(null);
const error = new Error('market down');
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- mockUseSWR.mockReturnValue({
- error,
- isLoading: false,
- isValidating: false,
- mutate: mockMutate,
+ vi.mocked(taskTemplateService.listDailyRecommend).mockRejectedValue(error);
+
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toEqual({ mode: 'skeleton', skeletonCount: 3 }));
+
+ mockUseResolvedInterestKeys.mockReturnValue(['coding']);
+ rerender();
+
+ await waitFor(() => expect(result.current).toEqual({ mode: 'hidden' }));
+ expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(1);
+ expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:listDailyRecommend]', error);
+ });
+
+ // Regression: the persisted row hydrated through an async SWR fetcher, so a
+ // reload rendered the skeleton for at least its first frame.
+ it('paints persisted cards on the very first render', async () => {
+ await seed([template]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+ const modes: string[] = [];
+
+ renderHook(
+ () => {
+ const state = useDailyBriefRecommendationsUI();
+ modes.push(state.mode);
+ return state;
+ },
+ { wrapper },
+ );
+
+ expect(modes[0]).toBe('cards');
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
});
+ expect(modes.every((mode) => mode === 'cards')).toBe(true);
+ });
- const { result } = renderHook(() => useDailyBriefRecommendationsUI());
+ // Regression: cards painted from the synchronous peek had no store entry
+ // until hydration settled, so a dismiss / create in that window was dropped.
+ it('applies a dismiss made before hydration settles', async () => {
+ const other = { ...template, id: 102, title: 'Other' };
+ await seed([template, other]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+ vi.mocked(taskTemplateService.dismiss).mockResolvedValue(undefined as any);
- try {
- expect(result.current).toEqual({ mode: 'hidden' });
- await waitFor(() =>
- expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:listDailyRecommend]', error),
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ const first = result.current;
+ if (first.mode !== 'cards') throw new Error('expected cards on the first render');
+
+ await act(async () => {
+ await first.onDismiss(template.id);
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(taskTemplateService.dismiss).toHaveBeenCalledWith(template.id);
+ expect(result.current).toMatchObject({ mode: 'cards', templates: [other] });
+ await waitFor(async () => {
+ const row = await dailyRecommendResource.storage!.get({
+ queryKey: dailyRecommendResource.storageKey(params()),
+ scope,
+ });
+ expect(row?.data).toEqual([other]);
+ });
+ });
+
+ it('applies a create made before hydration settles', async () => {
+ const other = { ...template, id: 102, title: 'Other' };
+ await seed([template, other]);
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ const first = result.current;
+ if (first.mode !== 'cards') throw new Error('expected cards on the first render');
+
+ act(() => first.onCreated(template.id));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(result.current).toMatchObject({ mode: 'cards', templates: [other] });
+ });
+
+ // Regression: a dismiss / create on the retained batch during a refresh only
+ // touched the old entry, so the refreshing entry brought the card back when
+ // its response included the same template.
+ it.each(['dismiss', 'create'] as const)(
+ 'carries a %s on the retained batch into the refreshing entry',
+ async (action) => {
+ const other = { ...template, id: 102, title: 'Other' };
+ vi.mocked(taskTemplateService.dismiss).mockResolvedValue(undefined as any);
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), {
+ wrapper,
+ });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ let resolveRefresh!: (value: unknown) => void;
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(
+ () => new Promise((resolve) => (resolveRefresh = resolve)) as any,
);
- } finally {
- consoleErrorSpy.mockRestore();
- }
+ mockRefreshSeed.value = 'next-seed';
+ rerender();
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(2));
+ if (result.current.mode !== 'cards') throw new Error('expected retained cards');
+
+ const { onCreated, onDismiss } = result.current;
+ await act(async () => {
+ if (action === 'dismiss') await onDismiss(template.id);
+ else onCreated(template.id);
+ });
+
+ await act(async () => {
+ resolveRefresh({ data: [template, other], success: true });
+ });
+
+ await waitFor(() => expect(result.current).toMatchObject({ templates: [other] }));
+ await waitFor(async () => {
+ const row = await dailyRecommendResource.storage!.get({
+ queryKey: dailyRecommendResource.storageKey(params({ refreshSeed: 'next-seed' })),
+ scope,
+ });
+ expect(row?.data).toEqual([other]);
+ });
+ },
+ );
+
+ // Regression: a carried dismissal was applied (and persisted) to the
+ // refreshing entry before the server answered, so a refused dismiss that
+ // settled after the refresh left the card removed for good.
+ it('restores a carried dismissal the server refuses after the refresh lands', async () => {
+ const other = { ...template, id: 102, title: 'Other' };
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ let rejectDismiss!: (error: unknown) => void;
+ vi.mocked(taskTemplateService.dismiss).mockImplementation(
+ () => new Promise((_, reject) => (rejectDismiss = reject)) as any,
+ );
+ const { rerender, result } = renderHook(() => useDailyBriefRecommendationsUI(), { wrapper });
+ await waitFor(() => expect(result.current).toMatchObject({ mode: 'cards' }));
+
+ let resolveRefresh!: (value: unknown) => void;
+ vi.mocked(taskTemplateService.listDailyRecommend).mockImplementation(
+ () => new Promise((resolve) => (resolveRefresh = resolve)) as any,
+ );
+ mockRefreshSeed.value = 'next-seed';
+ rerender();
+ await waitFor(() => expect(taskTemplateService.listDailyRecommend).toHaveBeenCalledTimes(2));
+ if (result.current.mode !== 'cards') throw new Error('expected retained cards');
+
+ let dismissing: Promise<void> | undefined;
+ const { onDismiss } = result.current;
+ act(() => {
+ dismissing = onDismiss(template.id) as unknown as Promise<void>;
+ });
+
+ await act(async () => {
+ resolveRefresh({ data: [template, other], success: true });
+ });
+ // Hidden while the dismiss is pending.
+ await waitFor(() => expect(result.current).toMatchObject({ templates: [other] }));
+
+ await act(async () => {
+ rejectDismiss(new Error('dismiss failed'));
+ await dismissing;
+ });
+
+ expect(result.current).toMatchObject({ templates: [template, other] });
+ const row = await dailyRecommendResource.storage!.get({
+ queryKey: dailyRecommendResource.storageKey(params({ refreshSeed: 'next-seed' })),
+ scope,
+ });
+ expect(row?.data).toEqual([template, other]);
+ expect(consoleErrorSpy).toHaveBeenCalledWith('[taskTemplate:dismiss]', expect.any(Error));
});
});
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
index e022ab040c8..3193971c1bb 100644
--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts
@@ -1,17 +1,13 @@
-import type {
- TaskTemplate,
- TaskTemplateConnector,
- TaskTemplateConnectorSource,
-} from '@lobechat/const';
+import type { TaskTemplate, TaskTemplateConnectorSource } from '@lobechat/const';
import { TASK_TEMPLATE_RECOMMEND_COUNT } from '@lobechat/const';
import { createNanoId } from '@lobechat/utils';
import { toast } from '@lobehub/ui';
import { useSessionStorageState } from 'ahooks';
-import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
-import { taskTemplateKeys } from '@/libs/swr/keys';
+import { useSingleton } from '@/hooks/useSingleton';
+import { cacheScope } from '@/libs/replica';
import { taskTemplateService } from '@/services/taskTemplate';
import { useBriefStore } from '@/store/brief';
import { briefListSelectors } from '@/store/brief/selectors';
@@ -19,11 +15,22 @@ import { useToolStore } from '@/store/tool';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/slices/auth/selectors';
-import { getProviderMeta } from './providerMeta';
+import {
+ dailyRecommendKey,
+ type DailyRecommendParams,
+ normalizeTaskTemplateRecommendations,
+ peekDailyRecommendations,
+} from './projection';
+import {
+ dailyRecommendErrorId,
+ dailyRecommendReplica,
+ useTaskTemplateRecommendationStore,
+} from './recommendationStore';
import { useResolvedInterestKeys } from './useResolvedInterestKeys';
const REFRESH_SEED_STORAGE_KEY = 'lobehub:taskTemplate:refreshSeed';
const nextRefreshSeed = createNanoId(8);
+const RECOMMENDATION_DEDUPE_INTERVAL = 10_000;
export type DailyBriefRecommendationsUIState =
| { mode: 'hidden' }
@@ -41,60 +48,6 @@ interface UseDailyBriefRecommendationsUIOptions {
count?: number;
}
-const isRecord = (value: unknown): value is Record<PropertyKey, unknown> =>
- typeof value === 'object' && value !== null;
-
-const isTaskTemplateConnectorSource = (value: unknown): value is TaskTemplateConnectorSource =>
- value === 'composio' || value === 'lobehub';
-
-const isTaskTemplateConnector = (value: unknown): value is TaskTemplateConnector => {
- if (!isRecord(value)) return false;
- if (typeof value.identifier !== 'string') return false;
- if (!isTaskTemplateConnectorSource(value.source)) return false;
- return (
- typeof value.required === 'boolean' &&
- Boolean(getProviderMeta({ identifier: value.identifier, source: value.source }))
- );
-};
-
-const isTaskTemplateRecommendationCandidate = (value: unknown): value is TaskTemplate => {
- if (!isRecord(value)) return false;
- return (
- typeof value.category === 'string' &&
- Array.isArray(value.connectors) &&
- value.connectors.every(isTaskTemplateConnector) &&
- typeof value.cronPattern === 'string' &&
- typeof value.description === 'string' &&
- typeof value.id === 'number' &&
- typeof value.identifier === 'string' &&
- typeof value.instruction === 'string' &&
- Array.isArray(value.interests) &&
- typeof value.title === 'string'
- );
-};
-
-/**
- * v2.2.6 returned legacy recommendation rows before `connectors` and text fields existed.
- * Drop legacy rows from version-skewed self-host servers so they cannot crash the home screen.
- */
-const normalizeTaskTemplateRecommendation = (template: unknown): TaskTemplate | undefined => {
- if (!isTaskTemplateRecommendationCandidate(template)) return undefined;
- return template;
-};
-
-/**
- * Persisted SWR data can be stale or corrupted, for example `{ data: { ... } }`.
- * Treat non-array payloads as empty so home rendering and cache mutations stay defensive.
- */
-const normalizeTaskTemplateRecommendations = (templates: unknown): TaskTemplate[] => {
- if (!Array.isArray(templates)) return [];
-
- return templates.flatMap((template) => {
- const normalized = normalizeTaskTemplateRecommendation(template);
- return normalized ? [normalized] : [];
- });
-};
-
interface ResolveDailyBriefRecommendationRequestParams {
interestKeys: string[] | null;
isLogin: boolean | undefined;
@@ -112,12 +65,11 @@ export const resolveDailyBriefRecommendationRequest = ({
}: ResolveDailyBriefRecommendationRequestParams) => {
const enabled = isLogin === true;
- return {
- key: enabled
- ? taskTemplateKeys.listDailyRecommend(refreshSeed ?? '', recommendationCount, locale)
- : null,
- shouldFetch: enabled && interestKeys !== null,
- };
+ const params: DailyRecommendParams | null = enabled
+ ? { count: recommendationCount, interestKeys, locale, refreshSeed: refreshSeed ?? '' }
+ : null;
+
+ return { params, shouldFetch: enabled && interestKeys !== null };
};
interface ResolveDailyBriefRecommendationDisplayModeParams {
@@ -184,31 +136,44 @@ export function useDailyBriefRecommendationsUI(
}),
[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 { params, shouldFetch: canFetchRecommendations } = recommendationRequest;
+ const key = params ? dailyRecommendKey(params) : undefined;
+ const entry = useTaskTemplateRecommendationStore((s) =>
+ key ? s.dailyRecommendMap[key] : undefined,
+ );
- const { data, error, isLoading, isValidating, mutate } = useSWR(
- recommendationRequest.key,
- recommendationFetcher,
- {
- keepPreviousData: true,
- revalidateIfStale: canFetchRecommendations,
- revalidateOnFocus: false,
- revalidateOnMount: canFetchRecommendations,
- revalidateOnReconnect: false,
- },
+ // The persisted row hydrates as soon as the user is known; the network read
+ // waits for resolved interests (they are sent with the request). Several views
+ // (home rail, its visibility probe, the task empty state) mount this hook:
+ // the dedupe window lets one mounting shortly after another share its read.
+ // `isPaused` holds the network read until the interests resolve, also when
+ // the entry key changes (scope, locale, seed) before they do: the persisted
+ // row still hydrates, and the read starts once they resolve (below).
+ const interestsPendingRef = useRef(interestKeys === null);
+ interestsPendingRef.current = interestKeys === null;
+ const isPaused = useCallback(() => interestsPendingRef.current, []);
+ const {
+ error: syncError,
+ isHydrated,
+ isValidating,
+ } = dailyRecommendReplica.useSync(params, {
+ dedupingInterval: RECOMMENDATION_DEDUPE_INTERVAL,
+ isPaused,
+ revalidateIfStale: canFetchRecommendations,
+ revalidateOnFocus: false,
+ revalidateOnMount: canFetchRecommendations,
+ revalidateOnReconnect: false,
+ });
+ // A failure of either the sync or the `fetch` below lands here.
+ const scope = cacheScope.use();
+ const storedError = useTaskTemplateRecommendationStore((s) =>
+ key ? s.dailyRecommendErrorMap[dailyRecommendErrorId(scope, key)] : undefined,
);
+ const error = syncError ?? storedError;
const waitedForInterestsRef = useRef(false);
useEffect(() => {
- if (!recommendationRequest.key) {
+ if (!key) {
waitedForInterestsRef.current = false;
return;
}
@@ -218,59 +183,170 @@ export function useDailyBriefRecommendationsUI(
return;
}
- if (!waitedForInterestsRef.current) return;
+ if (!waitedForInterestsRef.current || !params) return;
waitedForInterestsRef.current = false;
- void mutate();
- }, [interestKeys, mutate, recommendationRequest.key]);
+ // `fetch` joins a request already in flight for the entry, so every mounted
+ // view resolving its interests in the same frame sends one request (a
+ // `revalidate` per view would force one each).
+ // A failure is stored by the slice effects (`dailyRecommendErrorMap`) and
+ // logged through `error` below.
+ dailyRecommendReplica.fetch(params).catch(() => {});
+ }, [interestKeys, key, params]);
useEffect(() => {
if (error) console.error('[taskTemplate:listDailyRecommend]', error);
}, [error]);
- const handleRefresh = useCallback(() => {
- setRefreshSeed(nextRefreshSeed());
- }, [setRefreshSeed]);
-
- const removeTemplateFromList = useCallback(
- (templateId: number) => {
- mutate(
- (current) =>
- current
- ? {
- ...current,
- data: normalizeTaskTemplateRecommendations(current.data).filter(
- (tmpl) => tmpl.id !== templateId,
- ),
- }
- : current,
- { revalidate: false },
+ // A refresh mints a new seed (a new entry): keep the previous batch on screen
+ // until the new one lands — or after it fails — instead of dropping back to
+ // the skeleton. Only the previous entry's key is remembered and its batch is
+ // read from the store, which a scope switch clears, so another identity's
+ // batch is never shown.
+ const retainedKeyRef = useRef<string | undefined>(undefined);
+ if (!key) retainedKeyRef.current = undefined;
+ else if (entry) retainedKeyRef.current = key;
+ const retainedKey = retainedKeyRef.current;
+ const retained = useTaskTemplateRecommendationStore((s) =>
+ key && retainedKey ? s.dailyRecommendMap[retainedKey] : undefined,
+ );
+ // Until the async hydrate settles, read the persisted row synchronously, so
+ // a reload paints the cards on its first frame instead of the skeleton.
+ const peeked = useMemo(
+ () => (!isHydrated && params ? peekDailyRecommendations(params, scope) : undefined),
+ [isHydrated, params, scope],
+ );
+ const shown = entry ?? (peeked as TaskTemplate[] | undefined) ?? retained;
+ // Card actions target the entry whose batch is on screen.
+ const shownKey = entry || peeked ? key : retained ? retainedKey : undefined;
+
+ // Cards painted from the peek have no store entry yet: seed it (memory only,
+ // the row is already persisted) so an action in that window lands. A later
+ // hydrate only fills an empty entry, so it never overwrites the result.
+ const peekedRef = useRef(peeked);
+ peekedRef.current = peeked;
+ const seedPeeked = useCallback((target: string) => {
+ const batch = peekedRef.current;
+ if (!batch || useTaskTemplateRecommendationStore.getState().dailyRecommendMap[target]) return;
+ dailyRecommendReplica.update(target, () => normalizeTaskTemplateRecommendations(batch), {
+ persist: false,
+ });
+ }, []);
+
+ // Cards created / dismissed from the retained batch while a refresh is in
+ // flight: the refreshing entry may return them again. Keyed by the
+ // refreshing entry (scope + key → template ids):
+ // - `pendingRemovals`: dismissals the server has not confirmed yet, only
+ // hidden on screen, so a refused dismiss leaves nothing to undo;
+ // - `confirmedRemovals`: created cards and confirmed dismissals, removed from
+ // the refreshing entry (and its persisted row) as soon as it holds them.
+ const pendingRemovals = useSingleton(() => new Map<string, Set<number>>());
+ const confirmedRemovals = useSingleton(() => new Map<string, Set<number>>());
+ const [, bumpPendingRemovals] = useReducer((count: number) => count + 1, 0);
+ const refreshingId = key ? `${scope}\u0000${key}` : undefined;
+ const toggleRemoval = (
+ map: Map<string, Set<number>>,
+ id: string,
+ templateId: number,
+ add: boolean,
+ ) => {
+ const ids = map.get(id) ?? new Set<number>();
+ if (add) ids.add(templateId);
+ else ids.delete(templateId);
+ if (ids.size > 0) map.set(id, ids);
+ else map.delete(id);
+ };
+ const applyConfirmedRemovals = useCallback(
+ (target: string, id: string) => {
+ const ids = confirmedRemovals.get(id);
+ const current = useTaskTemplateRecommendationStore.getState().dailyRecommendMap[target];
+ if (!ids || !current) return;
+ confirmedRemovals.delete(id);
+ if (!current.some((tmpl) => ids.has(tmpl?.id))) return;
+ dailyRecommendReplica.update(target, (batch) =>
+ batch
+ ? normalizeTaskTemplateRecommendations(batch).filter((tmpl) => !ids.has(tmpl.id))
+ : batch,
);
},
- [mutate],
+ [confirmedRemovals],
);
+ // Before paint, so a removed card never flashes back in.
+ useLayoutEffect(() => {
+ if (key && refreshingId && entry) applyConfirmedRemovals(key, refreshingId);
+ }, [applyConfirmedRemovals, entry, key, refreshingId]);
+
+ const handleRefresh = useCallback(() => {
+ setRefreshSeed(nextRefreshSeed());
+ }, [setRefreshSeed]);
const handleCreated = useCallback(
(templateId: number) => {
- removeTemplateFromList(templateId);
+ if (!shownKey) return;
+ seedPeeked(shownKey);
+ dailyRecommendReplica.update(shownKey, (current) =>
+ current
+ ? normalizeTaskTemplateRecommendations(current).filter((tmpl) => tmpl.id !== templateId)
+ : current,
+ );
+ if (!key || !refreshingId || shownKey === key) return;
+ toggleRemoval(confirmedRemovals, refreshingId, templateId, true);
+ applyConfirmedRemovals(key, refreshingId);
},
- [removeTemplateFromList],
+ [applyConfirmedRemovals, confirmedRemovals, key, refreshingId, seedPeeked, shownKey],
);
const handleDismiss = useCallback(
async (templateId: number) => {
- removeTemplateFromList(templateId);
+ if (!shownKey) return;
+ seedPeeked(shownKey);
+ if (!useTaskTemplateRecommendationStore.getState().dailyRecommendMap[shownKey]) return;
+ // A dismiss on the retained batch while a refresh is in flight.
+ const carriedTo = key && refreshingId && shownKey !== key ? refreshingId : undefined;
+ if (carriedTo) {
+ toggleRemoval(pendingRemovals, carriedTo, templateId, true);
+ bumpPendingRemovals();
+ }
try {
- await taskTemplateService.dismiss(templateId);
+ // Rolls the card back if the server refuses.
+ await dailyRecommendReplica.optimistic(
+ shownKey,
+ // A hydrated row may still hold rows the cards dropped as malformed.
+ (current) =>
+ normalizeTaskTemplateRecommendations(current).filter((tmpl) => tmpl.id !== templateId),
+ () => taskTemplateService.dismiss(templateId),
+ );
+ if (carriedTo && key) {
+ toggleRemoval(confirmedRemovals, carriedTo, templateId, true);
+ applyConfirmedRemovals(key, carriedTo);
+ }
} catch (error) {
console.error('[taskTemplate:dismiss]', error);
toast.error(t('taskTemplate.action.dismiss.error'));
- mutate();
+ } finally {
+ if (carriedTo) {
+ toggleRemoval(pendingRemovals, carriedTo, templateId, false);
+ bumpPendingRemovals();
+ }
}
},
- [mutate, removeTemplateFromList, t],
+ [
+ applyConfirmedRemovals,
+ confirmedRemovals,
+ key,
+ pendingRemovals,
+ refreshingId,
+ seedPeeked,
+ shownKey,
+ t,
+ ],
);
- const templates = useMemo(() => normalizeTaskTemplateRecommendations(data?.data ?? []), [data]);
+ const hiddenIds = refreshingId ? pendingRemovals.get(refreshingId) : undefined;
+ const templates = useMemo(() => {
+ const normalized = normalizeTaskTemplateRecommendations(shown);
+ return hiddenIds?.size ? normalized.filter((tmpl) => !hiddenIds.has(tmpl.id)) : normalized;
+ // `hiddenIds` is mutated in place; its size (bumped on every change) is the dependency.
+ }, [shown, hiddenIds, hiddenIds?.size]);
const requiredSources = useMemo(() => {
const sources = new Set<TaskTemplateConnectorSource>();
for (const tmpl of templates) {
@@ -287,14 +363,16 @@ export function useDailyBriefRecommendationsUI(
const displayMode = resolveDailyBriefRecommendationDisplayMode({
canFetchRecommendations,
- hasRecommendationKey: Boolean(recommendationRequest.key),
+ hasRecommendationKey: Boolean(key),
hasTemplates: templates.length > 0,
isInit,
- isLoading,
+ // Nothing settled for this entry yet: its persisted row is still being read.
+ isLoading: !isHydrated,
isValidating,
isWaitingForInterestsFetch: interestKeys !== null && waitedForInterestsRef.current,
});
- if (error) return { mode: 'hidden' };
+ // A failed refresh keeps the cards it already has; a failed first load hides.
+ if (error && templates.length === 0) return { mode: 'hidden' };
if (displayMode === 'hidden') return { mode: 'hidden' };
if (displayMode === 'skeleton') return { mode: 'skeleton', skeletonCount: recommendationCount };
diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.ts
index 1e978a23047..484e2f050ec 100644
--- a/src/libs/swr/keys.test.ts
+++ b/src/libs/swr/keys.test.ts
@@ -3,7 +3,6 @@ import { unstable_serialize } from 'swr';
import { describe, expect, it } from 'vitest';
import {
- agentBuilderKeys,
documentCommentKeys,
isAcceptanceListKey,
isDocumentCommentKeyForEvent,
@@ -152,18 +151,3 @@ describe('isDocumentCommentKeyForEvent', () => {
).toBe(false);
});
});
-
-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);
- });
-});
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 33e0e527ecf..54f2df2a722 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -209,27 +209,6 @@ export const isDocumentCommentKeyForEvent = (
return false;
};
-// ---- agent builder (opening-suggestion chips) ---------------------------
-// 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, locale?: string) => [
- 'agentBuilder:suggestions',
- mode,
- builderAgentId,
- targetId,
- locale ?? null,
- ],
- ),
-};
-
// ---- group --------------------------------------------------------------
export const groupKeys = {
/** Agent picker for the "create group" modal. */
@@ -916,25 +895,6 @@ export const topicActionKeys = {
};
// ---- misc remaining domains ---------------------------------------------
-/**
- * Daily task-template recommendation cache schema version. Bump this when the
- * persisted recommendation row shape changes incompatibly so desktop clients
- * stop reading stale localStorage SWR entries.
- */
-export const TASK_TEMPLATE_RECOMMENDATION_CACHE_VERSION = 2;
-const TASK_TEMPLATE_DAILY_RECOMMEND_ROOT = `taskTemplate:listDailyRecommend:v${TASK_TEMPLATE_RECOMMENDATION_CACHE_VERSION}`;
-
-export const taskTemplateKeys = {
- listDailyRecommend: def(
- TASK_TEMPLATE_DAILY_RECOMMEND_ROOT,
- (refreshSeed: unknown, recommendationCount: number, locale: string) => [
- TASK_TEMPLATE_DAILY_RECOMMEND_ROOT,
- refreshSeed,
- recommendationCount,
- locale,
- ],
- ),
-};
export const resourceKeys = {
list: def('resource:list', (params: unknown, workspaceId: string | null) => [
'resource:list',
@@ -986,7 +946,6 @@ export const matchDomain =
*/
export const swrKeys = {
agent: agentConfigKeys,
- agentBuilder: agentBuilderKeys,
agentDocument: agentDocumentSWRKeys,
agentHome: agentHomeKeys,
agentSignal: agentSignalKeys,
@@ -1024,7 +983,6 @@ export const swrKeys = {
serverConfig: serverConfigKeys,
share: shareKeys,
stats: statsKeys,
- taskTemplate: taskTemplateKeys,
thread: threadKeys,
tool: toolKeys,
topic: topicKeys,
diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.ts
index b75273a918b..e8659653dc4 100644
--- a/src/libs/swr/localStorageProvider.test.ts
+++ b/src/libs/swr/localStorageProvider.test.ts
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { bootTiming } from '@/libs/bootTiming';
-import { taskTemplateKeys } from './keys';
import { buildLocalDataKey, localDataCache } from './localDataCache';
import {
CACHE_TIERS,
@@ -104,7 +103,7 @@ describe('createCacheProvider — tiering', () => {
localPatterns: [...CACHE_TIERS.local],
});
const map = provider();
- const key = JSON.stringify(taskTemplateKeys.listDailyRecommend('', 3, 'zh-CN'));
+ const key = JSON.stringify(['taskTemplate:listDailyRecommend:v2', '', 3, 'zh-CN']);
map.set(key, { data: [{ id: 1, title: 'Daily brief' }] });
diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.ts
index 3135094694b..41bedd7277f 100644
--- a/src/store/user/slices/common/action.test.ts
+++ b/src/store/user/slices/common/action.test.ts
@@ -3,9 +3,9 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_PREFERENCE } from '@/const/user';
-import { cacheScope } from '@/libs/replica';
+import { dailyRecommendResource } from '@/features/RecommendTaskTemplates/projection';
+import { cacheScope, replicaKeys } from '@/libs/replica';
import type * as SWRLib from '@/libs/swr';
-import { taskTemplateKeys } from '@/libs/swr/keys';
import { userService } from '@/services/user';
import { useUserStore } from '@/store/user';
import { readUserDisplaySnapshot, writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';
@@ -14,7 +14,6 @@ import { type GlobalServerConfig } from '@/types/serverConfig';
import { type UserInitializationState, type UserPreference } from '@/types/user';
import { withSWR } from '~test-utils';
-import { isTaskTemplateRecommendationKey } from './action';
import { initialCommonState } from './initialState';
const swrMocks = vi.hoisted(() => ({
@@ -66,18 +65,6 @@ afterEach(() => {
});
describe('createCommonSlice', () => {
- describe('isTaskTemplateRecommendationKey', () => {
- it('matches every daily recommendation cache variant', () => {
- expect(
- isTaskTemplateRecommendationKey(taskTemplateKeys.listDailyRecommend('seed', 3, 'zh-CN')),
- ).toBe(true);
- expect(
- isTaskTemplateRecommendationKey(['taskTemplate:listDailyRecommend', 'seed', 3, 'zh-CN']),
- ).toBe(false);
- expect(isTaskTemplateRecommendationKey(['topic:list'])).toBe(false);
- });
- });
-
describe('updateAvatar', () => {
it('should update avatar', async () => {
const { result } = renderHook(() => useUserStore());
@@ -96,6 +83,9 @@ describe('createCommonSlice', () => {
});
describe('updateInterests', () => {
+ const recommendSyncKey = (scope: string) =>
+ replicaKeys.sync(dailyRecommendResource.name, dailyRecommendResource.version, scope, 'k', {});
+
it('optimistically updates user.interests before the service call resolves', async () => {
act(() => {
useUserStore.setState({ user: { id: 'u1', interests: ['old'] } as any });
@@ -124,6 +114,28 @@ describe('createCommonSlice', () => {
expect(updateSpy).toHaveBeenCalledWith(['new']);
});
+ // Regression: interests stay out of the recommendation sync key, so an edit
+ // must re-run every mounted recommendation read of the active scope.
+ it('revalidates the task-template recommendation replica', async () => {
+ act(() => {
+ useUserStore.setState({ user: { id: 'u1', interests: ['old'] } as any });
+ });
+ vi.spyOn(userService, 'updateInterests').mockResolvedValue(undefined as any);
+
+ await useUserStore.getState().updateInterests(['new']);
+
+ const matchers = swrMocks.mutate.mock.calls
+ .map(([key]) => key)
+ .filter((key): key is (key: unknown) => boolean => typeof key === 'function');
+ expect(matchers.some((match) => match(recommendSyncKey(SCOPE)))).toBe(true);
+ expect(matchers.some((match) => match(recommendSyncKey('other-user:personal')))).toBe(false);
+ expect(
+ matchers.some((match) =>
+ match(replicaKeys.sync('agentBuilderSuggestions', 1, SCOPE, 'k', {})),
+ ),
+ ).toBe(false);
+ });
+
it('does not fail the interest update when recommendation cache invalidation fails', async () => {
act(() => {
useUserStore.setState({ user: { id: 'u1', interests: ['old'] } as any });
@@ -133,7 +145,8 @@ describe('createCommonSlice', () => {
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);
+ if (typeof key === 'function' && key(recommendSyncKey(SCOPE)))
+ return Promise.reject(cacheError);
return Promise.resolve(undefined);
});
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index 160c8a38608..92081be2a66 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -7,10 +7,16 @@ import useSWR from 'swr';
import { type PartialDeep } from 'type-fest';
import { DEFAULT_PREFERENCE } from '@/const/user';
+import { TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA } from '@/features/RecommendTaskTemplates/const';
import { analyticsClient } from '@/libs/analytics/client';
-import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';
-import { mutate } from '@/libs/swr';
-import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';
+import {
+ cacheScope,
+ createReplicaSlice,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+ revalidateReplica,
+} from '@/libs/replica';
+import { userKeys } from '@/libs/swr/keys';
import { userService } from '@/services/user';
import { type StoreSetter } from '@/store/types';
import { type UserStore } from '@/store/user';
@@ -50,9 +56,6 @@ 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;
@@ -184,7 +187,11 @@ export class CommonActionImpl {
this.#set({ user: { ...previousUser, interests } }, false, n('updateInterests/optimistic'));
}
await userService.updateInterests(interests);
- void mutate(isTaskTemplateRecommendationKey).catch((error) => {
+ // Recommendations are ranked by interests, which stay out of their sync key.
+ void revalidateReplica({
+ name: TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA,
+ scope: cacheScope,
+ }).catch((error) => {
console.error('[taskTemplate:recommendationCache:invalidate]', error);
});
await this.#get().refreshUserState();