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(groupProfile): move the save status onto @lobechat/replica (#20617)

Arvin Xue4f49694b7a8
diff --git a/src/routes/(main)/group/profile/StoreSync.tsx b/src/routes/(main)/group/profile/StoreSync.tsx
index 113fef0f611..c5c98f2bd5e 100644
--- a/src/routes/(main)/group/profile/StoreSync.tsx
+++ b/src/routes/(main)/group/profile/StoreSync.tsx
@@ -43,18 +43,10 @@ const StoreSync = memo(() => {
useRegisterFilesHotkeys();
useSaveDocumentHotkey(flushSave);
- // Clear state when unmounting
+ // Clear state when unmounting: the store action drops the save-state view and
+ // its replica bookkeeping together.
useUnmount(() => {
- useGroupProfileStore.setState(
- {
- activeTabId: 'group',
- editor: undefined,
- editorState: undefined,
- saveStateMap: {},
- },
- false,
- 'GroupProfileUnmounted',
- );
+ useGroupProfileStore.getState().clearProfileState();
});
return null;
diff --git a/src/store/groupProfile/action.ts b/src/store/groupProfile/action.ts
index 2c3850077b6..8725ba54b47 100644
--- a/src/store/groupProfile/action.ts
+++ b/src/store/groupProfile/action.ts
@@ -2,11 +2,13 @@ import { debounce } from 'es-toolkit/compat';
import { type StateCreator } from 'zustand';
import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';
+import { createReplicaSlice, createReplicaState, recordLens } from '@/libs/replica';
import { type StoreSetter } from '@/store/types';
import { flattenActions } from '@/store/utils/flattenActions';
import { type SaveState, type SaveStatus, type State } from './initialState';
import { initialState } from './initialState';
+import { groupProfileSaveResource } from './projection';
type SaveContentPayload = {
content: string;
@@ -26,6 +28,8 @@ type Setter = StoreSetter<Store>;
export class ActionImpl {
#debouncedSave: ReturnType<typeof debounce>;
#get: () => Store;
+ /** Local-first replica of the per-tab save status (`saveStateMap` is its view). */
+ #saveStates;
#set: Setter;
constructor(set: Setter, get: () => Store, _api?: unknown) {
@@ -34,6 +38,14 @@ export class ActionImpl {
this.#get = get;
this.#set = set;
+ this.#saveStates = createReplicaSlice(groupProfileSaveResource, {
+ actionPrefix: 'groupProfile/save',
+ get,
+ set,
+ stateKey: 'saveStateMapReplica',
+ view: recordLens<Store, SaveState>('saveStateMap'),
+ });
+
this.#debouncedSave = debounce(
async (payload: SaveContentPayload) => {
const tabId = currentTabIdRef;
@@ -55,17 +67,15 @@ export class ActionImpl {
}
#updateSaveStatusInternal = (tabId: string, status: SaveStatus) => {
- const { saveStateMap } = this.#get();
- const currentState = saveStateMap[tabId] || DEFAULT_SAVE_STATE;
- this.#set({
- saveStateMap: {
- ...saveStateMap,
- [tabId]: {
- ...currentState,
- lastUpdatedTime: status === 'saved' ? new Date() : currentState.lastUpdatedTime,
- saveStatus: status,
- },
- },
+ // Write through the replica engine so the view and its bookkeeping slot
+ // (`saveStateMapReplica`) always move together.
+ this.#saveStates.update(tabId, (current) => {
+ const previous = current ?? DEFAULT_SAVE_STATE;
+ return {
+ ...previous,
+ lastUpdatedTime: status === 'saved' ? new Date() : previous.lastUpdatedTime,
+ saveStatus: status,
+ };
});
};
@@ -84,6 +94,25 @@ export class ActionImpl {
}
};
+ /**
+ * Drop everything the profile page put in the store when it unmounts. The
+ * view (`saveStateMap`) and its replica bookkeeping are cleared together, so
+ * a later visit never sees a stale entry.
+ */
+ clearProfileState = (): void => {
+ this.#set(
+ {
+ activeTabId: 'group',
+ editor: undefined,
+ editorState: undefined,
+ saveStateMap: {},
+ saveStateMapReplica: createReplicaState(),
+ },
+ false,
+ 'clearProfileState',
+ );
+ };
+
finishStreaming = async (
saveCallback: (payload: SaveContentPayload) => Promise<void>,
): Promise<void> => {
diff --git a/src/store/groupProfile/index.ts b/src/store/groupProfile/index.ts
index 7898280a3bc..e3b4fb0a3bc 100644
--- a/src/store/groupProfile/index.ts
+++ b/src/store/groupProfile/index.ts
@@ -4,6 +4,7 @@ import { shallow } from 'zustand/shallow';
import { createWithEqualityFn } from 'zustand/traditional';
import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
import { type Store } from './action';
import { store } from './action';
@@ -14,4 +15,6 @@ const devtools = createDevtools('group_profile');
export const useGroupProfileStore = createWithEqualityFn<Store>()(devtools(store), shallow);
+expose('groupProfile', useGroupProfileStore);
+
export { selectors } from './selectors';
diff --git a/src/store/groupProfile/initialState.ts b/src/store/groupProfile/initialState.ts
index 0ceb2b33764..a59c208c7a9 100644
--- a/src/store/groupProfile/initialState.ts
+++ b/src/store/groupProfile/initialState.ts
@@ -1,5 +1,7 @@
import { type IEditor } from '@lobehub/editor';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
export type SaveStatus = 'idle' | 'saving' | 'saved';
export interface SaveState {
@@ -27,9 +29,12 @@ export interface State extends PublicState {
editor?: IEditor;
editorState?: any; // EditorState from useEditorState hook
/**
- * Save state map by tab ID (key: 'group' | agentId)
+ * Save state map by tab ID (key: 'group' | agentId). This is the replica view
+ * of `groupProfileSaveResource`.
*/
saveStateMap: Record<string, SaveState>;
+ /** Replica bookkeeping for `saveStateMap` (see `groupProfileSaveResource`). */
+ saveStateMapReplica: ReplicaState<SaveState>;
/**
* Content being streamed from AI
*/
@@ -44,6 +49,7 @@ export const initialState: State = {
activeTabId: 'group',
chatPanelExpanded: true,
saveStateMap: {},
+ saveStateMapReplica: createReplicaState(),
streamingContent: undefined,
streamingInProgress: false,
};
diff --git a/src/store/groupProfile/projection.ts b/src/store/groupProfile/projection.ts
new file mode 100644
index 00000000000..4266dee3496
--- /dev/null
+++ b/src/store/groupProfile/projection.ts
@@ -0,0 +1,26 @@
+import { defineReplica } from '@/libs/replica';
+
+import type { SaveState } from './initialState';
+
+export interface GroupProfileSaveParams {
+ tabId: string;
+}
+
+/**
+ * The save status of one profile tab (`saveStateMap[tabId]`).
+ *
+ * Keyed by the tab id — `'group'` for the group editor, an agent id for each
+ * member editor — so the concurrent editors each keep their own entry, and
+ * partitioned by identity scope so an account / workspace switch never paints
+ * another identity's save status.
+ *
+ * Memory-only: `idle` / `saving` / `saved` plus `lastUpdatedTime` is transient
+ * editor UI state produced by the debounced save cycle (there is no GET over a
+ * stable key), so it must never be written to, or hydrated from, storage.
+ */
+export const groupProfileSaveResource = defineReplica<GroupProfileSaveParams, SaveState>({
+ key: ({ tabId }) => tabId,
+ name: 'groupProfileSave',
+ storage: 'memory',
+ version: 1,
+});
diff --git a/src/store/groupProfile/replica.test.ts b/src/store/groupProfile/replica.test.ts
new file mode 100644
index 00000000000..3ea0c85c4c9
--- /dev/null
+++ b/src/store/groupProfile/replica.test.ts
@@ -0,0 +1,102 @@
+/**
+ * The group-profile save status is a replica: `saveStateMap` is its view,
+ * `saveStateMapReplica` its bookkeeping. It is memory-only — the status is
+ * transient editor UI state, never written to or hydrated from storage — and a
+ * write under a new identity scope drops the previous identity's entries
+ * instead of letting them bleed across users / workspaces.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, createReplicaState } from '@/libs/replica';
+
+import { useGroupProfileStore } from './index';
+import { groupProfileSaveResource } from './projection';
+import { selectors } from './selectors';
+
+const GROUP = 'group';
+const AGENT = 'agent-1';
+
+const saveState = (tabId: string) => useGroupProfileStore.getState().saveStateMap[tabId];
+const entry = (tabId: string) => useGroupProfileStore.getState().saveStateMapReplica.entries[tabId];
+
+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);
+};
+
+describe('groupProfile replica', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ useScope('u1:personal');
+ useGroupProfileStore.setState(
+ {
+ activeTabId: GROUP,
+ editor: undefined,
+ editorState: undefined,
+ saveStateMap: {},
+ saveStateMapReplica: createReplicaState(),
+ },
+ false,
+ );
+ });
+
+ it('is a memory-only resource (save status is transient UI state)', () => {
+ expect(groupProfileSaveResource.persisted).toBe(false);
+ expect(groupProfileSaveResource.storage).toBeUndefined();
+ });
+
+ it('writes the save status through the engine and keeps the bookkeeping in step', () => {
+ useGroupProfileStore.getState().updateSaveStatus(GROUP, 'saving');
+
+ expect(saveState(GROUP)?.saveStatus).toBe('saving');
+ expect(saveState(GROUP)?.lastUpdatedTime).toBeNull();
+ // The view is backed by the replica engine (a local write, not a fetch).
+ expect(entry(GROUP)?.source).toBe('local');
+ expect(useGroupProfileStore.getState().saveStateMapReplica.scope).toBe('u1:personal');
+ // Selectors keep reading the same view location.
+ expect(selectors.getSaveState(GROUP)(useGroupProfileStore.getState()).saveStatus).toBe(
+ 'saving',
+ );
+ });
+
+ it('stamps the save time on `saved` and keys the view per tab', () => {
+ const before = Date.now();
+ useGroupProfileStore.getState().updateSaveStatus(GROUP, 'saved');
+ useGroupProfileStore.getState().updateSaveStatus(AGENT, 'saving');
+
+ expect(saveState(GROUP)?.saveStatus).toBe('saved');
+ expect(saveState(GROUP)?.lastUpdatedTime).toBeInstanceOf(Date);
+ expect((saveState(GROUP)?.lastUpdatedTime as Date).getTime()).toBeGreaterThanOrEqual(before);
+
+ // A second tab (a member editor) keeps its own entry.
+ expect(saveState(AGENT)?.saveStatus).toBe('saving');
+ expect(saveState(AGENT)?.lastUpdatedTime).toBeNull();
+ });
+
+ it('drops the previous identity’s save states when the scope switches', () => {
+ useGroupProfileStore.getState().updateSaveStatus(GROUP, 'saved');
+ expect(saveState(GROUP)?.saveStatus).toBe('saved');
+
+ useScope('u2:personal');
+ // Any write under the new identity first drops the old identity's view.
+ useGroupProfileStore.getState().updateSaveStatus(AGENT, 'saving');
+
+ expect(saveState(GROUP)).toBeUndefined();
+ expect(saveState(AGENT)?.saveStatus).toBe('saving');
+ expect(useGroupProfileStore.getState().saveStateMapReplica.scope).toBe('u2:personal');
+ });
+
+ it('clearProfileState clears the view and the replica bookkeeping together', () => {
+ useGroupProfileStore.getState().updateSaveStatus(GROUP, 'saved');
+
+ useGroupProfileStore.getState().clearProfileState();
+
+ expect(useGroupProfileStore.getState().saveStateMap).toEqual({});
+ expect(useGroupProfileStore.getState().saveStateMapReplica.entries).toEqual({});
+ expect(useGroupProfileStore.getState().activeTabId).toBe(GROUP);
+ expect(useGroupProfileStore.getState().editor).toBeUndefined();
+ });
+});