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(agent): move the builtin agents onto @lobechat/replica (#20673)

Arvin Xu9993b179541f
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index f32e8471549..86fe2c07eb2 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -1324,13 +1324,6 @@ export const userKeys = {
checkTrace: def('user:checkTrace', () => ['user:checkTrace']),
initState: def('user:initState', () => ['user:initState']),
};
-export const builtinAgentKeys = {
- init: def('builtinAgent:init', (slug: string, scope: string) => [
- 'builtinAgent:init',
- slug,
- scope,
- ]),
-};
export const imessageKeys = {
bridgeStatus: def('imessage:bridgeStatus', () => ['imessage:bridgeStatus']),
};
@@ -1369,7 +1362,6 @@ export const swrKeys = {
aiModel: aiModelKeys,
auth: authKeys,
brief: briefKeys,
- builtinAgent: builtinAgentKeys,
changelog: changelogKeys,
cron: cronKeys,
device: deviceKeys,
diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.ts
index 3d06e30388e..064e27076f5 100644
--- a/src/libs/swr/localStorageProvider.test.ts
+++ b/src/libs/swr/localStorageProvider.test.ts
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { bootTiming } from '@/libs/bootTiming';
-import { builtinAgentKeys, taskTemplateKeys } from './keys';
+import { taskKeys, taskTemplateKeys } from './keys';
import { buildLocalDataKey, localDataCache } from './localDataCache';
import {
CACHE_TIERS,
@@ -60,13 +60,13 @@ describe('createCacheProvider β€” tiering', () => {
expect(getScopedCacheKey('anon:personal')).not.toBe(getScopedCacheKey('u1:personal'));
});
- it('restores the builtin agent configuration from durable storage after a reload', async () => {
+ it('restores an idb-tier entry from durable storage after a reload, isolated per scope', async () => {
const scope = { value: 's1' };
const options = { idbPatterns: [...CACHE_TIERS.idb], localPatterns: [...CACHE_TIERS.local] };
const { provider } = buildProvider(scope, options);
await provider.hydrateScope?.();
- const key = JSON.stringify(builtinAgentKeys.init('inbox', 's1'));
- const data = { data: { id: 'inbox-1', profile: { fullBodyArtwork: '/custom.webp' } } };
+ const key = JSON.stringify(taskKeys.myList('assigned'));
+ const data = { data: [{ id: 'task-1', title: 'Keep me' }] };
provider().set(key, data);
await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index e30838f58cf..d849788e037 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -483,7 +483,6 @@ export const CACHE_TIERS = {
'message:', // chat messages (conversation + legacy stores)
'topic:', // topic lists / agent view / search
'agent:', // sidebar agent list + agent documents
- 'builtinAgent:', // builtin identity and configuration used by the first paint
'group:detail', // group detail (group list stays in localStorage)
'task:', // task lists + detail
'document:', // editor document content
diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
index 854c385772b..179fa01ca47 100644
--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
@@ -16,6 +16,7 @@ const chatState = vi.hoisted(() => ({
replaceMessages: vi.fn(),
}));
const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);
+const preHydrateBuiltinAgentMock = vi.hoisted(() => vi.fn(async () => true));
vi.mock('@lobechat/builtin-agents', () => ({
BUILTIN_AGENT_SLUGS: { inbox: 'inbox' },
@@ -26,7 +27,9 @@ vi.mock('@/hooks/chatTopicListQuery', () => ({
}));
vi.mock('@/store/agent', () => ({
- useAgentStore: { getState: () => ({ builtinAgentIdMap }) },
+ useAgentStore: {
+ getState: () => ({ builtinAgentIdMap, preHydrateBuiltinAgent: preHydrateBuiltinAgentMock }),
+ },
}));
vi.mock('@/store/agent/selectors', () => ({
@@ -52,6 +55,8 @@ describe('agent chat topic list loader', () => {
beforeEach(() => {
preHydrateTopicListMock.mockClear();
preHydrateTopicListMock.mockResolvedValue(true);
+ preHydrateBuiltinAgentMock.mockClear();
+ preHydrateBuiltinAgentMock.mockResolvedValue(true);
getSidebarTopicListParamsMock.mockReset();
getSidebarTopicListParamsMock.mockReturnValue({ agentId: 'agt_1', pageSize: 20 });
});
@@ -69,6 +74,19 @@ describe('agent chat topic list loader', () => {
expect(preHydrateTopicListMock).toHaveBeenCalledWith({ agentId: 'agt_1', pageSize: 20 });
});
+ it('pre-hydrates the persisted builtin before resolving a builtin slug', async () => {
+ await expect(agentChatTopicListLoader(loaderArgs('inbox'))).resolves.toBeNull();
+
+ expect(preHydrateBuiltinAgentMock).toHaveBeenCalledWith('inbox');
+ expect(getSidebarTopicListParamsMock).toHaveBeenCalledWith({ agentId: 'agt_inbox' });
+ });
+
+ it('does not pre-hydrate a builtin for a concrete agent id', async () => {
+ await agentChatTopicListLoader(loaderArgs('agt_1'));
+
+ expect(preHydrateBuiltinAgentMock).not.toHaveBeenCalled();
+ });
+
it('resolves a builtin slug to its agent id', async () => {
await preHydrateTopicListForRoute('inbox');
diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.ts
index 67c63a00798..05c361309f9 100644
--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts
+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts
@@ -81,6 +81,19 @@ export const preHydrateMessagesForRoute = async (
/** Loader for the agent chat routes (`/agent/:aid`, `/agent/:aid/:topicId`). */
export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {
+ /**
+ * A builtin slug (`inbox`, …) resolves to its id from `builtinAgentIdMap`, so
+ * the persisted builtin agent must be seeded before `resolveRouteAgentId` runs.
+ * The replica's storage read is the only place it can land pre-paint β€” the
+ * mount-time sync (and its hydrate) has not run yet.
+ */
+ if (params.aid && builtinAgentSlugs.has(params.aid)) {
+ await settleWithin(
+ useAgentStore.getState().preHydrateBuiltinAgent(params.aid),
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ );
+ }
+
await Promise.all([
preHydrateTopicListForRoute(params.aid),
preHydrateMessagesForRoute(params.aid, params.topicId),
diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.ts
index defc2f0e092..cd88bb0536a 100644
--- a/src/store/agent/slices/agent/action.test.ts
+++ b/src/store/agent/slices/agent/action.test.ts
@@ -1,14 +1,11 @@
import { CHAT_GROUP_SESSION_ID_PREFIX } from '@lobechat/types';
import { toast } from '@lobehub/ui/base-ui';
import { act, renderHook, waitFor } from '@testing-library/react';
-import { createElement, type PropsWithChildren } from 'react';
-import { SWRConfig, unstable_serialize } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as activeWorkspaceModule from '@/business/client/hooks/useActiveWorkspaceId';
import { cacheScope, createReplicaState, replicaKeys } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr';
-import { builtinAgentKeys } from '@/libs/swr/keys';
import * as cacheScopeModule from '@/libs/swr/useCacheScope';
import { getCacheScope } from '@/libs/swr/useCacheScope';
import { agentService } from '@/services/agent';
@@ -82,6 +79,8 @@ beforeEach(() => {
agentMap: {},
agentNotFoundMap: {},
builtinAgentIdMap: {},
+ builtinAgentMap: {},
+ builtinAgentReplica: createReplicaState(),
availableAgents: undefined,
updateAgentConfigSignal: undefined,
agentDocumentsMap: {},
@@ -98,185 +97,6 @@ afterEach(() => {
});
describe('AgentSlice Actions', () => {
- describe('builtin agent cache hydration', () => {
- it('does not apply an old user response after switching personal accounts', async () => {
- let scope = 'user-a:personal';
- vi.spyOn(cacheScopeModule, 'getCacheScope').mockImplementation(() => scope);
- let resolveOld!: (value: Awaited<ReturnType<typeof agentService.getBuiltinAgent>>) => void;
- vi.mocked(agentService.getBuiltinAgent).mockImplementation(
- () =>
- new Promise((resolve) => {
- if (scope === 'user-a:personal') resolveOld = resolve;
- }),
- );
- const cachedUserB = { id: 'inbox-b', name: 'Chief B' };
- const cache = new Map([
- [
- unstable_serialize(builtinAgentKeys.init('inbox', 'user-b:personal')),
- { data: cachedUserB },
- ],
- ]);
- const wrapper = ({ children }: PropsWithChildren) =>
- createElement(SWRConfig, { value: { provider: () => cache } }, children);
- const hook = renderHook(
- () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),
- { wrapper },
- );
- await waitFor(() => expect(resolveOld).toBeDefined());
- scope = 'user-b:personal';
- hook.rerender();
- expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-b');
-
- await act(async () => {
- resolveOld({ id: 'inbox-a', name: 'Chief A' } as Awaited<
- ReturnType<typeof agentService.getBuiltinAgent>
- >);
- });
- expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-b');
- expect(useAgentStore.getState().agentMap['inbox-a']).toBeUndefined();
- hook.unmount();
- });
-
- it('seeds the startup snapshot without refetching after changing the builtin agent name', async () => {
- const scopedMutate = vi.fn().mockResolvedValue(undefined);
- setScopedMutate(scopedMutate);
- useAgentStore.setState({ builtinAgentIdMap: { inbox: 'inbox-1' } });
- const updatedAgent = {
- id: 'inbox-1',
- name: 'Renamed chief',
- profile: { fullBodyArtwork: '/custom-chief.webp' },
- } as LobeAgentConfig;
- vi.mocked(agentService.updateAgentMeta).mockResolvedValue({
- agent: updatedAgent,
- success: true,
- });
-
- await useAgentStore
- .getState()
- .optimisticUpdateAgentMeta('inbox-1', { name: 'Renamed chief' });
-
- expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();
- expect(useAgentStore.getState().agentMap['inbox-1']).toMatchObject({ name: 'Renamed chief' });
- expect(scopedMutate).toHaveBeenCalledWith(
- builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope()),
- updatedAgent,
- { revalidate: false },
- );
- });
-
- it('does not seed a metadata response into a changed cache scope', async () => {
- let scope = 'user-a:personal';
- vi.spyOn(cacheScopeModule, 'getCacheScope').mockImplementation(() => scope);
- const scopedMutate = vi.fn().mockResolvedValue(undefined);
- setScopedMutate(scopedMutate);
- useAgentStore.setState({ builtinAgentIdMap: { inbox: 'inbox-1' } });
-
- let resolveUpdate!: (value: any) => void;
- vi.mocked(agentService.updateAgentMeta).mockImplementation(
- () =>
- new Promise((resolve) => {
- resolveUpdate = resolve;
- }),
- );
-
- let save!: Promise<void>;
- act(() => {
- save = useAgentStore
- .getState()
- .optimisticUpdateAgentMeta('inbox-1', { name: 'Renamed chief' });
- });
- await waitFor(() => expect(resolveUpdate).toBeDefined());
-
- scope = 'user-b:personal';
- useAgentStore.setState({ agentMap: {}, builtinAgentIdMap: {} });
- await act(async () => {
- resolveUpdate({
- agent: { id: 'inbox-1', name: 'Renamed chief' } as LobeAgentConfig,
- success: true,
- });
- await save;
- });
-
- expect(useAgentStore.getState().agentMap['inbox-1']).toBeUndefined();
- expect(
- scopedMutate.mock.calls.some(
- ([key]) =>
- JSON.stringify(key) ===
- JSON.stringify(builtinAgentKeys.init('inbox', 'user-b:personal')),
- ),
- ).toBe(false);
- });
-
- it('keeps the network refresh for an explicit builtin config refresh', async () => {
- const scopedMutate = vi.fn().mockResolvedValue(undefined);
- setScopedMutate(scopedMutate);
- useAgentStore.setState({ builtinAgentIdMap: { inbox: 'inbox-1' } });
- vi.mocked(agentService.getBuiltinAgent).mockResolvedValue({
- id: 'inbox-1',
- } as Awaited<ReturnType<typeof agentService.getBuiltinAgent>>);
-
- await act(async () => {
- await useAgentStore.getState().internal_refreshAgentConfig('inbox-1');
- });
-
- expect(agentService.getBuiltinAgent).toHaveBeenCalledWith('inbox');
- });
-
- it('restores the inbox identity and custom artwork while revalidation is pending', () => {
- const data = {
- id: 'cached-inbox',
- name: 'Custom chief',
- profile: { fullBodyArtwork: 'https://example.com/custom-chief.webp' },
- };
- vi.mocked(agentService.getBuiltinAgent).mockImplementation(() => new Promise(() => {}));
- const cache = new Map([
- [
- unstable_serialize(builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope())),
- { data },
- ],
- ]);
- const wrapper = ({ children }: PropsWithChildren) =>
- createElement(SWRConfig, { value: { provider: () => cache } }, children);
-
- const hook = renderHook(
- () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),
- { wrapper },
- );
-
- expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('cached-inbox');
- expect(useAgentStore.getState().agentMap['cached-inbox']).toMatchObject(data);
- hook.unmount();
- });
-
- it('reads the workspace inbox cache instead of the personal inbox cache', () => {
- vi.spyOn(activeWorkspaceModule, 'useActiveWorkspaceId').mockReturnValue('workspace-1');
- vi.mocked(agentService.getBuiltinAgent).mockImplementation(() => new Promise(() => {}));
- const cache = new Map([
- [
- unstable_serialize(builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope())),
- { data: { id: 'personal-inbox' } },
- ],
- [
- unstable_serialize([
- ...builtinAgentKeys.init('inbox', cacheScopeModule.getCacheScope()),
- 'workspace-1',
- ]),
- { data: { id: 'workspace-inbox' } },
- ],
- ]);
- const wrapper = ({ children }: PropsWithChildren) =>
- createElement(SWRConfig, { value: { provider: () => cache } }, children);
- const hook = renderHook(
- () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),
- { wrapper },
- );
-
- expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('workspace-inbox');
- expect(useAgentStore.getState().agentMap['personal-inbox']).toBeUndefined();
- hook.unmount();
- });
- });
-
describe('system role streaming', () => {
it('accepts chunks and lets only the stream owner clear the visual buffer', async () => {
const { result } = renderHook(() => useAgentStore());
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index 6b7c6ae0a2d..ae11d2d6f7c 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -23,7 +23,7 @@ import {
revalidateReplica,
} from '@/libs/replica';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
-import { agentConfigKeys, builtinAgentKeys } from '@/libs/swr/keys';
+import { agentConfigKeys } from '@/libs/swr/keys';
import { getCacheScope } from '@/libs/swr/useCacheScope';
import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@/services/agent';
import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';
@@ -818,12 +818,8 @@ export class AgentSliceActionImpl {
* other mutations still need a network refresh.
*/
if (updatedAgent) {
- await Promise.all(
- slugs.map((slug) =>
- mutate(builtinAgentKeys.init(slug, scope), updatedAgent as AgentItem, {
- revalidate: false,
- }),
- ),
+ slugs.forEach((slug) =>
+ this.#get().internal_replaceBuiltinAgent(slug, updatedAgent as AgentItem, scope),
);
return;
}
diff --git a/src/store/agent/slices/builtin/action.ts b/src/store/agent/slices/builtin/action.ts
index 17d203c794a..b4e9d3cb01d 100644
--- a/src/store/agent/slices/builtin/action.ts
+++ b/src/store/agent/slices/builtin/action.ts
@@ -1,15 +1,18 @@
import { type AgentItem, type LobeAgentConfig } from '@lobechat/types';
import { useLayoutEffect } from 'react';
-import { type SWRResponse } from 'swr';
import { type PartialDeep } from 'type-fest';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { builtinAgentKeys } from '@/libs/swr/keys';
-import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';
+import {
+ cacheScope,
+ createReplicaSlice,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
import { agentService } from '@/services/agent';
import { type StoreSetter } from '@/store/types';
import { type AgentStore } from '../../store';
+import { type BuiltinAgentParams, builtinAgentResource } from './projection';
interface UseInitBuiltinAgentContext {
/**
@@ -19,9 +22,52 @@ interface UseInitBuiltinAgentContext {
isLogin?: boolean;
}
+/** `useInitBuiltinAgent` result: replica flags plus the SWR-era aliases. */
+export interface BuiltinAgentSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and there is nothing cached to show for this entry yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+}
+
+const fetchBuiltinAgent = ({ slug }: BuiltinAgentParams): Promise<AgentItem> =>
+ agentService.getBuiltinAgent(slug) as Promise<AgentItem>;
+
+/**
+ * The replica view keeps the long-standing `builtinAgentIdMap` (slug β†’ id) as a
+ * derived index alongside the materialized `builtinAgentMap` (slug β†’ item): the
+ * id index is what selectors and route loaders read, and the full item is what
+ * re-seeds `agentMap` before paint. Both move in one commit, so a reader never
+ * sees an id without its item (or vice versa).
+ */
+const builtinAgentLens: ReplicaLens<AgentStore, AgentItem> = {
+ clear: () => ({ builtinAgentIdMap: {}, builtinAgentMap: {} }),
+ get: (state, key) => state.builtinAgentMap[key],
+ keys: (state) => Object.keys(state.builtinAgentMap),
+ set: (state, key, data) => {
+ const map = { ...state.builtinAgentMap };
+ const idMap = { ...state.builtinAgentIdMap };
+
+ if (data === undefined) {
+ delete map[key];
+ delete idMap[key];
+ } else {
+ map[key] = data;
+ if (data.id) idMap[key] = data.id;
+ else delete idMap[key];
+ }
+
+ return { builtinAgentIdMap: idMap, builtinAgentMap: map };
+ },
+};
+
/**
* Builtin Agent Slice Actions
* Handles initialization and management of builtin agents (page-agent, inbox, etc.)
+ *
+ * The server row is a replica: the first frame paints the persisted id + config,
+ * the network only confirms, and the store remains the only writer of
+ * `builtinAgentMap` / `builtinAgentIdMap`.
*/
type Setter = StoreSetter<AgentStore>;
@@ -29,69 +75,119 @@ export const createBuiltinAgentSlice = (set: Setter, get: () => AgentStore, _api
new BuiltinAgentSliceActionImpl(set, get, _api);
export class BuiltinAgentSliceActionImpl {
+ readonly #builtin;
readonly #get: () => AgentStore;
- readonly #set: Setter;
constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
void _api;
- this.#set = set;
this.#get = get;
+ this.#builtin = createReplicaSlice(builtinAgentResource, {
+ actionPrefix: 'builtinAgent',
+ fetcher: fetchBuiltinAgent,
+ get,
+ set,
+ stateKey: 'builtinAgentReplica',
+ view: builtinAgentLens,
+ });
}
+ /**
+ * Seed `agentMap` so a surface reading the builtin's own config (inbox
+ * identity / artwork) paints it instead of the default chief. In-memory only:
+ * the persisted copy lives in the builtin replica, not `agentConfig`.
+ */
+ #seedAgentMap = (item: AgentItem | null | undefined): void => {
+ if (!item?.id) return;
+ this.#get().internal_dispatchAgentMap(item.id, item as PartialDeep<LobeAgentConfig>);
+ };
+
+ /**
+ * Whether `scope` is still the identity the replica is partitioned by. An
+ * async round-trip resolves under the scope it started in; a result that
+ * arrives after an identity switch must not paint or seed the switched-to
+ * identity's view (the engine drops the replica write, this guards the
+ * `agentMap` seed that sits outside the replica).
+ */
+ #isCurrentScope = (scope: string): boolean => this.#builtin.resource.scope.get() === scope;
+
+ /**
+ * Confirm a builtin agent's latest value without a network round-trip β€” the
+ * authoritative update response is already in hand (e.g. after a meta edit).
+ * Writes the slug β†’ id index and its item, then seeds `agentMap`. A response
+ * captured under a scope that is no longer active is dropped.
+ */
+ internal_replaceBuiltinAgent = (
+ slug: string,
+ item: AgentItem,
+ scope = cacheScope.get(),
+ ): void => {
+ if (!item?.id) return;
+ this.#builtin.replace({ slug }, item, scope);
+ if (this.#isCurrentScope(scope)) this.#seedAgentMap(item);
+ };
+
+ /**
+ * Re-read a builtin agent from the network and confirm it locally.
+ *
+ * Imperative by design: unlike the mount-time `useInitBuiltinAgent` sync, it
+ * does not depend on a mounted subscriber, so the create-Agent / create-Page
+ * flows can ensure a slug resolves on demand.
+ *
+ * The scope is captured before the await: when the identity changes while the
+ * request is in flight, the late response is not written into the new scope,
+ * matching the guard the swap-era code applied with `scope === getCacheScope()`.
+ */
refreshBuiltinAgent = async (slug: string): Promise<void> => {
- const scope = getCacheScope();
- const data = await agentService.getBuiltinAgent(slug);
- if (data?.id && scope === getCacheScope()) {
- this.#get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);
- // Mirror useInitBuiltinAgent's hydration: keep builtinAgentIdMap in sync
- // so callers can rely on this as a real "ensure" path instead of just a
- // post-init refresh.
- this.#set(
- { builtinAgentIdMap: { ...this.#get().builtinAgentIdMap, [slug]: data.id } },
- false,
- `refreshBuiltinAgent/${slug}`,
- );
- await mutate(builtinAgentKeys.init(slug, scope), data, { revalidate: false });
- }
+ const scope = cacheScope.get();
+ const data = await fetchBuiltinAgent({ slug });
+ if (!data?.id) return;
+ this.internal_replaceBuiltinAgent(slug, data, scope);
};
useInitBuiltinAgent = (
slug: string,
context?: UseInitBuiltinAgentContext,
- ): SWRResponse<AgentItem | null> => {
- const scope = useCacheScope();
- const response = useClientDataSWR<AgentItem | null>(
- context?.isLogin === false ? null : builtinAgentKeys.init(slug, scope),
- async () => {
- const data = await agentService.getBuiltinAgent(slug);
-
- return scope === getCacheScope() ? (data as AgentItem | null) : null;
- },
- {
- dedupingInterval: 2000,
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- },
- );
-
- const { data } = response;
+ ): BuiltinAgentSyncResult => {
+ // The old SWR sync never refetched on focus / reconnect: a builtin's identity
+ // and config change through an explicit edit, not by the tab regaining focus.
+ const sync = this.#builtin.useSync(context?.isLogin === false ? null : { slug }, {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ });
+ const data = this.#get().builtinAgentMap[slug];
+
/**
* Cache hits do not invoke SWR's onSuccess. Restore the identity and artwork
- * before paint as well as after revalidation, so a reload does not briefly
- * display the default chief. Ignore responses from an obsolete identity scope.
+ * before paint on every commit of the entry (hydrate as well as background
+ * revalidation), so a reload does not briefly display the default chief. The
+ * scope guard is the engine's: a response from an obsolete identity scope is
+ * dropped before it reaches this view.
*/
useLayoutEffect(() => {
- if (context?.isLogin === false || !data?.id || scope !== getCacheScope()) return;
+ if (context?.isLogin === false) return;
+ this.#seedAgentMap(data);
+ }, [data, context?.isLogin]);
- this.#get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);
- this.#set(
- { builtinAgentIdMap: { ...this.#get().builtinAgentIdMap, [slug]: data.id } },
- false,
- `useInitBuiltinAgent/${slug}`,
- );
- }, [data, slug, scope, context?.isLogin]);
+ return {
+ ...sync,
+ isLoading: sync.isValidating && !data,
+ mutate: sync.revalidate,
+ };
+ };
+
+ /**
+ * Seed the persisted builtin agent β€” the slug β†’ id mapping and its config β€”
+ * before a route loader resolves a slug (see `agentChatTopicListLoader`).
+ * A route loader is the one place the async (IndexedDB) read can land before
+ * the route commits, so the id is known without waiting for the network.
+ */
+ preHydrateBuiltinAgent = async (slug: string): Promise<boolean> => {
+ const scope = cacheScope.get();
+ this.#builtin.ensureScope(scope);
+ const hydrated = await this.#builtin.hydrate({ slug }, scope);
+ this.#seedAgentMap(this.#get().builtinAgentMap[slug]);
- return response;
+ return hydrated;
};
}
diff --git a/src/store/agent/slices/builtin/index.ts b/src/store/agent/slices/builtin/index.ts
index bdd356bc5cb..018cdeab6f8 100644
--- a/src/store/agent/slices/builtin/index.ts
+++ b/src/store/agent/slices/builtin/index.ts
@@ -1,2 +1,7 @@
-export { type BuiltinAgentSliceAction, createBuiltinAgentSlice } from './action';
+export {
+ type BuiltinAgentSliceAction,
+ type BuiltinAgentSyncResult,
+ createBuiltinAgentSlice,
+} from './action';
export { type BuiltinAgentSliceState, initialBuiltinAgentSliceState } from './initialState';
+export { type BuiltinAgentParams, builtinAgentResource } from './projection';
diff --git a/src/store/agent/slices/builtin/initialState.ts b/src/store/agent/slices/builtin/initialState.ts
index dac2acef185..93c1ab4da14 100644
--- a/src/store/agent/slices/builtin/initialState.ts
+++ b/src/store/agent/slices/builtin/initialState.ts
@@ -1,11 +1,25 @@
+import { type AgentItem } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
export interface BuiltinAgentSliceState {
/**
* Builtin agent id mapping { [slug]: agentId }
* Used to store IDs of builtin agents (page-agent, etc.)
+ *
+ * Derived from {@link builtinAgentMap} by the replica lens, so the two never
+ * disagree; kept as its own field because selectors and route loaders read it
+ * directly.
*/
builtinAgentIdMap: Record<string, string>;
+ /** Replica view of each builtin agent, keyed by slug. */
+ builtinAgentMap: Record<string, AgentItem>;
+ /** Replica bookkeeping of `builtinAgentMap`. */
+ builtinAgentReplica: ReplicaState<AgentItem>;
}
export const initialBuiltinAgentSliceState: BuiltinAgentSliceState = {
builtinAgentIdMap: {},
+ builtinAgentMap: {},
+ builtinAgentReplica: createReplicaState(),
};
diff --git a/src/store/agent/slices/builtin/projection.ts b/src/store/agent/slices/builtin/projection.ts
new file mode 100644
index 00000000000..62d59f900ac
--- /dev/null
+++ b/src/store/agent/slices/builtin/projection.ts
@@ -0,0 +1,25 @@
+import { type AgentItem } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+
+export interface BuiltinAgentParams {
+ /** Builtin agent slug (`inbox`, `page-agent`, the builders, …). */
+ slug: string;
+}
+
+/**
+ * One builtin agent per slug, keyed by its slug.
+ *
+ * The server provisions the row on first read (`agent.getBuiltinAgent`) and
+ * returns the whole `AgentItem`. Persisted so a reload can restore both the
+ * slug β†’ id mapping (`builtinAgentIdMap`) and the config the surface paints with
+ * (inbox identity / artwork) before the network answers, then revalidate in the
+ * background β€” the same first-frame the SWR `builtinAgent:init` entry used to
+ * provide.
+ */
+export const builtinAgentResource = defineReplica<BuiltinAgentParams, AgentItem>({
+ key: ({ slug }) => slug,
+ name: 'builtinAgent',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/agent/slices/builtin/replica.test.ts b/src/store/agent/slices/builtin/replica.test.ts
new file mode 100644
index 00000000000..776cc750c7c
--- /dev/null
+++ b/src/store/agent/slices/builtin/replica.test.ts
@@ -0,0 +1,241 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The builtin agents (inbox, page-agent, the builders, …) are a replica: the
+ * first frame paints the persisted slug β†’ id mapping and config, the network
+ * only confirms, a scope switch drops the previous identity before the next
+ * paints, and the imperative paths (refresh / pre-paint hydrate / meta confirm)
+ * keep the store the only writer.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { agentService } from '@/services/agent';
+
+import { useAgentStore } from '../../store';
+import { initialBuiltinAgentSliceState } from './initialState';
+import { builtinAgentResource } from './projection';
+
+vi.mock('@/services/agent', () => ({
+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
+ agentService: {
+ getBuiltinAgent: vi.fn(),
+ },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const builtin = (id: string, extra: Record<string, unknown> = {}) =>
+ ({ id, name: id, ...extra }) as any;
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {}) as Promise<any>;
+
+/** Row key of the builtin replica entry (`key` is the slug, no query). */
+const PERSIST_KEY = builtinAgentResource.storageKey({ slug: 'inbox' });
+
+describe('builtin agent replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`builtin-user-${randomUUID()}:personal`);
+ act(() => useAgentStore.setState(initialBuiltinAgentSliceState));
+ vi.mocked(agentService.getBuiltinAgent).mockReset();
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].map((value) =>
+ builtinAgentResource.storage!.remove({ queryKey: PERSIST_KEY, scope: value }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted slug β†’ id and config before the network answers', async () => {
+ await builtinAgentResource.storage!.set(
+ { queryKey: PERSIST_KEY, scope },
+ {
+ data: builtin('cached-inbox', {
+ name: 'Custom chief',
+ profile: { fullBodyArtwork: '/custom-chief.webp' },
+ }),
+ updatedAt: 1,
+ },
+ );
+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(pending);
+
+ const sync = renderHook(
+ () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('cached-inbox'),
+ );
+ expect(useAgentStore.getState().builtinAgentMap.inbox).toMatchObject({
+ name: 'Custom chief',
+ });
+ // The persisted config re-seeds the surface that paints the builtin identity.
+ expect(useAgentStore.getState().agentMap['cached-inbox']).toMatchObject({
+ name: 'Custom chief',
+ profile: { fullBodyArtwork: '/custom-chief.webp' },
+ });
+ expect(useAgentStore.getState().builtinAgentReplica.entries['inbox'].source).toBe('storage');
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ // Data is on screen, so nothing is loading from the caller's point of view.
+ expect(sync.result.current.isLoading).toBe(false);
+ expect(typeof sync.result.current.mutate).toBe('function');
+ });
+
+ it('replaces with the server answer and persists it', async () => {
+ vi.mocked(agentService.getBuiltinAgent).mockResolvedValue(
+ builtin('inbox-1', { name: 'Server chief' }),
+ );
+
+ const sync = renderHook(
+ () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-1'));
+ expect(useAgentStore.getState().agentMap['inbox-1']).toMatchObject({ name: 'Server chief' });
+ expect(agentService.getBuiltinAgent).toHaveBeenCalledWith('inbox');
+
+ await waitFor(async () =>
+ expect(
+ (await builtinAgentResource.storage!.get({ queryKey: PERSIST_KEY, scope }))?.data,
+ ).toMatchObject({ id: 'inbox-1' }),
+ );
+ expect(sync.result.current.isLoading).toBe(false);
+ });
+
+ it('drops the previous identity’s builtin before the next one paints', async () => {
+ vi.mocked(agentService.getBuiltinAgent).mockResolvedValue(builtin('inbox-a'));
+ const sync = renderHook(
+ () => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: true }),
+ { wrapper },
+ );
+ await waitFor(() => expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-a'));
+
+ // The switched-to identity has nothing persisted and its fetch hangs.
+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(pending);
+ useScope(`builtin-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBeUndefined());
+ expect(useAgentStore.getState().builtinAgentMap.inbox).toBeUndefined();
+ expect(useAgentStore.getState().builtinAgentReplica.scope).toBe(scope);
+ });
+
+ it('pre-hydrates the persisted builtin for a route loader before the network answers', async () => {
+ await builtinAgentResource.storage!.set(
+ { queryKey: PERSIST_KEY, scope },
+ { data: builtin('cached-inbox', { name: 'Custom chief' }), updatedAt: 1 },
+ );
+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(pending);
+
+ let hydrated = false;
+ await act(async () => {
+ hydrated = await useAgentStore.getState().preHydrateBuiltinAgent('inbox');
+ });
+
+ expect(hydrated).toBe(true);
+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('cached-inbox');
+ expect(useAgentStore.getState().builtinAgentMap.inbox).toMatchObject({
+ name: 'Custom chief',
+ });
+ expect(useAgentStore.getState().agentMap['cached-inbox']).toBeDefined();
+ // The loader path never hits the network: it only reads the local copy.
+ expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();
+ });
+
+ it('does not paint or persist a refresh response after an identity switch', async () => {
+ let resolveFetch!: (value: any) => void;
+ vi.mocked(agentService.getBuiltinAgent).mockImplementation(
+ () => new Promise((resolve) => (resolveFetch = resolve)),
+ );
+
+ const operation = useAgentStore.getState().refreshBuiltinAgent('inbox');
+
+ // The user switches identity while the refresh is in flight.
+ const switched = `builtin-user-${randomUUID()}:personal`;
+ useScope(switched);
+
+ await act(async () => {
+ resolveFetch(builtin('inbox-a'));
+ await operation;
+ });
+
+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBeUndefined();
+ expect(useAgentStore.getState().agentMap['inbox-a']).toBeUndefined();
+ expect(
+ (await builtinAgentResource.storage!.get({ queryKey: PERSIST_KEY, scope: switched }))?.data,
+ ).toBeUndefined();
+ });
+
+ it('confirms a meta-edit response on the builtin without a network round-trip', () => {
+ act(() => {
+ useAgentStore.setState({
+ builtinAgentIdMap: { inbox: 'inbox-1' },
+ builtinAgentMap: { inbox: builtin('inbox-1', { name: 'Old chief' }) },
+ });
+ });
+
+ act(() => {
+ useAgentStore.getState().internal_replaceBuiltinAgent(
+ 'inbox',
+ builtin('inbox-1', {
+ name: 'Renamed chief',
+ profile: { fullBodyArtwork: '/new-chief.webp' },
+ }),
+ );
+ });
+
+ expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();
+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBe('inbox-1');
+ expect(useAgentStore.getState().builtinAgentMap.inbox).toMatchObject({ name: 'Renamed chief' });
+ expect(useAgentStore.getState().agentMap['inbox-1']).toMatchObject({ name: 'Renamed chief' });
+ });
+
+ it('does not fetch while the caller is logged out', async () => {
+ renderHook(() => useAgentStore.getState().useInitBuiltinAgent('inbox', { isLogin: false }), {
+ wrapper,
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(agentService.getBuiltinAgent).not.toHaveBeenCalled();
+ expect(useAgentStore.getState().builtinAgentIdMap.inbox).toBeUndefined();
+ });
+});