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(user): move the common slice onto @lobechat/replica (#20707)

Arvin Xu7b92287d1867
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
index 3e578fd1dc6..23657a81fb2 100644
--- a/packages/replica/src/zustand/createReplicaSlice.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -143,7 +143,11 @@ describe('createReplicaSlice', () => {
// The callback also receives the key/scope the failing read was captured
// under, so a terminal removal can be bound to the right scope.
await waitFor(() =>
- expect(onError).toHaveBeenCalledWith(failure, { key: 'b', scope: 'user-1:personal' }),
+ expect(onError).toHaveBeenCalledWith(failure, {
+ isActive: true,
+ key: 'b',
+ scope: 'user-1:personal',
+ }),
);
expect(failing.store.getState().lists.b).toBeUndefined();
});
@@ -450,6 +454,123 @@ describe('createReplicaSlice', () => {
expect(store.getState().lists.a).toBeUndefined();
});
+ it("drops a settled request's success side effects once the store has left its scope", () => {
+ // A response can settle after an identity/workspace switch. The engine
+ // refuses the off-scope `replace`, but the caller's callbacks carry the
+ // previous identity's side effects, so they must not run either — and a
+ // switch to a scope reading the same key/query defeats both the
+ // moved-past-query and since-clear guards.
+ const requests: {
+ onError: (error: unknown) => void;
+ onSuccess: (data: string[]) => void;
+ }[] = [];
+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {
+ if (key !== null) requests.push({ onError: options.onError, onSuccess: options.onSuccess });
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'staleScopeCallbacks',
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ const onSuccess = vi.fn();
+ const onError = vi.fn();
+ renderHook(() => slice.useSync({ id: 'a' }, { onError, onSuccess }), { wrapper });
+
+ const captured = requests.find((request) => request)!;
+
+ // The identity/workspace switches while the request is still in flight.
+ scopeState.current = 'user-2:personal';
+
+ act(() => captured.onSuccess(['stale']));
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(store.getState().lists.a).toBeUndefined();
+
+ // A failure is still handed over, bound to the scope it was captured
+ // under and flagged as no longer active, so the caller can purge that
+ // scope's row (see below) without repainting the current view.
+ act(() => captured.onError(new Error('stale')));
+ expect(onError).toHaveBeenCalledWith(expect.any(Error), {
+ isActive: false,
+ key: 'a',
+ scope: 'user-1:personal',
+ });
+ });
+
+ it('lets a late terminal error purge its captured scope through the sync callback', async () => {
+ const requests: { onError: (error: unknown) => void }[] = [];
+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {
+ // The sync request carries the callbacks; the hydration read does not.
+ if (key !== null && options?.onError) requests.push({ onError: options.onError });
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const memory = createMemoryStorage();
+ memory.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'lateTerminalError',
+ scope,
+ storage: memory.storage,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ scopeState.current = 'user-1:personal';
+ const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];
+ renderHook(
+ () =>
+ slice.useSync(
+ { id: 'a' },
+ {
+ onError: (_error, context) => {
+ contexts.push(context);
+ if (context.key) slice.remove(context.key, context.scope);
+ },
+ },
+ ),
+ { wrapper },
+ );
+ const request = requests.find((entry) => entry)!;
+
+ // The identity switches and loads its own entry before the denial lands.
+ scopeState.current = 'user-2:personal';
+ act(() => slice.replace({ id: 'a' }, ['b-value']));
+
+ act(() => request.onError(new Error('NOT_FOUND')));
+
+ // The callback still runs, flagged as belonging to a scope left behind, so
+ // the consumer can purge that scope without repainting the current one.
+ expect(contexts[0]).toMatchObject({ isActive: false, key: 'a', scope: 'user-1:personal' });
+ // The scope on screen keeps its entry; the denied scope's row is purged.
+ expect(store.getState().lists.a).toEqual(['b-value']);
+ await waitFor(() => expect(memory.rows.get('user-1:personal|a')).toBeUndefined());
+ });
+
it('purges the captured scope row for a removal that lands after a scope switch', async () => {
const storage = createMemoryStorage();
storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });
@@ -494,7 +615,7 @@ describe('createReplicaSlice', () => {
throw new Error('not found');
});
const { slice } = setup({ fetcher });
- const contexts: { key: string | undefined; scope: string }[] = [];
+ const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];
scopeState.current = 'user-1:personal';
renderHook(
@@ -503,7 +624,7 @@ describe('createReplicaSlice', () => {
);
await waitFor(() => expect(contexts.length).toBeGreaterThan(0));
- expect(contexts[0]).toEqual({ key: 'a', scope: 'user-1:personal' });
+ expect(contexts[0]).toEqual({ isActive: true, key: 'a', scope: 'user-1:personal' });
});
it('evicts the persisted row when a response has nothing to persist', async () => {
@@ -1254,7 +1375,11 @@ describe('createReplicaSlice', () => {
const failure = new Error('search failed');
act(() => search.onError(failure));
- expect(onError).toHaveBeenCalledWith(failure, { key: 'a', scope: 'user-1:personal' });
+ expect(onError).toHaveBeenCalledWith(failure, {
+ isActive: true,
+ key: 'a',
+ scope: 'user-1:personal',
+ });
});
});
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index 602b6f98cf6..ef92f80e34f 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -43,6 +43,13 @@ export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> ext
* callback runs (an identity / workspace switch in between).
*/
export interface ReplicaSyncErrorContext {
+ /**
+ * Whether the captured `scope` is still the one the store is on. A failure
+ * with `isActive: false` belongs to an identity / workspace the store has
+ * left: surface it on the *current* view only when this is true, while still
+ * using the captured `key` / `scope` to clean up the scope it came from.
+ */
+ isActive: boolean;
/** The entry key the read was for; `undefined` for a disabled read. */
key: string | undefined;
/** The cache scope the read was captured under. */
@@ -193,6 +200,17 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
requestGeneration.delete(id);
return started === undefined || started === clearGeneration(scope);
};
+ /**
+ * Whether the entry is still on the scope the request was captured under.
+ *
+ * A response can settle after an identity/workspace switch. `replace` drops
+ * it — the engine refuses off-scope actions — but the caller's `onSuccess`
+ * must not run either: it carries the previous identity's side effects
+ * (onboarding redirect, display snapshot, analytics identify, settings
+ * writes). The captured key/scope is not enough on its own, because a switch
+ * to a scope that reads the same key/query satisfies both guards above.
+ */
+ const isActiveScope = () => resource.scope.get() === scope;
const sync = driver.useQuery<TFetched>(
syncKey,
@@ -203,19 +221,26 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
{
...schedule,
// A failure of a query the entry has moved past (or of a request from
- // before a clear) must not surface on the query now on screen. The
- // captured key/scope is bound so a late terminal removal cannot land in
- // a scope that became active after the request.
+ // before a clear) must not surface on the query now on screen. Unlike
+ // success, an off-scope failure is still forwarded: the captured
+ // key/scope is bound so a late terminal answer (NOT_FOUND / FORBIDDEN)
+ // can purge *its own* scope's persisted row via `remove(key, scope)`
+ // without touching the scope now on screen — dropping it would leave
+ // that row to hydrate again when the user switches back.
// Always installed, so a failed request's generation record is dropped
// even when the caller has no error side effects.
onError: (error: unknown) => {
if (!isSinceClear() || !isActiveQuery()) return;
- onError?.(error, { key, scope });
+ // Forwarded even off-scope: the captured `key`/`scope` lets a consumer
+ // purge that scope's row. `isActive` tells it whether the failure also
+ // belongs to the view on screen.
+ onError?.(error, { isActive: isActiveScope(), key, scope });
},
onSuccess: (data) => {
// Discard a head response the entry has moved past (the newer query
- // owns the view, see `headQuery`) or one that started before a clear.
- if (!isSinceClear() || !isActiveQuery()) return;
+ // owns the view, see `headQuery`), one that started before a clear, or
+ // one captured under a scope the store has since left.
+ if (!isSinceClear() || !isActiveQuery() || !isActiveScope()) return;
replace(params!, data, scope);
onSuccess?.(data);
},
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index dbfc67a8fcc..4c3e14b3fc4 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -1124,7 +1124,6 @@ export const gatewayKeys = {
};
export const userKeys = {
checkTrace: def('user:checkTrace', () => ['user:checkTrace']),
- initState: def('user:initState', () => ['user:initState']),
};
export const imessageKeys = {
bridgeStatus: def('imessage:bridgeStatus', () => ['imessage:bridgeStatus']),
diff --git a/src/store/user/slices/auth/action.test.ts b/src/store/user/slices/auth/action.test.ts
index ae6a9e6aba2..7ef0486a0b7 100644
--- a/src/store/user/slices/auth/action.test.ts
+++ b/src/store/user/slices/auth/action.test.ts
@@ -2,7 +2,6 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mutate } from '@/libs/swr';
-import { userKeys } from '@/libs/swr/keys';
import { useUserStore } from '@/store/user';
import { readUserDisplaySnapshot, writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';
@@ -48,7 +47,9 @@ describe('createAuthSlice', () => {
await result.current.refreshUserState();
});
- expect(mutate).toHaveBeenCalledWith(userKeys.initState());
+ // The bootstrap payload now lives in a replica resource: a refresh
+ // re-mutates the cache through the replica driver's key predicate.
+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));
});
});
diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.ts
index 7d59d640b27..3135094694b 100644
--- a/src/store/user/slices/common/action.test.ts
+++ b/src/store/user/slices/common/action.test.ts
@@ -1,9 +1,11 @@
+import { DEFAULT_SETTINGS } from '@lobechat/config';
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 type * as SWRLib from '@/libs/swr';
-import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';
+import { taskTemplateKeys } from '@/libs/swr/keys';
import { userService } from '@/services/user';
import { useUserStore } from '@/store/user';
import { readUserDisplaySnapshot, writeUserDisplaySnapshot } from '@/store/user/displaySnapshot';
@@ -13,6 +15,7 @@ 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(() => ({
mutate: vi.fn(),
@@ -35,10 +38,27 @@ vi.mock('swr', async (importOriginal) => {
};
});
+/**
+ * Pin the identity scope: the projection sets `user.id` from the payload, and
+ * an unmocked `useCacheScope` would recompute from that id mid-test.
+ */
+const SCOPE = 'user-common-test:personal';
+
beforeEach(() => {
localStorage.clear();
swrMocks.mutate.mockReset();
swrMocks.mutate.mockResolvedValue(undefined);
+ vi.spyOn(cacheScope, 'get').mockReturnValue(SCOPE);
+ vi.spyOn(cacheScope, 'use').mockReturnValue(SCOPE);
+ useUserStore.setState({
+ ...initialCommonState,
+ defaultSettings: DEFAULT_SETTINGS,
+ isUserStateInitError: undefined,
+ onboarding: undefined,
+ preference: DEFAULT_PREFERENCE,
+ settings: {},
+ user: undefined,
+ });
});
afterEach(() => {
@@ -54,7 +74,7 @@ describe('createCommonSlice', () => {
expect(
isTaskTemplateRecommendationKey(['taskTemplate:listDailyRecommend', 'seed', 3, 'zh-CN']),
).toBe(false);
- expect(isTaskTemplateRecommendationKey(userKeys.initState())).toBe(false);
+ expect(isTaskTemplateRecommendationKey(['topic:list'])).toBe(false);
});
});
@@ -154,8 +174,52 @@ describe('createCommonSlice', () => {
expect(userService.getUserState).not.toHaveBeenCalled();
// 也不会触发 onSuccess 回调
expect(successCallback).not.toHaveBeenCalled();
- // 确保状态未改变
- expect(result.current.data).toBeUndefined();
+ // 确保状态未被错误更新
+ expect(useUserStore.getState().isUserStateInit).toBe(false);
+ expect(result.current.isValidating).toBe(false);
+ });
+
+ it('records a bootstrap failure of the active scope as the init error', async () => {
+ const failure = new Error('bootstrap failed');
+ vi.spyOn(userService, 'getUserState').mockRejectedValue(failure);
+ const errorCallback = vi.fn();
+
+ renderHook(
+ () => useUserStore().useInitUserState(true, mockServerConfig, { onError: errorCallback }),
+ { wrapper: withSWR },
+ );
+
+ await waitFor(() => expect(useUserStore.getState().isUserStateInitError).toBe(failure));
+ expect(errorCallback).toHaveBeenCalledWith(failure);
+ });
+
+ it('ignores a bootstrap failure that settles after the scope switched away', async () => {
+ let rejectBootstrap!: (error: Error) => void;
+ vi.spyOn(userService, 'getUserState').mockImplementation(
+ () =>
+ new Promise<UserInitializationState>((_resolve, reject) => {
+ rejectBootstrap = reject;
+ }),
+ );
+ const errorCallback = vi.fn();
+
+ renderHook(
+ () => useUserStore().useInitUserState(true, mockServerConfig, { onError: errorCallback }),
+ { wrapper: withSWR },
+ );
+ await waitFor(() => expect(userService.getUserState).toHaveBeenCalled());
+
+ // Identity / workspace switch while the previous scope's bootstrap is in
+ // flight: its failure belongs to the scope left behind.
+ vi.mocked(cacheScope.get).mockReturnValue('user-common-test:other-workspace');
+ await act(async () => {
+ rejectBootstrap(new Error('previous identity failed'));
+ });
+
+ // Give a (wrongly) forwarded error time to land before asserting it did not.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(useUserStore.getState().isUserStateInitError).toBeUndefined();
+ expect(errorCallback).not.toHaveBeenCalled();
});
it('should fetch user state correctly when user is login', async () => {
@@ -175,7 +239,7 @@ describe('createCommonSlice', () => {
vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);
const successCallback = vi.fn();
- const { result } = renderHook(
+ renderHook(
() =>
useUserStore().useInitUserState(true, mockServerConfig, {
onSuccess: successCallback,
@@ -185,19 +249,20 @@ describe('createCommonSlice', () => {
},
);
- // 等待 SWR 完成数据获取
- await waitFor(() => expect(result.current.data).toEqual(mockUserState));
+ // 等待 replica 的 bootstrap 同步落库
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
// 验证状态是否正确更新
- expect(useUserStore.getState().user?.avatar).toBe(mockUserState.avatar);
- expect(userGeneralSettingsSelectors.config(useUserStore.getState() as any)).toEqual(
+ const state = useUserStore.getState();
+ expect(state.user?.avatar).toBe(mockUserState.avatar);
+ expect(userGeneralSettingsSelectors.config(state)).toEqual(
expect.objectContaining({
fontSize: 14,
responseLanguage: expect.any(String),
timezone: 'America/New_York',
}),
);
- expect(useUserStore.getState().user?.email).toEqual(mockUserState.email);
+ expect(state.user?.email).toEqual(mockUserState.email);
expect(successCallback).toHaveBeenCalledWith(mockUserState);
});
@@ -213,12 +278,11 @@ describe('createCommonSlice', () => {
vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);
- const { result } = renderHook(() => useUserStore().useInitUserState(true, mockServerConfig), {
+ renderHook(() => useUserStore().useInitUserState(true, mockServerConfig), {
wrapper: withSWR,
});
- // 等待 SWR 完成数据获取
- await waitFor(() => expect(result.current.data).toEqual(mockUserState));
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
});
it('should fetch use server config correctly', async () => {
@@ -232,9 +296,9 @@ describe('createCommonSlice', () => {
};
vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);
- const { result } = renderHook(() => useUserStore().useInitUserState(true, mockServerConfig));
+ renderHook(() => useUserStore().useInitUserState(true, mockServerConfig));
- await waitFor(() => expect(result.current.data).toEqual(mockUserState));
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
});
it('should return saved preference when local storage has data', async () => {
@@ -256,15 +320,13 @@ describe('createCommonSlice', () => {
};
vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);
- const { result: preference } = renderHook(
- () => result.current.useInitUserState(true, mockServerConfig),
- { wrapper: withSWR },
- );
+ renderHook(() => result.current.useInitUserState(true, mockServerConfig), {
+ wrapper: withSWR,
+ });
await waitFor(() => {
- expect(preference.current.data?.preference).toEqual(savedPreference);
- expect(result.current.isUserStateInit).toBeTruthy();
- expect(result.current.preference).toEqual(savedPreference);
+ expect(useUserStore.getState().isUserStateInit).toBeTruthy();
+ expect(useUserStore.getState().preference).toEqual(savedPreference);
});
});
@@ -329,13 +391,13 @@ describe('createCommonSlice', () => {
wrapper: withSWR,
});
- // 等待 SWR 完成数据获取
await waitFor(() => {
- expect(result.current.isUserStateInit).toBeTruthy();
+ const state = useUserStore.getState();
+ expect(state.isUserStateInit).toBeTruthy();
// 验证状态未被错误更新
- expect(result.current.user?.avatar).toEqual('abc');
+ expect(state.user?.avatar).toEqual('abc');
// When settings is null, auto-detect general settings will set them
- expect(result.current.settings).toEqual({
+ expect(state.settings).toEqual({
general: { responseLanguage: expect.any(String), timezone: expect.any(String) },
});
});
@@ -358,8 +420,8 @@ describe('createCommonSlice', () => {
});
await waitFor(() => {
- expect(result.current.isUserStateInit).toBeTruthy();
- expect(result.current.settings.general?.responseLanguage).toBeUndefined();
+ expect(useUserStore.getState().isUserStateInit).toBeTruthy();
+ expect(useUserStore.getState().settings.general?.responseLanguage).toBeUndefined();
});
});
@@ -374,7 +436,6 @@ describe('createCommonSlice', () => {
general: { fontSize: 12 },
},
};
-
vi.spyOn(userService, 'getUserState').mockResolvedValueOnce(mockUserState);
renderHook(() => result.current.useInitUserState(true, mockServerConfig), {
@@ -382,8 +443,8 @@ describe('createCommonSlice', () => {
});
await waitFor(() => {
- expect(result.current.isUserStateInit).toBeTruthy();
- expect(result.current.preference).toEqual(DEFAULT_PREFERENCE);
+ expect(useUserStore.getState().isUserStateInit).toBeTruthy();
+ expect(useUserStore.getState().preference).toEqual(DEFAULT_PREFERENCE);
});
});
});
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index 9ef3b5adb61..7666d02f6bc 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -1,12 +1,15 @@
import { isDesktop } from '@lobechat/const';
+import type { ReplicaSlice } from '@lobechat/replica/zustand';
import type { UserGeneralConfig } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
import { type PartialDeep } from 'type-fest';
import { DEFAULT_PREFERENCE } from '@/const/user';
import { analyticsClient } from '@/libs/analytics/client';
-import { mutate, useOnlyFetchOnceSWR } from '@/libs/swr';
+import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';
+import { mutate } from '@/libs/swr';
import { taskTemplateKeys, userKeys } from '@/libs/swr/keys';
import { userService } from '@/services/user';
import { type StoreSetter } from '@/store/types';
@@ -19,9 +22,26 @@ import { setNamespace } from '@/utils/storeDebug';
import { writeUserDisplaySnapshot } from '../../displaySnapshot';
import { userGeneralSettingsSelectors } from '../settings/selectors';
+import type { CommonState } from './initialState';
+import { createUserStateResource, USER_STATE_KEY } from './projection';
const n = setNamespace('common');
+/**
+ * The fields the bootstrap projection owns. Resetting drops the replica view
+ * (so a scope switch re-gates on the new identity's response) without touching
+ * `user` / `settings` / `preference`, which other slices also write.
+ */
+const EMPTY_BOOTSTRAP: Partial<CommonState> = {
+ isUserStateInit: false,
+ isUserStateInitError: undefined,
+ userState: undefined,
+};
+
+const USER_STATE_PARAMS = {} as Record<string, never>;
+
+type UserStateReplica = ReplicaSlice<UserStore, Record<string, never>, UserInitializationState>;
+
/**
* Common actions
*/
@@ -36,6 +56,18 @@ export const isTaskTemplateRecommendationKey = (key: unknown): boolean =>
export class CommonActionImpl {
readonly #get: () => UserStore;
readonly #set: Setter;
+ /**
+ * Replica of the bootstrap payload; the flat flags below are its view.
+ * Created on first use — the resource lives on the user store, which the
+ * replica wiring itself reads back (see `createUserStateResource`).
+ */
+ #userState?: UserStateReplica;
+ /**
+ * The server config of the current app instance. It is not part of the
+ * replica value (it is a boot-time global, not user data), so the projection
+ * reads it from the latest `useInitUserState` call.
+ */
+ #serverConfig?: GlobalServerConfig;
constructor(set: Setter, get: () => UserStore, _api?: unknown) {
void _api;
@@ -43,8 +75,92 @@ export class CommonActionImpl {
this.#get = get;
}
+ /**
+ * Project the confirmed bootstrap payload onto the flat store fields every
+ * selector already reads. Mirrors the previous hand-written `#set` block.
+ */
+ #project = (state: UserStore, data: UserInitializationState): Partial<UserStore> => {
+ // merge settings
+ const serverSettings: PartialDeep<UserSettings> = {
+ defaultAgent: this.#serverConfig?.defaultAgent,
+ image: this.#serverConfig?.image,
+ systemAgent: this.#serverConfig?.systemAgent,
+ };
+
+ const defaultSettings = merge(state.defaultSettings, serverSettings);
+
+ // merge preference
+ const isEmpty = Object.keys(data.preference || {}).length === 0;
+ const preference = isEmpty ? DEFAULT_PREFERENCE : data.preference;
+
+ // if there is avatar or userId (from client DB), update it into user
+ const user =
+ data.avatar || data.userId
+ ? merge(state.user, {
+ avatar: data.avatar,
+ email: data.email,
+ firstName: data.firstName,
+ fullName: data.fullName,
+ id: data.userId,
+ interests: data.interests,
+ latestName: data.lastName,
+ username: data.username,
+ } as LobeUser)
+ : state.user;
+
+ return {
+ defaultSettings,
+ isFreePlan: data.isFreePlan,
+ isIdentityResolved: true,
+ isOnboard: data.isOnboard,
+ isShowPWAGuide: data.canEnablePWAGuide,
+ isSignedIn: Boolean(data.userId) || state.isSignedIn,
+ isUserCanEnableTrace: data.canEnableTrace,
+ isUserHasConversation: data.hasConversation,
+ isUserStateInit: true,
+ isUserStateInitError: undefined,
+ onboarding: data.onboarding,
+ preference,
+ referralStatus: data.referralStatus,
+ settings: data.settings || {},
+ subscriptionPlan: data.subscriptionPlan,
+ user,
+ userState: data,
+ };
+ };
+
+ #ensureUserState = (): UserStateReplica => {
+ if (!this.#userState) {
+ const view: ReplicaLens<UserStore, UserInitializationState> = {
+ clear: () => EMPTY_BOOTSTRAP,
+ get: (state) => state.userState,
+ keys: (state) => (state.userState ? [USER_STATE_KEY] : []),
+ set: (state, _key, data) => (data ? this.#project(state, data) : EMPTY_BOOTSTRAP),
+ };
+
+ this.#userState = createReplicaSlice(createUserStateResource(), {
+ actionPrefix: n('userState'),
+ fetcher: () => userService.getUserState(),
+ get: this.#get,
+ // An unchanged payload must not re-render every `user` / `settings`
+ // consumer on a refresh.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set: this.#set,
+ stateKey: 'userStateReplica',
+ view,
+ });
+ }
+
+ return this.#userState;
+ };
+
+ /**
+ * Re-run the bootstrap fetch for the active identity. The replica owns the
+ * request, so `revalidate` only matches the current scope's entry — a switch
+ * that is still in flight is never answered with another identity's payload.
+ */
refreshUserState = async (): Promise<void> => {
- await mutate(userKeys.initState());
+ await this.#ensureUserState().revalidate();
};
updateAvatar = async (avatar: string): Promise<void> => {
@@ -57,6 +173,11 @@ export class CommonActionImpl {
await this.#get().refreshUserState();
};
+ /**
+ * Optimistic: the interests row repaints before the write resolves. There is
+ * no list to reconcile — only this one user field — so it patches `user`
+ * directly and lets the bootstrap revalidation confirm it.
+ */
updateInterests = async (interests: string[]): Promise<void> => {
const previousUser = this.#get().user;
if (previousUser) {
@@ -95,6 +216,11 @@ export class CommonActionImpl {
);
};
+ /**
+ * Fetch orchestration for the bootstrap entry: returns the replica's sync
+ * flags, never the data. Read `isUserStateInit` / `user` / `settings` from
+ * the store — the projection writes them.
+ */
useInitUserState = (
isLogin: boolean | undefined,
serverConfig: GlobalServerConfig,
@@ -102,115 +228,77 @@ export class CommonActionImpl {
onError?: (error: any) => void;
onSuccess?: (data: UserInitializationState) => void;
},
- ): SWRResponse => {
- return useOnlyFetchOnceSWR<UserInitializationState>(
- !!isLogin || isDesktop ? userKeys.initState() : null,
- () => userService.getUserState(),
- {
- onError: (error) => {
- // Record the init failure so gated tabs (Advanced / ServiceModel) can
- // render error + Retry instead of a permanent skeleton.
- this.#set({ isUserStateInitError: error }, false, n('initUserState/error'));
- options?.onError?.(error);
- },
- onSuccess: (data) => {
- options?.onSuccess?.(data);
-
- if (data) {
- // merge settings
- const serverSettings: PartialDeep<UserSettings> = {
- defaultAgent: serverConfig.defaultAgent,
- image: serverConfig.image,
- systemAgent: serverConfig.systemAgent,
- };
-
- const defaultSettings = merge(this.#get().defaultSettings, serverSettings);
-
- // merge preference
- const isEmpty = Object.keys(data.preference || {}).length === 0;
- const preference = isEmpty ? DEFAULT_PREFERENCE : data.preference;
-
- writeUserDisplaySnapshot(data.userId, {
- avatar: data.avatar ?? '',
- preference,
- });
-
- // if there is avatar or userId (from client DB), update it into user
- const user =
- data.avatar || data.userId
- ? merge(this.#get().user, {
- avatar: data.avatar,
- email: data.email,
- firstName: data.firstName,
- fullName: data.fullName,
- id: data.userId,
- interests: data.interests,
- latestName: data.lastName,
- username: data.username,
- } as LobeUser)
- : this.#get().user;
-
- this.#set(
- {
- defaultSettings,
- isFreePlan: data.isFreePlan,
- isOnboard: data.isOnboard,
- isShowPWAGuide: data.canEnablePWAGuide,
- isUserCanEnableTrace: data.canEnableTrace,
- isUserHasConversation: data.hasConversation,
- isIdentityResolved: true,
- isSignedIn: Boolean(data.userId) || this.#get().isSignedIn,
- isUserStateInit: true,
- isUserStateInitError: undefined,
- onboarding: data.onboarding,
- preference,
- referralStatus: data.referralStatus,
- settings: data.settings || {},
- subscriptionPlan: data.subscriptionPlan,
- user,
- },
- false,
- n('initUserState'),
- );
-
- const autoDetectedGeneralConfig: Partial<UserGeneralConfig> = {};
- const currentGeneralSettings = data.settings?.general;
-
- // Auto-detect and sync browser timezone on first load
- if (!currentGeneralSettings?.timezone && typeof Intl !== 'undefined') {
- const detectedTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- if (detectedTimezone) autoDetectedGeneralConfig.timezone = detectedTimezone;
- }
-
- // Keep reply language aligned with the browser locale until the user makes a choice.
- // Only auto-fill once onboarding has finished — otherwise it pre-empts the
- // language step in the onboarding flow, skipping past the user's explicit choice.
- const hasFinishedOnboarding = !!data.onboarding?.finishedAt;
- if (
- hasFinishedOnboarding &&
- !currentGeneralSettings?.responseLanguage &&
- typeof navigator !== 'undefined'
- ) {
- autoDetectedGeneralConfig.responseLanguage =
- userGeneralSettingsSelectors.currentResponseLanguage(this.#get());
- }
-
- if (Object.keys(autoDetectedGeneralConfig).length > 0) {
- this.#get()
- .updateGeneralConfig(autoDetectedGeneralConfig)
- .catch(() => {});
- }
-
- analyticsClient.identify(data.userId || '', {
- email: data.email,
- firstName: data.firstName,
- lastName: data.lastName,
- username: data.username,
- });
+ ): ReplicaSyncResult => {
+ this.#serverConfig = serverConfig;
+
+ return this.#ensureUserState().useSync(USER_STATE_PARAMS, {
+ enabled: !!isLogin || isDesktop,
+ // One-shot bootstrap, like the `useOnlyFetchOnceSWR` it replaced: focus or
+ // reconnect must not re-run the display snapshot, settings auto-detection
+ // and analytics identify below. Explicit refreshes go through
+ // `refreshUserState`.
+ refreshWhenOffline: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ onError: (error, { isActive }) => {
+ // The replica forwards a failed bootstrap even after an identity /
+ // workspace switch, so its captured scope can still clean up. This
+ // resource is memory-only, so there is nothing of the previous identity
+ // to purge — and `isActive: false` means the failure belongs to that
+ // previous identity, which must not paint the current one's error state
+ // (`isUserStateInitError`) over its loading state.
+ if (!isActive) return;
+ // Record the init failure so gated tabs (Advanced / ServiceModel) can
+ // render error + Retry instead of a permanent skeleton.
+ this.#set({ isUserStateInitError: error }, false, n('initUserState/error'));
+ options?.onError?.(error);
+ },
+ onSuccess: (data) => {
+ options?.onSuccess?.(data);
+
+ if (data) {
+ writeUserDisplaySnapshot(data.userId, {
+ avatar: data.avatar ?? '',
+ preference: this.#get().preference,
+ });
+
+ const autoDetectedGeneralConfig: Partial<UserGeneralConfig> = {};
+ const currentGeneralSettings = data.settings?.general;
+
+ // Auto-detect and sync browser timezone on first load
+ if (!currentGeneralSettings?.timezone && typeof Intl !== 'undefined') {
+ const detectedTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ if (detectedTimezone) autoDetectedGeneralConfig.timezone = detectedTimezone;
}
- },
+
+ // Keep reply language aligned with the browser locale until the user makes a choice.
+ // Only auto-fill once onboarding has finished — otherwise it pre-empts the
+ // language step in the onboarding flow, skipping past the user's explicit choice.
+ const hasFinishedOnboarding = !!data.onboarding?.finishedAt;
+ if (
+ hasFinishedOnboarding &&
+ !currentGeneralSettings?.responseLanguage &&
+ typeof navigator !== 'undefined'
+ ) {
+ autoDetectedGeneralConfig.responseLanguage =
+ userGeneralSettingsSelectors.currentResponseLanguage(this.#get());
+ }
+
+ if (Object.keys(autoDetectedGeneralConfig).length > 0) {
+ this.#get()
+ .updateGeneralConfig(autoDetectedGeneralConfig)
+ .catch(() => {});
+ }
+
+ analyticsClient.identify(data.userId || '', {
+ email: data.email,
+ firstName: data.firstName,
+ lastName: data.lastName,
+ username: data.username,
+ });
+ }
},
- );
+ });
};
}
diff --git a/src/store/user/slices/common/initialState.ts b/src/store/user/slices/common/initialState.ts
index 8ba8e9ca009..c01900ec9ef 100644
--- a/src/store/user/slices/common/initialState.ts
+++ b/src/store/user/slices/common/initialState.ts
@@ -1,4 +1,13 @@
-import { type Plans, type ReferralStatusString } from '@lobechat/types';
+// Import the framework-agnostic core directly, not `@/libs/replica`: the app
+// wiring pulls `@/libs/swr/useCacheScope`, which reads this very store, and the
+// cycle would leave `createReplicaState` undefined while the initial state is
+// built.
+import { createReplicaState, type ReplicaState } from '@lobechat/replica';
+import {
+ type Plans,
+ type ReferralStatusString,
+ type UserInitializationState,
+} from '@lobechat/types';
export interface CommonState {
isFreePlan?: boolean;
@@ -12,6 +21,14 @@ export interface CommonState {
isUserStateInitError?: unknown;
referralStatus?: ReferralStatusString;
subscriptionPlan?: Plans;
+ /**
+ * The confirmed bootstrap payload — the replica value behind the flat fields
+ * above. Kept so the replica can read its own entry (and so a revalidation
+ * that returns an unchanged payload skips the re-commit).
+ */
+ userState?: UserInitializationState;
+ /** Replica bookkeeping for `userState` (see `createUserStateResource`). */
+ userStateReplica: ReplicaState<UserInitializationState>;
}
export const initialCommonState: CommonState = {
@@ -22,4 +39,5 @@ export const initialCommonState: CommonState = {
isUserHasConversation: false,
isUserStateInit: false,
referralStatus: undefined,
+ userStateReplica: createReplicaState(),
};
diff --git a/src/store/user/slices/common/projection.ts b/src/store/user/slices/common/projection.ts
new file mode 100644
index 00000000000..54f0868c2b0
--- /dev/null
+++ b/src/store/user/slices/common/projection.ts
@@ -0,0 +1,33 @@
+import type { UserInitializationState } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+
+/** The bootstrap payload is one entry per identity scope. */
+export const USER_STATE_KEY = 'current';
+
+/**
+ * The user bootstrap payload (`userService.getUserState()`), one entry per
+ * identity scope (`${userId}:${workspaceId}`).
+ *
+ * Memory-only on purpose. `@/store/user/displaySnapshot` persists *only* the
+ * display fields (avatar + preference) for the cold-boot bridge precisely
+ * because restoring the whole response would also restore stale entitlement
+ * (`isFreePlan` / `subscriptionPlan`) and onboarding state. A persisted replica
+ * of this payload would re-introduce exactly that, so the entry is never written
+ * to — or hydrated from — storage: every boot fetches it fresh, and the display
+ * snapshot keeps painting the identity until that response lands.
+ *
+ * Built through a factory instead of at module scope: this resource is owned by
+ * the user store, and `@/libs/replica` pulls in `@/libs/swr/useCacheScope`,
+ * which reads that same store. The store is constructed while that cycle is
+ * still initializing, so calling `defineReplica` here at module scope would read
+ * it before it is assigned. Create it on first use instead
+ * (`CommonActionImpl.#ensureUserState`).
+ */
+export const createUserStateResource = () =>
+ defineReplica<Record<string, never>, UserInitializationState>({
+ key: () => USER_STATE_KEY,
+ name: 'userState',
+ storage: 'memory',
+ version: 1,
+ });
diff --git a/src/store/user/slices/common/replica.test.ts b/src/store/user/slices/common/replica.test.ts
new file mode 100644
index 00000000000..699fcf39ec7
--- /dev/null
+++ b/src/store/user/slices/common/replica.test.ts
@@ -0,0 +1,155 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The user bootstrap is a `@lobechat/replica` resource whose view is the user
+ * store's flat flags (`isUserStateInit`, `user`, `settings` …). It stays
+ * memory-only on purpose: `@/store/user/displaySnapshot` — not a persisted
+ * payload — bridges a cold boot, so entitlement (`isFreePlan`) and onboarding
+ * can never be restored stale. Scope isolation is the other guarantee: a switch
+ * drops the previous identity's bootstrap before the new response lands.
+ */
+import type { UserInitializationState } from '@lobechat/types';
+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 { userService } from '@/services/user';
+import { useUserStore } from '@/store/user';
+import { type GlobalServerConfig } from '@/types/serverConfig';
+
+import { initialCommonState } from './initialState';
+import { createUserStateResource } from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ {
+ value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false },
+ },
+ createElement(MutateBridge),
+ children,
+ );
+
+const SERVER_CONFIG = {} as GlobalServerConfig;
+
+const payload = (overrides: Partial<UserInitializationState> = {}): UserInitializationState =>
+ ({ preference: {}, settings: {}, userId: 'user-1', ...overrides }) as UserInitializationState;
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+describe('user bootstrap replica', () => {
+ let scope = '';
+
+ const useScope = (next: string) => {
+ scope = next;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope('user-a:personal');
+ useUserStore.setState({ ...initialCommonState });
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ const renderSync = () =>
+ renderHook(() => useUserStore((s) => s.useInitUserState)(true, SERVER_CONFIG), { wrapper });
+
+ it('is memory-only — it never writes to, or hydrates from, storage', () => {
+ const resource = createUserStateResource();
+ expect(resource.persisted).toBe(false);
+ expect(resource.storage).toBeUndefined();
+ });
+
+ it('projects the confirmed payload onto the flat flags', async () => {
+ vi.spyOn(userService, 'getUserState').mockResolvedValue(
+ payload({ avatar: 'a1', canEnableTrace: false, isFreePlan: false }),
+ );
+
+ renderSync();
+
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
+ expect(useUserStore.getState().isFreePlan).toBe(false);
+ expect(useUserStore.getState().user?.avatar).toBe('a1');
+ expect(useUserStore.getState().user?.id).toBe('user-1');
+ });
+
+ it('keeps the confirmed payload reference when a refresh returns an unchanged value', async () => {
+ const getUserState = vi.spyOn(userService, 'getUserState').mockResolvedValue(payload());
+ renderSync();
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
+ const before = useUserStore.getState().userState;
+
+ getUserState.mockResolvedValue(payload());
+ await act(() => useUserStore.getState().refreshUserState());
+
+ expect(useUserStore.getState().userState).toBe(before);
+ });
+
+ it('drops the previous identity’s bootstrap on a cache-scope switch', async () => {
+ const getUserState = vi
+ .spyOn(userService, 'getUserState')
+ .mockResolvedValue(payload({ userId: 'user-a' }));
+ const { rerender } = renderSync();
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
+
+ // Switch identity: the new scope's response is still in flight.
+ useScope('user-b:personal');
+ getUserState.mockImplementation(pending);
+ rerender();
+
+ expect(useUserStore.getState().isUserStateInit).toBe(false);
+ expect(useUserStore.getState().userState).toBeUndefined();
+ });
+
+ it('fetches once: focus and reconnect never re-run the bootstrap', async () => {
+ const getUserState = vi.spyOn(userService, 'getUserState').mockResolvedValue(payload());
+ renderSync();
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
+ expect(getUserState).toHaveBeenCalledTimes(1);
+
+ // Well past any focus throttle window.
+ const now = Date.now();
+ vi.spyOn(Date, 'now').mockReturnValue(now + 60 * 60 * 1000);
+ await act(async () => {
+ window.dispatchEvent(new Event('focus'));
+ window.dispatchEvent(new Event('online'));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ expect(getUserState).toHaveBeenCalledTimes(1);
+ });
+
+ it('records the init error and settles it once a retry succeeds', async () => {
+ const getUserState = vi
+ .spyOn(userService, 'getUserState')
+ .mockRejectedValueOnce(new Error('boom'));
+ renderSync();
+
+ await waitFor(() => expect(useUserStore.getState().isUserStateInitError).toBeInstanceOf(Error));
+ expect(useUserStore.getState().isUserStateInit).toBe(false);
+
+ getUserState.mockResolvedValue(payload());
+ await act(() => useUserStore.getState().refreshUserState());
+
+ await waitFor(() => expect(useUserStore.getState().isUserStateInit).toBe(true));
+ expect(useUserStore.getState().isUserStateInitError).toBeUndefined();
+ });
+});