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 workspaceUserSettings slice onto @lobechat/replica (#20708)

Arvin Xu099c46347868
diff --git a/src/libs/replica/cacheScope.cycle.test.ts b/src/libs/replica/cacheScope.cycle.test.ts
new file mode 100644
index 00000000000..35575412d33
--- /dev/null
+++ b/src/libs/replica/cacheScope.cycle.test.ts
@@ -0,0 +1,25 @@
+/**
+ * `useCacheScope` is the entry of a module cycle: it imports `@/store/user`,
+ * and the user-store slices import `@/libs/replica`, which imports
+ * `useCacheScope` back. Evaluating `useCacheScope` first therefore runs
+ * `@/libs/replica`'s body while `useCacheScope`'s exports are still
+ * uninitialized β€” the body must not read them at that point, or every replica
+ * resource silently gets a scope with no `get`/`use`/`canPersist`.
+ *
+ * The import order below is the whole point of the file: the first import has
+ * to be `useCacheScope` for the cycle to be entered from that side.
+ */
+import '@/libs/swr/useCacheScope';
+
+import { describe, expect, it } from 'vitest';
+
+import { cacheScope } from './index';
+
+describe('@/libs/replica cacheScope under the user-store cycle', () => {
+ it('is fully wired when useCacheScope is evaluated first', () => {
+ expect(typeof cacheScope.canPersist).toBe('function');
+ expect(typeof cacheScope.get).toBe('function');
+ expect(typeof cacheScope.use).toBe('function');
+ expect(typeof cacheScope.get()).toBe('string');
+ });
+});
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
index bd67640fb35..467b7caf3dc 100644
--- a/src/libs/replica/index.ts
+++ b/src/libs/replica/index.ts
@@ -47,11 +47,22 @@ export const setReplicaPersistedHydration = (enabled: boolean): void => {
replicaHydrationEnabled = enabled;
};
+/**
+ * The scope hook, wrapped so `cacheScope` does not *read* it while this module
+ * body runs. `@/libs/swr/useCacheScope` imports `@/store/user`, and a user-store
+ * slice imports this module β€” so when `useCacheScope` is the entry of that
+ * cycle this module's body executes before `useCacheScope`'s exports are
+ * initialized. Referencing them here directly would bake `undefined` into the
+ * scope (a resource would then have no `scope.get`); resolving at call time is
+ * equivalent because they are stateless delegating functions.
+ */
+const useCacheScopeLazy = (): string => useCacheScope();
+
export const cacheScope: ReplicaScope = {
canHydrate: () => replicaHydrationEnabled,
- canPersist: isScopeTrusted,
- get: getCacheScope,
- use: useCacheScope,
+ canPersist: () => isScopeTrusted(),
+ get: () => getCacheScope(),
+ use: useCacheScopeLazy,
};
export type ReplicaStorageKind = 'indexedDB' | 'localStorage' | 'memory';
diff --git a/src/store/user/slices/workspaceUserSettings/action.test.ts b/src/store/user/slices/workspaceUserSettings/action.test.ts
index 42c8d778edf..9ddfa843218 100644
--- a/src/store/user/slices/workspaceUserSettings/action.test.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.test.ts
@@ -1,132 +1,137 @@
+import type { WorkspaceUserPreference } from '@lobechat/types';
+import { act } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
+import { useUserStore } from '@/store/user';
-import { WorkspaceUserSettingsActionImpl } from './action';
-
-const { mockMutate } = vi.hoisted(() => ({ mockMutate: vi.fn() }));
+const active = vi.hoisted(() => ({ id: 'workspace-1' as string | null }));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- getActiveWorkspaceId: () => 'workspace-1',
- useActiveWorkspaceId: () => 'workspace-1',
+ getActiveWorkspaceId: () => active.id,
+ useActiveWorkspaceId: () => active.id,
}));
-vi.mock('@/libs/swr', () => ({
- mutate: mockMutate,
- useClientDataSWR: vi.fn(),
+vi.mock('@/services/workspaceUserSettings', () => ({
+ workspaceUserSettingsService: {
+ getPreference: vi.fn(),
+ updatePreference: vi.fn(),
+ },
}));
+const state = () => useUserStore.getState();
+
+/** Seed the active workspace's bucket as if the replica had already loaded it. */
+const seed = (preference: WorkspaceUserPreference) =>
+ useUserStore.setState({
+ workspaceUserPreference: preference,
+ workspaceUserPreferenceWorkspaceId: 'workspace-1',
+ });
+
describe('WorkspaceUserSettingsActionImpl', () => {
beforeEach(() => {
+ active.id = 'workspace-1';
vi.clearAllMocks();
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockResolvedValue(undefined);
+ useUserStore.setState({
+ workspaceUserPreference: {},
+ workspaceUserPreferenceWorkspaceId: null,
+ });
});
it('optimistically deep-merges one Agent model choice without dropping other choices', async () => {
- const state = {
- workspaceUserPreference: {
- agentDeviceOverrides: {
- deviceAgent: { executionTarget: 'sandbox' as const },
- },
+ seed({
+ agentDeviceOverrides: { deviceAgent: { executionTarget: 'sandbox' as const } },
+ agentModelOverrides: { existing: { model: 'existing-model', provider: 'existing-provider' } },
+ agentModeOverrides: { existing: true },
+ });
+
+ await act(() =>
+ state().updateWorkspaceUserPreference({
agentModelOverrides: {
- existing: { model: 'existing-model', provider: 'existing-provider' },
- },
- agentModeOverrides: {
- existing: true,
+ selected: { model: 'selected-model', provider: 'selected-provider' },
},
- },
- };
- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
- const action = new WorkspaceUserSettingsActionImpl(set as never, () => state as never);
- vi.spyOn(workspaceUserSettingsService, 'updatePreference').mockResolvedValue();
+ }),
+ );
- await action.updateWorkspaceUserPreference({
+ expect(state().workspaceUserPreference).toEqual({
+ agentDeviceOverrides: { deviceAgent: { executionTarget: 'sandbox' } },
agentModelOverrides: {
+ existing: { model: 'existing-model', provider: 'existing-provider' },
selected: { model: 'selected-model', provider: 'selected-provider' },
},
+ agentModeOverrides: { existing: true },
});
-
- expect(state.workspaceUserPreference).toEqual({
- agentDeviceOverrides: {
- deviceAgent: { executionTarget: 'sandbox' },
- },
+ expect(workspaceUserSettingsService.updatePreference).toHaveBeenCalledWith({
agentModelOverrides: {
- existing: { model: 'existing-model', provider: 'existing-provider' },
selected: { model: 'selected-model', provider: 'selected-provider' },
},
- agentModeOverrides: {
- existing: true,
- },
});
- expect(mockMutate).toHaveBeenCalledWith(
- ['FETCH_WORKSPACE_USER_SETTINGS', 'workspace-1'],
- state.workspaceUserPreference,
- { revalidate: false },
- );
});
it('optimistically deep-merges one Agent mode without dropping other modes', async () => {
- const state = {
- workspaceUserPreference: {
- agentModeOverrides: { existing: true },
- },
- };
- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
- const action = new WorkspaceUserSettingsActionImpl(set as never, () => state as never);
- vi.spyOn(workspaceUserSettingsService, 'updatePreference').mockResolvedValue();
+ seed({ agentModeOverrides: { existing: true } });
- await action.updateWorkspaceUserPreference({
- agentModeOverrides: { selected: false },
- });
+ await act(() =>
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { selected: false } }),
+ );
- expect(state.workspaceUserPreference.agentModeOverrides).toEqual({
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({
existing: true,
selected: false,
});
});
- it('optimistically deep-merges sidebar visibility without dropping other items', async () => {
- const state = {
- workspaceUserPreference: {
- sidebarAgentVisibilityOverrides: { existing: true },
- },
- };
- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
- const action = new WorkspaceUserSettingsActionImpl(set as never, () => state as never);
- vi.spyOn(workspaceUserSettingsService, 'updatePreference').mockResolvedValue();
+ it('optimistically deep-merges one Agent device override without dropping others', async () => {
+ seed({ agentDeviceOverrides: { keep: { executionTarget: 'local' } } });
- await action.updateWorkspaceUserPreference({
- sidebarAgentVisibilityOverrides: { selected: false },
+ await act(() =>
+ state().updateWorkspaceUserPreference({
+ agentDeviceOverrides: { selected: { executionTarget: 'sandbox' as const } },
+ }),
+ );
+
+ expect(state().workspaceUserPreference.agentDeviceOverrides).toEqual({
+ keep: { executionTarget: 'local' },
+ selected: { executionTarget: 'sandbox' },
});
+ });
- expect(state.workspaceUserPreference.sidebarAgentVisibilityOverrides).toEqual({
+ it('optimistically deep-merges sidebar visibility without dropping other items', async () => {
+ seed({ sidebarAgentVisibilityOverrides: { existing: true } });
+
+ await act(() =>
+ state().updateWorkspaceUserPreference({
+ sidebarAgentVisibilityOverrides: { selected: false },
+ }),
+ );
+
+ expect(state().workspaceUserPreference.sidebarAgentVisibilityOverrides).toEqual({
existing: true,
selected: false,
});
});
it('optimistically deep-merges one notification switch without dropping sibling toggles', async () => {
- const state = {
- workspaceUserPreference: {
- notification: {
- email: { items: { workspace: { workspace_member_joined: false } } },
- inbox: { enabled: false },
- },
+ seed({
+ notification: {
+ email: { items: { workspace: { workspace_member_joined: false } } },
+ inbox: { enabled: false },
},
- };
- const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
- const action = new WorkspaceUserSettingsActionImpl(set as never, () => state as never);
- vi.spyOn(workspaceUserSettingsService, 'updatePreference').mockResolvedValue();
+ });
// Patch a single other leaf β€” the earlier email item toggle and the inbox
- // master switch must both survive in the optimistic cache, mirroring what
+ // master switch must both survive in the optimistic view, mirroring what
// the server-side deep merge keeps in the DB.
- await action.updateWorkspaceUserPreference({
- notification: {
- email: { items: { workspace: { workspace_payment_failed: false } } },
- },
- });
+ await act(() =>
+ state().updateWorkspaceUserPreference({
+ notification: {
+ email: { items: { workspace: { workspace_payment_failed: false } } },
+ },
+ }),
+ );
- expect(state.workspaceUserPreference.notification).toEqual({
+ expect(state().workspaceUserPreference.notification).toEqual({
email: {
items: {
workspace: { workspace_member_joined: false, workspace_payment_failed: false },
@@ -135,4 +140,32 @@ describe('WorkspaceUserSettingsActionImpl', () => {
inbox: { enabled: false },
});
});
+
+ it('rolls the view back when the mutation fails', async () => {
+ seed({ agentModeOverrides: { existing: true } });
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockRejectedValue(new Error('boom'));
+
+ await act(async () => {
+ await expect(
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { selected: false } }),
+ ).rejects.toThrow('boom');
+ });
+
+ expect(state().workspaceUserPreference).toEqual({ agentModeOverrides: { existing: true } });
+ });
+
+ it('keeps the pre-migration server call in personal mode (no active workspace)', async () => {
+ active.id = null;
+ seed({ agentModeOverrides: { existing: true } });
+
+ await act(() =>
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { selected: false } }),
+ );
+
+ expect(workspaceUserSettingsService.updatePreference).toHaveBeenCalledWith({
+ agentModeOverrides: { selected: false },
+ });
+ // No workspace key to write under β€” the view is untouched.
+ expect(state().workspaceUserPreference).toEqual({ agentModeOverrides: { existing: true } });
+ });
});
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index a711636d39b..2f3d9147e4b 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -1,148 +1,247 @@
+import type { ReplicaSlice } from '@lobechat/replica/zustand';
import type { WorkspaceUserPreference } from '@lobechat/types';
import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';
-import { useEffect } from 'react';
+import isEqual from 'fast-deep-equal';
+import { useSyncExternalStore } from 'react';
import {
getActiveWorkspaceId,
useActiveWorkspaceId,
} from '@/business/client/hooks/useActiveWorkspaceId';
-import { mutate, useClientDataSWR } from '@/libs/swr';
+import { createReplicaSlice, type ReplicaLens } from '@/libs/replica';
import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
import { type StoreSetter } from '@/store/types';
-import { type UserStore } from '@/store/user';
import { setNamespace } from '@/utils/storeDebug';
-const n = setNamespace('workspaceUserSettings');
+import type { UserState } from '../../initialState';
+import type { UserStore } from '../../store';
+import {
+ getWorkspaceUserPreferenceResource,
+ type WorkspaceUserPreferenceParams,
+} from './projection';
-const WORKSPACE_USER_SETTINGS_SWR_KEY = 'FETCH_WORKSPACE_USER_SETTINGS';
+const n = setNamespace('workspaceUserSettings');
type Setter = StoreSetter<UserStore>;
+type PreferenceSlice = ReplicaSlice<
+ UserStore,
+ WorkspaceUserPreferenceParams,
+ WorkspaceUserPreference,
+ WorkspaceUserPreference | null
+>;
+
+/**
+ * Read side of the store api this slice needs to observe its own view. It reads
+ * through the store instead of importing `useUserStore`: this slice is part of
+ * that store, so a value import closes the `store β†’ slice β†’ store` module cycle
+ * the circular lint rejects (see `useFetchWorkspaceUserPreference`).
+ */
+interface PreferenceStoreApi {
+ getState: () => UserState;
+ subscribe: (listener: () => void) => () => void;
+}
+
+/** Never notifies β€” what the snapshot falls back to when no store api is wired. */
+const EMPTY_SUBSCRIBE = () => () => {};
+
+/**
+ * Fold a preference patch onto the current bucket, mirroring the server's deep
+ * merge (`WorkspaceUserSettingsModel`) so an optimistic write never drops a
+ * sibling override / notification toggle the DB keeps.
+ */
+const mergePreference = (
+ previous: WorkspaceUserPreference,
+ patch: Partial<WorkspaceUserPreference>,
+): WorkspaceUserPreference => ({
+ ...previous,
+ ...patch,
+ ...(patch.agentDeviceOverrides
+ ? { agentDeviceOverrides: { ...previous.agentDeviceOverrides, ...patch.agentDeviceOverrides } }
+ : {}),
+ ...(patch.agentModelOverrides
+ ? { agentModelOverrides: { ...previous.agentModelOverrides, ...patch.agentModelOverrides } }
+ : {}),
+ ...(patch.agentModeOverrides
+ ? { agentModeOverrides: { ...previous.agentModeOverrides, ...patch.agentModeOverrides } }
+ : {}),
+ ...(patch.notification
+ ? { notification: mergeNotificationSettings(previous.notification, patch.notification) }
+ : {}),
+ ...(patch.sidebarAgentVisibilityOverrides
+ ? {
+ sidebarAgentVisibilityOverrides: {
+ ...previous.sidebarAgentVisibilityOverrides,
+ ...patch.sidebarAgentVisibilityOverrides,
+ },
+ }
+ : {}),
+});
+
+/**
+ * Single-slot view of the workspace-user preference replica: the active
+ * workspace's bucket stays on the long-standing fields
+ * (`workspaceUserPreference` + `workspaceUserPreferenceWorkspaceId`), so every
+ * existing selector / consumer keeps reading the same place. Only the entry of
+ * the active workspace is materialized β€” the marker gates that.
+ */
+const workspaceUserPreferenceLens: ReplicaLens<UserStore, WorkspaceUserPreference> = {
+ clear: () => ({ workspaceUserPreference: {}, workspaceUserPreferenceWorkspaceId: null }),
+ get: (state, key) =>
+ state.workspaceUserPreferenceWorkspaceId === key ? state.workspaceUserPreference : undefined,
+ keys: (state) =>
+ state.workspaceUserPreferenceWorkspaceId === null
+ ? []
+ : [state.workspaceUserPreferenceWorkspaceId],
+ set: (_state, key, data) =>
+ data === undefined
+ ? { workspaceUserPreference: {}, workspaceUserPreferenceWorkspaceId: null }
+ : { workspaceUserPreference: data, workspaceUserPreferenceWorkspaceId: key },
+};
+
/**
- * Slice for the caller's `workspace_user_settings.preference` bucket. Reads
- * are SWR-cached and keyed on the ACTIVE workspaceId β€” switching workspaces
- * auto-refetches; personal mode short-circuits without hitting the network
- * (the row doesn't exist there and the server would reject the request).
+ * Slice for the caller's `workspace_user_settings.preference` bucket. Reads go
+ * through the replica (local-first, idempotent, scope-partitioned): the
+ * identity partition `${userId}:${workspaceId}` owns the workspace boundary, so
+ * switching workspaces drops the previous bucket before paint and reads the
+ * right one. Personal mode short-circuits without hitting the network β€” the row
+ * doesn't exist there and the server would reject the request.
*
- * Writes go through the tRPC mutation, then merge the returned bucket back
- * into local state so pickers observe their pick immediately without waiting
- * for the SWR revalidation cycle.
+ * Writes merge the patch into the view optimistically (so a picker observes its
+ * pick immediately) and roll the view back if the mutation fails.
*/
export const createWorkspaceUserSettingsSlice = (
set: Setter,
get: () => UserStore,
- _api?: unknown,
+ _api?: PreferenceStoreApi,
) => new WorkspaceUserSettingsActionImpl(set, get, _api);
export class WorkspaceUserSettingsActionImpl {
+ readonly #api: PreferenceStoreApi | undefined;
readonly #get: () => UserStore;
readonly #set: Setter;
+ /**
+ * Local-first replica of the active workspace's preference bucket (its view
+ * is `workspaceUserPreference`), created on first use rather than in the
+ * constructor: `@/libs/replica` reaches `@/store/user` through its
+ * cache-scope wiring, and the constructor runs while the user store module is
+ * still initializing β€” evaluating the binding there is a module cycle (see
+ * `projection.ts`).
+ */
+ #preference?: PreferenceSlice;
- constructor(set: Setter, get: () => UserStore, _api?: unknown) {
- void _api;
+ constructor(set: Setter, get: () => UserStore, _api?: PreferenceStoreApi) {
+ this.#api = _api;
this.#set = set;
this.#get = get;
}
+ #replica(): PreferenceSlice {
+ this.#preference ??= createReplicaSlice(getWorkspaceUserPreferenceResource(), {
+ actionPrefix: n('preference'),
+ fetcher: () => workspaceUserSettingsService.getPreference(),
+ get: this.#get,
+ // A `null` response (no server row) reads as the empty bucket; an
+ // unchanged response must not re-render every consumer.
+ merge: (incoming, confirmed) => {
+ const next = incoming ?? {};
+ return isEqual(next, confirmed) ? undefined : next;
+ },
+ set: this.#set,
+ stateKey: 'workspaceUserPreferenceReplica',
+ view: workspaceUserPreferenceLens,
+ });
+ return this.#preference;
+ }
+
+ /**
+ * Sync the active workspace's preference into the store view. Several
+ * surfaces mount this (sidebar, chat input, view-all page); the replica
+ * dedupes the underlying read by scope + key, so calling it from each is
+ * safe. Returns the shape the existing consumers expect
+ * (`{ data, isLoading, mutate }`), where `data === undefined` means "not
+ * loaded yet β€” fall back to the store bucket".
+ */
useFetchWorkspaceUserPreference = () => {
const workspaceId = useActiveWorkspaceId();
- const swr = useClientDataSWR<WorkspaceUserPreference | null>(
- workspaceId ? [WORKSPACE_USER_SETTINGS_SWR_KEY, workspaceId] : null,
- async () => workspaceUserSettingsService.getPreference(),
+ const sync = this.#replica().useSync(workspaceId ? { workspaceId } : null, {
+ enabled: !!workspaceId,
+ });
+
+ // Read the view through the store api rather than `useUserStore`: importing
+ // the store hook here would close a `store β†’ slice β†’ store` module cycle
+ // (`dpdm` rejects it). Same reactive read, no module edge β€” the shape
+ // mirrors `useChatInputResourceAccess`.
+ const api = this.#api;
+ const data = useSyncExternalStore(
+ api ? api.subscribe : EMPTY_SUBSCRIBE,
+ () => {
+ const state = api ? api.getState() : this.#get();
+ return workspaceId && state.workspaceUserPreferenceWorkspaceId === workspaceId
+ ? state.workspaceUserPreference
+ : undefined;
+ },
+ () => undefined,
);
- // Sync EVERY data change into the (un-keyed) store bucket β€” not just
- // fetch successes. On a workspace switch-back the SWR cache serves the
- // new workspace's preference synchronously, and an `onSuccess`-only sync
- // would leave the bucket holding the previous workspace's data until
- // revalidation lands; imperative readers (send-time cwd resolution) read
- // the bucket, so it must be corrected on the first render. A `null`
- // response (no server row) clears the bucket for the same reason.
- const data = swr.data;
- useEffect(() => {
- if (data === undefined || !workspaceId) return;
- this.#set(
- { workspaceUserPreference: data ?? {}, workspaceUserPreferenceWorkspaceId: workspaceId },
- false,
- n('useFetchWorkspaceUserPreference/sync'),
- );
- }, [data, workspaceId]);
-
- return swr;
+ return {
+ data,
+ // Mirrors the old SWR `isLoading`: no value for this workspace yet and
+ // the local copy hasn't settled (or the network is still confirming it).
+ isLoading: !!workspaceId && data === undefined && (!sync.isHydrated || sync.isValidating),
+ mutate: sync.revalidate,
+ };
};
updateWorkspaceUserPreference = async (
patch: Partial<WorkspaceUserPreference>,
): Promise<void> => {
- // Optimistic merge β€” the picker's own re-render should see the new
- // choice on the very next frame, not wait for the mutation round-trip.
- // Mirror the write into the SWR cache too: readers that prefer the
- // workspace-keyed SWR data over this un-keyed bucket (see
- // `useEffectiveAgencyConfig`) must observe the optimistic value as well.
- const previous = this.#get().workspaceUserPreference;
- const optimistic: WorkspaceUserPreference = {
- ...previous,
- ...patch,
- ...(patch.agentDeviceOverrides
- ? {
- agentDeviceOverrides: {
- ...previous.agentDeviceOverrides,
- ...patch.agentDeviceOverrides,
- },
- }
- : {}),
- ...(patch.agentModelOverrides
- ? {
- agentModelOverrides: {
- ...previous.agentModelOverrides,
- ...patch.agentModelOverrides,
- },
- }
- : {}),
- ...(patch.agentModeOverrides
- ? {
- agentModeOverrides: {
- ...previous.agentModeOverrides,
- ...patch.agentModeOverrides,
- },
- }
- : {}),
- // Mirror the server's deep merge (WorkspaceUserSettingsModel) so the
- // optimistic cache never drops sibling notification toggles the DB keeps.
- ...(patch.notification
- ? { notification: mergeNotificationSettings(previous.notification, patch.notification) }
- : {}),
- ...(patch.sidebarAgentVisibilityOverrides
- ? {
- sidebarAgentVisibilityOverrides: {
- ...previous.sidebarAgentVisibilityOverrides,
- ...patch.sidebarAgentVisibilityOverrides,
- },
- }
- : {}),
- };
const workspaceId = getActiveWorkspaceId();
- const swrKey = workspaceId ? [WORKSPACE_USER_SETTINGS_SWR_KEY, workspaceId] : null;
- this.#set(
- { workspaceUserPreference: optimistic },
- false,
- n('updateWorkspaceUserPreference/optimistic'),
- );
- if (swrKey) void mutate(swrKey, optimistic, { revalidate: false });
+ const previous = this.#get().workspaceUserPreference;
- try {
+ // Personal mode (no active workspace) has no row to key on; keep the server
+ // call so the pre-migration contract is unchanged.
+ if (!workspaceId) {
await workspaceUserSettingsService.updatePreference(patch);
- } catch (error) {
- // Roll back the optimistic write so the picker doesn't strand a state
- // that never made it to the server.
- this.#set(
- { workspaceUserPreference: previous },
- false,
- n('updateWorkspaceUserPreference/rollback'),
- );
- if (swrKey) void mutate(swrKey, previous, { revalidate: false });
- throw error;
+ return;
}
+
+ const replica = this.#replica();
+
+ // A picker can fire before the local copy was read. Read it first: seeding
+ // an entry now would make the persisted bucket unhydratable (hydration only
+ // fills an empty slot), so a failed write would hide the cached overrides
+ // and a successful one would persist the bare patch over them. Only a write
+ // that finds nothing loaded pays for the (local, IndexedDB) read.
+ if (replica.getConfirmed(workspaceId) === undefined) {
+ await replica.hydrate({ workspaceId });
+
+ // The active workspace can change while the (local, IndexedDB) read is
+ // pending. Everything after this point β€” the local seed/overlay and, above
+ // all, the service call, which carries the *current* workspace context β€”
+ // would then apply a preference picked in the previous workspace to the
+ // new one. Abandon the write: the pick belonged to the workspace that was
+ // active when it was made.
+ if (getActiveWorkspaceId() !== workspaceId) return;
+ }
+
+ // Seed the active entry when there is still nothing loaded (no local copy),
+ // so the optimistic overlay below always has a value to apply onto.
+ // `persist: false` β€” this is not a server-confirmed value.
+ replica.update(workspaceId, (data) => data ?? previous, { persist: false });
+
+ // Optimistic merge: the picker's own re-render sees the new choice on the
+ // next frame, and a failed write rolls the view back to the pre-write
+ // bucket. Revalidate once the write settles: it supersedes a read that
+ // started before the write (the driver discards that response), which
+ // would otherwise land after the overlay is gone and restore the old value
+ // in the view and IndexedDB.
+ await replica.optimistic(
+ workspaceId,
+ (data) => mergePreference(data, patch),
+ () => workspaceUserSettingsService.updatePreference(patch),
+ { revalidate: true },
+ );
};
}
diff --git a/src/store/user/slices/workspaceUserSettings/initialState.ts b/src/store/user/slices/workspaceUserSettings/initialState.ts
index 46b88ed1a4a..457f8d31239 100644
--- a/src/store/user/slices/workspaceUserSettings/initialState.ts
+++ b/src/store/user/slices/workspaceUserSettings/initialState.ts
@@ -1,22 +1,30 @@
import type { WorkspaceUserPreference } from '@lobechat/types';
+import type { ReplicaState } from '@/libs/replica';
+
/**
- * Cached copy of the caller's `workspace_user_settings.preference` row for
- * the currently-active workspace. Refreshed via SWR keyed on the active
- * `workspaceId`, so switching workspaces auto-refetches the right bucket.
+ * Replica-backed copy of the caller's `workspace_user_settings.preference`
+ * row for the currently-active workspace (see
+ * `getWorkspaceUserPreferenceResource`). The replica is keyed on the active
+ * `workspaceId` and partitioned by the identity scope, so switching workspaces
+ * drops the previous workspace's bucket before paint and reads the right one.
*/
export interface WorkspaceUserSettingsState {
/**
- * Empty on first load / while SWR is fetching / when the caller is in
- * personal mode. Consumers should treat empty as "no override β€” use the
- * shared defaults", identical to the pre behaviour.
+ * The active workspace's preference bucket β€” the replica view. Empty on
+ * first load / while the local copy is being read / in personal mode.
+ * Consumers treat empty as "no override β€” use the shared defaults",
+ * identical to the pre-migration behaviour.
*/
workspaceUserPreference: WorkspaceUserPreference;
+ /** Replica bookkeeping for `workspaceUserPreference` (see `getWorkspaceUserPreferenceResource`). */
+ workspaceUserPreferenceReplica: ReplicaState<WorkspaceUserPreference>;
/**
* The workspace whose preference row `workspaceUserPreference` currently
- * holds, or `null` before the first fetch resolves. Lets consumers tell
- * "loaded and empty" apart from "not fetched yet" (e.g. the sidebar bridge
- * must not clear the overlay until the active workspace's row has loaded).
+ * holds, or `null` before the first hydrate/fetch resolves. Lets consumers
+ * tell "loaded and empty" apart from "not fetched yet" (e.g. the sidebar
+ * bridge must not clear the overlay until the active workspace's row has
+ * loaded β€” see `workspaceUserSettingsSelectors.preferenceWorkspaceId`).
*/
workspaceUserPreferenceWorkspaceId: string | null;
}
@@ -24,4 +32,9 @@ export interface WorkspaceUserSettingsState {
export const initialWorkspaceUserSettingsState: WorkspaceUserSettingsState = {
workspaceUserPreference: {},
workspaceUserPreferenceWorkspaceId: null,
+ // The literal is the same `{ entries: {} }` `createReplicaState()` returns,
+ // written out because `@/libs/replica` imports `@/store/user` through its
+ // cache-scope wiring: evaluating that module while the user store initializes
+ // its own state is a cycle (see `projection.ts`).
+ workspaceUserPreferenceReplica: { entries: {} },
};
diff --git a/src/store/user/slices/workspaceUserSettings/projection.ts b/src/store/user/slices/workspaceUserSettings/projection.ts
new file mode 100644
index 00000000000..2ff96c918b0
--- /dev/null
+++ b/src/store/user/slices/workspaceUserSettings/projection.ts
@@ -0,0 +1,49 @@
+import type { WorkspaceUserPreference } from '@lobechat/types';
+
+import { defineReplica, type ReplicaResource } from '@/libs/replica';
+
+export interface WorkspaceUserPreferenceParams {
+ /** The currently-active workspace; the preference row is one per workspace. */
+ workspaceId: string;
+}
+
+type WorkspaceUserPreferenceResource = ReplicaResource<
+ WorkspaceUserPreferenceParams,
+ WorkspaceUserPreference,
+ WorkspaceUserPreference | null
+>;
+
+let resource: WorkspaceUserPreferenceResource | undefined;
+
+/**
+ * The caller's `workspace_user_settings.preference` bucket of one workspace,
+ * keyed by the active `workspaceId` (`workspaceUserPreference` is its view).
+ *
+ * The identity partition (`${userId}:${workspaceId}`) already owns the
+ * workspace boundary β€” switching workspaces is a scope change, so a projection
+ * is read and revalidated for the right workspace without the fetcher naming it
+ * (the tRPC context carries the workspace).
+ *
+ * Persisted to IndexedDB so a reload paints the member's last-known preference
+ * from the local copy instead of the empty bucket, with the network only
+ * confirming it. The fetched value may be `null` when the workspace has no row
+ * yet; the view folds that to the empty bucket.
+ *
+ * Built lazily on purpose: `@/libs/replica` reaches `@/store/user` through its
+ * cache-scope wiring (`useCacheScope`), so the user store must not evaluate
+ * this resource while its own module (and store) is being created β€” that would
+ * read `@/libs/replica`'s exports mid-cycle. Resolving the binding on first use
+ * is safe in both import orders: whether the user store or `@/libs/replica`
+ * loads first, both modules have settled by then.
+ */
+export const getWorkspaceUserPreferenceResource = (): WorkspaceUserPreferenceResource =>
+ (resource ??= defineReplica<
+ WorkspaceUserPreferenceParams,
+ WorkspaceUserPreference,
+ WorkspaceUserPreference | null
+ >({
+ key: ({ workspaceId }) => workspaceId,
+ name: 'workspaceUserSettings',
+ storage: 'indexedDB',
+ version: 1,
+ }));
diff --git a/src/store/user/slices/workspaceUserSettings/replica.test.ts b/src/store/user/slices/workspaceUserSettings/replica.test.ts
new file mode 100644
index 00000000000..617b28198d4
--- /dev/null
+++ b/src/store/user/slices/workspaceUserSettings/replica.test.ts
@@ -0,0 +1,323 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The workspace-user preference bucket is a `@lobechat/replica` resource whose
+ * view is the user store's flat `workspaceUserPreference` field (+ the
+ * `workspaceUserPreferenceWorkspaceId` loaded marker): a persisted projection
+ * paints while the network confirms it, personal mode never hits the network,
+ * and a cache-scope switch drops the previous workspace's bucket before paint β€”
+ * applying a foreign workspace's overrides would route the wrong model / device.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { WorkspaceUserPreference } 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 { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
+import { useUserStore } from '@/store/user';
+
+import { initialWorkspaceUserSettingsState } from './initialState';
+import { getWorkspaceUserPreferenceResource } from './projection';
+
+// The OSS build stubs the active-workspace hook to `null`; workspace behaviour
+// only exists where a workspace is active, so drive it with a controllable id.
+const active = vi.hoisted(() => ({ id: 'ws-1' as string | null }));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => active.id,
+ useActiveWorkspaceId: () => active.id,
+}));
+
+vi.mock('@/services/workspaceUserSettings', () => ({
+ workspaceUserSettingsService: {
+ getPreference: vi.fn(),
+ updatePreference: 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,
+ );
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const state = () => useUserStore.getState();
+const resource = getWorkspaceUserPreferenceResource();
+const storageKey = resource.storageKey({ workspaceId: 'ws-1' });
+const entry = (workspaceId: string) => state().workspaceUserPreferenceReplica.entries[workspaceId];
+
+const renderSync = () =>
+ renderHook(() => useUserStore((s) => s.useFetchWorkspaceUserPreference)(), { wrapper });
+
+describe('workspace user preference 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(() => {
+ active.id = 'ws-1';
+ useScope(`wp-user-${randomUUID()}:ws-1`);
+ useUserStore.setState({ ...initialWorkspaceUserSettingsState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].map((value) => resource.storage!.remove({ queryKey: storageKey, scope: value })),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('fetches the active workspace preference and paints the view', async () => {
+ const preference: WorkspaceUserPreference = {
+ agentModelOverrides: { a1: { model: 'gpt-5', provider: 'openai' } },
+ };
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue(preference);
+
+ const { result } = renderSync();
+
+ await waitFor(() => expect(state().workspaceUserPreference).toEqual(preference));
+ expect(state().workspaceUserPreferenceWorkspaceId).toBe('ws-1');
+ expect(entry('ws-1').source).toBe('server');
+ expect(workspaceUserSettingsService.getPreference).toHaveBeenCalledTimes(1);
+
+ // The hook keeps the shape the consumers expect: `data` is the loaded view.
+ expect(result.current.data).toEqual(preference);
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('paints the persisted projection before the network answers', async () => {
+ await resource.storage!.set(
+ { queryKey: storageKey, scope },
+ { data: { agentModeOverrides: { a1: true } }, updatedAt: 1 },
+ );
+ vi.mocked(workspaceUserSettingsService.getPreference).mockImplementation(pending);
+
+ renderSync();
+
+ await waitFor(() => expect(state().workspaceUserPreferenceWorkspaceId).toBe('ws-1'));
+ expect(state().workspaceUserPreference).toEqual({ agentModeOverrides: { a1: true } });
+ expect(entry('ws-1').source).toBe('storage');
+ });
+
+ it('reads a null server row as a loaded, empty bucket', async () => {
+ // A workspace with no row yet: the server answers `null`.
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue(
+ null as unknown as WorkspaceUserPreference,
+ );
+
+ renderSync();
+
+ await waitFor(() => expect(state().workspaceUserPreferenceWorkspaceId).toBe('ws-1'));
+ expect(state().workspaceUserPreference).toEqual({});
+ expect(entry('ws-1').source).toBe('server');
+ });
+
+ it('never hits the network in personal mode (no active workspace)', async () => {
+ active.id = null;
+
+ const { result } = renderSync();
+ await act(async () => {});
+
+ expect(workspaceUserSettingsService.getPreference).not.toHaveBeenCalled();
+ expect(state().workspaceUserPreferenceWorkspaceId).toBeNull();
+ expect(state().workspaceUserPreference).toEqual({});
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('drops the previous workspace bucket on a scope switch, before paint', async () => {
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue({
+ agentModeOverrides: { a1: true },
+ });
+ const { rerender } = renderSync();
+ await waitFor(() => expect(state().workspaceUserPreferenceWorkspaceId).toBe('ws-1'));
+
+ // Switch workspace: the new scope's read is still in flight.
+ const user = scope.split(':')[0];
+ useScope(`${user}:ws-2`);
+ active.id = 'ws-2';
+ vi.mocked(workspaceUserSettingsService.getPreference).mockImplementation(pending);
+ rerender();
+
+ expect(state().workspaceUserPreference).toEqual({});
+ expect(state().workspaceUserPreferenceWorkspaceId).toBeNull();
+ });
+
+ it('optimistically merges a write into the view and rolls it back on failure', async () => {
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue({
+ agentModeOverrides: { existing: true },
+ });
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockResolvedValue(undefined);
+ renderSync();
+ await waitFor(() =>
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({ existing: true }),
+ );
+
+ // The server holds the merged row once the write lands (the write revalidates).
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue({
+ agentModeOverrides: { existing: true, selected: false },
+ });
+ await act(() =>
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { selected: false } }),
+ );
+
+ // The sibling override survives the optimistic merge (server-side deep merge).
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({
+ existing: true,
+ selected: false,
+ });
+ expect(workspaceUserSettingsService.updatePreference).toHaveBeenCalledWith({
+ agentModeOverrides: { selected: false },
+ });
+
+ // A failed write returns the view to the pre-write bucket.
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockRejectedValue(new Error('nope'));
+ await act(async () => {
+ await expect(
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { boom: true } }),
+ ).rejects.toThrow('nope');
+ });
+
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({
+ existing: true,
+ selected: false,
+ });
+ });
+
+ it('applies a write made before hydration onto the persisted bucket, not over it', async () => {
+ await resource.storage!.set(
+ { queryKey: storageKey, scope },
+ { data: { agentModeOverrides: { cached: true } }, updatedAt: 1 },
+ );
+ vi.mocked(workspaceUserSettingsService.getPreference).mockImplementation(pending);
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockResolvedValue(undefined);
+
+ // A picker fires before anything read the local copy.
+ await act(() =>
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { picked: false } }),
+ );
+
+ // The persisted bucket is the base: the pick never hides the cached overrides.
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({
+ cached: true,
+ picked: false,
+ });
+ await waitFor(async () =>
+ expect(
+ (await resource.storage!.get({ queryKey: storageKey, scope }))?.data.agentModeOverrides,
+ ).toEqual({ cached: true, picked: false }),
+ );
+ });
+
+ it('keeps the cached bucket when a write before hydration fails offline', async () => {
+ await resource.storage!.set(
+ { queryKey: storageKey, scope },
+ { data: { agentModeOverrides: { cached: true } }, updatedAt: 1 },
+ );
+ vi.mocked(workspaceUserSettingsService.getPreference).mockImplementation(pending);
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockRejectedValue(
+ new Error('offline'),
+ );
+
+ await act(async () => {
+ await expect(
+ state().updateWorkspaceUserPreference({ agentModeOverrides: { picked: false } }),
+ ).rejects.toThrow('offline');
+ });
+
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({ cached: true });
+ });
+
+ it('does not let a read that started before a write overwrite it', async () => {
+ vi.mocked(workspaceUserSettingsService.getPreference).mockResolvedValue({
+ agentModeOverrides: { a1: true },
+ });
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockResolvedValue(undefined);
+ const { result } = renderSync();
+ await waitFor(() =>
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({ a1: true }),
+ );
+
+ // A revalidation reads the old value and is still in flight…
+ let resolveStale!: (value: WorkspaceUserPreference) => void;
+ vi.mocked(workspaceUserSettingsService.getPreference)
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveStale = resolve)))
+ .mockResolvedValue({ agentModeOverrides: { a1: false } });
+ act(() => {
+ void result.current.mutate();
+ });
+ await waitFor(() => expect(resolveStale).toBeDefined());
+
+ // …when the user picks the new value…
+ await act(() => state().updateWorkspaceUserPreference({ agentModeOverrides: { a1: false } }));
+
+ // …and the stale read answers afterwards.
+ await act(async () => {
+ resolveStale({ agentModeOverrides: { a1: true } });
+ });
+
+ await waitFor(() =>
+ expect(workspaceUserSettingsService.getPreference).toHaveBeenCalledTimes(3),
+ );
+ await waitFor(() =>
+ expect(state().workspaceUserPreference.agentModeOverrides).toEqual({ a1: false }),
+ );
+ await waitFor(async () =>
+ expect(
+ (await resource.storage!.get({ queryKey: storageKey, scope }))?.data.agentModeOverrides,
+ ).toEqual({ a1: false }),
+ );
+ });
+
+ it('abandons a write when the active workspace changed during the pending local read', async () => {
+ vi.mocked(workspaceUserSettingsService.getPreference).mockImplementation(pending);
+ vi.mocked(workspaceUserSettingsService.updatePreference).mockResolvedValue(undefined);
+
+ // Nothing is loaded for ws-1, so the write waits on the local read; hold it.
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));
+ const storage = resource.storage!;
+ vi.spyOn(storage, 'get').mockImplementation(async () => {
+ await readGate;
+ return undefined;
+ });
+
+ const write = state().updateWorkspaceUserPreference({ agentModeOverrides: { a1: true } });
+
+ // The workspace switches before that read resolves.
+ active.id = 'ws-2';
+ releaseRead();
+ await write;
+
+ // The pick belonged to ws-1: it is not applied locally, and β€” the real
+ // hazard β€” the service call never carries it into ws-2.
+ expect(workspaceUserSettingsService.updatePreference).not.toHaveBeenCalled();
+ expect(state().workspaceUserPreference.agentModeOverrides).toBeUndefined();
+ });
+});