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(store): migrate to class-based actions with flattenActions (#12081)

Innei046eb729619e
diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.md
index 1bfc31d65d3..e158d719423 100644
--- a/.agents/skills/zustand/SKILL.md
+++ b/.agents/skills/zustand/SKILL.md
@@ -8,29 +8,37 @@ description: Zustand state management guide. Use when working with store code (s
## Action Type Hierarchy
### 1. Public Actions
+
Main interfaces for UI components:
+
- Naming: Verb form (`createTopic`, `sendMessage`)
- Responsibilities: Parameter validation, flow orchestration
### 2. Internal Actions (`internal_*`)
+
Core business logic implementation:
+
- Naming: `internal_` prefix (`internal_createTopic`)
- Responsibilities: Optimistic updates, service calls, error handling
- Should not be called directly by UI
### 3. Dispatch Methods (`internal_dispatch*`)
+
State update handlers:
+
- Naming: `internal_dispatch` + entity (`internal_dispatchTopic`)
- Responsibilities: Calling reducers, updating store
## When to Use Reducer vs Simple `set`
**Use Reducer Pattern:**
+
- Managing object lists/maps (`messagesMap`, `topicMaps`)
- Optimistic updates
- Complex state transitions
**Use Simple `set`:**
+
- Toggling booleans
- Updating simple values
- Setting single state fields
@@ -61,12 +69,14 @@ internal_createTopic: async (params) => {
## Naming Conventions
**Actions:**
+
- Public: `createTopic`, `sendMessage`
- Internal: `internal_createTopic`, `internal_updateMessageContent`
- Dispatch: `internal_dispatchTopic`
- Toggle: `internal_toggleMessageLoading`
**State:**
+
- ID arrays: `messageLoadingIds`, `topicEditingIds`
- Maps: `topicMaps`, `messagesMap`
- Active: `activeTopicId`
@@ -76,3 +86,94 @@ internal_createTopic: async (params) => {
- Action patterns: `references/action-patterns.md`
- Slice organization: `references/slice-organization.md`
+
+## Class-Based Action Implementation
+
+We are migrating slices from plain `StateCreator` objects to **class-based actions**.
+
+### Pattern
+
+- Define a class that encapsulates actions and receives `(set, get, api)` in the constructor.
+- Use `#private` fields (e.g., `#set`, `#get`) to avoid leaking internals.
+- Prefer shared typing helpers:
+ - `StoreSetter<T>` from `@/store/types` for `set`.
+ - `Pick<ActionImpl, keyof ActionImpl>` to expose only public methods.
+- Export a `create*Slice` helper that returns a class instance.
+
+```ts
+type Setter = StoreSetter<HomeStore>;
+export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new RecentActionImpl(set, get, _api);
+
+export class RecentActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ useFetchRecentTopics = () => {
+ // ...
+ };
+}
+
+export type RecentAction = Pick<RecentActionImpl, keyof RecentActionImpl>;
+```
+
+### Composition
+
+- In store files, merge class instances with `flattenActions` (do not spread class instances).
+- `flattenActions` binds methods to the original class instance and supports prototype methods and class fields.
+
+```ts
+const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (...params) => ({
+ ...initialState,
+ ...flattenActions<HomeStoreAction>([
+ createRecentSlice(...params),
+ createHomeInputSlice(...params),
+ ]),
+});
+```
+
+### Multi-Class Slices
+
+- For large slices that need multiple action classes, compose them in the slice entry using `flattenActions`.
+- Use a local `PublicActions<T>` helper if you need to combine multiple classes and hide private fields.
+
+```ts
+type PublicActions<T> = { [K in keyof T]: T[K] };
+
+export type ChatGroupAction = PublicActions<
+ ChatGroupInternalAction & ChatGroupLifecycleAction & ChatGroupMemberAction & ChatGroupCurdAction
+>;
+
+export const chatGroupAction: StateCreator<
+ ChatGroupStore,
+ [['zustand/devtools', never]],
+ [],
+ ChatGroupAction
+> = (...params) =>
+ flattenActions<ChatGroupAction>([
+ new ChatGroupInternalAction(...params),
+ new ChatGroupLifecycleAction(...params),
+ new ChatGroupMemberAction(...params),
+ new ChatGroupCurdAction(...params),
+ ]);
+```
+
+### Store-Access Types
+
+- For class methods that depend on actions in other classes, define explicit store augmentations:
+ - `ChatGroupStoreWithSwitchTopic` for lifecycle `switchTopic`
+ - `ChatGroupStoreWithRefresh` for member refresh
+ - `ChatGroupStoreWithInternal` for curd `internal_dispatchChatGroup`
+
+### Do / Don't
+
+- **Do**: keep constructor signature aligned with `StateCreator` params `(set, get, api)`.
+- **Do**: use `#private` to avoid `set/get` being exposed.
+- **Do**: use `flattenActions` instead of spreading class instances.
+- **Don't**: keep both old slice objects and class actions active at the same time.
diff --git a/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx b/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx
index 9716dfb360f..50b492fb780 100644
--- a/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/components/SearchBar.tsx
@@ -69,7 +69,7 @@ const SearchBar = memo<SearchBarProps>(
searchTimeRange: time_range,
};
onSearch?.(data);
- await reSearchWithSearXNG(messageId, data, { aiSummary });
+ await reSearchWithSearXNG(messageId, data);
};
const searchComponent = (
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index 3f0fd7cd34e..5d2c68f7719 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -3,11 +3,11 @@ import isEqual from 'fast-deep-equal';
import { produce } from 'immer';
import type { SWRResponse } from 'swr';
import type { PartialDeep } from 'type-fest';
-import { type StateCreator } from 'zustand/vanilla';
import { MESSAGE_CANCEL_FLAT } from '@/const/message';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { type CreateAgentParams, type CreateAgentResult, agentService } from '@/services/agent';
+import { type StoreSetter } from '@/store/types';
import { getUserStoreState } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import {
@@ -27,90 +27,27 @@ const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';
* Agent Slice Actions
* Handles agent CRUD operations (config/meta updates)
*/
-export interface AgentSliceAction {
- /**
- * Append content chunk to streaming system role
- */
- appendStreamingSystemRole: (chunk: string) => void;
- /**
- * Create a new agent with session
- * @returns Created agent result with agentId and sessionId
- */
- createAgent: (params: CreateAgentParams) => Promise<CreateAgentResult>;
- /**
- * Finish streaming and save final content to agent config
- */
- finishStreamingSystemRole: (agentId: string) => Promise<void>;
- internal_createAbortController: (key: keyof AgentSliceState) => AbortController;
- internal_dispatchAgentMap: (id: string, config: PartialDeep<LobeAgentConfig>) => void;
- internal_refreshAgentConfig: (id: string) => Promise<void>;
- optimisticUpdateAgentConfig: (
- id: string,
- data: PartialDeep<LobeAgentConfig>,
- signal?: AbortSignal,
- ) => Promise<void>;
- optimisticUpdateAgentMeta: (
- id: string,
- meta: Partial<MetaData>,
- signal?: AbortSignal,
- ) => Promise<void>;
- /**
- * Update current active agent id
- */
- setActiveAgentId: (agentId?: string) => void;
- /**
- * Set the agent panel pinned state
- */
- setAgentPinned: (pinned: boolean | ((prev: boolean) => boolean)) => void;
- /**
- * Start streaming system role update
- */
- startStreamingSystemRole: () => void;
- /**
- * Toggle the agent panel pinned state
- */
- toggleAgentPinned: () => void;
- /**
- * Toggle a plugin for the current agent
- * @param pluginId - The plugin identifier
- * @param state - Optional explicit state (true = enable, false = disable). If not provided, toggles.
- */
- toggleAgentPlugin: (pluginId: string, state?: boolean) => Promise<void>;
- updateAgentChatConfig: (config: Partial<LobeAgentChatConfig>) => Promise<void>;
- updateAgentChatConfigById: (
- agentId: string,
- config: Partial<LobeAgentChatConfig>,
- ) => Promise<void>;
- updateAgentConfig: (config: PartialDeep<LobeAgentConfig>) => Promise<void>;
- updateAgentConfigById: (agentId: string, config: PartialDeep<LobeAgentConfig>) => Promise<void>;
- updateAgentLocalSystemConfigById: (
- agentId: string,
- config: Partial<LocalSystemConfig>,
- ) => Promise<void>;
- updateAgentMeta: (meta: Partial<MetaData>) => Promise<void>;
- /**
- * Update loading state for meta fields (used during autocomplete)
- */
- updateLoadingState: (key: keyof LoadingState, value: boolean) => void;
- /**
- * Update save status for showing auto-save hint
- */
- updateSaveStatus: (status: SaveStatus) => void;
- useFetchAgentConfig: (isLogin: boolean | undefined, id: string) => SWRResponse<LobeAgentConfig>;
-}
-export const createAgentSlice: StateCreator<
- AgentStore,
- [['zustand/devtools', never]],
- [],
- AgentSliceAction
-> = (set, get) => ({
- appendStreamingSystemRole: (chunk) => {
- const currentContent = get().streamingSystemRole || '';
- set({ streamingSystemRole: currentContent + chunk }, false, 'appendStreamingSystemRole');
- },
-
- createAgent: async (params) => {
+type Setter = StoreSetter<AgentStore>;
+export const createAgentSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
+ new AgentSliceActionImpl(set, get, _api);
+
+export class AgentSliceActionImpl {
+ readonly #get: () => AgentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ appendStreamingSystemRole = (chunk: string): void => {
+ const currentContent = this.#get().streamingSystemRole || '';
+ this.#set({ streamingSystemRole: currentContent + chunk }, false, 'appendStreamingSystemRole');
+ };
+
+ createAgent = async (params: CreateAgentParams): Promise<CreateAgentResult> => {
const result = await agentService.createAgent(params);
// Track new agent creation analytics
@@ -132,23 +69,23 @@ export const createAgentSlice: StateCreator<
}
return result;
- },
+ };
- finishStreamingSystemRole: async (agentId) => {
- const { streamingSystemRole } = get();
+ finishStreamingSystemRole = async (agentId: string): Promise<void> => {
+ const { streamingSystemRole } = this.#get();
if (!streamingSystemRole) {
- set({ streamingSystemRoleInProgress: false }, false, 'finishStreamingSystemRole');
+ this.#set({ streamingSystemRoleInProgress: false }, false, 'finishStreamingSystemRole');
return;
}
// Save the final content to agent config
- await get().optimisticUpdateAgentConfig(agentId, {
+ await this.#get().optimisticUpdateAgentConfig(agentId, {
systemRole: streamingSystemRole,
});
// Reset streaming state
- set(
+ this.#set(
{
streamingSystemRole: undefined,
streamingSystemRoleInProgress: false,
@@ -156,28 +93,28 @@ export const createAgentSlice: StateCreator<
false,
'finishStreamingSystemRole',
);
- },
+ };
- setActiveAgentId: (agentId) => {
- set(
+ setActiveAgentId = (agentId?: string): void => {
+ this.#set(
(state) => (state.activeAgentId === agentId ? state : { activeAgentId: agentId }),
false,
'setActiveAgentId',
);
- },
+ };
- setAgentPinned: (value) => {
- set(
+ setAgentPinned = (value: boolean | ((prev: boolean) => boolean)): void => {
+ this.#set(
(state) => ({
isAgentPinned: typeof value === 'function' ? value(state.isAgentPinned) : value,
}),
false,
'setAgentPinned',
);
- },
+ };
- startStreamingSystemRole: () => {
- set(
+ startStreamingSystemRole = (): void => {
+ this.#set(
{
streamingSystemRole: '',
streamingSystemRoleInProgress: true,
@@ -185,14 +122,14 @@ export const createAgentSlice: StateCreator<
false,
'startStreamingSystemRole',
);
- },
+ };
- toggleAgentPinned: () => {
- set((state) => ({ isAgentPinned: !state.isAgentPinned }), false, 'toggleAgentPinned');
- },
+ toggleAgentPinned = (): void => {
+ this.#set((state) => ({ isAgentPinned: !state.isAgentPinned }), false, 'toggleAgentPinned');
+ };
- toggleAgentPlugin: async (pluginId, state) => {
- const { activeAgentId, agentMap, updateAgentConfig } = get();
+ toggleAgentPlugin = async (pluginId: string, state?: boolean): Promise<void> => {
+ const { activeAgentId, agentMap, updateAgentConfig } = this.#get();
if (!activeAgentId) return;
const currentPlugins = (agentMap[activeAgentId]?.plugins as string[]) || [];
@@ -212,73 +149,89 @@ export const createAgentSlice: StateCreator<
}
await updateAgentConfig({ plugins: newPlugins });
- },
+ };
- updateAgentChatConfig: async (config) => {
- const { activeAgentId } = get();
+ updateAgentChatConfig = async (config: Partial<LobeAgentChatConfig>): Promise<void> => {
+ const { activeAgentId } = this.#get();
if (!activeAgentId) return;
- await get().updateAgentConfig({ chatConfig: config });
- },
+ await this.#get().updateAgentConfig({ chatConfig: config });
+ };
- updateAgentChatConfigById: async (agentId, config) => {
+ updateAgentChatConfigById = async (
+ agentId: string,
+ config: Partial<LobeAgentChatConfig>,
+ ): Promise<void> => {
if (!agentId) return;
- await get().updateAgentConfigById(agentId, { chatConfig: config });
- },
+ await this.#get().updateAgentConfigById(agentId, { chatConfig: config });
+ };
- updateAgentConfig: async (config) => {
- const { activeAgentId } = get();
+ updateAgentConfig = async (config: PartialDeep<LobeAgentConfig>): Promise<void> => {
+ const { activeAgentId } = this.#get();
if (!activeAgentId) return;
- const controller = get().internal_createAbortController('updateAgentConfigSignal');
+ const controller = this.#get().internal_createAbortController('updateAgentConfigSignal');
- await get().optimisticUpdateAgentConfig(activeAgentId, config, controller.signal);
- },
+ await this.#get().optimisticUpdateAgentConfig(activeAgentId, config, controller.signal);
+ };
- updateAgentConfigById: async (agentId, config) => {
+ updateAgentConfigById = async (
+ agentId: string,
+ config: PartialDeep<LobeAgentConfig>,
+ ): Promise<void> => {
if (!agentId) return;
- const controller = get().internal_createAbortController('updateAgentConfigSignal');
+ const controller = this.#get().internal_createAbortController('updateAgentConfigSignal');
- await get().optimisticUpdateAgentConfig(agentId, config, controller.signal);
- },
+ await this.#get().optimisticUpdateAgentConfig(agentId, config, controller.signal);
+ };
- updateAgentLocalSystemConfigById: async (agentId, config) => {
+ updateAgentLocalSystemConfigById = async (
+ agentId: string,
+ config: Partial<LocalSystemConfig>,
+ ): Promise<void> => {
if (!agentId) return;
- await get().updateAgentChatConfigById(agentId, { localSystem: config });
- },
+ await this.#get().updateAgentChatConfigById(agentId, { localSystem: config });
+ };
- updateAgentMeta: async (meta) => {
- const { activeAgentId } = get();
+ updateAgentMeta = async (meta: Partial<MetaData>): Promise<void> => {
+ const { activeAgentId } = this.#get();
if (!activeAgentId) return;
- const controller = get().internal_createAbortController('updateAgentMetaSignal');
+ const controller = this.#get().internal_createAbortController('updateAgentMetaSignal');
- await get().optimisticUpdateAgentMeta(activeAgentId, meta, controller.signal);
- },
+ await this.#get().optimisticUpdateAgentMeta(activeAgentId, meta, controller.signal);
+ };
- updateLoadingState: (key, value) => {
- set({ loadingState: { ...get().loadingState, [key]: value } }, false, 'updateLoadingState');
- },
+ updateLoadingState = (key: keyof LoadingState, value: boolean): void => {
+ this.#set(
+ { loadingState: { ...this.#get().loadingState, [key]: value } },
+ false,
+ 'updateLoadingState',
+ );
+ };
- updateSaveStatus: (status) => {
- set(
+ updateSaveStatus = (status: SaveStatus): void => {
+ this.#set(
{
- lastUpdatedTime: status === 'saved' ? new Date() : get().lastUpdatedTime,
+ lastUpdatedTime: status === 'saved' ? new Date() : this.#get().lastUpdatedTime,
saveStatus: status,
},
false,
'updateSaveStatus',
);
- },
+ };
- useFetchAgentConfig: (isLogin, agentId) =>
- useClientDataSWR<LobeAgentConfig>(
+ useFetchAgentConfig = (
+ isLogin: boolean | undefined,
+ agentId: string,
+ ): SWRResponse<LobeAgentConfig> => {
+ return useClientDataSWR<LobeAgentConfig>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true && agentId && !agentId.startsWith('cg_')
? ([FETCH_AGENT_CONFIG_KEY, agentId] as const)
@@ -289,17 +242,16 @@ export const createAgentSlice: StateCreator<
},
{
onSuccess: (data) => {
- get().internal_dispatchAgentMap(agentId, data);
+ this.#get().internal_dispatchAgentMap(agentId, data);
- set({ activeAgentId: data.id }, false, 'fetchAgentConfig');
+ this.#set({ activeAgentId: data.id }, false, 'fetchAgentConfig');
},
},
- ),
-
- /* eslint-disable sort-keys-fix/sort-keys-fix */
+ );
+ };
- internal_dispatchAgentMap: (id, config) => {
- const agentMap = produce(get().agentMap, (draft) => {
+ internal_dispatchAgentMap = (id: string, config: PartialDeep<LobeAgentConfig>): void => {
+ const agentMap = produce(this.#get().agentMap, (draft) => {
if (!draft[id]) {
draft[id] = config;
} else {
@@ -307,13 +259,17 @@ export const createAgentSlice: StateCreator<
}
});
- if (isEqual(get().agentMap, agentMap)) return;
+ if (isEqual(this.#get().agentMap, agentMap)) return;
- set({ agentMap }, false, 'dispatchAgentMap');
- },
+ this.#set({ agentMap }, false, 'dispatchAgentMap');
+ };
- optimisticUpdateAgentConfig: async (id, data, signal) => {
- const { internal_dispatchAgentMap, updateSaveStatus } = get();
+ optimisticUpdateAgentConfig = async (
+ id: string,
+ data: PartialDeep<LobeAgentConfig>,
+ signal?: AbortSignal,
+ ): Promise<void> => {
+ const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();
// 1. Optimistic update (instant UI feedback)
internal_dispatchAgentMap(id, data);
@@ -336,10 +292,14 @@ export const createAgentSlice: StateCreator<
updateSaveStatus('idle');
}
}
- },
+ };
- optimisticUpdateAgentMeta: async (id, meta, signal) => {
- const { internal_dispatchAgentMap, updateSaveStatus } = get();
+ optimisticUpdateAgentMeta = async (
+ id: string,
+ meta: Partial<MetaData>,
+ signal?: AbortSignal,
+ ): Promise<void> => {
+ const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();
// 1. Optimistic update - meta fields are at the top level of agent config
internal_dispatchAgentMap(id, meta as PartialDeep<LobeAgentConfig>);
@@ -362,18 +322,20 @@ export const createAgentSlice: StateCreator<
updateSaveStatus('idle');
}
}
- },
+ };
- internal_refreshAgentConfig: async (id) => {
+ internal_refreshAgentConfig = async (id: string): Promise<void> => {
await mutate([FETCH_AGENT_CONFIG_KEY, id]);
- },
+ };
- internal_createAbortController: (key) => {
- const abortController = get()[key] as AbortController;
+ internal_createAbortController = (key: keyof AgentSliceState): AbortController => {
+ const abortController = this.#get()[key] as AbortController;
if (abortController) abortController.abort(MESSAGE_CANCEL_FLAT);
const controller = new AbortController();
- set({ [key]: controller }, false, 'internal_createAbortController');
+ this.#set({ [key]: controller }, false, 'internal_createAbortController');
return controller;
- },
-});
+ };
+}
+
+export type AgentSliceAction = Pick<AgentSliceActionImpl, keyof AgentSliceActionImpl>;
diff --git a/src/store/agent/slices/builtin/action.ts b/src/store/agent/slices/builtin/action.ts
index 4a84b3ecb95..47628481cd1 100644
--- a/src/store/agent/slices/builtin/action.ts
+++ b/src/store/agent/slices/builtin/action.ts
@@ -1,10 +1,10 @@
import { type AgentItem, type LobeAgentConfig } from '@lobechat/types';
import { type SWRResponse } from 'swr';
import type { PartialDeep } from 'type-fest';
-import { type StateCreator } from 'zustand/vanilla';
import { useOnlyFetchOnceSWR } from '@/libs/swr';
import { agentService } from '@/services/agent';
+import { type StoreSetter } from '@/store/types';
import type { AgentStore } from '../../store';
@@ -20,28 +20,26 @@ interface UseInitBuiltinAgentContext {
* Builtin Agent Slice Actions
* Handles initialization and management of builtin agents (page-agent, inbox, etc.)
*/
-export interface BuiltinAgentSliceAction {
- /**
- * Generic hook to initialize a builtin agent by slug.
- * Fetches the builtin agent (creating it if it doesn't exist)
- *
- * @param slug - The builtin agent slug (e.g., 'page-agent', 'inbox')
- * @param context - Optional context with isLogin flag
- */
- useInitBuiltinAgent: (
+
+type Setter = StoreSetter<AgentStore>;
+export const createBuiltinAgentSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
+ new BuiltinAgentSliceActionImpl(set, get, _api);
+
+export class BuiltinAgentSliceActionImpl {
+ readonly #get: () => AgentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ useInitBuiltinAgent = (
slug: string,
context?: UseInitBuiltinAgentContext,
- ) => SWRResponse<AgentItem | null>;
-}
-
-export const createBuiltinAgentSlice: StateCreator<
- AgentStore,
- [['zustand/devtools', never]],
- [],
- BuiltinAgentSliceAction
-> = (set, get) => ({
- useInitBuiltinAgent: (slug, context) =>
- useOnlyFetchOnceSWR(
+ ): SWRResponse<AgentItem | null> => {
+ return useOnlyFetchOnceSWR(
context?.isLogin === false ? null : `initBuiltinAgent:${slug}`,
async () => {
const data = await agentService.getBuiltinAgent(slug);
@@ -54,15 +52,21 @@ export const createBuiltinAgentSlice: StateCreator<
// Update builtinAgentIdMap with the agent id
// Update agentMap with the agent config
// AgentItem contains all fields needed for LobeAgentConfig
- get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);
+ this.#get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);
- set(
- { builtinAgentIdMap: { ...get().builtinAgentIdMap, [slug]: data.id } },
+ this.#set(
+ { builtinAgentIdMap: { ...this.#get().builtinAgentIdMap, [slug]: data.id } },
false,
`useInitBuiltinAgent/${slug}`,
);
}
},
},
- ),
-});
+ );
+ };
+}
+
+export type BuiltinAgentSliceAction = Pick<
+ BuiltinAgentSliceActionImpl,
+ keyof BuiltinAgentSliceActionImpl
+>;
diff --git a/src/store/agent/slices/cron/action.ts b/src/store/agent/slices/cron/action.ts
index a40f25cdd77..5b449fe723b 100644
--- a/src/store/agent/slices/cron/action.ts
+++ b/src/store/agent/slices/cron/action.ts
@@ -1,10 +1,10 @@
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import type { AgentCronJob } from '@/database/schemas/agentCronJob';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { lambdaClient } from '@/libs/trpc/client/lambda';
import { agentCronJobService } from '@/services/agentCronJob';
+import { type StoreSetter } from '@/store/types';
import type { AgentStore } from '../../store';
@@ -29,23 +29,23 @@ export interface CronTopicGroupWithJobInfo {
* Cron Slice Actions
* Handles agent cron job operations
*/
-export interface CronSliceAction {
- createAgentCronJob: () => Promise<string | null>;
- internal_refreshCronTopics: () => Promise<void>;
- useFetchCronTopicsWithJobInfo: (
- agentId?: string,
- enabled?: boolean,
- ) => SWRResponse<CronTopicGroupWithJobInfo[]>;
-}
-export const createCronSlice: StateCreator<
- AgentStore,
- [['zustand/devtools', never]],
- [],
- CronSliceAction
-> = (set, get) => ({
- createAgentCronJob: async () => {
- const { activeAgentId, internal_refreshCronTopics } = get();
+type Setter = StoreSetter<AgentStore>;
+export const createCronSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
+ new CronSliceActionImpl(set, get, _api);
+
+export class CronSliceActionImpl {
+ readonly #get: () => AgentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ createAgentCronJob = async (): Promise<string | null> => {
+ const { activeAgentId, internal_refreshCronTopics } = this.#get();
if (!activeAgentId) return null;
try {
@@ -65,14 +65,17 @@ export const createCronSlice: StateCreator<
console.error('Failed to create cron job:', error);
return null;
}
- },
+ };
- internal_refreshCronTopics: async () => {
- await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, get().activeAgentId]);
- },
+ internal_refreshCronTopics = async (): Promise<void> => {
+ await mutate([FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, this.#get().activeAgentId]);
+ };
- useFetchCronTopicsWithJobInfo: (agentId, enabled = true) =>
- useClientDataSWR<CronTopicGroupWithJobInfo[]>(
+ useFetchCronTopicsWithJobInfo = (
+ agentId?: string,
+ enabled: boolean = true,
+ ): SWRResponse<CronTopicGroupWithJobInfo[]> => {
+ return useClientDataSWR<CronTopicGroupWithJobInfo[]>(
enabled && agentId ? [FETCH_CRON_TOPICS_WITH_JOB_INFO_KEY, agentId] : null,
async ([, id]: [string, string]) => {
const [cronJobsResult, cronTopicsGroups] = await Promise.all([
@@ -106,5 +109,8 @@ export const createCronSlice: StateCreator<
fallbackData: [],
revalidateOnFocus: false,
},
- ),
-});
+ );
+ };
+}
+
+export type CronSliceAction = Pick<CronSliceActionImpl, keyof CronSliceActionImpl>;
diff --git a/src/store/agent/slices/knowledge/action.test.ts b/src/store/agent/slices/knowledge/action.test.ts
index bdae595f401..3637f68b587 100644
--- a/src/store/agent/slices/knowledge/action.test.ts
+++ b/src/store/agent/slices/knowledge/action.test.ts
@@ -279,9 +279,12 @@ describe('KnowledgeSlice Actions', () => {
useAgentStore.setState({ activeAgentId: 'agent-1' });
});
- const { result } = renderHook(() => useAgentStore().useFetchFilesAndKnowledgeBases('agent-1'), {
- wrapper: withSWR,
- });
+ const { result } = renderHook(
+ () => useAgentStore().useFetchFilesAndKnowledgeBases('agent-1'),
+ {
+ wrapper: withSWR,
+ },
+ );
await waitFor(() => expect(result.current.data).toEqual(mockData));
@@ -295,9 +298,12 @@ describe('KnowledgeSlice Actions', () => {
useAgentStore.setState({ activeAgentId: 'agent-1' });
});
- const { result } = renderHook(() => useAgentStore().useFetchFilesAndKnowledgeBases('agent-1'), {
- wrapper: withSWR,
- });
+ const { result } = renderHook(
+ () => useAgentStore().useFetchFilesAndKnowledgeBases('agent-1'),
+ {
+ wrapper: withSWR,
+ },
+ );
await waitFor(() => expect(result.current.data).toEqual([]));
});
diff --git a/src/store/agent/slices/knowledge/action.ts b/src/store/agent/slices/knowledge/action.ts
index 17319723a40..ba7b433a99b 100644
--- a/src/store/agent/slices/knowledge/action.ts
+++ b/src/store/agent/slices/knowledge/action.ts
@@ -1,9 +1,9 @@
import { type KnowledgeItem } from '@lobechat/types';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { agentService } from '@/services/agent';
+import { type StoreSetter } from '@/store/types';
import type { AgentStore } from '../../store';
@@ -13,81 +13,83 @@ const FETCH_AGENT_KNOWLEDGE_KEY = 'FETCH_AGENT_KNOWLEDGE';
* Knowledge Slice Actions
* Handles knowledge base and file operations
*/
-export interface KnowledgeSliceAction {
- addFilesToAgent: (fileIds: string[], enabled?: boolean) => Promise<void>;
- addKnowledgeBaseToAgent: (knowledgeBaseId: string) => Promise<void>;
- internal_refreshAgentKnowledge: () => Promise<void>;
- removeFileFromAgent: (fileId: string) => Promise<void>;
- removeKnowledgeBaseFromAgent: (knowledgeBaseId: string) => Promise<void>;
- toggleFile: (id: string, open?: boolean) => Promise<void>;
- toggleKnowledgeBase: (id: string, open?: boolean) => Promise<void>;
- useFetchFilesAndKnowledgeBases: (agentId?: string) => SWRResponse<KnowledgeItem[]>;
-}
-export const createKnowledgeSlice: StateCreator<
- AgentStore,
- [['zustand/devtools', never]],
- [],
- KnowledgeSliceAction
-> = (set, get) => ({
- addFilesToAgent: async (fileIds, enabled) => {
- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();
+type Setter = StoreSetter<AgentStore>;
+export const createKnowledgeSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
+ new KnowledgeSliceActionImpl(set, get, _api);
+
+export class KnowledgeSliceActionImpl {
+ readonly #get: () => AgentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ addFilesToAgent = async (fileIds: string[], enabled?: boolean): Promise<void> => {
+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } =
+ this.#get();
if (!activeAgentId) return;
if (fileIds.length === 0) return;
await agentService.createAgentFiles(activeAgentId, fileIds, enabled);
await internal_refreshAgentConfig(activeAgentId);
await internal_refreshAgentKnowledge();
- },
+ };
- addKnowledgeBaseToAgent: async (knowledgeBaseId) => {
- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();
+ addKnowledgeBaseToAgent = async (knowledgeBaseId: string): Promise<void> => {
+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } =
+ this.#get();
if (!activeAgentId) return;
await agentService.createAgentKnowledgeBase(activeAgentId, knowledgeBaseId, true);
await internal_refreshAgentConfig(activeAgentId);
await internal_refreshAgentKnowledge();
- },
+ };
- internal_refreshAgentKnowledge: async () => {
- await mutate([FETCH_AGENT_KNOWLEDGE_KEY, get().activeAgentId]);
- },
+ internal_refreshAgentKnowledge = async (): Promise<void> => {
+ await mutate([FETCH_AGENT_KNOWLEDGE_KEY, this.#get().activeAgentId]);
+ };
- removeFileFromAgent: async (fileId) => {
- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();
+ removeFileFromAgent = async (fileId: string): Promise<void> => {
+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } =
+ this.#get();
if (!activeAgentId) return;
await agentService.deleteAgentFile(activeAgentId, fileId);
await internal_refreshAgentConfig(activeAgentId);
await internal_refreshAgentKnowledge();
- },
+ };
- removeKnowledgeBaseFromAgent: async (knowledgeBaseId) => {
- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();
+ removeKnowledgeBaseFromAgent = async (knowledgeBaseId: string): Promise<void> => {
+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } =
+ this.#get();
if (!activeAgentId) return;
await agentService.deleteAgentKnowledgeBase(activeAgentId, knowledgeBaseId);
await internal_refreshAgentConfig(activeAgentId);
await internal_refreshAgentKnowledge();
- },
+ };
- toggleFile: async (id, open) => {
- const { activeAgentId, internal_refreshAgentConfig } = get();
+ toggleFile = async (id: string, open?: boolean): Promise<void> => {
+ const { activeAgentId, internal_refreshAgentConfig } = this.#get();
if (!activeAgentId) return;
await agentService.toggleFile(activeAgentId, id, open);
await internal_refreshAgentConfig(activeAgentId);
- },
+ };
- toggleKnowledgeBase: async (id, open) => {
- const { activeAgentId, internal_refreshAgentConfig } = get();
+ toggleKnowledgeBase = async (id: string, open?: boolean): Promise<void> => {
+ const { activeAgentId, internal_refreshAgentConfig } = this.#get();
if (!activeAgentId) return;
await agentService.toggleKnowledgeBase(activeAgentId, id, open);
await internal_refreshAgentConfig(activeAgentId);
- },
+ };
- useFetchFilesAndKnowledgeBases: (agentId) => {
+ useFetchFilesAndKnowledgeBases = (agentId?: string): SWRResponse<KnowledgeItem[]> => {
return useClientDataSWR<KnowledgeItem[]>(
agentId ? [FETCH_AGENT_KNOWLEDGE_KEY, agentId] : null,
([, id]: string[]) => agentService.getFilesAndKnowledgeBases(id),
@@ -95,5 +97,7 @@ export const createKnowledgeSlice: StateCreator<
fallbackData: [],
},
);
- },
-});
+ };
+}
+
+export type KnowledgeSliceAction = Pick<KnowledgeSliceActionImpl, keyof KnowledgeSliceActionImpl>;
diff --git a/src/store/agent/slices/plugin/action.ts b/src/store/agent/slices/plugin/action.ts
index 26b8def96c5..ebfc4d92158 100644
--- a/src/store/agent/slices/plugin/action.ts
+++ b/src/store/agent/slices/plugin/action.ts
@@ -1,5 +1,6 @@
import { produce } from 'immer';
-import { type StateCreator } from 'zustand/vanilla';
+
+import { type StoreSetter } from '@/store/types';
import { agentSelectors } from '../../selectors';
import type { AgentStore } from '../../store';
@@ -8,23 +9,27 @@ import type { AgentStore } from '../../store';
* Plugin Slice Actions
* Handles plugin toggle operations
*/
-export interface PluginSliceAction {
- removePlugin: (id: string) => Promise<void>;
- togglePlugin: (id: string, open?: boolean) => Promise<void>;
-}
-export const createPluginSlice: StateCreator<
- AgentStore,
- [['zustand/devtools', never]],
- [],
- PluginSliceAction
-> = (set, get) => ({
- removePlugin: async (id) => {
- await get().togglePlugin(id, false);
- },
+type Setter = StoreSetter<AgentStore>;
+export const createPluginSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
+ new PluginSliceActionImpl(set, get, _api);
+
+export class PluginSliceActionImpl {
+ readonly #get: () => AgentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- togglePlugin: async (id, open) => {
- const originConfig = agentSelectors.currentAgentConfig(get());
+ removePlugin = async (id: string): Promise<void> => {
+ await this.#get().togglePlugin(id, false);
+ };
+
+ togglePlugin = async (id: string, open?: boolean): Promise<void> => {
+ const originConfig = agentSelectors.currentAgentConfig(this.#get());
const config = produce(originConfig, (draft) => {
draft.plugins = produce(draft.plugins || [], (plugins) => {
@@ -45,6 +50,8 @@ export const createPluginSlice: StateCreator<
});
});
- await get().updateAgentConfig(config);
- },
-});
+ await this.#get().updateAgentConfig(config);
+ };
+}
+
+export type PluginSliceAction = Pick<PluginSliceActionImpl, keyof PluginSliceActionImpl>;
diff --git a/src/store/agent/store.ts b/src/store/agent/store.ts
index 93c6df2ca8c..4d0f9d5e6c0 100644
--- a/src/store/agent/store.ts
+++ b/src/store/agent/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type AgentStoreState, initialState } from './initialState';
import { type AgentSliceAction, createAgentSlice } from './slices/agent';
import { type BuiltinAgentSliceAction, createBuiltinAgentSlice } from './slices/builtin';
@@ -21,13 +22,23 @@ export interface AgentStore
PluginSliceAction,
AgentStoreState {}
-const createStore: StateCreator<AgentStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type AgentStoreAction = AgentSliceAction &
+ BuiltinAgentSliceAction &
+ CronSliceAction &
+ KnowledgeSliceAction &
+ PluginSliceAction;
+
+const createStore: StateCreator<AgentStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<AgentStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createAgentSlice(...parameters),
- ...createBuiltinAgentSlice(...parameters),
- ...createCronSlice(...parameters),
- ...createKnowledgeSlice(...parameters),
- ...createPluginSlice(...parameters),
+ ...flattenActions<AgentStoreAction>([
+ createAgentSlice(...parameters),
+ createBuiltinAgentSlice(...parameters),
+ createCronSlice(...parameters),
+ createKnowledgeSlice(...parameters),
+ createPluginSlice(...parameters),
+ ]),
});
// =============== implement useStore ============ //
diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.ts
index 3ebef8564cb..f785b00c786 100644
--- a/src/store/agentGroup/action.ts
+++ b/src/store/agentGroup/action.ts
@@ -9,18 +9,19 @@ import { chatGroupService } from '@/services/chatGroup';
import { getAgentStoreState } from '@/store/agent';
import { type ChatGroupStore } from '@/store/agentGroup/store';
import { useChatStore } from '@/store/chat';
+import { type StoreSetter } from '@/store/types';
+import { flattenActions } from '@/store/utils/flattenActions';
import { setNamespace } from '@/utils/storeDebug';
import { type ChatGroupState } from './initialState';
-import { type ChatGroupReducer, chatGroupReducers } from './reducers';
import {
- type ChatGroupCurdAction,
- type ChatGroupLifecycleAction,
- type ChatGroupMemberAction,
- chatGroupCurdSlice,
- chatGroupLifecycleSlice,
- chatGroupMemberSlice,
-} from './slices';
+ type ChatGroupDispatchPayloads,
+ type ChatGroupReducer,
+ chatGroupReducers,
+} from './reducers';
+import { ChatGroupCurdAction } from './slices/curd';
+import { ChatGroupLifecycleAction } from './slices/lifecycle';
+import { ChatGroupMemberAction } from './slices/member';
const n = setNamespace('chatGroup');
@@ -36,264 +37,244 @@ const toAgentGroupDetail = (group: ChatGroupItem): AgentGroupDetail =>
agents: [],
}) as AgentGroupDetail;
-// Internal action interface
-export interface ChatGroupInternalAction {
- internal_dispatchChatGroup: (
- payload:
- | {
- type: string;
- }
- | {
- payload: any;
- type: string;
- },
- ) => void;
- /**
- * Fetch group detail directly and update store.
- * Unlike refreshGroupDetail which uses SWR mutate, this method fetches immediately
- * and is useful when SWR hook is not yet mounted (e.g., after createGroup).
- */
- internal_fetchGroupDetail: (groupId: string) => Promise<void>;
- internal_updateGroupMaps: (groups: ChatGroupItem[]) => void;
- loadGroups: () => Promise<void>;
- refreshGroupDetail: (groupId: string) => Promise<void>;
- refreshGroups: () => Promise<void>;
- toggleGroupSetting: (open: boolean) => void;
- toggleThread: (agentId: string) => void;
- useFetchGroupDetail: (enabled: boolean, groupId: string) => any;
- useFetchGroups: (enabled: boolean, isLogin: boolean) => any;
-}
+type Setter = StoreSetter<ChatGroupStore>;
+class ChatGroupInternalAction {
+ readonly #get: () => ChatGroupState;
+ readonly #set: Setter;
-// Combined action interface
-export interface ChatGroupAction
- extends
- ChatGroupInternalAction,
- ChatGroupLifecycleAction,
- ChatGroupMemberAction,
- ChatGroupCurdAction {}
+ constructor(set: Setter, get: () => ChatGroupState, _api?: unknown) {
+ // keep signature aligned with StateCreator params: (set, get, api)
+ void _api;
-const chatGroupInternalSlice: StateCreator<
- ChatGroupStore,
- [['zustand/devtools', never]],
- [],
- ChatGroupInternalAction
-> = (set, get) => {
- const dispatch: ChatGroupInternalAction['internal_dispatchChatGroup'] = (payload) => {
- set(
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_dispatchChatGroup = <T extends keyof ChatGroupDispatchPayloads>(payload: {
+ payload: ChatGroupDispatchPayloads[T];
+ type: T;
+ }) => {
+ this.#set(
produce((draft: ChatGroupState) => {
- const reducer = chatGroupReducers[
- payload.type as keyof typeof chatGroupReducers
- ] as ChatGroupReducer;
- if (reducer) {
- // Apply the reducer and return the new state
- return reducer(draft, payload);
- }
+ const reducer = chatGroupReducers[payload.type] as ChatGroupReducer | undefined;
+ if (reducer) return reducer(draft, payload);
}),
false,
payload,
);
};
- return {
- internal_dispatchChatGroup: dispatch,
-
- internal_fetchGroupDetail: async (groupId: string) => {
- const groupDetail = await chatGroupService.getGroupDetail(groupId);
- if (!groupDetail) return;
+ internal_fetchGroupDetail = async (groupId: string) => {
+ const groupDetail = await chatGroupService.getGroupDetail(groupId);
+ if (!groupDetail) return;
+
+ // Update groupMap with full group detail including supervisorAgentId and agents
+ this.internal_dispatchChatGroup({
+ payload: { id: groupDetail.id, value: groupDetail },
+ type: 'updateGroup',
+ });
+
+ // Sync group agents to agentStore for builtin agent resolution
+ const agentStore = getAgentStoreState();
+ for (const agent of groupDetail.agents) {
+ agentStore.internal_dispatchAgentMap(agent.id, agent as any);
+ }
+
+ // Set activeAgentId to supervisor for correct model resolution
+ if (groupDetail.supervisorAgentId) {
+ agentStore.setActiveAgentId(groupDetail.supervisorAgentId);
+ useChatStore.setState(
+ { activeAgentId: groupDetail.supervisorAgentId },
+ false,
+ 'syncActiveAgentIdFromAgentGroup',
+ );
+ }
+ };
- // Update groupMap with full group detail including supervisorAgentId and agents
- dispatch({ payload: { id: groupDetail.id, value: groupDetail }, type: 'updateGroup' });
+ internal_updateGroupMaps = (groups: ChatGroupItem[]) => {
+ // Build a candidate map from incoming groups
+ const incomingMap = groups.reduce(
+ (map, group) => {
+ map[group.id] = group;
+ return map;
+ },
+ {} as Record<string, ChatGroupItem>,
+ );
- // Sync group agents to agentStore for builtin agent resolution
- const agentStore = getAgentStoreState();
- for (const agent of groupDetail.agents) {
- agentStore.internal_dispatchAgentMap(agent.id, agent as any);
+ // Merge with existing map, preserving existing config and agents if present
+ const mergedMap = produce(this.#get().groupMap, (draft) => {
+ for (const id of Object.keys(incomingMap)) {
+ const incoming = incomingMap[id];
+ const existing = draft[id];
+ if (existing) {
+ draft[id] = {
+ ...existing,
+ ...incoming,
+
+ // Preserve existing agents data
+ agents: existing.agents,
+
+ // Keep existing config (authoritative) if present; do not overwrite
+ config: existing.config || incoming.config,
+ } as AgentGroupDetail;
+ } else {
+ draft[id] = toAgentGroupDetail(incoming);
+ }
}
+ });
- // Set activeAgentId to supervisor for correct model resolution
- if (groupDetail.supervisorAgentId) {
- agentStore.setActiveAgentId(groupDetail.supervisorAgentId);
- useChatStore.setState(
- { activeAgentId: groupDetail.supervisorAgentId },
- false,
- 'syncActiveAgentIdFromAgentGroup',
- );
- }
- },
-
- internal_updateGroupMaps: (groups) => {
- // Build a candidate map from incoming groups
- const incomingMap = groups.reduce(
- (map, group) => {
- map[group.id] = group;
- return map;
- },
- {} as Record<string, ChatGroupItem>,
- );
+ this.#set(
+ {
+ groupMap: mergedMap,
+ groupsInit: true,
+ },
+ false,
+ n('internal_updateGroupMaps/chatGroup'),
+ );
+ };
- // Merge with existing map, preserving existing config and agents if present
- const mergedMap = produce(get().groupMap, (draft) => {
- for (const id of Object.keys(incomingMap)) {
- const incoming = incomingMap[id];
- const existing = draft[id];
- if (existing) {
- draft[id] = {
- ...existing,
- ...incoming,
-
- // Preserve existing agents data
- agents: existing.agents,
-
- // Keep existing config (authoritative) if present; do not overwrite
- config: existing.config || incoming.config,
- } as AgentGroupDetail;
- } else {
- draft[id] = toAgentGroupDetail(incoming);
- }
- }
- });
+ loadGroups = async () => {
+ const groups = await chatGroupService.getGroups();
+ this.internal_dispatchChatGroup({ payload: groups, type: 'loadGroups' });
+ };
- set(
- {
- groupMap: mergedMap,
- groupsInit: true,
- },
- false,
- n('internal_updateGroupMaps/chatGroup'),
- );
- },
-
- loadGroups: async () => {
- const groups = await chatGroupService.getGroups();
- dispatch({ payload: groups, type: 'loadGroups' });
- },
-
- refreshGroupDetail: async (groupId: string) => {
- await mutate([FETCH_GROUP_DETAIL_KEY, groupId]);
- },
-
- refreshGroups: async () => {
- await mutate([FETCH_GROUPS_KEY, true]);
- },
-
- toggleGroupSetting: (open) => {
- set({ showGroupSetting: open }, false, 'toggleGroupSetting');
- },
-
- toggleThread: (agentId) => {
- set({ activeThreadAgentId: agentId }, false, 'toggleThread');
- },
-
- useFetchGroupDetail: (enabled, groupId) =>
- useClientDataSWRWithSync<AgentGroupDetail | null>(
- enabled && groupId ? [FETCH_GROUP_DETAIL_KEY, groupId] : null,
- async () => {
- const groupDetail = await chatGroupService.getGroupDetail(groupId);
- if (!groupDetail) throw new Error(`Group ${groupId} not found`);
- return groupDetail;
- },
- {
- onData: (groupDetail) => {
- if (!groupDetail) return;
-
- // Update groupMap with detailed group info including agents
- const currentGroup = get().groupMap[groupDetail.id];
- if (isEqual(currentGroup, groupDetail)) return;
-
- const nextGroupMap = {
- ...get().groupMap,
- [groupDetail.id]: groupDetail,
- };
-
- set(
- {
- groupMap: nextGroupMap,
- },
- false,
- n('useFetchGroupDetail/onData', { groupId: groupDetail.id }),
- );
+ refreshGroupDetail = async (groupId: string) => {
+ await mutate([FETCH_GROUP_DETAIL_KEY, groupId]);
+ };
- // Sync group agents to agentStore for builtin agent resolution (e.g., supervisor slug)
- // Use smart merge: only overwrite if server data is newer to prevent race conditions
- const agentStore = getAgentStoreState();
- for (const agent of groupDetail.agents) {
- const currentAgentInStore = agentStore.agentMap[agent.id];
-
- // Only overwrite if:
- // 1. Agent doesn't exist in store
- // 2. Server data is newer than store data (based on updatedAt)
- if (
- !currentAgentInStore ||
- new Date(agent.updatedAt) > new Date(currentAgentInStore.updatedAt || 0)
- ) {
- // AgentGroupMember extends AgentItem which shares fields with LobeAgentConfig
- agentStore.internal_dispatchAgentMap(agent.id, agent as any);
- }
- }
+ refreshGroups = async () => {
+ await mutate([FETCH_GROUPS_KEY, true]);
+ };
- // Set activeAgentId to supervisor for correct model resolution in sendMessage
- if (groupDetail.supervisorAgentId) {
- agentStore.setActiveAgentId(groupDetail.supervisorAgentId);
- useChatStore.setState(
- { activeAgentId: groupDetail.supervisorAgentId },
- false,
- 'syncActiveAgentIdFromAgentGroup',
- );
- }
- },
- },
- ),
-
- // SWR Hooks for data fetching
- // This is not used for now, as we are combining group in the session lambda's response
- useFetchGroups: (enabled, isLogin) =>
- useClientDataSWRWithSync<ChatGroupItem[]>(
- enabled ? [FETCH_GROUPS_KEY, isLogin] : null,
- async () => chatGroupService.getGroups(),
- {
- fallbackData: [],
- onData: (groups) => {
- // Update both groups list and groupMap
- const currentMap = get().groupMap;
- const nextGroupMap = groups.reduce(
- (map, group) => {
- // Preserve existing agents data if available
- const existing = currentMap[group.id];
- map[group.id] = existing
- ? ({ ...existing, ...group } as AgentGroupDetail)
- : toAgentGroupDetail(group);
- return map;
- },
- {} as Record<string, AgentGroupDetail>,
- );
+ toggleGroupSetting = (open: boolean) => {
+ this.#set({ showGroupSetting: open }, false, 'toggleGroupSetting');
+ };
+
+ toggleThread = (agentId: string) => {
+ this.#set({ activeThreadAgentId: agentId }, false, 'toggleThread');
+ };
- if (get().groupsInit && isEqual(currentMap, nextGroupMap)) {
- return;
+ useFetchGroupDetail = (enabled: boolean, groupId: string) =>
+ useClientDataSWRWithSync<AgentGroupDetail | null>(
+ enabled && groupId ? [FETCH_GROUP_DETAIL_KEY, groupId] : null,
+ async () => {
+ const groupDetail = await chatGroupService.getGroupDetail(groupId);
+ if (!groupDetail) throw new Error(`Group ${groupId} not found`);
+ return groupDetail;
+ },
+ {
+ onData: (groupDetail) => {
+ if (!groupDetail) return;
+
+ // Update groupMap with detailed group info including agents
+ const currentGroup = this.#get().groupMap[groupDetail.id];
+ if (isEqual(currentGroup, groupDetail)) return;
+
+ const nextGroupMap = {
+ ...this.#get().groupMap,
+ [groupDetail.id]: groupDetail,
+ };
+
+ this.#set(
+ {
+ groupMap: nextGroupMap,
+ },
+ false,
+ n('useFetchGroupDetail/onData', { groupId: groupDetail.id }),
+ );
+
+ // Sync group agents to agentStore for builtin agent resolution (e.g., supervisor slug)
+ // Use smart merge: only overwrite if server data is newer to prevent race conditions
+ const agentStore = getAgentStoreState();
+ for (const agent of groupDetail.agents) {
+ const currentAgentInStore = agentStore.agentMap[agent.id];
+
+ // Only overwrite if:
+ // 1. Agent doesn't exist in store
+ // 2. Server data is newer than store data (based on updatedAt)
+ if (
+ !currentAgentInStore ||
+ new Date(agent.updatedAt) > new Date(currentAgentInStore.updatedAt || 0)
+ ) {
+ // AgentGroupMember extends AgentItem which shares fields with LobeAgentConfig
+ agentStore.internal_dispatchAgentMap(agent.id, agent as any);
}
+ }
- set(
- {
- groupMap: nextGroupMap,
- groupsInit: true,
- },
+ // Set activeAgentId to supervisor for correct model resolution in sendMessage
+ if (groupDetail.supervisorAgentId) {
+ agentStore.setActiveAgentId(groupDetail.supervisorAgentId);
+ useChatStore.setState(
+ { activeAgentId: groupDetail.supervisorAgentId },
false,
- n('useFetchGroups/onData'),
+ 'syncActiveAgentIdFromAgentGroup',
);
- },
- suspense: true,
+ }
},
- ),
- };
-};
+ },
+ );
+
+ // SWR Hooks for data fetching
+ // This is not used for now, as we are combining group in the session lambda's response
+ useFetchGroups = (enabled: boolean, isLogin: boolean) =>
+ useClientDataSWRWithSync<ChatGroupItem[]>(
+ enabled ? [FETCH_GROUPS_KEY, isLogin] : null,
+ async () => chatGroupService.getGroups(),
+ {
+ fallbackData: [],
+ onData: (groups) => {
+ // Update both groups list and groupMap
+ const currentMap = this.#get().groupMap;
+ const nextGroupMap = groups.reduce(
+ (map, group) => {
+ // Preserve existing agents data if available
+ const existing = currentMap[group.id];
+ map[group.id] = existing
+ ? ({ ...existing, ...group } as AgentGroupDetail)
+ : toAgentGroupDetail(group);
+ return map;
+ },
+ {} as Record<string, AgentGroupDetail>,
+ );
+
+ if (this.#get().groupsInit && isEqual(currentMap, nextGroupMap)) {
+ return;
+ }
+
+ this.#set(
+ {
+ groupMap: nextGroupMap,
+ groupsInit: true,
+ },
+ false,
+ n('useFetchGroups/onData'),
+ );
+ },
+ suspense: true,
+ },
+ );
+}
+
+type PublicActions<T> = { [K in keyof T]: T[K] };
+
+// Combined action type (public methods only)
+export type ChatGroupAction = PublicActions<
+ ChatGroupInternalAction & ChatGroupLifecycleAction & ChatGroupMemberAction & ChatGroupCurdAction
+>;
export const chatGroupAction: StateCreator<
ChatGroupStore,
[['zustand/devtools', never]],
[],
ChatGroupAction
-> = (...params) => ({
- ...chatGroupInternalSlice(...params),
- ...chatGroupLifecycleSlice(...params),
- ...chatGroupMemberSlice(...params),
- ...chatGroupCurdSlice(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<ChatGroupStore, [['zustand/devtools', never]], [], ChatGroupAction>
+ >
+) =>
+ flattenActions<ChatGroupAction>([
+ new ChatGroupInternalAction(...params),
+ new ChatGroupLifecycleAction(...params),
+ new ChatGroupMemberAction(...params),
+ new ChatGroupCurdAction(...params),
+ ]);
diff --git a/src/store/agentGroup/slices/curd.ts b/src/store/agentGroup/slices/curd.ts
index 1157bfc9173..2824fdc60a3 100644
--- a/src/store/agentGroup/slices/curd.ts
+++ b/src/store/agentGroup/slices/curd.ts
@@ -1,55 +1,63 @@
import type { LobeChatGroupConfig } from '@lobechat/types';
-import { type StateCreator } from 'zustand/vanilla';
import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
import type { ChatGroupItem } from '@/database/schemas/chatGroup';
import { chatGroupService } from '@/services/chatGroup';
import { type ChatGroupStore } from '@/store/agentGroup/store';
+import { type StoreSetter } from '@/store/types';
import { agentGroupSelectors } from '../selectors';
-export interface ChatGroupCurdAction {
+type Setter = StoreSetter<ChatGroupStore>;
+
+type ChatGroupStoreWithInternal = ChatGroupStore & {
+ internal_dispatchChatGroup: (payload: {
+ payload: { id: string; value: Partial<ChatGroupItem> };
+ type: 'updateGroup';
+ }) => void;
+ refreshGroupDetail: (groupId: string) => Promise<void>;
+};
+
+export class ChatGroupCurdAction {
+ readonly #get: () => ChatGroupStoreWithInternal;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatGroupStoreWithInternal, _api?: unknown) {
+ // keep signature aligned with StateCreator params: (set, get, api)
+ void _api;
+
+ this.#set = set;
+ this.#get = get;
+ }
+
/**
* Append content chunk to streaming system prompt
*/
- appendStreamingSystemPrompt: (chunk: string) => void;
+ appendStreamingSystemPrompt = (chunk: string) => {
+ const currentContent = this.#get().streamingSystemPrompt || '';
+ this.#set(
+ { streamingSystemPrompt: currentContent + chunk },
+ false,
+ 'appendStreamingSystemPrompt',
+ );
+ };
+
/**
* Finish streaming and save final content to group config
*/
- finishStreamingSystemPrompt: () => Promise<void>;
- /**
- * Start streaming system prompt update
- */
- startStreamingSystemPrompt: () => void;
- updateGroup: (id: string, value: Partial<ChatGroupItem>) => Promise<void>;
- updateGroupConfig: (config: Partial<LobeChatGroupConfig>) => Promise<void>;
- updateGroupMeta: (meta: Partial<ChatGroupItem>) => Promise<void>;
-}
-
-export const chatGroupCurdSlice: StateCreator<
- ChatGroupStore,
- [['zustand/devtools', never]],
- [],
- ChatGroupCurdAction
-> = (set, get) => ({
- appendStreamingSystemPrompt: (chunk) => {
- const currentContent = get().streamingSystemPrompt || '';
- set({ streamingSystemPrompt: currentContent + chunk }, false, 'appendStreamingSystemPrompt');
- },
-
- finishStreamingSystemPrompt: async () => {
- const { streamingSystemPrompt, updateGroupConfig } = get();
+ finishStreamingSystemPrompt = async () => {
+ const { streamingSystemPrompt } = this.#get();
if (!streamingSystemPrompt) {
- set({ streamingSystemPromptInProgress: false }, false, 'finishStreamingSystemPrompt');
+ this.#set({ streamingSystemPromptInProgress: false }, false, 'finishStreamingSystemPrompt');
return;
}
// Save the streamed content to group config
- await updateGroupConfig({ systemPrompt: streamingSystemPrompt });
+ await this.updateGroupConfig({ systemPrompt: streamingSystemPrompt });
// Reset streaming state
- set(
+ this.#set(
{
streamingSystemPrompt: undefined,
streamingSystemPromptInProgress: false,
@@ -57,10 +65,13 @@ export const chatGroupCurdSlice: StateCreator<
false,
'finishStreamingSystemPrompt',
);
- },
+ };
- startStreamingSystemPrompt: () => {
- set(
+ /**
+ * Start streaming system prompt update
+ */
+ startStreamingSystemPrompt = () => {
+ this.#set(
{
streamingSystemPrompt: '',
streamingSystemPromptInProgress: true,
@@ -68,16 +79,16 @@ export const chatGroupCurdSlice: StateCreator<
false,
'startStreamingSystemPrompt',
);
- },
+ };
- updateGroup: async (id, value) => {
+ updateGroup = async (id: string, value: Partial<ChatGroupItem>) => {
await chatGroupService.updateGroup(id, value);
- get().internal_dispatchChatGroup({ payload: { id, value }, type: 'updateGroup' });
- await get().refreshGroupDetail(id);
- },
+ this.#get().internal_dispatchChatGroup({ payload: { id, value }, type: 'updateGroup' });
+ await this.#get().refreshGroupDetail(id);
+ };
- updateGroupConfig: async (config) => {
- const group = agentGroupSelectors.currentGroup(get());
+ updateGroupConfig = async (config: Partial<LobeChatGroupConfig>) => {
+ const group = agentGroupSelectors.currentGroup(this.#get());
if (!group) return;
const mergedConfig = {
@@ -91,24 +102,24 @@ export const chatGroupCurdSlice: StateCreator<
// Immediately update the local store to ensure configuration is available
// Note: reducer expects payload: { id, value }
- get().internal_dispatchChatGroup({
+ this.#get().internal_dispatchChatGroup({
payload: { id: group.id, value: { config: mergedConfig } },
type: 'updateGroup',
});
// Refresh groups to ensure consistency
- await get().refreshGroupDetail(group.id);
- },
+ await this.#get().refreshGroupDetail(group.id);
+ };
- updateGroupMeta: async (meta) => {
- const group = agentGroupSelectors.currentGroup(get());
+ updateGroupMeta = async (meta: Partial<ChatGroupItem>) => {
+ const group = agentGroupSelectors.currentGroup(this.#get());
if (!group) return;
const id = group.id;
await chatGroupService.updateGroup(id, meta);
// Keep local store in sync immediately
- get().internal_dispatchChatGroup({ payload: { id, value: meta }, type: 'updateGroup' });
- await get().refreshGroupDetail(id);
- },
-});
+ this.#get().internal_dispatchChatGroup({ payload: { id, value: meta }, type: 'updateGroup' });
+ await this.#get().refreshGroupDetail(id);
+ };
+}
diff --git a/src/store/agentGroup/slices/lifecycle.ts b/src/store/agentGroup/slices/lifecycle.ts
index 5946a1350e5..1c81d41f2ef 100644
--- a/src/store/agentGroup/slices/lifecycle.ts
+++ b/src/store/agentGroup/slices/lifecycle.ts
@@ -1,37 +1,32 @@
import type { NewChatGroup } from '@lobechat/types';
import urlJoin from 'url-join';
-import { type StateCreator } from 'zustand/vanilla';
import { chatGroupService } from '@/services/chatGroup';
-import { type ChatGroupStore } from '@/store/agentGroup/store';
import { useChatStore } from '@/store/chat';
import { getHomeStoreState } from '@/store/home';
-export interface ChatGroupLifecycleAction {
- createGroup: (
- group: Omit<NewChatGroup, 'userId'>,
- agentIds?: string[],
- silent?: boolean,
- ) => Promise<string>;
- /**
- * Switch to a new topic in the group
- * Clears activeTopicId and navigates to group root
- */
- switchToNewTopic: () => void;
- /**
- * Switch to a topic in the group with proper route handling
- * @param topicId - Topic ID to switch to, or undefined/null for new topic
- */
+import type { ChatGroupStore } from '../store';
+
+type ChatGroupStoreWithSwitchTopic = ChatGroupStore & {
switchTopic: (topicId?: string | null) => void;
-}
+};
+
+export class ChatGroupLifecycleAction {
+ readonly #get: () => ChatGroupStoreWithSwitchTopic;
-export const chatGroupLifecycleSlice: StateCreator<
- ChatGroupStore,
- [['zustand/devtools', never]],
- [],
- ChatGroupLifecycleAction
-> = (_, get) => ({
- createGroup: async (newGroup, agentIds, silent = false) => {
+ constructor(_set: unknown, get: () => ChatGroupStoreWithSwitchTopic, _api?: unknown) {
+ // keep signature aligned with StateCreator params: (set, get, api)
+ void _set;
+ void _api;
+
+ this.#get = get;
+ }
+
+ createGroup = async (
+ newGroup: Omit<NewChatGroup, 'userId'>,
+ agentIds?: string[],
+ silent: any = false,
+ ) => {
const { switchToGroup, refreshAgentList } = getHomeStoreState();
const { group } = await chatGroupService.createGroup(newGroup);
@@ -46,10 +41,10 @@ export const chatGroupLifecycleSlice: StateCreator<
});
}
- get().internal_dispatchChatGroup({ payload: group, type: 'addGroup' });
+ this.#get().internal_dispatchChatGroup({ payload: group, type: 'addGroup' });
// Fetch full group detail to get supervisorAgentId and agents for tools injection
- await get().internal_fetchGroupDetail(group.id);
+ await this.#get().internal_fetchGroupDetail(group.id);
refreshAgentList();
@@ -58,14 +53,22 @@ export const chatGroupLifecycleSlice: StateCreator<
}
return group.id;
- },
+ };
- switchToNewTopic: () => {
- get().switchTopic(undefined);
- },
+ /**
+ * Switch to a new topic in the group
+ * Clears activeTopicId and navigates to group root
+ */
+ switchToNewTopic = () => {
+ this.#get().switchTopic(undefined);
+ };
- switchTopic: (topicId) => {
- const { activeGroupId, router } = get();
+ /**
+ * Switch to a topic in the group with proper route handling
+ * @param topicId - Topic ID to switch to, or undefined/null for new topic
+ */
+ switchTopic = (topicId?: string | null) => {
+ const { activeGroupId, router } = this.#get();
if (!activeGroupId || !router) return;
// Update chat store's activeTopicId
@@ -76,5 +79,5 @@ export const chatGroupLifecycleSlice: StateCreator<
query: { topic: topicId ?? null },
replace: true,
});
- },
-});
+ };
+}
diff --git a/src/store/agentGroup/slices/member.ts b/src/store/agentGroup/slices/member.ts
index 3c313dd38f3..3c29bbfda1a 100644
--- a/src/store/agentGroup/slices/member.ts
+++ b/src/store/agentGroup/slices/member.ts
@@ -1,58 +1,59 @@
import type { LobeAgentConfig } from '@lobechat/types';
import type { PartialDeep } from 'type-fest';
-import { type StateCreator } from 'zustand/vanilla';
import { chatGroupService } from '@/services/chatGroup';
import { getAgentStoreState } from '@/store/agent';
import { type ChatGroupStore } from '@/store/agentGroup/store';
-export interface ChatGroupMemberAction {
- addAgentsToGroup: (groupId: string, agentIds: string[]) => Promise<void>;
- removeAgentFromGroup: (groupId: string, agentId: string) => Promise<void>;
- reorderGroupMembers: (groupId: string, orderedAgentIds: string[]) => Promise<void>;
- /**
- * Update member agent config in group
- * Persists to database via agentStore and refreshes group detail to sync UI
- */
- updateMemberAgentConfig: (
- groupId: string,
- agentId: string,
- config: PartialDeep<LobeAgentConfig>,
- ) => Promise<void>;
-}
+type ChatGroupStoreWithRefresh = ChatGroupStore & {
+ refreshGroupDetail: (groupId: string) => Promise<void>;
+};
+
+export class ChatGroupMemberAction {
+ readonly #get: () => ChatGroupStoreWithRefresh;
+
+ constructor(_set: unknown, get: () => ChatGroupStoreWithRefresh, _api?: unknown) {
+ // keep signature aligned with StateCreator params: (set, get, api)
+ void _set;
+ void _api;
-export const chatGroupMemberSlice: StateCreator<
- ChatGroupStore,
- [['zustand/devtools', never]],
- [],
- ChatGroupMemberAction
-> = (_, get) => ({
- addAgentsToGroup: async (groupId, agentIds) => {
+ this.#get = get;
+ }
+
+ addAgentsToGroup = async (groupId: string, agentIds: string[]) => {
await chatGroupService.addAgentsToGroup(groupId, agentIds);
- await get().refreshGroupDetail(groupId);
- },
+ await this.#get().refreshGroupDetail(groupId);
+ };
- removeAgentFromGroup: async (groupId, agentId) => {
+ removeAgentFromGroup = async (groupId: string, agentId: string) => {
await chatGroupService.removeAgentsFromGroup(groupId, [agentId]);
- await get().refreshGroupDetail(groupId);
- },
+ await this.#get().refreshGroupDetail(groupId);
+ };
- reorderGroupMembers: async (groupId, orderedAgentIds) => {
+ reorderGroupMembers = async (groupId: string, orderedAgentIds: string[]) => {
await Promise.all(
orderedAgentIds.map((agentId, index) =>
chatGroupService.updateAgentInGroup(groupId, agentId, { order: index }),
),
);
- await get().refreshGroupDetail(groupId);
- },
+ await this.#get().refreshGroupDetail(groupId);
+ };
- updateMemberAgentConfig: async (groupId, agentId, config) => {
+ /**
+ * Update member agent config in group
+ * Persists to database via agentStore and refreshes group detail to sync UI
+ */
+ updateMemberAgentConfig = async (
+ groupId: string,
+ agentId: string,
+ config: PartialDeep<LobeAgentConfig>,
+ ) => {
// 1. Persist to database via agentStore
const agentStore = getAgentStoreState();
await agentStore.updateAgentConfigById(agentId, config);
// 2. Refresh group detail to sync the updated agent data to groupMap
- await get().refreshGroupDetail(groupId);
- },
-});
+ await this.#get().refreshGroupDetail(groupId);
+ };
+}
diff --git a/src/store/agentGroup/store.ts b/src/store/agentGroup/store.ts
index fa667783e32..e1225067b3e 100644
--- a/src/store/agentGroup/store.ts
+++ b/src/store/agentGroup/store.ts
@@ -8,7 +8,9 @@ import { type ChatGroupState, initialChatGroupState } from './initialState';
export type ChatGroupStore = ChatGroupState & ChatGroupAction;
-const createStore: StateCreator<ChatGroupStore, [['zustand/devtools', never]]> = (...params) => ({
+const createStore: StateCreator<ChatGroupStore, [['zustand/devtools', never]]> = (
+ ...params: Parameters<StateCreator<ChatGroupStore, [['zustand/devtools', never]]>>
+) => ({
...initialChatGroupState,
...chatGroupAction(...params),
});
diff --git a/src/store/aiInfra/slices/aiModel/action.ts b/src/store/aiInfra/slices/aiModel/action.ts
index 2a43fd0eeda..b0797a44a49 100644
--- a/src/store/aiInfra/slices/aiModel/action.ts
+++ b/src/store/aiInfra/slices/aiModel/action.ts
@@ -6,74 +6,65 @@ import {
type ToggleAiModelEnableParams,
} from 'model-bank';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { aiModelService } from '@/services/aiModel';
import { type AiInfraStore } from '@/store/aiInfra/store';
+import { type StoreSetter } from '@/store/types';
const FETCH_AI_PROVIDER_MODEL_LIST_KEY = 'FETCH_AI_PROVIDER_MODELS';
-export interface AiModelAction {
- batchToggleAiModels: (ids: string[], enabled: boolean) => Promise<void>;
- batchUpdateAiModels: (models: AiProviderModelListItem[]) => Promise<void>;
- clearModelsByProvider: (provider: string) => Promise<void>;
- clearRemoteModels: (provider: string) => Promise<void>;
- createNewAiModel: (params: CreateAiModelParams) => Promise<void>;
- fetchRemoteModelList: (providerId: string) => Promise<void>;
- internal_toggleAiModelLoading: (id: string, loading: boolean) => void;
-
- refreshAiModelList: () => Promise<void>;
- removeAiModel: (id: string, providerId: string) => Promise<void>;
- toggleModelEnabled: (params: Omit<ToggleAiModelEnableParams, 'providerId'>) => Promise<void>;
- updateAiModelsConfig: (
- id: string,
- providerId: string,
- data: Partial<AiProviderModelListItem>,
- ) => Promise<void>;
- updateAiModelsSort: (providerId: string, items: AiModelSortMap[]) => Promise<void>;
+type Setter = StoreSetter<AiInfraStore>;
+export const createAiModelSlice = (set: Setter, get: () => AiInfraStore, _api?: unknown) =>
+ new AiModelActionImpl(set, get, _api);
- useFetchAiProviderModels: (id: string) => SWRResponse<AiProviderModelListItem[]>;
-}
+export class AiModelActionImpl {
+ readonly #get: () => AiInfraStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AiInfraStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createAiModelSlice: StateCreator<
- AiInfraStore,
- [['zustand/devtools', never]],
- [],
- AiModelAction
-> = (set, get) => ({
- batchToggleAiModels: async (ids, enabled) => {
- const { activeAiProvider } = get();
+ batchToggleAiModels = async (ids: string[], enabled: boolean): Promise<void> => {
+ const { activeAiProvider } = this.#get();
if (!activeAiProvider) return;
await aiModelService.batchToggleAiModels(activeAiProvider, ids, enabled);
- await get().refreshAiModelList();
- },
- batchUpdateAiModels: async (models) => {
- const { activeAiProvider: id } = get();
+ await this.#get().refreshAiModelList();
+ };
+
+ batchUpdateAiModels = async (models: AiProviderModelListItem[]): Promise<void> => {
+ const { activeAiProvider: id } = this.#get();
if (!id) return;
await aiModelService.batchUpdateAiModels(id, models);
- await get().refreshAiModelList();
- },
- clearModelsByProvider: async (provider) => {
+ await this.#get().refreshAiModelList();
+ };
+
+ clearModelsByProvider = async (provider: string): Promise<void> => {
await aiModelService.clearModelsByProvider(provider);
- await get().refreshAiModelList();
- },
- clearRemoteModels: async (provider) => {
+ await this.#get().refreshAiModelList();
+ };
+
+ clearRemoteModels = async (provider: string): Promise<void> => {
await aiModelService.clearRemoteModels(provider);
- await get().refreshAiModelList();
- },
- createNewAiModel: async (data) => {
+ await this.#get().refreshAiModelList();
+ };
+
+ createNewAiModel = async (data: CreateAiModelParams): Promise<void> => {
await aiModelService.createAiModel(data);
- await get().refreshAiModelList();
- },
- fetchRemoteModelList: async (providerId) => {
+ await this.#get().refreshAiModelList();
+ };
+
+ fetchRemoteModelList = async (providerId: string): Promise<void> => {
const { modelsService } = await import('@/services/models');
const data = await modelsService.getModels(providerId);
if (data) {
- await get().batchUpdateAiModels(
+ await this.#get().batchUpdateAiModels(
data.map((model) => ({
...model,
abilities: {
@@ -91,11 +82,12 @@ export const createAiModelSlice: StateCreator<
})),
);
- await get().refreshAiModelList();
+ await this.#get().refreshAiModelList();
}
- },
- internal_toggleAiModelLoading: (id, loading) => {
- set(
+ };
+
+ internal_toggleAiModelLoading = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading) return { aiModelLoadingIds: [...state.aiModelLoadingIds, id] };
@@ -104,52 +96,66 @@ export const createAiModelSlice: StateCreator<
false,
'toggleAiModelLoading',
);
- },
- refreshAiModelList: async () => {
- await mutate([FETCH_AI_PROVIDER_MODEL_LIST_KEY, get().activeAiProvider]);
+ };
+
+ refreshAiModelList = async (): Promise<void> => {
+ await mutate([FETCH_AI_PROVIDER_MODEL_LIST_KEY, this.#get().activeAiProvider]);
// make refresh provide runtime state async, not block
- get().refreshAiProviderRuntimeState();
- },
- removeAiModel: async (id, providerId) => {
+ this.#get().refreshAiProviderRuntimeState();
+ };
+
+ removeAiModel = async (id: string, providerId: string): Promise<void> => {
await aiModelService.deleteAiModel({ id, providerId });
- await get().refreshAiModelList();
- },
- toggleModelEnabled: async (params) => {
- const { activeAiProvider } = get();
+ await this.#get().refreshAiModelList();
+ };
+
+ toggleModelEnabled = async (
+ params: Omit<ToggleAiModelEnableParams, 'providerId'>,
+ ): Promise<void> => {
+ const { activeAiProvider } = this.#get();
if (!activeAiProvider) return;
- get().internal_toggleAiModelLoading(params.id, true);
+ this.#get().internal_toggleAiModelLoading(params.id, true);
await aiModelService.toggleModelEnabled({ ...params, providerId: activeAiProvider });
- await get().refreshAiModelList();
+ await this.#get().refreshAiModelList();
- get().internal_toggleAiModelLoading(params.id, false);
- },
+ this.#get().internal_toggleAiModelLoading(params.id, false);
+ };
- updateAiModelsConfig: async (id, providerId, data) => {
+ updateAiModelsConfig = async (
+ id: string,
+ providerId: string,
+ data: Partial<AiProviderModelListItem>,
+ ): Promise<void> => {
await aiModelService.updateAiModel(id, providerId, data);
- await get().refreshAiModelList();
- },
- updateAiModelsSort: async (id, items) => {
+ await this.#get().refreshAiModelList();
+ };
+
+ updateAiModelsSort = async (id: string, items: AiModelSortMap[]): Promise<void> => {
await aiModelService.updateAiModelOrder(id, items);
- await get().refreshAiModelList();
- },
+ await this.#get().refreshAiModelList();
+ };
- useFetchAiProviderModels: (id) =>
- useClientDataSWR<AiProviderModelListItem[]>(
+ useFetchAiProviderModels = (id: string): SWRResponse<AiProviderModelListItem[]> => {
+ return useClientDataSWR<AiProviderModelListItem[]>(
[FETCH_AI_PROVIDER_MODEL_LIST_KEY, id],
([, id]) => aiModelService.getAiProviderModelList(id as string),
{
onSuccess: (data) => {
// no need to update list if the list have been init and data is the same
- if (get().isAiModelListInit && isEqual(data, get().aiProviderModelList)) return;
+ if (this.#get().isAiModelListInit && isEqual(data, this.#get().aiProviderModelList))
+ return;
- set(
+ this.#set(
{ aiProviderModelList: data, isAiModelListInit: true },
false,
`useFetchAiProviderModels/${id}`,
);
},
},
- ),
-});
+ );
+ };
+}
+
+export type AiModelAction = Pick<AiModelActionImpl, keyof AiModelActionImpl>;
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index e434be893d7..b77fe792c77 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -111,11 +111,13 @@ const isModelHasBuiltinSearch = (id: string, provider: string) => (s: AIProvider
return !!searchImpl;
};
-const isModelBuiltinSearchInternal = (id: string, provider: string) => (s: AIProviderStoreState): boolean => {
- const searchImpl = modelBuiltinSearchImpl(id, provider)(s);
+const isModelBuiltinSearchInternal =
+ (id: string, provider: string) =>
+ (s: AIProviderStoreState): boolean => {
+ const searchImpl = modelBuiltinSearchImpl(id, provider)(s);
- return searchImpl === ModelSearchImplement.Internal;
-};
+ return searchImpl === ModelSearchImplement.Internal;
+ };
const isModelHasBuiltinSearchConfig =
(id: string, provider: string) => (s: AIProviderStoreState) => {
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index b9697474509..b68ff99bad0 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -9,11 +9,11 @@ import {
type Pricing,
} from 'model-bank';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { aiProviderService } from '@/services/aiProvider';
import { type AiInfraStore } from '@/store/aiInfra/store';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
import {
@@ -168,52 +168,33 @@ type AiProviderRuntimeStateWithBuiltinModels = AiProviderRuntimeState & {
enabledImageModelList?: EnabledProviderWithModels[];
};
-export interface AiProviderAction {
- createNewAiProvider: (params: CreateAiProviderParams) => Promise<void>;
- deleteAiProvider: (id: string) => Promise<void>;
- internal_toggleAiProviderConfigUpdating: (id: string, loading: boolean) => void;
- internal_toggleAiProviderLoading: (id: string, loading: boolean) => void;
- refreshAiProviderDetail: () => Promise<void>;
- refreshAiProviderList: () => Promise<void>;
- refreshAiProviderRuntimeState: () => Promise<void>;
- removeAiProvider: (id: string) => Promise<void>;
- toggleProviderEnabled: (id: string, enabled: boolean) => Promise<void>;
- updateAiProvider: (id: string, value: UpdateAiProviderParams) => Promise<void>;
- updateAiProviderConfig: (id: string, value: UpdateAiProviderConfigParams) => Promise<void>;
- updateAiProviderSort: (items: AiProviderSortMap[]) => Promise<void>;
-
- useFetchAiProviderItem: (id: string) => SWRResponse<AiProviderDetailItem | undefined>;
- useFetchAiProviderList: (params?: {
- enabled?: boolean;
- suspense?: boolean;
- }) => SWRResponse<AiProviderListItem[]>;
- /**
- * fetch provider keyVaults and user enabled model list
- * @param isLoginOnInit
- */
- useFetchAiProviderRuntimeState: (
- isLoginOnInit: boolean | undefined,
- isSyncActive?: boolean,
- ) => SWRResponse<AiProviderRuntimeStateWithBuiltinModels | undefined>;
-}
+type Setter = StoreSetter<AiInfraStore>;
+export const createAiProviderSlice = (set: Setter, get: () => AiInfraStore, _api?: unknown) =>
+ new AiProviderActionImpl(set, get, _api);
-export const createAiProviderSlice: StateCreator<
- AiInfraStore,
- [['zustand/devtools', never]],
- [],
- AiProviderAction
-> = (set, get) => ({
- createNewAiProvider: async (params) => {
+export class AiProviderActionImpl {
+ readonly #get: () => AiInfraStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => AiInfraStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ createNewAiProvider = async (params: CreateAiProviderParams): Promise<void> => {
await aiProviderService.createAiProvider({ ...params, source: AiProviderSourceEnum.Custom });
- await get().refreshAiProviderList();
- },
- deleteAiProvider: async (id: string) => {
+ await this.#get().refreshAiProviderList();
+ };
+
+ deleteAiProvider = async (id: string): Promise<void> => {
await aiProviderService.deleteAiProvider(id);
- await get().refreshAiProviderList();
- },
- internal_toggleAiProviderConfigUpdating: (id, loading) => {
- set(
+ await this.#get().refreshAiProviderList();
+ };
+
+ internal_toggleAiProviderConfigUpdating = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading)
return { aiProviderConfigUpdatingIds: [...state.aiProviderConfigUpdatingIds, id] };
@@ -225,9 +206,10 @@ export const createAiProviderSlice: StateCreator<
false,
'toggleAiProviderLoading',
);
- },
- internal_toggleAiProviderLoading: (id, loading) => {
- set(
+ };
+
+ internal_toggleAiProviderLoading = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading) return { aiProviderLoadingIds: [...state.aiProviderLoadingIds, id] };
@@ -236,33 +218,37 @@ export const createAiProviderSlice: StateCreator<
false,
'toggleAiProviderLoading',
);
- },
- refreshAiProviderDetail: async () => {
- await mutate([AiProviderSwrKey.fetchAiProviderItem, get().activeAiProvider]);
- await get().refreshAiProviderRuntimeState();
- },
- refreshAiProviderList: async () => {
+ };
+
+ refreshAiProviderDetail = async (): Promise<void> => {
+ await mutate([AiProviderSwrKey.fetchAiProviderItem, this.#get().activeAiProvider]);
+ await this.#get().refreshAiProviderRuntimeState();
+ };
+
+ refreshAiProviderList = async (): Promise<void> => {
await mutate(AiProviderSwrKey.fetchAiProviderList);
- await get().refreshAiProviderRuntimeState();
- },
- refreshAiProviderRuntimeState: async () => {
+ await this.#get().refreshAiProviderRuntimeState();
+ };
+
+ refreshAiProviderRuntimeState = async (): Promise<void> => {
await Promise.all([
mutate([AiProviderSwrKey.fetchAiProviderRuntimeState, true]),
mutate([AiProviderSwrKey.fetchAiProviderRuntimeState, false]),
]);
- },
- removeAiProvider: async (id) => {
+ };
+
+ removeAiProvider = async (id: string): Promise<void> => {
await aiProviderService.deleteAiProvider(id);
- await get().refreshAiProviderList();
- },
+ await this.#get().refreshAiProviderList();
+ };
- toggleProviderEnabled: async (id: string, enabled: boolean) => {
- get().internal_toggleAiProviderLoading(id, true);
+ toggleProviderEnabled = async (id: string, enabled: boolean): Promise<void> => {
+ this.#get().internal_toggleAiProviderLoading(id, true);
await aiProviderService.toggleProviderEnabled(id, enabled);
// Immediately update local aiProviderList to reflect the change
// This ensures the switch displays correctly without waiting for SWR refresh
- set(
+ this.#set(
(state) => ({
aiProviderList: state.aiProviderList.map((item) =>
item.id === id ? { ...item, enabled } : item,
@@ -272,26 +258,29 @@ export const createAiProviderSlice: StateCreator<
'toggleProviderEnabled/syncEnabled',
);
- await get().refreshAiProviderList();
+ await this.#get().refreshAiProviderList();
- get().internal_toggleAiProviderLoading(id, false);
- },
+ this.#get().internal_toggleAiProviderLoading(id, false);
+ };
- updateAiProvider: async (id, value) => {
- get().internal_toggleAiProviderLoading(id, true);
+ updateAiProvider = async (id: string, value: UpdateAiProviderParams): Promise<void> => {
+ this.#get().internal_toggleAiProviderLoading(id, true);
await aiProviderService.updateAiProvider(id, value);
- await get().refreshAiProviderList();
- await get().refreshAiProviderDetail();
+ await this.#get().refreshAiProviderList();
+ await this.#get().refreshAiProviderDetail();
- get().internal_toggleAiProviderLoading(id, false);
- },
+ this.#get().internal_toggleAiProviderLoading(id, false);
+ };
- updateAiProviderConfig: async (id, value) => {
- get().internal_toggleAiProviderConfigUpdating(id, true);
+ updateAiProviderConfig = async (
+ id: string,
+ value: UpdateAiProviderConfigParams,
+ ): Promise<void> => {
+ this.#get().internal_toggleAiProviderConfigUpdating(id, true);
await aiProviderService.updateAiProviderConfig(id, value);
// Immediately update local state for instant UI feedback
- set(
+ this.#set(
(state) => {
const currentRuntimeConfig = state.aiProviderRuntimeConfig[id];
const currentDetailConfig = state.aiProviderDetailMap[id];
@@ -344,24 +333,25 @@ export const createAiProviderSlice: StateCreator<
'updateAiProviderConfig/syncChanges',
);
- await get().refreshAiProviderDetail();
+ await this.#get().refreshAiProviderDetail();
- get().internal_toggleAiProviderConfigUpdating(id, false);
- },
+ this.#get().internal_toggleAiProviderConfigUpdating(id, false);
+ };
- updateAiProviderSort: async (items) => {
+ updateAiProviderSort = async (items: AiProviderSortMap[]): Promise<void> => {
await aiProviderService.updateAiProviderOrder(items);
- await get().refreshAiProviderList();
- },
- useFetchAiProviderItem: (id) =>
- useClientDataSWR<AiProviderDetailItem | undefined>(
+ await this.#get().refreshAiProviderList();
+ };
+
+ useFetchAiProviderItem = (id: string): SWRResponse<AiProviderDetailItem | undefined> => {
+ return useClientDataSWR<AiProviderDetailItem | undefined>(
[AiProviderSwrKey.fetchAiProviderItem, id],
() => aiProviderService.getAiProviderById(id),
{
onSuccess: (data) => {
if (!data) return;
- set(
+ this.#set(
(state) => ({
activeAiProvider: id,
aiProviderDetailMap: { ...state.aiProviderDetailMap, [id]: data },
@@ -371,16 +361,21 @@ export const createAiProviderSlice: StateCreator<
);
},
},
- ),
- useFetchAiProviderList: (opts) =>
- useClientDataSWR<AiProviderListItem[]>(
+ );
+ };
+
+ useFetchAiProviderList = (opts?: {
+ enabled?: boolean;
+ suspense?: boolean;
+ }): SWRResponse<AiProviderListItem[]> => {
+ return useClientDataSWR<AiProviderListItem[]>(
opts?.enabled === false ? null : AiProviderSwrKey.fetchAiProviderList,
() => aiProviderService.getAiProviderList(),
{
fallbackData: [],
onSuccess: (data) => {
- if (!get().initAiProviderList) {
- set(
+ if (!this.#get().initAiProviderList) {
+ this.#set(
{ aiProviderList: data, initAiProviderList: true },
false,
'useFetchAiProviderList/init',
@@ -388,12 +383,18 @@ export const createAiProviderSlice: StateCreator<
return;
}
- set({ aiProviderList: data }, false, 'useFetchAiProviderList/refresh');
+ this.#set({ aiProviderList: data }, false, 'useFetchAiProviderList/refresh');
},
},
- ),
+ );
+ };
- useFetchAiProviderRuntimeState: (isLogin) => {
+ useFetchAiProviderRuntimeState = (
+ isLoginOnInit: boolean | undefined,
+ isSyncActive?: boolean,
+ ): SWRResponse<AiProviderRuntimeStateWithBuiltinModels | undefined> => {
+ void isSyncActive;
+ const isLogin = isLoginOnInit;
const isAuthLoaded = useUserStore(authSelectors.isLoaded);
// Only fetch when auth is loaded and login status is explicitly defined (true or false)
// Prevents unnecessary requests when login state is null/undefined
@@ -461,7 +462,7 @@ export const createAiProviderSlice: StateCreator<
onSuccess: (data) => {
if (!data) return;
- set(
+ this.#set(
{
aiProviderRuntimeConfig: data.runtimeConfig,
builtinAiModelList: data.builtinAiModelList,
@@ -477,5 +478,7 @@ export const createAiProviderSlice: StateCreator<
},
},
);
- },
-});
+ };
+}
+
+export type AiProviderAction = Pick<AiProviderActionImpl, keyof AiProviderActionImpl>;
diff --git a/src/store/aiInfra/store.ts b/src/store/aiInfra/store.ts
index 1eb96cf2357..3d6a309c20f 100644
--- a/src/store/aiInfra/store.ts
+++ b/src/store/aiInfra/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type AIProviderStoreState, initialState } from './initialState';
import { type AiModelAction, createAiModelSlice } from './slices/aiModel';
import { type AiProviderAction, createAiProviderSlice } from './slices/aiProvider';
@@ -13,10 +14,16 @@ export interface AiInfraStore extends AIProviderStoreState, AiProviderAction, Ai
/* empty */
}
-const createStore: StateCreator<AiInfraStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type AiInfraStoreAction = AiProviderAction & AiModelAction;
+
+const createStore: StateCreator<AiInfraStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<AiInfraStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createAiModelSlice(...parameters),
- ...createAiProviderSlice(...parameters),
+ ...flattenActions<AiInfraStoreAction>([
+ createAiModelSlice(...parameters),
+ createAiProviderSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index e9557091317..36e7c74201c 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -520,7 +520,7 @@ export const createAgentExecutors = (context: {
toolName,
!!runtimeContext?.stepContext?.todos,
);
- const result = await context
+ const result: any = await context
.get()
.internal_invokeDifferentTypePlugin(
toolMessageId,
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
index cdcf3b5c6ce..4b647f24d8b 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
@@ -67,7 +67,7 @@ const resetTestEnvironment = () => {
};
// Helper to create test context
-const createTestContext = (overrides = {}) => ({
+const createTestContext = (overrides: any = {}) => ({
agentId: TEST_IDS.AGENT_ID,
groupId: TEST_IDS.GROUP_ID,
topicId: null as string | null,
@@ -76,7 +76,7 @@ const createTestContext = (overrides = {}) => ({
});
// Helper to create mock response from execGroupAgent
-const createMockExecGroupAgentResponse = (overrides = {}) => ({
+const createMockExecGroupAgentResponse = (overrides: any = {}) => ({
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
operationId: TEST_IDS.OPERATION_ID,
topicId: TEST_IDS.TOPIC_ID,
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
index 7bf126a8529..8eb9cb71c19 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
@@ -29,7 +29,7 @@ const resetTestEnvironment = () => {
};
// Helper to create streaming context
-const createStreamingContext = (overrides = {}) => ({
+const createStreamingContext = (overrides: any = {}) => ({
assistantId: '',
content: '',
reasoning: '',
diff --git a/src/store/chat/slices/aiAgent/actions/agentGroup.ts b/src/store/chat/slices/aiAgent/actions/agentGroup.ts
index 2e5b0c1c2bc..f5243a00aaf 100644
--- a/src/store/chat/slices/aiAgent/actions/agentGroup.ts
+++ b/src/store/chat/slices/aiAgent/actions/agentGroup.ts
@@ -3,31 +3,32 @@ import { LOADING_FLAT } from '@lobechat/const';
import { type SendGroupMessageParams } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import debug from 'debug';
-import { type StateCreator } from 'zustand/vanilla';
import { lambdaClient } from '@/libs/trpc/client';
import { type StreamEvent, agentRuntimeClient } from '@/services/agentRuntime';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
const log = debug('store:chat:ai-agent:agentGroup');
const n = setNamespace('aiAgentGroup');
-export interface ChatGroupChatAction {
- /**
- * Sends a new message to a group chat and triggers agent responses
- */
- sendGroupMessage: (params: SendGroupMessageParams) => Promise<void>;
-}
+type Setter = StoreSetter<ChatStore>;
+export const agentGroupSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatGroupChatActionImpl(set, get, _api);
+
+export class ChatGroupChatActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const agentGroupSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatGroupChatAction
-> = (set, get) => ({
- sendGroupMessage: async ({ context, message, files }) => {
+ sendGroupMessage = async ({ context, message, files }: SendGroupMessageParams): Promise<void> => {
if (!message.trim() && (!files || files.length === 0)) return;
const { agentId, groupId, topicId } = context;
@@ -37,7 +38,8 @@ export const agentGroupSlice: StateCreator<
return;
}
- const { internal_handleAgentStreamEvent, optimisticCreateTmpMessage, startOperation } = get();
+ const { internal_handleAgentStreamEvent, optimisticCreateTmpMessage, startOperation } =
+ this.#get();
log(
'sendGroupMessage: agentId=%s, groupId=%s, message=%s',
@@ -46,7 +48,7 @@ export const agentGroupSlice: StateCreator<
message.slice(0, 50),
);
- set({ isCreatingMessage: true }, false, n('sendGroupMessage/start'));
+ this.#set({ isCreatingMessage: true }, false, n('sendGroupMessage/start'));
// 0. Create execServerAgentRuntime operation FIRST for correct loading state
// This ensures isAgentRuntimeRunningByContext returns true during mutate call
@@ -87,8 +89,8 @@ export const agentGroupSlice: StateCreator<
);
// Start loading state for temp messages
- get().internal_toggleMessageLoading(true, tempUserId);
- get().internal_toggleMessageLoading(true, tempAssistantId);
+ this.#get().internal_toggleMessageLoading(true, tempUserId);
+ this.#get().internal_toggleMessageLoading(true, tempAssistantId);
try {
// 2. Call backend execGroupAgent - creates messages and triggers Agent
@@ -108,7 +110,7 @@ export const agentGroupSlice: StateCreator<
// 3. Update topics if new topic was created
if (result.topics) {
const pageSize = 20; // Default page size for topics
- get().internal_updateTopics(agentId, {
+ this.#get().internal_updateTopics(agentId, {
groupId,
items: result.topics.items as any, // Type from DB may have null vs undefined differences
pageSize,
@@ -118,7 +120,10 @@ export const agentGroupSlice: StateCreator<
// 4. Switch to new topic if created
if (result.isCreateNewTopic && result.topicId) {
- await get().switchTopic(result.topicId, { clearNewKey: true, skipRefreshMessage: true });
+ await this.#get().switchTopic(result.topicId, {
+ clearNewKey: true,
+ skipRefreshMessage: true,
+ });
}
// 5. Create execContext with updated topicId from server response
@@ -127,12 +132,12 @@ export const agentGroupSlice: StateCreator<
// 6. Replace temp messages with server messages
// Messages include assistant message with error if operation failed to start
if (result.messages) {
- get().replaceMessages(result.messages, {
+ this.#get().replaceMessages(result.messages, {
action: n('sendGroupMessage/syncMessages'),
context: execContext,
});
// Delete temp messages - use execOperationId for correct context
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{ ids: [tempUserId, tempAssistantId], type: 'deleteMessages' },
{ operationId: execOperationId },
);
@@ -143,12 +148,12 @@ export const agentGroupSlice: StateCreator<
if (result.success === false) {
log('Agent operation failed to start: %s', result.error);
// Complete the operation with error status
- get().failOperation(execOperationId, {
+ this.#get().failOperation(execOperationId, {
message: result.error || 'Agent operation failed to start',
type: 'AgentStartupError',
});
// Stop loading state for assistant message
- get().internal_toggleMessageLoading(false, result.assistantMessageId);
+ this.#get().internal_toggleMessageLoading(false, result.assistantMessageId);
return;
}
@@ -161,7 +166,7 @@ export const agentGroupSlice: StateCreator<
};
// 9. Start child operation for SSE stream using backend operationId
- get().startOperation({
+ this.#get().startOperation({
context: { ...execContext, messageId: result.assistantMessageId },
label: 'Group Agent Stream',
operationId: result.operationId,
@@ -172,8 +177,8 @@ export const agentGroupSlice: StateCreator<
// Associate assistant message with both operations:
// - execServerAgentRuntime (parent) - for isGenerating detection
// - groupAgentStream (child) - for stream cancel handling
- get().associateMessageWithOperation(result.assistantMessageId, execOperationId);
- get().associateMessageWithOperation(result.assistantMessageId, result.operationId);
+ this.#get().associateMessageWithOperation(result.assistantMessageId, execOperationId);
+ this.#get().associateMessageWithOperation(result.assistantMessageId, result.operationId);
// 10. Connect to SSE stream
// Server will automatically close the connection after sending agent_runtime_end event
@@ -185,18 +190,18 @@ export const agentGroupSlice: StateCreator<
onDisconnect: () => {
log('Stream disconnected from %s', result.operationId);
// Complete both operations when stream disconnects (either by server close or client abort)
- get().completeOperation(result.operationId);
- get().completeOperation(execOperationId);
+ this.#get().completeOperation(result.operationId);
+ this.#get().completeOperation(execOperationId);
},
onError: (error: Error) => {
log('Stream error for %s: %O', result.operationId, error);
// Fail the stream operation on error
- get().failOperation(result.operationId, {
+ this.#get().failOperation(result.operationId, {
message: error.message,
type: 'AgentStreamError',
});
if (streamContext.assistantId) {
- get().internal_handleAgentError(streamContext.assistantId, error.message);
+ this.#get().internal_handleAgentError(streamContext.assistantId, error.message);
}
},
onEvent: async (event: StreamEvent) => {
@@ -205,7 +210,7 @@ export const agentGroupSlice: StateCreator<
});
// 11. Register cancel handler for aborting SSE stream
- get().onOperationCancel(result.operationId, () => {
+ this.#get().onOperationCancel(result.operationId, () => {
log('Cancelling SSE stream for operation %s', result.operationId);
eventSource.abort();
});
@@ -221,7 +226,7 @@ export const agentGroupSlice: StateCreator<
log('sendGroupMessage aborted by user');
// Operation was cancelled by user, status already updated by cancelOperation
// Just clean up temp messages
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{
ids: [tempUserId, tempAssistantId],
type: 'deleteMessages',
@@ -233,7 +238,7 @@ export const agentGroupSlice: StateCreator<
console.error('Failed to send group message:', error);
// Remove temp messages on error - use execOperationId for correct context
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{
ids: [tempUserId, tempAssistantId],
type: 'deleteMessages',
@@ -242,15 +247,17 @@ export const agentGroupSlice: StateCreator<
);
// Fail the execServerAgentRuntime operation
- get().failOperation(execOperationId, {
+ this.#get().failOperation(execOperationId, {
message: error instanceof Error ? error.message : 'Unknown error',
type: 'SendGroupMessageError',
});
}
} finally {
- get().internal_toggleMessageLoading(false, tempUserId);
- get().internal_toggleMessageLoading(false, tempAssistantId);
- set({ isCreatingMessage: false }, false, n('sendGroupMessage/end'));
+ this.#get().internal_toggleMessageLoading(false, tempUserId);
+ this.#get().internal_toggleMessageLoading(false, tempAssistantId);
+ this.#set({ isCreatingMessage: false }, false, n('sendGroupMessage/end'));
}
- },
-});
+ };
+}
+
+export type ChatGroupChatAction = Pick<ChatGroupChatActionImpl, keyof ChatGroupChatActionImpl>;
diff --git a/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts b/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts
index f0c3d7fdd45..ea26b8d9c85 100644
--- a/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts
+++ b/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts
@@ -4,13 +4,13 @@ import { GroupOrchestrationRuntime, GroupOrchestrationSupervisor } from '@lobech
import { type TaskStatusResult } from '@lobechat/types';
import debug from 'debug';
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWR } from '@/libs/swr';
import { aiAgentService } from '@/services/aiAgent';
import { createGroupOrchestrationExecutors } from '@/store/chat/agents/GroupOrchestration';
import { type ChatStore } from '@/store/chat/store';
import type { GroupOrchestrationCallbacks } from '@/store/tool/slices/builtin/types';
+import { type StoreSetter } from '@/store/types';
const log = debug('lobe-store:group-orchestration');
@@ -36,75 +36,33 @@ export interface GroupOrchestrationParams {
topicId?: string;
}
-export interface GroupOrchestrationAction {
- /**
- * Internal: Execute Group Orchestration Loop
- * Called by triggerSpeak/triggerBroadcast/triggerDelegate after supervisor decides next action
- */
- internal_execGroupOrchestration: (params: GroupOrchestrationParams) => Promise<AgentState>;
+type Setter = StoreSetter<ChatStore>;
+export const groupOrchestrationSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new GroupOrchestrationActionImpl(set, get, _api);
- /**
- * Get active group orchestration callbacks
- * Used by invokeBuiltinTool to inject callbacks into tool context
- */
- getGroupOrchestrationCallbacks: () => GroupOrchestrationCallbacks;
+export class GroupOrchestrationActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
- /**
- * Trigger speak - called by speak tool when supervisor decides to let an agent speak
- * This starts the group orchestration loop with supervisor_decided result
- */
- triggerSpeak: GroupOrchestrationCallbacks['triggerSpeak'];
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- /**
- * Trigger broadcast - called by broadcast tool when supervisor decides to broadcast
- * This starts the group orchestration loop with supervisor_decided result
- */
- triggerBroadcast: GroupOrchestrationCallbacks['triggerBroadcast'];
-
- /**
- * Trigger delegate - called by delegate tool when supervisor decides to delegate
- * This starts the group orchestration loop with supervisor_decided result
- */
- triggerDelegate: GroupOrchestrationCallbacks['triggerDelegate'];
-
- /**
- * Trigger execute task - called by executeTask tool when supervisor decides to execute an async task
- * This starts the group orchestration loop with supervisor_decided result
- */
- triggerExecuteTask: GroupOrchestrationCallbacks['triggerExecuteTask'];
-
- /**
- * Trigger execute tasks - called by executeTasks tool when supervisor decides to execute multiple async tasks in parallel
- * This starts the group orchestration loop with supervisor_decided result
- */
- triggerExecuteTasks: GroupOrchestrationCallbacks['triggerExecuteTasks'];
-
- /**
- * Enable polling for task status
- * Used by ProcessingState component to poll for real-time task updates
- *
- * @param threadId - Thread ID to poll status for
- * @param messageId - Message ID to update with taskDetail
- * @param enabled - Whether polling should be enabled (caller decides based on processing state and active operations)
- */
- useEnablePollingTaskStatus: (
- threadId: string | undefined,
- messageId: string | undefined,
- enabled: boolean,
- ) => SWRResponse<TaskStatusResult>;
-}
+ getGroupOrchestrationCallbacks = (): GroupOrchestrationCallbacks => {
+ return {
+ triggerSpeak: this.#get().triggerSpeak,
+ triggerBroadcast: this.#get().triggerBroadcast,
+ triggerDelegate: this.#get().triggerDelegate,
+ triggerExecuteTask: this.#get().triggerExecuteTask,
+ triggerExecuteTasks: this.#get().triggerExecuteTasks,
+ };
+ };
-export const groupOrchestrationSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- GroupOrchestrationAction
-> = (set, get) => ({
- /**
- * Trigger speak - Entry point when supervisor calls speak tool
- * Creates a supervisor_decided result with decision='speak' and starts orchestration
- */
- triggerSpeak: async (params) => {
+ triggerSpeak = async (
+ params: Parameters<GroupOrchestrationCallbacks['triggerSpeak']>[0],
+ ): Promise<void> => {
const { supervisorAgentId, agentId, instruction, skipCallSupervisor } = params;
log(
'[triggerSpeak] Starting orchestration with speak: supervisorAgentId=%s, agentId=%s, instruction=%s, skipCallSupervisor=%s',
@@ -114,17 +72,16 @@ export const groupOrchestrationSlice: StateCreator<
skipCallSupervisor,
);
- const groupId = get().activeGroupId;
+ const groupId = this.#get().activeGroupId;
if (!groupId) {
log('[triggerSpeak] No active group, skipping');
return;
}
- // Start orchestration loop with supervisor_decided result (decision=speak)
- await get().internal_execGroupOrchestration({
+ await this.#get().internal_execGroupOrchestration({
groupId,
supervisorAgentId,
- topicId: get().activeTopicId,
+ topicId: this.#get().activeTopicId,
initialResult: {
type: 'supervisor_decided',
payload: {
@@ -134,13 +91,11 @@ export const groupOrchestrationSlice: StateCreator<
},
},
});
- },
+ };
- /**
- * Trigger broadcast - Entry point when supervisor calls broadcast tool
- * Creates a supervisor_decided result with decision='broadcast' and starts orchestration
- */
- triggerBroadcast: async (params) => {
+ triggerBroadcast = async (
+ params: Parameters<GroupOrchestrationCallbacks['triggerBroadcast']>[0],
+ ): Promise<void> => {
const { supervisorAgentId, agentIds, instruction, skipCallSupervisor, toolMessageId } = params;
log(
'[triggerBroadcast] Starting orchestration with broadcast: supervisorAgentId=%s, agentIds=%o, instruction=%s, skipCallSupervisor=%s, toolMessageId=%s',
@@ -151,17 +106,16 @@ export const groupOrchestrationSlice: StateCreator<
toolMessageId,
);
- const groupId = get().activeGroupId;
+ const groupId = this.#get().activeGroupId;
if (!groupId) {
log('[triggerBroadcast] No active group, skipping');
return;
}
- // Start orchestration loop with supervisor_decided result (decision=broadcast)
- await get().internal_execGroupOrchestration({
+ await this.#get().internal_execGroupOrchestration({
groupId,
supervisorAgentId,
- topicId: get().activeTopicId,
+ topicId: this.#get().activeTopicId,
initialResult: {
type: 'supervisor_decided',
payload: {
@@ -171,13 +125,11 @@ export const groupOrchestrationSlice: StateCreator<
},
},
});
- },
+ };
- /**
- * Trigger delegate - Entry point when supervisor calls delegate tool
- * Creates a supervisor_decided result with decision='delegate' and starts orchestration
- */
- triggerDelegate: async (params) => {
+ triggerDelegate = async (
+ params: Parameters<GroupOrchestrationCallbacks['triggerDelegate']>[0],
+ ): Promise<void> => {
const { supervisorAgentId, agentId, reason } = params;
log(
'[triggerDelegate] Starting orchestration with delegate: supervisorAgentId=%s, agentId=%s, reason=%s',
@@ -186,33 +138,30 @@ export const groupOrchestrationSlice: StateCreator<
reason,
);
- const groupId = get().activeGroupId;
+ const groupId = this.#get().activeGroupId;
if (!groupId) {
log('[triggerDelegate] No active group, skipping');
return;
}
- // Start orchestration loop with supervisor_decided result (decision=delegate)
- await get().internal_execGroupOrchestration({
+ await this.#get().internal_execGroupOrchestration({
groupId,
supervisorAgentId,
- topicId: get().activeTopicId,
+ topicId: this.#get().activeTopicId,
initialResult: {
type: 'supervisor_decided',
payload: {
decision: 'delegate',
params: { agentId, reason },
- skipCallSupervisor: false, // delegate always ends orchestration
+ skipCallSupervisor: false,
},
},
});
- },
+ };
- /**
- * Trigger execute task - Entry point when supervisor calls executeTask tool
- * Creates a supervisor_decided result with decision='execute_task' and starts orchestration
- */
- triggerExecuteTask: async (params) => {
+ triggerExecuteTask = async (
+ params: Parameters<GroupOrchestrationCallbacks['triggerExecuteTask']>[0],
+ ): Promise<void> => {
const {
supervisorAgentId,
agentId,
@@ -233,17 +182,16 @@ export const groupOrchestrationSlice: StateCreator<
runInClient,
);
- const groupId = get().activeGroupId;
+ const groupId = this.#get().activeGroupId;
if (!groupId) {
log('[triggerExecuteTask] No active group, skipping');
return;
}
- // Start orchestration loop with supervisor_decided result (decision=execute_task)
- await get().internal_execGroupOrchestration({
+ await this.#get().internal_execGroupOrchestration({
groupId,
supervisorAgentId,
- topicId: get().activeTopicId,
+ topicId: this.#get().activeTopicId,
initialResult: {
type: 'supervisor_decided',
payload: {
@@ -253,13 +201,11 @@ export const groupOrchestrationSlice: StateCreator<
},
},
});
- },
+ };
- /**
- * Trigger execute tasks - Entry point when supervisor calls executeTasks tool
- * Creates a supervisor_decided result with decision='execute_tasks' and starts orchestration
- */
- triggerExecuteTasks: async (params) => {
+ triggerExecuteTasks = async (
+ params: Parameters<GroupOrchestrationCallbacks['triggerExecuteTasks']>[0],
+ ): Promise<void> => {
const { supervisorAgentId, tasks, toolMessageId, skipCallSupervisor } = params;
log(
'[triggerExecuteTasks] Starting orchestration with execute_tasks: supervisorAgentId=%s, tasks=%d, toolMessageId=%s, skipCallSupervisor=%s',
@@ -269,17 +215,16 @@ export const groupOrchestrationSlice: StateCreator<
skipCallSupervisor,
);
- const groupId = get().activeGroupId;
+ const groupId = this.#get().activeGroupId;
if (!groupId) {
log('[triggerExecuteTasks] No active group, skipping');
return;
}
- // Start orchestration loop with supervisor_decided result (decision=execute_tasks)
- await get().internal_execGroupOrchestration({
+ await this.#get().internal_execGroupOrchestration({
groupId,
supervisorAgentId,
- topicId: get().activeTopicId,
+ topicId: this.#get().activeTopicId,
initialResult: {
type: 'supervisor_decided',
payload: {
@@ -289,27 +234,11 @@ export const groupOrchestrationSlice: StateCreator<
},
},
});
- },
+ };
- /**
- * Get group orchestration callbacks
- * These are the action methods that tools can call to trigger orchestration
- */
- getGroupOrchestrationCallbacks: () => {
- return {
- triggerSpeak: get().triggerSpeak,
- triggerBroadcast: get().triggerBroadcast,
- triggerDelegate: get().triggerDelegate,
- triggerExecuteTask: get().triggerExecuteTask,
- triggerExecuteTasks: get().triggerExecuteTasks,
- };
- },
-
- /**
- * Internal: Execute the Group Orchestration Loop
- * Called after supervisor decides to speak/broadcast/delegate/execute_task
- */
- internal_execGroupOrchestration: async (params) => {
+ internal_execGroupOrchestration = async (
+ params: GroupOrchestrationParams,
+ ): Promise<AgentState> => {
const { groupId, topicId, initialResult, supervisorAgentId } = params;
log(
@@ -320,7 +249,7 @@ export const groupOrchestrationSlice: StateCreator<
);
// 1. Create Orchestration Operation
- const { operationId } = get().startOperation({
+ const { operationId } = this.#get().startOperation({
type: 'execAgentRuntime',
context: { groupId, topicId, agentId: supervisorAgentId, scope: 'group' },
label: `Group Orchestration (${initialResult.type})`,
@@ -344,7 +273,7 @@ export const groupOrchestrationSlice: StateCreator<
// 4. Create Executors (Execution Layer)
const executors = createGroupOrchestrationExecutors({
- get,
+ get: this.#get,
messageContext: { agentId: supervisorAgentId, groupId, scope: 'group', topicId },
orchestrationOperationId: operationId,
supervisorAgentId: groupConfig.supervisorAgentId,
@@ -355,7 +284,7 @@ export const groupOrchestrationSlice: StateCreator<
executors,
operationId,
getOperation: (opId: string) => {
- const op = get().operations[opId];
+ const op = this.#get().operations[opId];
if (!op) throw new Error(`Operation not found: ${opId}`);
return {
abortController: op.abortController,
@@ -381,7 +310,7 @@ export const groupOrchestrationSlice: StateCreator<
while (currentResult && state.status !== 'done' && state.status !== 'error') {
// Check if operation has been cancelled
- const currentOperation = get().operations[operationId];
+ const currentOperation = this.#get().operations[operationId];
if (currentOperation?.status === 'cancelled') {
log('[internal_execGroupOrchestration] Operation cancelled, stopping loop');
state = { ...state, status: 'done' };
@@ -418,10 +347,10 @@ export const groupOrchestrationSlice: StateCreator<
// 8. Complete Operation
if (state.status === 'done') {
- get().completeOperation(operationId);
+ this.#get().completeOperation(operationId);
log('[internal_execGroupOrchestration] Operation completed successfully');
} else if (state.status === 'error') {
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
type: 'orchestration_error',
message: 'Group orchestration execution failed',
});
@@ -429,13 +358,13 @@ export const groupOrchestrationSlice: StateCreator<
}
return state;
- },
+ };
- /**
- * Enable polling for task status using SWR
- * Caller is responsible for determining when to enable polling
- */
- useEnablePollingTaskStatus: (threadId, messageId, enabled) => {
+ useEnablePollingTaskStatus = (
+ threadId: string | undefined,
+ messageId: string | undefined,
+ enabled: boolean,
+ ): SWRResponse<TaskStatusResult> => {
return useClientDataSWR<TaskStatusResult>(
enabled && threadId && messageId ? [SWR_USE_POLLING_TASK_STATUS, threadId] : null,
async ([, tid]: [string, string]) => {
@@ -448,7 +377,7 @@ export const groupOrchestrationSlice: StateCreator<
onSuccess: (data) => {
if (data && messageId) {
// Update taskDetail and tasks (intermediate messages)
- get().internal_dispatchMessage({
+ this.#get().internal_dispatchMessage({
id: messageId,
type: 'updateMessage',
value: {
@@ -462,7 +391,7 @@ export const groupOrchestrationSlice: StateCreator<
(data.status === 'completed' || data.status === 'failed') &&
data.result !== undefined
) {
- get().internal_dispatchMessage({
+ this.#get().internal_dispatchMessage({
id: messageId,
type: 'updateMessage',
value: { content: data.result },
@@ -472,5 +401,10 @@ export const groupOrchestrationSlice: StateCreator<
},
},
);
- },
-});
+ };
+}
+
+export type GroupOrchestrationAction = Pick<
+ GroupOrchestrationActionImpl,
+ keyof GroupOrchestrationActionImpl
+>;
diff --git a/src/store/chat/slices/aiAgent/actions/index.ts b/src/store/chat/slices/aiAgent/actions/index.ts
index e4a6f5029bb..27c306819c5 100644
--- a/src/store/chat/slices/aiAgent/actions/index.ts
+++ b/src/store/chat/slices/aiAgent/actions/index.ts
@@ -1,23 +1,28 @@
import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { flattenActions } from '@/store/utils/flattenActions';
-import { type ChatGroupChatAction, agentGroupSlice } from './agentGroup';
-import { type GroupOrchestrationAction, groupOrchestrationSlice } from './groupOrchestration';
-import { type AgentAction, agentSlice } from './runAgent';
+import { type ChatGroupChatAction, ChatGroupChatActionImpl } from './agentGroup';
+import { type GroupOrchestrationAction, GroupOrchestrationActionImpl } from './groupOrchestration';
+import { type AgentAction, AgentActionImpl } from './runAgent';
+
+export type ChatAIAgentAction = AgentAction & ChatGroupChatAction & GroupOrchestrationAction;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
-export interface ChatAIAgentAction extends AgentAction, ChatGroupChatAction, GroupOrchestrationAction {
- /**/
-}
export const chatAiAgent: StateCreator<
ChatStore,
[['zustand/devtools', never]],
[],
ChatAIAgentAction
-> = (...params) => ({
- ...agentSlice(...params),
- ...agentGroupSlice(...params),
- ...groupOrchestrationSlice(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatAIAgentAction>
+ >
+) =>
+ flattenActions<ChatAIAgentAction>([
+ new AgentActionImpl(...params),
+ new ChatGroupChatActionImpl(...params),
+ new GroupOrchestrationActionImpl(...params),
+ ]);
diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.ts
index 369d410614d..5edbaa80e6a 100644
--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts
+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts
@@ -2,10 +2,10 @@ import { isDesktop } from '@lobechat/const';
import { type ChatToolPayload } from '@lobechat/types';
import debug from 'debug';
import i18n from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { type StreamEvent, agentRuntimeService } from '@/services/agentRuntime';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
const log = debug('store:chat:ai-agent:runAgent');
@@ -16,31 +16,24 @@ interface StreamingContext {
tmpAssistantId: string;
toolsCalling?: ChatToolPayload[];
}
-export interface AgentAction {
- internal_cleanupAgentOperation: (assistantId: string) => void;
- internal_handleAgentError: (assistantId: string, error: string) => void;
- /**
- * Agent Runtime 相关方法
- */
- internal_handleAgentStreamEvent: (
- operationId: string,
- event: StreamEvent,
- context: StreamingContext,
- ) => Promise<void>;
- internal_handleHumanIntervention: (
- assistantId: string,
- action: string,
- data?: any,
- ) => Promise<void>;
-}
-export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]], [], AgentAction> = (
- set,
- get,
-) => ({
- internal_cleanupAgentOperation: (assistantId: string) => {
+type Setter = StoreSetter<ChatStore>;
+export const agentSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new AgentActionImpl(set, get, _api);
+
+export class AgentActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_cleanupAgentOperation = (assistantId: string): void => {
// Find operation by messageId (assistantId)
- const messageOpId = get().messageOperationMap[assistantId];
+ const messageOpId = this.#get().messageOperationMap[assistantId];
if (!messageOpId) {
log(`No operation found for assistant message ${assistantId}`);
return;
@@ -49,23 +42,23 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
log(`Cleaning up agent operation for ${assistantId} (operationId: ${messageOpId})`);
// Cancel the operation (this will trigger the cancel handler which aborts the SSE stream)
- get().cancelOperation(messageOpId, 'Cleanup requested');
- },
+ this.#get().cancelOperation(messageOpId, 'Cleanup requested');
+ };
- internal_handleAgentError: (assistantId: string, errorMessage: string) => {
+ internal_handleAgentError = (assistantId: string, errorMessage: string): void => {
log(`Agent error for ${assistantId}: ${errorMessage}`);
// Find operation by messageId (assistantId) and fail it
- const messageOpId = get().messageOperationMap[assistantId];
+ const messageOpId = this.#get().messageOperationMap[assistantId];
if (messageOpId) {
- get().failOperation(messageOpId, {
+ this.#get().failOperation(messageOpId, {
message: errorMessage,
type: 'AgentExecutionError',
});
}
// Update error state in frontend only (backend already persists the error)
- get().internal_dispatchMessage({
+ this.#get().internal_dispatchMessage({
id: assistantId,
type: 'updateMessage',
value: {
@@ -77,23 +70,26 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
});
// 停止 loading 状态
- get().internal_toggleMessageLoading(false, assistantId);
+ this.#get().internal_toggleMessageLoading(false, assistantId);
// 清理操作 (this will cancel the operation)
- get().internal_cleanupAgentOperation(assistantId);
- },
+ this.#get().internal_cleanupAgentOperation(assistantId);
+ };
- // ======== Agent Runtime 相关方法 ========
- internal_handleAgentStreamEvent: async (operationId, event, context) => {
- const { internal_dispatchMessage } = get();
- const operation = get().operations[operationId];
+ internal_handleAgentStreamEvent = async (
+ operationId: string,
+ event: StreamEvent,
+ context: StreamingContext,
+ ): Promise<void> => {
+ const { internal_dispatchMessage } = this.#get();
+ const operation = this.#get().operations[operationId];
if (!operation) {
log(`No operation found for ${operationId}, ignoring event ${event.type}`);
return;
}
// 更新操作元数据
- get().updateOperationMetadata(operationId, {
+ this.#get().updateOperationMetadata(operationId, {
lastEventId: event.timestamp.toString(),
stepCount: event.stepIndex,
});
@@ -125,14 +121,14 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
// Update operation metadata with final state
if (finalState) {
- get().updateOperationMetadata(operationId, {
+ this.#get().updateOperationMetadata(operationId, {
finalStatus: finalState.status || reason,
});
}
// Stop loading state
log(`Stopping loading for completed agent runtime: ${assistantId}`);
- get().internal_toggleMessageLoading(false, assistantId);
+ this.#get().internal_toggleMessageLoading(false, assistantId);
break;
}
@@ -236,7 +232,7 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
// 停止 loading 状态
log(`Stopping loading for ${assistantId}`);
- get().internal_toggleMessageLoading(false, assistantId);
+ this.#get().internal_toggleMessageLoading(false, assistantId);
// 显示桌面通知
if (isDesktop) {
@@ -260,14 +256,14 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
if (phase === 'human_approval' && requiresApproval) {
// 需要人工批准
log(`Human approval required for ${assistantId}:`, pendingToolsCalling);
- get().updateOperationMetadata(operationId, {
+ this.#get().updateOperationMetadata(operationId, {
needsHumanInput: true,
pendingApproval: pendingToolsCalling,
});
// 停止 loading 状态,等待人工干预
log(`Stopping loading for human approval: ${assistantId}`);
- get().internal_toggleMessageLoading(false, assistantId);
+ this.#get().internal_toggleMessageLoading(false, assistantId);
} else if (phase === 'tool_execution' && toolCall) {
log(`Tool execution started for ${assistantId}: ${toolCall.function?.name}`);
}
@@ -280,16 +276,16 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
if (phase === 'tool_execution' && result) {
log(`Tool execution completed for ${assistantId} in ${executionTime}ms:`, result);
// 刷新消息以显示工具结果
- await get().refreshMessages();
+ await this.#get().refreshMessages();
} else if (phase === 'execution_complete' && finalState) {
// Agent 执行完成
log(`Agent execution completed for ${assistantId}:`, finalState);
- get().updateOperationMetadata(operationId, {
+ this.#get().updateOperationMetadata(operationId, {
finalStatus: finalState.status,
});
log(`Stopping loading for completed agent: ${assistantId}`);
- get().internal_toggleMessageLoading(false, assistantId);
+ this.#get().internal_toggleMessageLoading(false, assistantId);
}
break;
}
@@ -297,7 +293,10 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
case 'error': {
const { error, message, phase } = event.data || {};
log(`Error in ${phase} for ${assistantId}:`, error);
- get().internal_handleAgentError(assistantId, message || error || 'Unknown agent error');
+ this.#get().internal_handleAgentError(
+ assistantId,
+ message || error || 'Unknown agent error',
+ );
break;
}
@@ -306,17 +305,21 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
break;
}
}
- },
+ };
- internal_handleHumanIntervention: async (assistantId: string, action: string, data?: any) => {
+ internal_handleHumanIntervention = async (
+ assistantId: string,
+ action: string,
+ data?: any,
+ ): Promise<void> => {
// Find operation by messageId (assistantId)
- const messageOpId = get().messageOperationMap[assistantId];
+ const messageOpId = this.#get().messageOperationMap[assistantId];
if (!messageOpId) {
log(`No operation found for assistant message ${assistantId}`);
return;
}
- const operation = get().operations[messageOpId];
+ const operation = this.#get().operations[messageOpId];
if (!operation || !operation.metadata.needsHumanInput) {
log(`No human intervention needed for operation ${messageOpId}`);
return;
@@ -333,10 +336,10 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
});
// 重新开始 loading 状态
- get().internal_toggleMessageLoading(true, assistantId);
+ this.#get().internal_toggleMessageLoading(true, assistantId);
// 清除人工干预状态
- get().updateOperationMetadata(messageOpId, {
+ this.#get().updateOperationMetadata(messageOpId, {
needsHumanInput: false,
pendingApproval: undefined,
pendingPrompt: undefined,
@@ -346,10 +349,12 @@ export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]],
log(`Human intervention ${action} processed for operation ${messageOpId}`);
} catch (error) {
log(`Failed to handle human intervention for operation ${messageOpId}:`, error);
- get().internal_handleAgentError(
+ this.#get().internal_handleAgentError(
assistantId,
`Human intervention failed: ${(error as Error).message}`,
);
}
- },
-});
+ };
+}
+
+export type AgentAction = Pick<AgentActionImpl, keyof AgentActionImpl>;
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts b/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts
index 4abfa009b5e..59e1fbd8650 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts
@@ -39,25 +39,25 @@ export const createMockMessage = (overrides: Partial<UIChatMessage> = {}): UICha
};
export const createMockMessages = (count: number): UIChatMessage[] =>
- Array.from({ length: count }, (_, i) =>
+ Array.from({ length: count }, (_, i: any) =>
createMockMessage({
content: `Message ${i}`,
id: `msg-${i}`,
}),
);
-export const createMockAgentConfig = (overrides = {}) => ({
+export const createMockAgentConfig = (overrides: any = {}) => ({
...DEFAULT_AGENT_CONFIG,
...overrides,
});
-export const createMockChatConfig = (overrides = {}) => ({
+export const createMockChatConfig = (overrides: any = {}) => ({
...DEFAULT_AGENT_CHAT_CONFIG,
...overrides,
});
// Mock Store State Factory
-export const createMockStoreState = (overrides = {}) => ({
+export const createMockStoreState = (overrides: any = {}) => ({
activeAgentId: TEST_IDS.SESSION_ID,
activeTopicId: TEST_IDS.TOPIC_ID,
messagesMap: {},
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
index f13471e66a0..3de03e717ce 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
@@ -40,7 +40,7 @@ export const setupMockSelectors = (
*/
export const setupStoreWithMessages = (
messages: any[],
- sessionId = TEST_IDS.SESSION_ID,
+ sessionId: any = TEST_IDS.SESSION_ID,
topicId: string | null | undefined = TEST_IDS.TOPIC_ID,
) => {
useChatStore.setState({
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index 61dccb54ba7..cab53dd4ac9 100644
--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts
@@ -3,9 +3,9 @@
import { type AgentRuntimeContext } from '@lobechat/agent-runtime';
import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';
import { type ConversationContext } from '@lobechat/types';
-import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { displayMessageSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
@@ -15,73 +15,23 @@ import { dbMessageSelectors } from '../../message/selectors';
/**
* Actions for controlling conversation operations like cancellation and error handling
*/
-export interface ConversationControlAction {
- /**
- * Interrupts the ongoing ai message generation process
- */
- stopGenerateMessage: () => void;
- /**
- * Cancels sendMessage operation for a specific topic/session
- */
- cancelSendMessageInServer: (topicId?: string) => void;
- /**
- * Clears any error messages from the send message operation
- */
- clearSendMessageError: () => void;
- /**
- * Switches to a different branch of a message
- * @param messageId - The ID of the message to switch branch
- * @param branchIndex - The index of the branch to switch to
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- switchMessageBranch: (
- messageId: string,
- branchIndex: number,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
- /**
- * Approve tool intervention
- * @param toolMessageId - The ID of the tool message to approve
- * @param assistantGroupId - The ID of the assistant group
- * @param context - Optional conversation context (for non-main conversations like agent-builder)
- */
- approveToolCalling: (
- toolMessageId: string,
- assistantGroupId: string,
- context?: ConversationContext,
- ) => Promise<void>;
- /**
- * Reject tool intervention
- * @param messageId - The ID of the tool message to reject
- * @param reason - Optional rejection reason
- * @param context - Optional conversation context (for non-main conversations like agent-builder)
- */
- rejectToolCalling: (
- messageId: string,
- reason?: string,
- context?: ConversationContext,
- ) => Promise<void>;
- /**
- * Reject tool intervention and continue
- * @param messageId - The ID of the tool message to reject
- * @param reason - Optional rejection reason
- * @param context - Optional conversation context (for non-main conversations like agent-builder)
- */
- rejectAndContinueToolCalling: (
- messageId: string,
- reason?: string,
- context?: ConversationContext,
- ) => Promise<void>;
-}
-export const conversationControl: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ConversationControlAction
-> = (set, get) => ({
- stopGenerateMessage: () => {
- const { activeAgentId, activeTopicId, cancelOperations } = get();
+type Setter = StoreSetter<ChatStore>;
+export const conversationControl = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ConversationControlActionImpl(set, get, _api);
+
+export class ConversationControlActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ stopGenerateMessage = (): void => {
+ const { activeAgentId, activeTopicId, cancelOperations } = this.#get();
// Cancel all running execAgentRuntime operations in the current context
cancelOperations(
@@ -93,22 +43,22 @@ export const conversationControl: StateCreator<
},
MESSAGE_CANCEL_FLAT,
);
- },
+ };
- cancelSendMessageInServer: (topicId?: string) => {
- const { activeAgentId, activeTopicId } = get();
+ cancelSendMessageInServer = (topicId?: string): void => {
+ const { activeAgentId, activeTopicId } = this.#get();
// Determine which operation to cancel
const targetTopicId = topicId ?? activeTopicId;
const contextKey = messageMapKey({ agentId: activeAgentId, topicId: targetTopicId });
// Cancel operations in the operation system
- const operationIds = get().operationsByContext[contextKey] || [];
+ const operationIds = this.#get().operationsByContext[contextKey] || [];
operationIds.forEach((opId) => {
- const operation = get().operations[opId];
+ const operation = this.#get().operations[opId];
if (operation && operation.type === 'sendMessage' && operation.status === 'running') {
- get().cancelOperation(opId, 'User cancelled');
+ this.#get().cancelOperation(opId, 'User cancelled');
}
});
@@ -116,50 +66,59 @@ export const conversationControl: StateCreator<
if (contextKey === messageMapKey({ agentId: activeAgentId, topicId: activeTopicId })) {
// Find the latest sendMessage operation with editor state
for (const opId of [...operationIds].reverse()) {
- const op = get().operations[opId];
+ const op = this.#get().operations[opId];
if (op && op.type === 'sendMessage' && op.metadata.inputEditorTempState) {
- get().mainInputEditor?.setJSONState(op.metadata.inputEditorTempState);
+ this.#get().mainInputEditor?.setJSONState(op.metadata.inputEditorTempState);
break;
}
}
}
- },
+ };
- clearSendMessageError: () => {
- const { activeAgentId, activeTopicId } = get();
+ clearSendMessageError = (): void => {
+ const { activeAgentId, activeTopicId } = this.#get();
const contextKey = messageMapKey({ agentId: activeAgentId, topicId: activeTopicId });
- const operationIds = get().operationsByContext[contextKey] || [];
+ const operationIds = this.#get().operationsByContext[contextKey] || [];
// Clear error message from all sendMessage operations in current context
operationIds.forEach((opId) => {
- const op = get().operations[opId];
+ const op = this.#get().operations[opId];
if (op && op.type === 'sendMessage' && op.metadata.inputSendErrorMsg) {
- get().updateOperationMetadata(opId, { inputSendErrorMsg: undefined });
+ this.#get().updateOperationMetadata(opId, { inputSendErrorMsg: undefined });
}
});
- },
+ };
- switchMessageBranch: async (messageId, branchIndex, context) => {
- await get().optimisticUpdateMessageMetadata(
+ switchMessageBranch = async (
+ messageId: string,
+ branchIndex: number,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ await this.#get().optimisticUpdateMessageMetadata(
messageId,
{ activeBranchIndex: branchIndex },
context,
);
- },
- approveToolCalling: async (toolMessageId, _assistantGroupId, context) => {
- const { internal_execAgentRuntime, startOperation, completeOperation } = get();
+ };
+
+ approveToolCalling = async (
+ toolMessageId: string,
+ _assistantGroupId: string,
+ context?: ConversationContext,
+ ): Promise<void> => {
+ const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();
// Build effective context from provided context or global state
const effectiveContext: ConversationContext = context ?? {
- agentId: get().activeAgentId,
- topicId: get().activeTopicId,
- threadId: get().activeThreadId,
+ agentId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
+ threadId: this.#get().activeThreadId,
};
const { agentId, topicId, threadId, scope } = effectiveContext;
// 1. Get tool message and verify it exists
- const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(get());
+ const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());
if (!toolMessage) return;
// Create an operation to carry the context for optimistic updates
@@ -178,7 +137,7 @@ export const conversationControl: StateCreator<
const optimisticContext = { operationId };
// 2. Update intervention status to approved
- await get().optimisticUpdatePlugin(
+ await this.#get().optimisticUpdatePlugin(
toolMessageId,
{ intervention: { status: 'approved' } },
optimisticContext,
@@ -186,10 +145,10 @@ export const conversationControl: StateCreator<
// 3. Get current messages for state construction using context
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get());
+ const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
// 4. Create agent state and context with user intervention config
- const { state, context: initialContext } = get().internal_createAgentState({
+ const { state, context: initialContext } = this.#get().internal_createAgentState({
messages: currentMessages,
parentMessageId: toolMessageId,
agentId,
@@ -226,26 +185,30 @@ export const conversationControl: StateCreator<
} catch (error) {
const err = error as Error;
console.error('[approveToolCalling] Error executing agent runtime:', err);
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
type: 'approveToolCalling',
message: err.message || 'Unknown error',
});
}
- },
+ };
- rejectToolCalling: async (messageId, reason, context) => {
- const { startOperation, completeOperation } = get();
+ rejectToolCalling = async (
+ messageId: string,
+ reason?: string,
+ context?: ConversationContext,
+ ): Promise<void> => {
+ const { startOperation, completeOperation } = this.#get();
// Build effective context from provided context or global state
const effectiveContext: ConversationContext = context ?? {
- agentId: get().activeAgentId,
- topicId: get().activeTopicId,
- threadId: get().activeThreadId,
+ agentId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
+ threadId: this.#get().activeThreadId,
};
const { agentId, topicId, threadId, scope } = effectiveContext;
- const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(get());
+ const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(this.#get());
if (!toolMessage) return;
// Create an operation to carry the context for optimistic updates
@@ -267,13 +230,13 @@ export const conversationControl: StateCreator<
rejectedReason: reason,
status: 'rejected',
} as const;
- await get().optimisticUpdatePlugin(toolMessage.id, { intervention }, optimisticContext);
+ await this.#get().optimisticUpdatePlugin(toolMessage.id, { intervention }, optimisticContext);
const toolContent = !!reason
? `User reject this tool calling with reason: ${reason}`
: 'User reject this tool calling without reason';
- await get().optimisticUpdateMessageContent(
+ await this.#get().optimisticUpdateMessageContent(
messageId,
toolContent,
undefined,
@@ -281,22 +244,26 @@ export const conversationControl: StateCreator<
);
completeOperation(operationId);
- },
+ };
- rejectAndContinueToolCalling: async (messageId, reason, context) => {
+ rejectAndContinueToolCalling = async (
+ messageId: string,
+ reason?: string,
+ context?: ConversationContext,
+ ): Promise<void> => {
// Pass context to rejectToolCalling for proper context isolation
- await get().rejectToolCalling(messageId, reason, context);
+ await this.#get().rejectToolCalling(messageId, reason, context);
- const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(get());
+ const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(this.#get());
if (!toolMessage) return;
- const { internal_execAgentRuntime, startOperation, completeOperation } = get();
+ const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();
// Build effective context from provided context or global state
const effectiveContext: ConversationContext = context ?? {
- agentId: get().activeAgentId,
- topicId: get().activeTopicId,
- threadId: get().activeThreadId,
+ agentId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
+ threadId: this.#get().activeThreadId,
};
const { agentId, topicId, threadId, scope } = effectiveContext;
@@ -315,10 +282,10 @@ export const conversationControl: StateCreator<
// Get current messages for state construction using context
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
- const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get());
+ const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());
// Create agent state and context to continue from rejected tool message
- const { state, context: initialContext } = get().internal_createAgentState({
+ const { state, context: initialContext } = this.#get().internal_createAgentState({
messages: currentMessages,
parentMessageId: messageId,
agentId,
@@ -349,10 +316,15 @@ export const conversationControl: StateCreator<
} catch (error) {
const err = error as Error;
console.error('[rejectAndContinueToolCalling] Error executing agent runtime:', err);
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
type: 'rejectToolCalling',
message: err.message || 'Unknown error',
});
}
- },
-});
+ };
+}
+
+export type ConversationControlAction = Pick<
+ ConversationControlActionImpl,
+ keyof ConversationControlActionImpl
+>;
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index aa93ed11a0e..b3597950ee1 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -12,7 +12,6 @@ import {
import { nanoid } from '@lobechat/utils';
import { TRPCClientError } from '@trpc/client';
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { markUserValidAction } from '@/business/client/markUserValidAction';
import { aiChatService } from '@/services/aiChat';
@@ -23,6 +22,7 @@ import { type ChatStore } from '@/store/chat/store';
import { getFileStoreState } from '@/store/file/store';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { type StoreSetter } from '@/store/types';
import { useUserMemoryStore } from '@/store/userMemory';
import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../../../selectors';
@@ -55,26 +55,22 @@ export interface SendMessageResult {
* Actions managing the complete lifecycle of conversations including sending,
* regenerating, and resending messages
*/
-export interface ConversationLifecycleAction {
- /**
- * Sends a new message to the AI chat system
- * @param params - Message params with required context
- * @returns Result containing message IDs and created thread ID if applicable
- */
- sendMessage: (params: SendMessageWithContextParams) => Promise<SendMessageResult | undefined>;
- /**
- * Continue generating from current assistant message
- */
- continueGenerationMessage: (lastBlockId: string, messageId: string) => Promise<void>;
-}
-export const conversationLifecycle: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ConversationLifecycleAction
-> = (set, get) => ({
- sendMessage: async ({
+type Setter = StoreSetter<ChatStore>;
+export const conversationLifecycle = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ConversationLifecycleActionImpl(set, get, _api);
+
+export class ConversationLifecycleActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ sendMessage = async ({
message,
files,
onlyAddUserMessage,
@@ -82,8 +78,8 @@ export const conversationLifecycle: StateCreator<
messages: inputMessages,
parentId: inputParentId,
pageSelections,
- }) => {
- const { internal_execAgentRuntime, mainInputEditor } = get();
+ }: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {
+ const { internal_execAgentRuntime, mainInputEditor } = this.#get();
// Use context from params (required)
const { agentId } = context;
@@ -119,7 +115,7 @@ export const conversationLifecycle: StateCreator<
if (!message && !hasFile) return;
if (onlyAddUserMessage) {
- await get().addUserMessage({ message, fileList: fileIdList });
+ await this.#get().addUserMessage({ message, fileList: fileIdList });
return;
}
@@ -127,12 +123,12 @@ export const conversationLifecycle: StateCreator<
// Use provided messages or query from store
const contextKey = messageMapKey(context);
const messages =
- inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(get());
+ inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get());
const lastMessage = messages.at(-1);
useUserMemoryStore.getState().setActiveMemoryContext({
agent: agentSelectors.getAgentMetaById(agentId)(getAgentStoreState()),
- topic: topicSelectors.currentActiveTopic(get()),
+ topic: topicSelectors.currentActiveTopic(this.#get()),
latestUserMessage: lastMessage?.content,
sendingMessage: message,
});
@@ -140,13 +136,13 @@ export const conversationLifecycle: StateCreator<
// Use provided parentId or calculate from messages
let parentId: string | undefined = inputParentId;
if (!parentId && lastMessage) {
- parentId = displayMessageSelectors.findLastMessageId(lastMessage.id)(get());
+ parentId = displayMessageSelectors.findLastMessageId(lastMessage.id)(this.#get());
}
// Create operation for send message first, so we can use operationId for optimistic updates
const tempId = 'tmp_' + nanoid();
const tempAssistantId = 'tmp_' + nanoid();
- const { operationId, abortController } = get().startOperation({
+ const { operationId, abortController } = this.#get().startOperation({
type: 'sendMessage',
context: { ...operationContext, messageId: tempId },
label: 'Send Message',
@@ -174,7 +170,7 @@ export const conversationLifecycle: StateCreator<
}));
// use optimistic update to avoid the slow waiting (now with operationId for correct context)
- get().optimisticCreateTmpMessage(
+ this.#get().optimisticCreateTmpMessage(
{
content: message,
// if message has attached with files, then add files to message and the agent
@@ -191,7 +187,7 @@ export const conversationLifecycle: StateCreator<
},
{ operationId, tempMessageId: tempId },
);
- get().optimisticCreateTmpMessage(
+ this.#get().optimisticCreateTmpMessage(
{
content: LOADING_FLAT,
role: 'assistant',
@@ -204,15 +200,15 @@ export const conversationLifecycle: StateCreator<
},
{ operationId, tempMessageId: tempAssistantId },
);
- get().internal_toggleMessageLoading(true, tempId);
+ this.#get().internal_toggleMessageLoading(true, tempId);
// Associate temp messages with operation
- get().associateMessageWithOperation(tempId, operationId);
- get().associateMessageWithOperation(tempAssistantId, operationId);
+ this.#get().associateMessageWithOperation(tempId, operationId);
+ this.#get().associateMessageWithOperation(tempAssistantId, operationId);
// Store editor state in operation metadata for cancel restoration
const jsonState = mainInputEditor?.getJSONState();
- get().updateOperationMetadata(operationId, {
+ this.#get().updateOperationMetadata(operationId, {
inputEditorTempState: jsonState,
inputSendErrorMsg: undefined,
});
@@ -260,7 +256,7 @@ export const conversationLifecycle: StateCreator<
// refresh the total data
if (data?.topics) {
const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());
- get().internal_updateTopics(operationContext.agentId, {
+ this.#get().internal_updateTopics(operationContext.agentId, {
groupId: operationContext.groupId,
items: data.topics.items,
pageSize,
@@ -269,36 +265,39 @@ export const conversationLifecycle: StateCreator<
finalTopicId = data.topicId;
// Record the created topicId in metadata (not context)
- get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });
+ this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });
}
// Record created threadId in operation metadata
if (data.createdThreadId) {
- get().updateOperationMetadata(operationId, { createdThreadId: data.createdThreadId });
+ this.#get().updateOperationMetadata(operationId, { createdThreadId: data.createdThreadId });
// Update portalThreadId to switch from "new thread" mode to "existing thread" mode
// This ensures the Portal Thread UI displays correctly with the real thread ID
- get().openThreadInPortal(data.createdThreadId, context.sourceMessageId);
+ this.#get().openThreadInPortal(data.createdThreadId, context.sourceMessageId);
// Refresh threads list to update the sidebar
- get().refreshThreads();
+ this.#get().refreshThreads();
}
// Create final context with updated topicId/threadId from server response
const finalContext = { ...operationContext, topicId: finalTopicId, threadId: finalThreadId };
- get().replaceMessages(data.messages, {
+ this.#get().replaceMessages(data.messages, {
context: finalContext,
action: 'sendMessage/serverResponse',
});
if (data.isCreateNewTopic && data.topicId) {
// clearNewKey: true ensures the _new key data is cleared after topic creation
- await get().switchTopic(data.topicId, { clearNewKey: true, skipRefreshMessage: true });
+ await this.#get().switchTopic(data.topicId, {
+ clearNewKey: true,
+ skipRefreshMessage: true,
+ });
}
} catch (e) {
console.error(e);
// Fail operation on error
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
type: e instanceof Error ? e.name : 'unknown_error',
message: e instanceof Error ? e.message : 'Unknown error',
});
@@ -307,25 +306,25 @@ export const conversationLifecycle: StateCreator<
const isAbort = e.message.includes('aborted') || e.name === 'AbortError';
// Check if error is due to cancellation
if (!isAbort) {
- get().updateOperationMetadata(operationId, { inputSendErrorMsg: e.message });
- get().mainInputEditor?.setDocument('markdown', message);
+ this.#get().updateOperationMetadata(operationId, { inputSendErrorMsg: e.message });
+ this.#get().mainInputEditor?.setDocument('markdown', message);
}
}
} finally {
// 创建了新topic 或者 用户 cancel 了消息(或者失败了),此时无 data
if (data?.isCreateNewTopic || !data) {
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{ type: 'deleteMessages', ids: [tempId, tempAssistantId] },
{ operationId },
);
}
}
- get().internal_toggleMessageLoading(false, tempId);
+ this.#get().internal_toggleMessageLoading(false, tempId);
// Clear editor temp state after message created
if (data) {
- get().updateOperationMetadata(operationId, { inputEditorTempState: null });
+ this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });
}
if (ENABLE_BUSINESS_FEATURES) {
@@ -334,25 +333,25 @@ export const conversationLifecycle: StateCreator<
if (!data) return;
- if (data.topicId) get().internal_updateTopicLoading(data.topicId, true);
+ if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, true);
const summaryTitle = async () => {
// check activeTopic and then auto update topic title
if (data.isCreateNewTopic) {
- await get().summaryTopicTitle(data.topicId, data.messages);
+ await this.#get().summaryTopicTitle(data.topicId, data.messages);
return;
}
if (!data.topicId) return;
- const topic = topicSelectors.getTopicById(data.topicId)(get());
+ const topic = topicSelectors.getTopicById(data.topicId)(this.#get());
if (topic && !topic.title) {
const chats = displayMessageSelectors
- .getDisplayMessagesByKey(messageMapKey({ agentId, topicId: topic.id }))(get())
+ .getDisplayMessagesByKey(messageMapKey({ agentId, topicId: topic.id }))(this.#get())
.filter((item) => item.id !== data.assistantMessageId);
- await get().summaryTopicTitle(topic.id, chats);
+ await this.#get().summaryTopicTitle(topic.id, chats);
}
};
@@ -360,7 +359,7 @@ export const conversationLifecycle: StateCreator<
// Complete sendMessage operation here - message creation is done
// execAgentRuntime is a separate operation (child) that handles AI response generation
- get().completeOperation(operationId);
+ this.#get().completeOperation(operationId);
// Create final context for AI execution (with updated topicId/threadId from server)
const execContext = {
@@ -372,7 +371,7 @@ export const conversationLifecycle: StateCreator<
// Get the current messages to generate AI response
const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(
messageMapKey(execContext),
- )(get());
+ )(this.#get());
try {
await internal_execAgentRuntime({
@@ -387,7 +386,7 @@ export const conversationLifecycle: StateCreator<
});
const userFiles = dbMessageSelectors
- .dbUserFiles(get())
+ .dbUserFiles(this.#get())
.map((f) => f?.id)
.filter(Boolean) as string[];
@@ -397,7 +396,7 @@ export const conversationLifecycle: StateCreator<
} catch (e) {
console.error(e);
} finally {
- if (data.topicId) get().internal_updateTopicLoading(data.topicId, false);
+ if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, false);
}
// Return result for callers who need message IDs
@@ -406,13 +405,13 @@ export const conversationLifecycle: StateCreator<
createdThreadId: data.createdThreadId,
userMessageId: data.userMessageId,
};
- },
+ };
- continueGenerationMessage: async (id, messageId) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ continueGenerationMessage = async (id: string, messageId: string): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
- const { activeAgentId, activeTopicId, activeThreadId, activeGroupId } = get();
+ const { activeAgentId, activeTopicId, activeThreadId, activeGroupId } = this.#get();
// Create base context for continue operation (using global state)
const continueContext = {
@@ -423,15 +422,15 @@ export const conversationLifecycle: StateCreator<
};
// Create continue operation
- const { operationId } = get().startOperation({
+ const { operationId } = this.#get().startOperation({
type: 'continue',
context: { ...continueContext, messageId },
});
try {
- const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(get());
+ const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(this.#get());
- await get().internal_execAgentRuntime({
+ await this.#get().internal_execAgentRuntime({
context: continueContext,
messages: chats,
parentMessageId: id,
@@ -439,13 +438,18 @@ export const conversationLifecycle: StateCreator<
parentOperationId: operationId,
});
- get().completeOperation(operationId);
+ this.#get().completeOperation(operationId);
} catch (error) {
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
type: 'ContinueError',
message: error instanceof Error ? error.message : String(error),
});
throw error;
}
- },
-});
+ };
+}
+
+export type ConversationLifecycleAction = Pick<
+ ConversationLifecycleActionImpl,
+ keyof ConversationLifecycleActionImpl
+>;
diff --git a/src/store/chat/slices/aiChat/actions/index.ts b/src/store/chat/slices/aiChat/actions/index.ts
index 7bd013c4023..f80e6f29a0e 100644
--- a/src/store/chat/slices/aiChat/actions/index.ts
+++ b/src/store/chat/slices/aiChat/actions/index.ts
@@ -1,30 +1,40 @@
import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { flattenActions } from '@/store/utils/flattenActions';
-import { type ConversationControlAction, conversationControl } from './conversationControl';
-import { type ConversationLifecycleAction, conversationLifecycle } from './conversationLifecycle';
-import { type ChatMemoryAction, chatMemory } from './memory';
-import { type StreamingExecutorAction, streamingExecutor } from './streamingExecutor';
-import { type StreamingStatesAction, streamingStates } from './streamingStates';
+import {
+ type ConversationControlAction,
+ ConversationControlActionImpl,
+} from './conversationControl';
+import {
+ type ConversationLifecycleAction,
+ ConversationLifecycleActionImpl,
+} from './conversationLifecycle';
+import { type ChatMemoryAction, ChatMemoryActionImpl } from './memory';
+import { type StreamingExecutorAction, StreamingExecutorActionImpl } from './streamingExecutor';
+import { type StreamingStatesAction, StreamingStatesActionImpl } from './streamingStates';
-export interface ChatAIChatAction
- extends
- ChatMemoryAction,
- ConversationLifecycleAction,
- ConversationControlAction,
- StreamingExecutorAction,
- StreamingStatesAction {}
+export type ChatAIChatAction = ChatMemoryAction &
+ ConversationLifecycleAction &
+ ConversationControlAction &
+ StreamingExecutorAction &
+ StreamingStatesAction;
export const chatAiChat: StateCreator<
ChatStore,
[['zustand/devtools', never]],
[],
ChatAIChatAction
-> = (...params) => ({
- ...chatMemory(...params),
- ...conversationLifecycle(...params),
- ...conversationControl(...params),
- ...streamingExecutor(...params),
- ...streamingStates(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatAIChatAction>
+ >
+) =>
+ flattenActions<ChatAIChatAction>([
+ new ChatMemoryActionImpl(...params),
+ new ConversationLifecycleActionImpl(...params),
+ new ConversationControlActionImpl(...params),
+ new StreamingExecutorActionImpl(...params),
+ new StreamingStatesActionImpl(...params),
+ ]);
diff --git a/src/store/chat/slices/aiChat/actions/memory.ts b/src/store/chat/slices/aiChat/actions/memory.ts
index b909b548552..5f63ee4791b 100644
--- a/src/store/chat/slices/aiChat/actions/memory.ts
+++ b/src/store/chat/slices/aiChat/actions/memory.ts
@@ -1,25 +1,29 @@
import { chainSummaryHistory } from '@lobechat/prompts';
import { TraceNameMap, type UIChatMessage } from '@lobechat/types';
-import { type StateCreator } from 'zustand/vanilla';
import { chatService } from '@/services/chat';
import { topicService } from '@/services/topic';
import { type ChatStore } from '@/store/chat';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors } from '@/store/user/selectors';
-export interface ChatMemoryAction {
- internal_summaryHistory: (messages: UIChatMessage[]) => Promise<void>;
-}
+type Setter = StoreSetter<ChatStore>;
+export const chatMemory = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatMemoryActionImpl(set, get, _api);
+
+export class ChatMemoryActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const chatMemory: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatMemoryAction
-> = (set, get) => ({
- internal_summaryHistory: async (messages) => {
- const topicId = get().activeTopicId;
+ internal_summaryHistory = async (messages: UIChatMessage[]): Promise<void> => {
+ const topicId = this.#get().activeTopicId;
if (messages.length <= 1 || !topicId) return;
const { model, provider } = systemAgentSelectors.historyCompress(useUserStore.getState());
@@ -31,8 +35,8 @@ export const chatMemory: StateCreator<
},
params: { ...chainSummaryHistory(messages), model, provider, stream: false },
trace: {
- sessionId: get().activeAgentId,
- topicId: get().activeTopicId,
+ sessionId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
traceName: TraceNameMap.SummaryHistoryMessages,
},
});
@@ -41,7 +45,9 @@ export const chatMemory: StateCreator<
historySummary,
metadata: { model, provider },
});
- await get().refreshTopic();
- await get().refreshMessages();
- },
-});
+ await this.#get().refreshTopic();
+ await this.#get().refreshMessages();
+ };
+}
+
+export type ChatMemoryAction = Pick<ChatMemoryActionImpl, keyof ChatMemoryActionImpl>;
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 4b48294c4ee..4d8ee4e41b8 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -24,7 +24,6 @@ import {
} from '@lobechat/types';
import debug from 'debug';
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
import { chatService } from '@/services/chat';
@@ -34,6 +33,7 @@ import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
import { type ChatStore } from '@/store/chat/store';
import { getFileStoreState } from '@/store/file/store';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { type StoreSetter } from '@/store/types';
import { toolInterventionSelectors } from '@/store/user/selectors';
import { getUserStoreState } from '@/store/user/store';
@@ -48,136 +48,53 @@ const log = debug('lobe-store:streaming-executor');
/**
* Core streaming execution actions for AI chat
*/
-export interface StreamingExecutorAction {
- /**
- * Creates initial agent state and context with user intervention config
- */
- internal_createAgentState: (params: {
+
+type Setter = StoreSetter<ChatStore>;
+export const streamingExecutor = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new StreamingExecutorActionImpl(set, get, _api);
+
+export class StreamingExecutorActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_createAgentState = ({
+ messages,
+ parentMessageId,
+ agentId: paramAgentId,
+ disableTools,
+ topicId: paramTopicId,
+ threadId,
+ initialState,
+ initialContext,
+ operationId,
+ subAgentId: paramSubAgentId,
+ isSubTask,
+ }: {
messages: UIChatMessage[];
parentMessageId: string;
- /**
- * Explicit agentId for this execution (avoids using global activeAgentId)
- */
agentId?: string;
- /**
- * Whether to disable tools for this agent execution
- * When true, agent will respond without calling any tools
- */
disableTools?: boolean;
- /**
- * Explicit topicId for this execution (avoids using global activeTopicId)
- */
topicId?: string | null;
threadId?: string;
operationId?: string;
initialState?: AgentState;
initialContext?: AgentRuntimeContext;
- /**
- * Sub Agent ID for group orchestration scenarios
- * Used to get Agent config (model, provider, plugins) instead of agentId
- */
subAgentId?: string;
- /**
- * Whether this is a sub-task execution (disables lobe-gtd tools to prevent nested sub-tasks)
- */
isSubTask?: boolean;
- }) => {
+ }): {
state: AgentState;
context: AgentRuntimeContext;
- /** Resolved agent config with isSubTask filtering applied */
agentConfig: ResolvedAgentConfig;
- };
- /**
- * Retrieves an AI-generated chat message from the backend service with streaming
- */
- internal_fetchAIChatMessage: (params: {
- messageId: string;
- messages: UIChatMessage[];
- model: string;
- provider: string;
- operationId?: string;
- /** Pre-resolved agent config (from internal_createAgentState) with isSubTask filtering applied */
- agentConfig: ResolvedAgentConfig;
- traceId?: string;
- /** Initial context for page editor (captured at operation start) */
- initialContext?: RuntimeInitialContext;
- /** Step context for page editor (updated each step) */
- stepContext?: RuntimeStepContext;
- }) => Promise<{
- isFunctionCall: boolean;
- tools?: ChatToolPayload[];
- tool_calls?: MessageToolCall[];
- content: string;
- traceId?: string;
- finishType?: string;
- usage?: ModelUsage;
- }>;
- /**
- * Executes the core processing logic for AI messages
- * including preprocessing and postprocessing steps
- */
- internal_execAgentRuntime: (params: {
- /**
- * Full conversation context (required)
- * Contains agentId, topicId, threadId, groupId, scope, etc.
- */
- context: ConversationContext;
- /**
- * Whether to disable tools for this agent execution
- * When true, agent will respond without calling any tools
- */
- disableTools?: boolean;
- /**
- * Initial agent runtime context (for resuming execution from a specific phase)
- */
- initialContext?: AgentRuntimeContext;
- /**
- * Initial agent state (for resuming execution from a specific point)
- */
- initialState?: AgentState;
- inPortalThread?: boolean;
- inSearchWorkflow?: boolean;
- messages: UIChatMessage[];
- /**
- * Operation ID for this execution (automatically created if not provided)
- */
- operationId?: string;
- parentMessageId: string;
- parentMessageType: 'user' | 'assistant' | 'tool';
- /**
- * Parent operation ID (creates a child operation if provided)
- */
- parentOperationId?: string;
- skipCreateFirstMessage?: boolean;
- /**
- * Whether this is a sub-task execution (disables lobe-gtd tools to prevent nested sub-tasks)
- */
- isSubTask?: boolean;
- }) => Promise<{ cost?: Cost; usage?: Usage } | void>;
-}
-
-export const streamingExecutor: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- StreamingExecutorAction
-> = (set, get) => ({
- internal_createAgentState: ({
- messages,
- parentMessageId,
- agentId: paramAgentId,
- disableTools,
- topicId: paramTopicId,
- threadId,
- initialState,
- initialContext,
- operationId,
- subAgentId: paramSubAgentId,
- isSubTask,
- }) => {
+ } => {
// Use provided agentId/topicId or fallback to global state
// Note: Use || instead of ?? to also fallback when paramAgentId is empty string
- const { activeAgentId, activeTopicId } = get();
+ const { activeAgentId, activeTopicId } = this.#get();
const agentId = paramAgentId || activeAgentId;
const topicId = paramTopicId !== undefined ? paramTopicId : activeTopicId;
@@ -187,7 +104,7 @@ export const streamingExecutor: StateCreator<
const effectiveAgentId = paramSubAgentId || agentId;
// Get scope and groupId from operation context if available
- const operation = operationId ? get().operations[operationId] : undefined;
+ const operation = operationId ? this.#get().operations[operationId] : undefined;
const scope = operation?.context.scope;
const groupId = operation?.context.groupId;
@@ -328,9 +245,9 @@ export const streamingExecutor: StateCreator<
};
return { agentConfig: agentConfigWithTools, context, state };
- },
+ };
- internal_fetchAIChatMessage: async ({
+ internal_fetchAIChatMessage = async ({
messageId,
messages,
model,
@@ -340,12 +257,30 @@ export const streamingExecutor: StateCreator<
traceId: traceIdParam,
initialContext,
stepContext,
- }) => {
+ }: {
+ messageId: string;
+ messages: UIChatMessage[];
+ model: string;
+ provider: string;
+ operationId?: string;
+ traceId?: string;
+ agentConfig: ResolvedAgentConfig;
+ initialContext?: RuntimeInitialContext;
+ stepContext?: RuntimeStepContext;
+ }): Promise<{
+ isFunctionCall: boolean;
+ tools?: ChatToolPayload[];
+ tool_calls?: MessageToolCall[];
+ content: string;
+ traceId?: string;
+ finishType?: string;
+ usage?: ModelUsage;
+ }> => {
const {
optimisticUpdateMessageContent,
internal_dispatchMessage,
internal_toggleToolCallingStreaming,
- } = get();
+ } = this.#get();
// Get agentId, topicId, groupId and abortController from operation
let agentId: string;
@@ -358,7 +293,7 @@ export const streamingExecutor: StateCreator<
let abortController: AbortController;
if (operationId) {
- const operation = get().operations[operationId];
+ const operation = this.#get().operations[operationId];
if (!operation) {
log('[internal_fetchAIChatMessage] ERROR: Operation not found: %s', operationId);
throw new Error(`Operation not found: ${operationId}`);
@@ -393,9 +328,9 @@ export const streamingExecutor: StateCreator<
}
} else {
// Fallback to global state (for legacy code paths without operation)
- agentId = get().activeAgentId;
- topicId = get().activeTopicId;
- groupId = get().activeGroupId;
+ agentId = this.#get().activeAgentId;
+ topicId = this.#get().activeTopicId;
+ groupId = this.#get().activeGroupId;
abortController = new AbortController();
log(
'[internal_fetchAIChatMessage] use global context: agentId=%s, topicId=%s, groupId=%s',
@@ -480,15 +415,15 @@ export const streamingExecutor: StateCreator<
);
},
onReasoningStart: () => {
- const { operationId: reasoningOpId } = get().startOperation({
+ const { operationId: reasoningOpId } = this.#get().startOperation({
type: 'reasoning',
context: { ...fetchContext, messageId },
parentOperationId: operationId,
});
- get().associateMessageWithOperation(messageId, reasoningOpId);
+ this.#get().associateMessageWithOperation(messageId, reasoningOpId);
return reasoningOpId;
},
- onReasoningComplete: (opId) => get().completeOperation(opId),
+ onReasoningComplete: (opId) => this.#get().completeOperation(opId),
uploadBase64Image: (data) =>
getFileStoreState()
.uploadBase64FileWithProgress(data)
@@ -497,13 +432,13 @@ export const streamingExecutor: StateCreator<
url: file?.url,
alt: file?.filename || file?.id,
})),
- transformToolCalls: get().internal_transformToolCalls,
+ transformToolCalls: this.#get().internal_transformToolCalls,
toggleToolCallingStreaming: internal_toggleToolCallingStreaming,
},
);
const historySummary = chatConfig.enableCompressHistory
- ? topicSelectors.currentActiveTopicSummary(get())
+ ? topicSelectors.currentActiveTopicSummary(this.#get())
: undefined;
await chatService.createAssistantMessageStream({
abortController,
@@ -536,7 +471,7 @@ export const streamingExecutor: StateCreator<
error.message,
operationId,
);
- await get().optimisticUpdateMessageError(messageId, error, { operationId });
+ await this.#get().optimisticUpdateMessageError(messageId, error, { operationId });
},
onFinish: async (
content,
@@ -611,9 +546,23 @@ export const streamingExecutor: StateCreator<
tool_calls: finalToolCalls,
finishType: handler.getFinishType(),
};
- },
+ };
- internal_execAgentRuntime: async (params) => {
+ internal_execAgentRuntime = async (params: {
+ context: ConversationContext;
+ disableTools?: boolean;
+ initialContext?: AgentRuntimeContext;
+ initialState?: AgentState;
+ inPortalThread?: boolean;
+ inSearchWorkflow?: boolean;
+ messages: UIChatMessage[];
+ operationId?: string;
+ parentMessageId: string;
+ parentMessageType: 'user' | 'assistant' | 'tool';
+ parentOperationId?: string;
+ skipCreateFirstMessage?: boolean;
+ isSubTask?: boolean;
+ }): Promise<{ cost?: Cost; usage?: Usage } | void> => {
const {
disableTools,
messages: originalMessages,
@@ -637,7 +586,7 @@ export const streamingExecutor: StateCreator<
// Create or use provided operation
let operationId = params.operationId;
if (!operationId) {
- const { operationId: newOperationId } = get().startOperation({
+ const { operationId: newOperationId } = this.#get().startOperation({
type: 'execAgentRuntime',
context: { ...context, messageId: parentMessageId },
parentOperationId: params.parentOperationId, // Pass parent operation ID
@@ -651,7 +600,7 @@ export const streamingExecutor: StateCreator<
operationId = newOperationId;
// Associate message with operation
- get().associateMessageWithOperation(parentMessageId, operationId);
+ this.#get().associateMessageWithOperation(parentMessageId, operationId);
}
log(
@@ -679,7 +628,7 @@ export const streamingExecutor: StateCreator<
state: initialAgentState,
context: initialAgentContext,
agentConfig,
- } = get().internal_createAgentState({
+ } = this.#get().internal_createAgentState({
messages,
parentMessageId: params.parentMessageId,
agentId,
@@ -721,14 +670,14 @@ export const streamingExecutor: StateCreator<
const runtime = new AgentRuntime(agent, {
executors: createAgentExecutors({
agentConfig, // Pass pre-resolved config to callLLM executor
- get,
+ get: this.#get,
messageKey,
operationId,
parentId: params.parentMessageId,
skipCreateFirstMessage: params.skipCreateFirstMessage,
}),
getOperation: (opId: string) => {
- const op = get().operations[opId];
+ const op = this.#get().operations[opId];
if (!op) throw new Error(`Operation not found: ${opId}`);
return {
abortController: op.abortController,
@@ -750,7 +699,7 @@ export const streamingExecutor: StateCreator<
let stepCount = 0;
while (state.status !== 'done' && state.status !== 'error') {
// Check if operation has been cancelled
- const currentOperation = get().operations[operationId];
+ const currentOperation = this.#get().operations[operationId];
if (currentOperation?.status === 'cancelled') {
log('[internal_execAgentRuntime] Operation cancelled, marking state as interrupted');
@@ -769,7 +718,7 @@ export const streamingExecutor: StateCreator<
// Compute step context from current db messages before each step
// Use dbMessagesMap which contains persisted state (including pluginState.todos)
- const currentDBMessages = get().dbMessagesMap[messageKey] || [];
+ const currentDBMessages = this.#get().dbMessagesMap[messageKey] || [];
// Use selectTodosFromMessages selector (shared with UI display)
const todos = selectTodosFromMessages(currentDBMessages);
const stepContext = computeStepContext({ todos });
@@ -821,7 +770,7 @@ export const streamingExecutor: StateCreator<
log(
`[internal_execAgentRuntime] ${result.nextContext?.phase} completed, refreshing messages to sync state`,
);
- await get().refreshMessages(context);
+ await this.#get().refreshMessages(context);
}
// Handle completion and error events
@@ -835,7 +784,7 @@ export const streamingExecutor: StateCreator<
case 'error': {
log('[internal_execAgentRuntime] Received error event: %o', event.error);
// Find the assistant message to update error
- const currentMessages = get().messagesMap[messageKey] || [];
+ const currentMessages = this.#get().messagesMap[messageKey] || [];
const assistantMessage = currentMessages.findLast((m) => m.role === 'assistant');
if (assistantMessage) {
await messageService.updateMessageError(assistantMessage.id, event.error, {
@@ -844,8 +793,8 @@ export const streamingExecutor: StateCreator<
topicId,
});
}
- const finalMessages = get().messagesMap[messageKey] || [];
- get().replaceMessages(finalMessages, { context });
+ const finalMessages = this.#get().messagesMap[messageKey] || [];
+ this.#get().replaceMessages(finalMessages, { context });
break;
}
}
@@ -854,7 +803,7 @@ export const streamingExecutor: StateCreator<
state = result.newState;
// Check if operation was cancelled after step completion
- const operationAfterStep = get().operations[operationId];
+ const operationAfterStep = this.#get().operations[operationId];
if (operationAfterStep?.status === 'cancelled') {
log(
'[internal_execAgentRuntime] Operation cancelled after step %d, marking state as interrupted',
@@ -895,7 +844,7 @@ export const streamingExecutor: StateCreator<
// Execute afterCompletion hooks before completing operation
// These are registered by tools (e.g., speak/broadcast/delegate) that need to
// trigger actions after the AgentRuntime finishes
- const operation = get().operations[operationId];
+ const operation = this.#get().operations[operationId];
const afterCompletionCallbacks = operation?.metadata?.runtimeHooks?.afterCompletionCallbacks;
if (afterCompletionCallbacks && afterCompletionCallbacks.length > 0) {
log(
@@ -917,12 +866,12 @@ export const streamingExecutor: StateCreator<
// Complete operation based on final state
switch (state.status) {
case 'done': {
- get().completeOperation(operationId);
+ this.#get().completeOperation(operationId);
log('[internal_execAgentRuntime] Operation completed successfully');
break;
}
case 'error': {
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
type: 'runtime_error',
message: 'Agent runtime execution failed',
});
@@ -932,7 +881,7 @@ export const streamingExecutor: StateCreator<
case 'waiting_for_human': {
// When waiting for human intervention, complete the current operation
// A new operation will be created when user approves/rejects
- get().completeOperation(operationId);
+ this.#get().completeOperation(operationId);
log('[internal_execAgentRuntime] Operation paused for human intervention');
break;
}
@@ -943,7 +892,7 @@ export const streamingExecutor: StateCreator<
// Desktop notification (if not in tools calling mode)
if (isDesktop) {
try {
- const finalMessages = get().messagesMap[messageKey] || [];
+ const finalMessages = this.#get().messagesMap[messageKey] || [];
const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');
// Only show notification if there's content and no tools
@@ -963,5 +912,10 @@ export const streamingExecutor: StateCreator<
// Return usage and cost data for caller to use
return { cost: state.cost, usage: state.usage };
- },
-});
+ };
+}
+
+export type StreamingExecutorAction = Pick<
+ StreamingExecutorActionImpl,
+ keyof StreamingExecutorActionImpl
+>;
diff --git a/src/store/chat/slices/aiChat/actions/streamingStates.ts b/src/store/chat/slices/aiChat/actions/streamingStates.ts
index 5d44db114ff..14cd117493c 100644
--- a/src/store/chat/slices/aiChat/actions/streamingStates.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingStates.ts
@@ -1,35 +1,33 @@
import isEqual from 'fast-deep-equal';
import { produce } from 'immer';
-import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
/**
* Manages loading states during streaming operations
*/
-export interface StreamingStatesAction {
- /**
- * Toggles the loading state for search workflow
- */
- internal_toggleSearchWorkflow: (loading: boolean, id?: string) => void;
- /**
- * Controls the streaming state of tool calling processes, updating the UI accordingly
- */
- internal_toggleToolCallingStreaming: (id: string, streaming: boolean[] | undefined) => void;
-}
-export const streamingStates: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- StreamingStatesAction
-> = (set, get) => ({
- internal_toggleSearchWorkflow: (loading, id) => {
- return get().internal_toggleLoadingArrays('searchWorkflowLoadingIds', loading, id);
- },
-
- internal_toggleToolCallingStreaming: (id, streaming) => {
- const previous = get().toolCallingStreamIds;
+type Setter = StoreSetter<ChatStore>;
+export const streamingStates = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new StreamingStatesActionImpl(set, get, _api);
+
+export class StreamingStatesActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_toggleSearchWorkflow = (loading: boolean, id?: string): void => {
+ this.#get().internal_toggleLoadingArrays('searchWorkflowLoadingIds', loading, id);
+ };
+
+ internal_toggleToolCallingStreaming = (id: string, streaming: boolean[] | undefined): void => {
+ const previous = this.#get().toolCallingStreamIds;
const next = produce(previous, (draft) => {
if (!!streaming) {
draft[id] = streaming;
@@ -40,11 +38,16 @@ export const streamingStates: StateCreator<
if (isEqual(previous, next)) return;
- set(
+ this.#set(
{ toolCallingStreamIds: next },
false,
`toggleToolCallingStreaming/${!!streaming ? 'start' : 'end'}`,
);
- },
-});
+ };
+}
+
+export type StreamingStatesAction = Pick<
+ StreamingStatesActionImpl,
+ keyof StreamingStatesActionImpl
+>;
diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.ts
index eac130c06ae..daa819c1003 100644
--- a/src/store/chat/slices/builtinTool/actions/index.ts
+++ b/src/store/chat/slices/builtinTool/actions/index.ts
@@ -1,18 +1,24 @@
import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { flattenActions } from '@/store/utils/flattenActions';
-import { type ChatCodeInterpreterAction, codeInterpreterSlice } from './interpreter';
-import { type SearchAction, searchSlice } from './search';
+import { type ChatCodeInterpreterAction, ChatCodeInterpreterActionImpl } from './interpreter';
+import { type SearchAction, SearchActionImpl } from './search';
-export interface ChatBuiltinToolAction extends SearchAction, ChatCodeInterpreterAction {}
+export type ChatBuiltinToolAction = SearchAction & ChatCodeInterpreterAction;
export const chatToolSlice: StateCreator<
ChatStore,
[['zustand/devtools', never]],
[],
ChatBuiltinToolAction
-> = (...params) => ({
- ...searchSlice(...params),
- ...codeInterpreterSlice(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatBuiltinToolAction>
+ >
+) =>
+ flattenActions<ChatBuiltinToolAction>([
+ new SearchActionImpl(...params),
+ new ChatCodeInterpreterActionImpl(...params),
+ ]);
diff --git a/src/store/chat/slices/builtinTool/actions/interpreter.ts b/src/store/chat/slices/builtinTool/actions/interpreter.ts
index e695661ee81..8d8ffcffebe 100644
--- a/src/store/chat/slices/builtinTool/actions/interpreter.ts
+++ b/src/store/chat/slices/builtinTool/actions/interpreter.ts
@@ -8,7 +8,6 @@ import debug from 'debug';
import { produce } from 'immer';
import pMap from 'p-map';
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWR } from '@/libs/swr';
import { fileService } from '@/services/file';
@@ -16,6 +15,7 @@ import { pythonService } from '@/services/python';
import { dbMessageSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
import { useFileStore } from '@/store/file';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('codeInterpreter');
@@ -23,29 +23,27 @@ const log = debug('lobe-store:builtin-tool');
const SWR_FETCH_INTERPRETER_FILE_KEY = 'FetchCodeInterpreterFileItem';
-export interface ChatCodeInterpreterAction {
- python: (id: string, params: CodeInterpreterParams) => Promise<boolean | undefined>;
- updateInterpreterFileItem: (
- id: string,
- updater: (data: CodeInterpreterResponse) => void,
- ) => Promise<void>;
- uploadInterpreterFiles: (id: string, files: CodeInterpreterFileItem[]) => Promise<void>;
- useFetchInterpreterFileItem: (id?: string) => SWRResponse;
-}
+type Setter = StoreSetter<ChatStore>;
+export const codeInterpreterSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatCodeInterpreterActionImpl(set, get, _api);
+
+export class ChatCodeInterpreterActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
-export const codeInterpreterSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatCodeInterpreterAction
-> = (set, get) => ({
- python: async (id: string, params: CodeInterpreterParams) => {
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ python = async (id: string, params: CodeInterpreterParams): Promise<boolean | undefined> => {
// Get parent operationId from messageOperationMap (should be executeToolCall)
- const parentOperationId = get().messageOperationMap[id];
+ const parentOperationId = this.#get().messageOperationMap[id];
// Create child operation for interpreter execution
// Auto-associates message with this operation via messageId in context
- const { operationId: interpreterOpId, abortController } = get().startOperation({
+ const { operationId: interpreterOpId, abortController } = this.#get().startOperation({
context: {
messageId: id,
},
@@ -69,7 +67,7 @@ export const codeInterpreterSlice: StateCreator<
try {
// TODO: 应该只下载 AI 用到的文件
const files: File[] = [];
- for (const message of dbMessageSelectors.dbUserMessages(get())) {
+ for (const message of dbMessageSelectors.dbUserMessages(this.#get())) {
for (const file of message.fileList ?? []) {
const blob = await fetch(file.url).then((res) => res.blob());
files.push(new File([blob], file.name));
@@ -80,7 +78,7 @@ export const codeInterpreterSlice: StateCreator<
}
for (const tool of message.tools ?? []) {
if (tool.identifier === CloudSandboxIdentifier) {
- const message = dbMessageSelectors.getDbMessageByToolCallId(tool.id)(get());
+ const message = dbMessageSelectors.getDbMessageByToolCallId(tool.id)(this.#get());
if (message?.content) {
const content = JSON.parse(message.content) as CodeInterpreterResponse;
for (const file of content.files ?? []) {
@@ -96,13 +94,23 @@ export const codeInterpreterSlice: StateCreator<
const result = await pythonService.runPython(params.code, params.packages, files);
// Complete interpreter operation
- get().completeOperation(interpreterOpId);
+ this.#get().completeOperation(interpreterOpId);
if (result?.files) {
- await get().optimisticUpdateMessageContent(id, JSON.stringify(result), undefined, context);
- await get().uploadInterpreterFiles(id, result.files);
+ await this.#get().optimisticUpdateMessageContent(
+ id,
+ JSON.stringify(result),
+ undefined,
+ context,
+ );
+ await this.#get().uploadInterpreterFiles(id, result.files);
} else {
- await get().optimisticUpdateMessageContent(id, JSON.stringify(result), undefined, context);
+ await this.#get().optimisticUpdateMessageContent(
+ id,
+ JSON.stringify(result),
+ undefined,
+ context,
+ );
}
return true;
@@ -115,7 +123,7 @@ export const codeInterpreterSlice: StateCreator<
if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {
log('[python] Request aborted: messageId=%s', id);
// Fail interpreter operation for abort
- get().failOperation(interpreterOpId, {
+ this.#get().failOperation(interpreterOpId, {
message: 'User cancelled the request',
type: 'UserAborted',
});
@@ -124,23 +132,23 @@ export const codeInterpreterSlice: StateCreator<
}
// Fail interpreter operation for other errors
- get().failOperation(interpreterOpId, {
+ this.#get().failOperation(interpreterOpId, {
message: err.message,
type: 'PluginServerError',
});
// For other errors, update message
- await get().optimisticUpdatePluginState(id, { error }, context);
+ await this.#get().optimisticUpdatePluginState(id, { error }, context);
// 如果调用过程中出现了错误,不要触发 AI 消息
return;
}
- },
+ };
- updateInterpreterFileItem: async (
+ updateInterpreterFileItem = async (
id: string,
updater: (data: CodeInterpreterResponse) => void,
- ) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ ): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
const result: CodeInterpreterResponse = JSON.parse(message.content);
@@ -148,11 +156,11 @@ export const codeInterpreterSlice: StateCreator<
const nextResult = produce(result, updater);
- await get().optimisticUpdateMessageContent(id, JSON.stringify(nextResult));
- },
+ await this.#get().optimisticUpdateMessageContent(id, JSON.stringify(nextResult));
+ };
- uploadInterpreterFiles: async (id: string, files: CodeInterpreterFileItem[]) => {
- const { updateInterpreterFileItem } = get();
+ uploadInterpreterFiles = async (id: string, files: CodeInterpreterFileItem[]): Promise<void> => {
+ const { updateInterpreterFileItem } = this.#get();
if (!files) return;
@@ -178,15 +186,15 @@ export const codeInterpreterSlice: StateCreator<
console.error('Failed to upload CodeInterpreter file:', error);
}
});
- },
+ };
- useFetchInterpreterFileItem: (id) =>
- useClientDataSWR(id ? [SWR_FETCH_INTERPRETER_FILE_KEY, id] : null, async () => {
+ useFetchInterpreterFileItem = (id?: string): SWRResponse => {
+ return useClientDataSWR(id ? [SWR_FETCH_INTERPRETER_FILE_KEY, id] : null, async () => {
if (!id) return null;
const item = await fileService.getFile(id);
- set(
+ this.#set(
produce((draft) => {
if (!draft.codeInterpreterFileMap) {
draft.codeInterpreterFileMap = {};
@@ -200,5 +208,11 @@ export const codeInterpreterSlice: StateCreator<
);
return item;
- }),
-});
+ });
+ };
+}
+
+export type ChatCodeInterpreterAction = Pick<
+ ChatCodeInterpreterActionImpl,
+ keyof ChatCodeInterpreterActionImpl
+>;
diff --git a/src/store/chat/slices/builtinTool/actions/search.ts b/src/store/chat/slices/builtinTool/actions/search.ts
index fdf0355ecef..79a444d209c 100644
--- a/src/store/chat/slices/builtinTool/actions/search.ts
+++ b/src/store/chat/slices/builtinTool/actions/search.ts
@@ -1,42 +1,41 @@
import { WebBrowsingApiName, WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { type ChatToolPayload, type CreateMessageParams, type SearchQuery } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
-import { type StateCreator } from 'zustand/vanilla';
import { dbMessageSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
-export interface SearchAction {
- saveSearchResult: (id: string) => Promise<void>;
- togglePageContent: (url: string) => void;
- triggerSearchAgain: (
- id: string,
- data: SearchQuery,
- options?: { aiSummary: boolean },
- ) => Promise<void>;
-}
+type Setter = StoreSetter<ChatStore>;
+export const searchSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new SearchActionImpl(set, get, _api);
+
+export class SearchActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const searchSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- SearchAction
-> = (set, get) => ({
- saveSearchResult: async (id) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ saveSearchResult = async (id: string): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message || !message.plugin) return;
- const { optimisticAddToolToAssistantMessage, optimisticCreateMessage, openToolUI } = get();
+ const { optimisticAddToolToAssistantMessage, optimisticCreateMessage, openToolUI } =
+ this.#get();
// Get operationId from messageOperationMap
- const operationId = get().messageOperationMap[id];
+ const operationId = this.#get().messageOperationMap[id];
const context = operationId ? { operationId } : undefined;
// 1. 创建一个新的 tool call message
const newToolCallId = `tool_call_${nanoid()}`;
const toolMessage: CreateMessageParams = {
- agentId: message.agentId ?? get().activeAgentId,
+ agentId: message.agentId ?? this.#get().activeAgentId,
content: message.content,
id: undefined,
parentId: message.parentId,
@@ -44,7 +43,7 @@ export const searchSlice: StateCreator<
pluginState: message.pluginState,
role: 'tool',
tool_call_id: newToolCallId,
- topicId: message.topicId !== undefined ? message.topicId : get().activeTopicId,
+ topicId: message.topicId !== undefined ? message.topicId : this.#get().activeTopicId,
};
const addToolItem = async () => {
@@ -70,22 +69,22 @@ export const searchSlice: StateCreator<
// 将新创建的 tool message 激活
openToolUI(result.id, message.plugin.identifier);
- },
+ };
- togglePageContent: (url) => {
- set({ activePageContentUrl: url });
- },
+ togglePageContent = (url: string): void => {
+ this.#set({ activePageContentUrl: url });
+ };
- triggerSearchAgain: async (id, data) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ triggerSearchAgain = async (id: string, data: SearchQuery): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
// Get operationId from messageOperationMap to ensure proper context isolation
- const operationId = get().messageOperationMap[id];
+ const operationId = this.#get().messageOperationMap[id];
const context = operationId ? { operationId } : undefined;
// 1. 更新插件参数
- await get().optimisticUpdatePluginArguments(id, data, false, context);
+ await this.#get().optimisticUpdatePluginArguments(id, data, false, context);
// 2. 通过 invokeBuiltinTool 调用 Tool Store Executor
const payload = {
@@ -97,6 +96,8 @@ export const searchSlice: StateCreator<
type: 'builtin',
} as ChatToolPayload;
- await get().invokeBuiltinTool(id, payload);
- },
-});
+ await this.#get().invokeBuiltinTool(id, payload);
+ };
+}
+
+export type SearchAction = Pick<SearchActionImpl, keyof SearchActionImpl>;
diff --git a/src/store/chat/slices/builtinTool/initialState.ts b/src/store/chat/slices/builtinTool/initialState.ts
index 268c10fd30d..7955b48a26b 100644
--- a/src/store/chat/slices/builtinTool/initialState.ts
+++ b/src/store/chat/slices/builtinTool/initialState.ts
@@ -2,9 +2,11 @@ import { type FileItem } from '@/types/files';
export interface ChatToolState {
activePageContentUrl?: string;
+ codeInterpreterFileMap: Record<string, FileItem>;
codeInterpreterImageMap: Record<string, FileItem>;
}
export const initialToolState: ChatToolState = {
+ codeInterpreterFileMap: {},
codeInterpreterImageMap: {},
};
diff --git a/src/store/chat/slices/message/actions/index.ts b/src/store/chat/slices/message/actions/index.ts
index 895d7b7da89..aed354e0ca1 100644
--- a/src/store/chat/slices/message/actions/index.ts
+++ b/src/store/chat/slices/message/actions/index.ts
@@ -1,39 +1,42 @@
import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { flattenActions } from '@/store/utils/flattenActions';
-import { type MessageInternalsAction, messageInternals } from './internals';
-import { type MessageOptimisticUpdateAction, messageOptimisticUpdate } from './optimisticUpdate';
-import { type MessagePublicApiAction, messagePublicApi } from './publicApi';
-import { type MessageQueryAction, messageQuery } from './query';
-import { type MessageRuntimeStateAction, messageRuntimeState } from './runtimeState';
+import { type MessageInternalsAction, MessageInternalsActionImpl } from './internals';
+import {
+ type MessageOptimisticUpdateAction,
+ MessageOptimisticUpdateActionImpl,
+} from './optimisticUpdate';
+import { type MessagePublicApiAction, MessagePublicApiActionImpl } from './publicApi';
+import { type MessageQueryAction, MessageQueryActionImpl } from './query';
+import { type MessageRuntimeStateAction, MessageRuntimeStateActionImpl } from './runtimeState';
+
+export type ChatMessageAction = MessagePublicApiAction &
+ MessageOptimisticUpdateAction &
+ MessageQueryAction &
+ MessageRuntimeStateAction &
+ MessageInternalsAction;
/**
* Combined message action interface
* Aggregates all message-related actions
*/
-export interface ChatMessageAction
- extends MessagePublicApiAction,
- MessageOptimisticUpdateAction,
- MessageQueryAction,
- MessageRuntimeStateAction,
- MessageInternalsAction {
- /**/
-}
-/**
- * Combined message action creator
- * Merges all message action modules
- */
export const chatMessage: StateCreator<
ChatStore,
[['zustand/devtools', never]],
[],
ChatMessageAction
-> = (...params) => ({
- ...messagePublicApi(...params),
- ...messageOptimisticUpdate(...params),
- ...messageQuery(...params),
- ...messageRuntimeState(...params),
- ...messageInternals(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatMessageAction>
+ >
+) =>
+ flattenActions<ChatMessageAction>([
+ new MessagePublicApiActionImpl(...params),
+ new MessageOptimisticUpdateActionImpl(...params),
+ new MessageQueryActionImpl(...params),
+ new MessageRuntimeStateActionImpl(...params),
+ new MessageInternalsActionImpl(...params),
+ ]);
diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.ts
index f0f6593e700..ad03f0febcf 100644
--- a/src/store/chat/slices/message/actions/internals.ts
+++ b/src/store/chat/slices/message/actions/internals.ts
@@ -2,10 +2,10 @@ import { parse } from '@lobechat/conversation-flow';
import { type TraceEventPayloads } from '@lobechat/types';
import debug from 'debug';
import isEqual from 'fast-deep-equal';
-import { type StateCreator } from 'zustand/vanilla';
import { traceService } from '@/services/trace';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { displayMessageSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
@@ -16,29 +16,27 @@ const log = debug('lobe-store:message-internals');
/**
* Internal core methods that serve as building blocks for other actions
*/
-export interface MessageInternalsAction {
- /**
- * update message at the frontend
- * this method will not update messages to database
- */
- internal_dispatchMessage: (payload: MessageDispatch, context?: { operationId?: string }) => void;
-
- /**
- * trace message events for analytics
- */
- internal_traceMessage: (id: string, payload: TraceEventPayloads) => Promise<void>;
-}
-export const messageInternals: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- MessageInternalsAction
-> = (set, get) => ({
- // the internal process method of the AI message
- internal_dispatchMessage: (payload, context) => {
+type Setter = StoreSetter<ChatStore>;
+export const messageInternals = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new MessageInternalsActionImpl(set, get, _api);
+
+export class MessageInternalsActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_dispatchMessage = (
+ payload: MessageDispatch,
+ context?: { operationId?: string },
+ ): void => {
// Get full conversation context (including scope) from operation or global state
- const ctx = get().internal_getConversationContext(context);
+ const ctx = this.#get().internal_getConversationContext(context);
log(
'[internal_dispatchMessage] context: agentId=%s, topicId=%s, threadId=%s, scope=%s',
ctx.agentId,
@@ -50,26 +48,26 @@ export const messageInternals: StateCreator<
const messagesKey = messageMapKey(ctx);
// Get raw messages from dbMessagesMap and apply reducer
- const rawMessages = get().dbMessagesMap[messagesKey] || [];
+ const rawMessages = this.#get().dbMessagesMap[messagesKey] || [];
const updatedRawMessages = messagesReducer(rawMessages, payload);
- const nextDbMap = { ...get().dbMessagesMap, [messagesKey]: updatedRawMessages };
+ const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: updatedRawMessages };
- if (isEqual(nextDbMap, get().dbMessagesMap)) return;
+ if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;
// parse to get display messages
const { flatList } = parse(updatedRawMessages);
- const nextDisplayMap = { ...get().messagesMap, [messagesKey]: flatList };
+ const nextDisplayMap = { ...this.#get().messagesMap, [messagesKey]: flatList };
- set({ dbMessagesMap: nextDbMap, messagesMap: nextDisplayMap }, false, {
+ this.#set({ dbMessagesMap: nextDbMap, messagesMap: nextDisplayMap }, false, {
payload,
type: `dispatchMessage/${payload.type}`,
});
- },
+ };
- internal_traceMessage: async (id, payload) => {
+ internal_traceMessage = async (id: string, payload: TraceEventPayloads): Promise<void> => {
// tracing the diff of update
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message) return;
const traceId = message?.traceId;
@@ -80,5 +78,10 @@ export const messageInternals: StateCreator<
.traceEvent({ content: message.content, observationId, traceId, ...payload })
.catch();
}
- },
-});
+ };
+}
+
+export type MessageInternalsAction = Pick<
+ MessageInternalsActionImpl,
+ keyof MessageInternalsActionImpl
+>;
diff --git a/src/store/chat/slices/message/actions/optimisticUpdate.ts b/src/store/chat/slices/message/actions/optimisticUpdate.ts
index 1ca9a403331..5ca17b379a7 100644
--- a/src/store/chat/slices/message/actions/optimisticUpdate.ts
+++ b/src/store/chat/slices/message/actions/optimisticUpdate.ts
@@ -13,10 +13,10 @@ import {
type UpdateMessageRAGParams,
} from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
-import { type StateCreator } from 'zustand/vanilla';
import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
/**
* Context for optimistic updates to specify session/topic isolation
@@ -31,114 +31,35 @@ export interface OptimisticUpdateContext {
* Optimistic update operations
* All methods follow the pattern: update frontend first, then persist to database
*/
-export interface MessageOptimisticUpdateAction {
- /**
- * create a message with optimistic update
- * returns the created message ID and updated message list
- */
- optimisticCreateMessage: (
- params: CreateMessageParams,
+
+type Setter = StoreSetter<ChatStore>;
+export const messageOptimisticUpdate = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new MessageOptimisticUpdateActionImpl(set, get, _api);
+
+export class MessageOptimisticUpdateActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ optimisticCreateMessage = async (
+ message: CreateMessageParams,
context?: {
groupMessageId?: string;
operationId?: string;
tempMessageId?: string;
},
- ) => Promise<{ id: string; messages: UIChatMessage[] } | undefined>;
-
- /**
- * create a temp message for optimistic update
- * otherwise the message will be too slow to show
- */
- optimisticCreateTmpMessage: (
- params: CreateMessageParams,
- context?: OptimisticUpdateContext,
- ) => string;
-
- /**
- * delete the message content with optimistic update
- */
- optimisticDeleteMessage: (id: string, context?: OptimisticUpdateContext) => Promise<void>;
- optimisticDeleteMessages: (ids: string[], context?: OptimisticUpdateContext) => Promise<void>;
-
- /**
- * update the message content with optimistic update
- * a method used by other action
- */
- optimisticUpdateMessageContent: (
- id: string,
- content: string,
- extra?: {
- imageList?: ChatImageItem[];
- metadata?: MessageMetadata;
- model?: string;
- provider?: string;
- reasoning?: ModelReasoning;
- search?: GroundingSearch;
- tools?: ChatToolPayload[];
- },
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * update the message error with optimistic update
- */
- optimisticUpdateMessageError: (
- id: string,
- error: ChatMessageError | null,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * update the message metadata with optimistic update
- */
- optimisticUpdateMessageMetadata: (
- id: string,
- metadata: Partial<MessageMetadata>,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * Optimistic update for message pluginIntervention field (frontend only, no database persistence)
- * Use this when you need to update plugin intervention status
- */
- optimisticUpdateMessagePlugin: (
- id: string,
- value: Partial<MessagePluginItem>,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * update the message plugin error with optimistic update
- */
- optimisticUpdateMessagePluginError: (
- id: string,
- error: ChatMessagePluginError | null,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * update message RAG with optimistic update
- */
- optimisticUpdateMessageRAG: (
- id: string,
- input: UpdateMessageRAGParams,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-}
-
-export const messageOptimisticUpdate: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- MessageOptimisticUpdateAction
-> = (set, get) => ({
- optimisticCreateMessage: async (message, context) => {
+ ): Promise<{ id: string; messages: UIChatMessage[] } | undefined> => {
const {
optimisticCreateTmpMessage,
internal_toggleMessageLoading,
internal_dispatchMessage,
replaceMessages,
- } = get();
+ } = this.#get();
let tempId = context?.tempMessageId;
if (!tempId) {
@@ -150,7 +71,7 @@ export const messageOptimisticUpdate: StateCreator<
const result = await messageService.createMessage(message);
// Use the messages returned from createMessage (already grouped)
- const ctx = get().internal_getConversationContext(context);
+ const ctx = this.#get().internal_getConversationContext(context);
replaceMessages(result.messages, { context: ctx });
internal_toggleMessageLoading(false, tempId);
@@ -172,10 +93,13 @@ export const messageOptimisticUpdate: StateCreator<
context,
);
}
- },
+ };
- optimisticCreateTmpMessage: (message, context) => {
- const { internal_dispatchMessage } = get();
+ optimisticCreateTmpMessage = (
+ message: CreateMessageParams,
+ context?: OptimisticUpdateContext,
+ ): string => {
+ const { internal_dispatchMessage } = this.#get();
// use optimistic update to avoid the slow waiting
// use pre-generated tempMessageId if provided, otherwise generate a new one
@@ -183,28 +107,47 @@ export const messageOptimisticUpdate: StateCreator<
internal_dispatchMessage({ id: tempId, type: 'createMessage', value: message }, context);
return tempId;
- },
+ };
- optimisticDeleteMessage: async (id: string, context) => {
- get().internal_dispatchMessage({ id, type: 'deleteMessage' }, context);
- const ctx = get().internal_getConversationContext(context);
+ optimisticDeleteMessage = async (
+ id: string,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ this.#get().internal_dispatchMessage({ id, type: 'deleteMessage' }, context);
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.removeMessage(id, ctx);
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, { context: ctx });
+ this.#get().replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticDeleteMessages: async (ids, context) => {
- get().internal_dispatchMessage({ ids, type: 'deleteMessages' }, context);
- const ctx = get().internal_getConversationContext(context);
+ optimisticDeleteMessages = async (
+ ids: string[],
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ this.#get().internal_dispatchMessage({ ids, type: 'deleteMessages' }, context);
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.removeMessages(ids, ctx);
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, { context: ctx });
+ this.#get().replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticUpdateMessageContent: async (id, content, extra, context) => {
- const { internal_dispatchMessage, refreshMessages, replaceMessages } = get();
+ optimisticUpdateMessageContent = async (
+ id: string,
+ content: string,
+ extra?: {
+ imageList?: ChatImageItem[];
+ metadata?: MessageMetadata;
+ model?: string;
+ provider?: string;
+ reasoning?: ModelReasoning;
+ search?: GroundingSearch;
+ tools?: ChatToolPayload[];
+ },
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { internal_dispatchMessage, refreshMessages, replaceMessages } = this.#get();
// Due to the async update method and refresh need about 100ms
// we need to update the message content at the frontend to avoid the update flick
@@ -229,7 +172,7 @@ export const messageOptimisticUpdate: StateCreator<
);
}
- const ctx = get().internal_getConversationContext(context);
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.updateMessage(
id,
@@ -251,25 +194,33 @@ export const messageOptimisticUpdate: StateCreator<
} else {
await refreshMessages();
}
- },
+ };
- optimisticUpdateMessageError: async (id, error, context) => {
- get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } }, context);
- const ctx = get().internal_getConversationContext(context);
+ optimisticUpdateMessageError = async (
+ id: string,
+ error: ChatMessageError | null,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ this.#get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } }, context);
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.updateMessage(id, { error }, ctx);
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, { context: ctx });
+ this.#get().replaceMessages(result.messages, { context: ctx });
} else {
- await get().refreshMessages();
+ await this.#get().refreshMessages();
}
- },
+ };
- optimisticUpdateMessageMetadata: async (id, metadata, context) => {
- const { internal_dispatchMessage, refreshMessages, replaceMessages } = get();
+ optimisticUpdateMessageMetadata = async (
+ id: string,
+ metadata: Partial<MessageMetadata>,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { internal_dispatchMessage, refreshMessages, replaceMessages } = this.#get();
internal_dispatchMessage({ id, type: 'updateMessageMetadata', value: metadata }, context);
- const ctx = get().internal_getConversationContext(context);
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.updateMessageMetadata(id, metadata, ctx);
if (result?.success && result.messages) {
@@ -277,34 +228,51 @@ export const messageOptimisticUpdate: StateCreator<
} else {
await refreshMessages();
}
- },
+ };
- optimisticUpdateMessagePlugin: async (id, value, context) => {
- const { internal_dispatchMessage, replaceMessages } = get();
+ optimisticUpdateMessagePlugin = async (
+ id: string,
+ value: Partial<MessagePluginItem>,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { internal_dispatchMessage, replaceMessages } = this.#get();
internal_dispatchMessage({ id, type: 'updateMessagePlugin', value }, context);
- const ctx = get().internal_getConversationContext(context);
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.updateMessagePlugin(id, value, ctx);
if (result?.success && result.messages) {
replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticUpdateMessagePluginError: async (id, error, context) => {
- const ctx = get().internal_getConversationContext(context);
+ optimisticUpdateMessagePluginError = async (
+ id: string,
+ error: ChatMessagePluginError | null,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.updateMessagePluginError(id, error, ctx);
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, { context: ctx });
+ this.#get().replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticUpdateMessageRAG: async (id, data, context) => {
- const ctx = get().internal_getConversationContext(context);
+ optimisticUpdateMessageRAG = async (
+ id: string,
+ data: UpdateMessageRAGParams,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const ctx = this.#get().internal_getConversationContext(context);
const result = await messageService.updateMessageRAG(id, data, ctx);
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, { context: ctx });
+ this.#get().replaceMessages(result.messages, { context: ctx });
}
- },
-});
+ };
+}
+
+export type MessageOptimisticUpdateAction = Pick<
+ MessageOptimisticUpdateActionImpl,
+ keyof MessageOptimisticUpdateActionImpl
+>;
diff --git a/src/store/chat/slices/message/actions/publicApi.ts b/src/store/chat/slices/message/actions/publicApi.ts
index f4fa3863b37..c573a25c951 100644
--- a/src/store/chat/slices/message/actions/publicApi.ts
+++ b/src/store/chat/slices/message/actions/publicApi.ts
@@ -2,11 +2,11 @@
import { TraceEventType } from '@lobechat/types';
import { copyToClipboard } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
-import { type StateCreator } from 'zustand/vanilla';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { dbMessageSelectors, displayMessageSelectors } from '../../../selectors';
@@ -19,83 +19,22 @@ const n = setNamespace('m');
* Public API for components
* These methods are directly called by UI components
*/
-export interface MessagePublicApiAction {
- // ===== Create ===== //
- addAIMessage: () => Promise<void>;
- addUserMessage: (params: { message: string; fileList?: string[] }) => Promise<void>;
-
- // ===== Delete ===== //
- /**
- * clear message on the active session
- */
- clearMessage: () => Promise<void>;
- /**
- * Delete a message by id
- * @param id - message id
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- deleteMessage: (id: string, context?: OptimisticUpdateContext) => Promise<void>;
- /**
- * Delete an assistant message and its associated tool messages
- * @param id - message id
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- deleteAssistantMessage: (id: string, context?: OptimisticUpdateContext) => Promise<void>;
- deleteDBMessage: (id: string) => Promise<void>;
- deleteToolMessage: (id: string) => Promise<void>;
- clearAllMessages: () => Promise<void>;
-
- // ===== Update ===== //
- /**
- * Update message input box content
- */
- updateMessageInput: (message: string) => void;
- /**
- * Modify message content
- * @param id - message id
- * @param content - new content
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- modifyMessageContent: (
- id: string,
- content: string,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
- toggleMessageEditing: (id: string, editing: boolean) => void;
- /**
- * Toggle message collapsed state
- * @param id - message id
- * @param collapsed - collapsed state, if not provided, toggle current state
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- toggleMessageCollapsed: (
- id: string,
- collapsed?: boolean,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
- /**
- * Toggle tool inspect expanded state
- * @param id - message id
- * @param expanded - expanded state, if not provided, toggle current state
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- toggleInspectExpanded: (
- id: string,
- expanded?: boolean,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
- // ===== Others ===== //
- copyMessage: (id: string, content: string) => Promise<void>;
-}
+type Setter = StoreSetter<ChatStore>;
+export const messagePublicApi = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new MessagePublicApiActionImpl(set, get, _api);
-export const messagePublicApi: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- MessagePublicApiAction
-> = (set, get) => ({
- addAIMessage: async () => {
+export class MessagePublicApiActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ addAIMessage = async (): Promise<void> => {
const {
optimisticCreateMessage,
updateMessageInput,
@@ -104,10 +43,10 @@ export const messagePublicApi: StateCreator<
activeThreadId,
activeGroupId,
inputMessage,
- } = get();
+ } = this.#get();
if (!activeAgentId) return;
- const parentId = displayMessageSelectors.lastDisplayMessageId(get());
+ const parentId = displayMessageSelectors.lastDisplayMessageId(this.#get());
const result = await optimisticCreateMessage({
content: inputMessage,
@@ -122,9 +61,15 @@ export const messagePublicApi: StateCreator<
if (result) {
updateMessageInput('');
}
- },
-
- addUserMessage: async ({ message, fileList }) => {
+ };
+
+ addUserMessage = async ({
+ message,
+ fileList,
+ }: {
+ message: string;
+ fileList?: string[];
+ }): Promise<void> => {
const {
optimisticCreateMessage,
updateMessageInput,
@@ -132,10 +77,10 @@ export const messagePublicApi: StateCreator<
activeAgentId,
activeThreadId,
activeGroupId,
- } = get();
+ } = this.#get();
if (!activeAgentId) return;
- const parentId = displayMessageSelectors.lastDisplayMessageId(get());
+ const parentId = displayMessageSelectors.lastDisplayMessageId(this.#get());
const result = await optimisticCreateMessage({
content: message,
@@ -151,15 +96,15 @@ export const messagePublicApi: StateCreator<
if (result) {
updateMessageInput('');
}
- },
+ };
- deleteAssistantMessage: async (id, context) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ deleteAssistantMessage = async (id: string, context?: OptimisticUpdateContext): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
let ids = [message.id];
if (message.tools) {
- const allMessages = dbMessageSelectors.activeDbMessages(get());
+ const allMessages = dbMessageSelectors.activeDbMessages(this.#get());
const toolMessageIds = message.tools.flatMap((tool) => {
const messages = allMessages.filter((m) => m.tool_call_id === tool.id);
@@ -168,10 +113,11 @@ export const messagePublicApi: StateCreator<
ids = ids.concat(toolMessageIds);
}
- await get().optimisticDeleteMessages(ids, context);
- },
- deleteMessage: async (id, context) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ await this.#get().optimisticDeleteMessages(ids, context);
+ };
+
+ deleteMessage = async (id: string, context?: OptimisticUpdateContext): Promise<void> => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message) return;
let ids = [message.id];
@@ -190,36 +136,36 @@ export const messagePublicApi: StateCreator<
ids = ids.concat(toolResultIds);
}
- await get().optimisticDeleteMessages(ids, context);
- },
+ await this.#get().optimisticDeleteMessages(ids, context);
+ };
- deleteDBMessage: async (id) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ deleteDBMessage = async (id: string): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
let ids = [message.id];
- get().internal_dispatchMessage({ type: 'deleteMessages', ids });
- const ctx = get().internal_getConversationContext();
+ this.#get().internal_dispatchMessage({ type: 'deleteMessages', ids });
+ const ctx = this.#get().internal_getConversationContext();
// CRUD operations pass agentId - backend handles sessionId mapping
const result = await messageService.removeMessages(ids, ctx);
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, { context: ctx });
+ this.#get().replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- deleteToolMessage: async (id) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ deleteToolMessage = async (id: string): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message || message.role !== 'tool') return;
// Get operationId from messageOperationMap to ensure proper context isolation
- const operationId = get().messageOperationMap[id];
+ const operationId = this.#get().messageOperationMap[id];
const context = operationId ? { operationId } : undefined;
const removeToolInAssistantMessage = async () => {
if (!message.parentId) return;
- await get().optimisticRemoveToolFromAssistantMessage(
+ await this.#get().optimisticRemoveToolFromAssistantMessage(
message.parentId,
message.tool_call_id,
context,
@@ -228,14 +174,14 @@ export const messagePublicApi: StateCreator<
await Promise.all([
// 1. remove tool message
- get().optimisticDeleteMessage(id, context),
+ this.#get().optimisticDeleteMessage(id, context),
// 2. remove the tool item in the assistant tools
removeToolInAssistantMessage(),
]);
- },
+ };
- clearMessage: async () => {
- const { activeAgentId, activeTopicId, activeGroupId, refreshTopic, switchTopic } = get();
+ clearMessage = async (): Promise<void> => {
+ const { activeAgentId, activeTopicId, activeGroupId, refreshTopic, switchTopic } = this.#get();
// For group sessions, we need to clear group messages using groupId
// For regular sessions, we clear session messages using agentId
@@ -253,68 +199,89 @@ export const messagePublicApi: StateCreator<
await refreshTopic();
// Clear messages directly since all messages are deleted
- get().replaceMessages([]);
+ this.#get().replaceMessages([]);
// after remove topic , go back to default topic
switchTopic(null);
- },
+ };
- clearAllMessages: async () => {
+ clearAllMessages = async (): Promise<void> => {
await messageService.removeAllMessages();
// Clear messages directly since all messages are deleted
- get().replaceMessages([]);
- },
+ this.#get().replaceMessages([]);
+ };
- copyMessage: async (id, content) => {
+ copyMessage = async (id: string, content: string): Promise<void> => {
await copyToClipboard(content);
- get().internal_traceMessage(id, { eventType: TraceEventType.CopyMessage });
- },
+ this.#get().internal_traceMessage(id, { eventType: TraceEventType.CopyMessage });
+ };
- toggleMessageEditing: (id, editing) => {
- set(
- { messageEditingIds: toggleBooleanList(get().messageEditingIds, id, editing) },
+ toggleMessageEditing = (id: string, editing: boolean): void => {
+ this.#set(
+ { messageEditingIds: toggleBooleanList(this.#get().messageEditingIds, id, editing) },
false,
'toggleMessageEditing',
);
- },
+ };
- updateMessageInput: (message) => {
- if (isEqual(message, get().inputMessage)) return;
+ updateMessageInput = (message: string): void => {
+ if (isEqual(message, this.#get().inputMessage)) return;
- set({ inputMessage: message }, false, n('updateMessageInput', message));
- },
+ this.#set({ inputMessage: message }, false, n('updateMessageInput', message));
+ };
- modifyMessageContent: async (id, content, context) => {
+ modifyMessageContent = async (
+ id: string,
+ content: string,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
// tracing the diff of update
// due to message content will change, so we need send trace before update,or will get wrong data
- get().internal_traceMessage(id, {
+ this.#get().internal_traceMessage(id, {
eventType: TraceEventType.ModifyMessage,
nextContent: content,
});
- await get().optimisticUpdateMessageContent(id, content, undefined, context);
- },
+ await this.#get().optimisticUpdateMessageContent(id, content, undefined, context);
+ };
- toggleMessageCollapsed: async (id, collapsed, context) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ toggleMessageCollapsed = async (
+ id: string,
+ collapsed?: boolean,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message) return;
// 如果没有传入 collapsed,则取反当前状态
const nextCollapsed = collapsed ?? !message.metadata?.collapsed;
// 直接调用现有的 optimisticUpdateMessageMetadata
- await get().optimisticUpdateMessageMetadata(id, { collapsed: nextCollapsed }, context);
- },
+ await this.#get().optimisticUpdateMessageMetadata(id, { collapsed: nextCollapsed }, context);
+ };
- toggleInspectExpanded: async (id, expanded, context) => {
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ toggleInspectExpanded = async (
+ id: string,
+ expanded?: boolean,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
// 如果没有传入 expanded,则取反当前状态
const nextExpanded = expanded ?? !message.metadata?.inspectExpanded;
// 直接调用现有的 optimisticUpdateMessageMetadata
- await get().optimisticUpdateMessageMetadata(id, { inspectExpanded: nextExpanded }, context);
- },
-});
+ await this.#get().optimisticUpdateMessageMetadata(
+ id,
+ { inspectExpanded: nextExpanded },
+ context,
+ );
+ };
+}
+
+export type MessagePublicApiAction = Pick<
+ MessagePublicApiActionImpl,
+ keyof MessagePublicApiActionImpl
+>;
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 8aad3fd7b14..09d0dd16a08 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -2,11 +2,11 @@ import { parse } from '@lobechat/conversation-flow';
import { type ConversationContext, type UIChatMessage } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { type MessageMapKeyInput, messageMapKey } from '../../../utils/messageMapKey';
@@ -16,68 +16,45 @@ const SWR_USE_FETCH_MESSAGES = 'SWR_USE_FETCH_MESSAGES';
* Data query and synchronization actions
* Handles fetching, refreshing, and replacing message data
*/
-export interface MessageQueryAction {
- /**
- * Manually refresh messages from server
- */
- refreshMessages: (context?: Partial<ConversationContext>) => Promise<void>;
-
- /**
- * Replace current messages with new data
- */
- replaceMessages: (
+
+type Setter = StoreSetter<ChatStore>;
+export const messageQuery = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new MessageQueryActionImpl(set, get, _api);
+
+export class MessageQueryActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ refreshMessages = async (context?: Partial<ConversationContext>): Promise<void> => {
+ const agentId = context?.agentId ?? this.#get().activeAgentId;
+ const topicId = context?.topicId !== undefined ? context.topicId : this.#get().activeTopicId;
+ // TODO: Support threadId refresh when needed
+ await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'session']);
+ await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'group']);
+ };
+
+ replaceMessages = (
messages: UIChatMessage[],
params?: {
action?: any;
- /**
- * Conversation context for message storage key
- * If not provided, uses active context from state
- */
+
context?: Partial<ConversationContext>;
- /**
- * Operation ID for context retrieval
- * @deprecated Use context instead
- */
+
operationId?: string;
},
- ) => void;
-
- /**
- * Fetch messages for a specific context using SWR
- * Used for fetching thread messages or messages for a specific context
- *
- * @param context - Conversation context with agentId, topicId, threadId, etc.
- * @param skipFetch - When true, SWR key is null and no fetch occurs
- */
- useFetchMessages: (
- context: ConversationContext,
- skipFetch?: boolean,
- ) => SWRResponse<UIChatMessage[]>;
-}
-
-export const messageQuery: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- MessageQueryAction
-> = (set, get) => ({
- // TODO: The mutate should only be called once, but since we haven't merge session and group,
- // we need to call it twice
- refreshMessages: async (context?: Partial<ConversationContext>) => {
- const agentId = context?.agentId ?? get().activeAgentId;
- const topicId = context?.topicId !== undefined ? context.topicId : get().activeTopicId;
- // TODO: Support threadId refresh when needed
- await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'session']);
- await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'group']);
- },
-
- replaceMessages: (messages, params) => {
+ ): void => {
let ctx: MessageMapKeyInput;
// Priority 1: Use explicit context if provided (preserving scope)
if (params?.context) {
ctx = {
- agentId: params.context.agentId ?? get().activeAgentId,
+ agentId: params.context.agentId ?? this.#get().activeAgentId,
// Preserve groupId from context
groupId: params.context.groupId,
// Preserve scope from context
@@ -87,46 +64,49 @@ export const messageQuery: StateCreator<
threadId: params.context.threadId,
topicId:
- params.context.topicId !== undefined ? params.context.topicId : get().activeTopicId,
+ params.context.topicId !== undefined ? params.context.topicId : this.#get().activeTopicId,
};
}
// Priority 2: Get full context from operation if operationId is provided (deprecated)
else if (params?.operationId) {
- ctx = get().internal_getConversationContext(params);
+ ctx = this.#get().internal_getConversationContext(params);
}
// Priority 3: Fallback to global state
else {
ctx = {
- agentId: get().activeAgentId,
- groupId: get().activeGroupId,
- threadId: get().activeThreadId,
- topicId: get().activeTopicId,
+ agentId: this.#get().activeAgentId,
+ groupId: this.#get().activeGroupId,
+ threadId: this.#get().activeThreadId,
+ topicId: this.#get().activeTopicId,
};
}
const messagesKey = messageMapKey(ctx);
// Get raw messages from dbMessagesMap and apply reducer
- const nextDbMap = { ...get().dbMessagesMap, [messagesKey]: messages };
+ const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: messages };
- if (isEqual(nextDbMap, get().dbMessagesMap)) return;
+ if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;
// Parse messages using conversation-flow
const { flatList } = parse(messages);
- set(
+ this.#set(
{
// Store raw messages from backend
dbMessagesMap: nextDbMap,
// Store parsed messages for display
- messagesMap: { ...get().messagesMap, [messagesKey]: flatList },
+ messagesMap: { ...this.#get().messagesMap, [messagesKey]: flatList },
},
false,
params?.action ?? 'replaceMessages',
);
- },
+ };
- useFetchMessages: (context, skipFetch) => {
+ useFetchMessages = (
+ context: ConversationContext,
+ skipFetch?: boolean,
+ ): SWRResponse<UIChatMessage[]> => {
// Skip fetch when skipFetch is true or required fields are missing
const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;
@@ -138,9 +118,11 @@ export const messageQuery: StateCreator<
if (!data || !context.topicId) return;
// Use replaceMessages to store the fetched messages
- get().replaceMessages(data, { action: 'useFetchMessages', context });
+ this.#get().replaceMessages(data, { action: 'useFetchMessages', context });
},
},
);
- },
-});
+ };
+}
+
+export type MessageQueryAction = Pick<MessageQueryActionImpl, keyof MessageQueryActionImpl>;
diff --git a/src/store/chat/slices/message/actions/runtimeState.ts b/src/store/chat/slices/message/actions/runtimeState.ts
index 10aef5ad560..8c006018fe1 100644
--- a/src/store/chat/slices/message/actions/runtimeState.ts
+++ b/src/store/chat/slices/message/actions/runtimeState.ts
@@ -1,6 +1,5 @@
-import { type StateCreator } from 'zustand/vanilla';
-
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { type Action } from '@/utils/storeDebug';
import type { ChatStoreState } from '../../../initialState';
@@ -10,41 +9,36 @@ import { preventLeavingFn, toggleBooleanList } from '../../../utils';
* Runtime state management for message-related states
* Handles loading states, active session tracking, etc.
*/
-export interface MessageRuntimeStateAction {
- /**
- * helper to toggle the loading state of the array,used by these three toggleXXXLoading
- */
- internal_toggleLoadingArrays: (
+
+type Setter = StoreSetter<ChatStore>;
+export const messageRuntimeState = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new MessageRuntimeStateActionImpl(set, get, _api);
+
+export class MessageRuntimeStateActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_toggleLoadingArrays = (
key: keyof ChatStoreState,
loading: boolean,
id?: string,
action?: Action,
- ) => AbortController | undefined;
-
- /**
- * method to toggle message create loading state
- * the AI message status is creating -> generating
- * other message role like user and tool , only this method need to be called
- */
- internal_toggleMessageLoading: (loading: boolean, id: string) => void;
-}
-
-export const messageRuntimeState: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- MessageRuntimeStateAction
-> = (set, get) => ({
- internal_toggleLoadingArrays: (key, loading, id, action) => {
+ ): AbortController | undefined => {
const abortControllerKey = `${key}AbortController`;
if (loading) {
window.addEventListener('beforeunload', preventLeavingFn);
const abortController = new AbortController();
- set(
+ this.#set(
{
[abortControllerKey]: abortController,
- [key]: toggleBooleanList(get()[key] as string[], id!, loading),
+ [key]: toggleBooleanList(this.#get()[key] as string[], id!, loading),
},
false,
action,
@@ -53,12 +47,12 @@ export const messageRuntimeState: StateCreator<
return abortController;
} else {
if (!id) {
- set({ [abortControllerKey]: undefined, [key]: [] }, false, action);
+ this.#set({ [abortControllerKey]: undefined, [key]: [] }, false, action);
} else
- set(
+ this.#set(
{
[abortControllerKey]: undefined,
- [key]: toggleBooleanList(get()[key] as string[], id, loading),
+ [key]: toggleBooleanList(this.#get()[key] as string[], id, loading),
},
false,
action,
@@ -66,15 +60,20 @@ export const messageRuntimeState: StateCreator<
window.removeEventListener('beforeunload', preventLeavingFn);
}
- },
+ };
- internal_toggleMessageLoading: (loading, id) => {
- set(
+ internal_toggleMessageLoading = (loading: boolean, id: string): void => {
+ this.#set(
{
- messageLoadingIds: toggleBooleanList(get().messageLoadingIds, id, loading),
+ messageLoadingIds: toggleBooleanList(this.#get().messageLoadingIds, id, loading),
},
false,
`internal_toggleMessageLoading/${loading ? 'start' : 'end'}`,
);
- },
-});
+ };
+}
+
+export type MessageRuntimeStateAction = Pick<
+ MessageRuntimeStateActionImpl,
+ keyof MessageRuntimeStateActionImpl
+>;
diff --git a/src/store/chat/slices/message/supervisor.ts b/src/store/chat/slices/message/supervisor.ts
index af770f6391f..943c279062e 100644
--- a/src/store/chat/slices/message/supervisor.ts
+++ b/src/store/chat/slices/message/supervisor.ts
@@ -250,14 +250,14 @@ export class GroupChatSupervisor {
case 'create_todo': {
if (context.scene === 'productive') {
const changed = this.applyCreateTodo(todos, call.parameter);
- todoUpdated = todoUpdated || changed;
+ if (changed) todoUpdated = true;
}
break;
}
case 'finish_todo': {
if (context.scene === 'productive') {
const changed = this.applyFinishTodo(todos, call.parameter);
- todoUpdated = todoUpdated || changed;
+ if (changed) todoUpdated = true;
}
break;
}
@@ -449,7 +449,7 @@ export class GroupChatSupervisor {
if (!targetExists) target = undefined;
}
- if (context.allowDM === false) {
+ if (context.allowDM === false && target === 'user') {
target = undefined;
}
@@ -534,7 +534,7 @@ export class GroupChatSupervisor {
typeof (item as any).content === 'string' &&
typeof (item as any).finished === 'boolean',
)
- .map((item) => ({
+ .map((item: any) => ({
assignee:
typeof (item as any).assignee === 'string' && (item as any).assignee.trim()
? ((item as any).assignee as string).trim()
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index 6b3bb6f91bf..83b6195f444 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -2,10 +2,10 @@
import { nanoid } from '@lobechat/utils';
import debug from 'debug';
import { produce } from 'immer';
-import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
import { type MessageMapKeyInput, messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type {
@@ -25,121 +25,24 @@ const log = debug('lobe-store:operation');
/**
* Operation Actions
*/
-export interface OperationActions {
- /**
- * Associate message with operation (for automatic context retrieval)
- */
- associateMessageWithOperation: (messageId: string, operationId: string) => void;
-
- /**
- * Cancel all operations
- */
- cancelAllOperations: (reason?: string) => void;
-
- /**
- * Cancel operation (recursively cancel all child operations)
- */
- cancelOperation: (operationId: string, reason?: string) => void;
-
- /**
- * Cancel operations by filter
- */
- cancelOperations: (filter: OperationFilter, reason?: string) => string[];
-
- /**
- * Clean up completed or cancelled operations
- * Removes operations that are older than the specified age (default: 30 seconds)
- */
- cleanupCompletedOperations: (maxAgeMs?: number) => number;
-
- /**
- * Complete operation
- */
- completeOperation: (operationId: string, metadata?: Partial<OperationMetadata>) => void;
-
- /**
- * Mark operation as failed
- */
- failOperation: (
- operationId: string,
- error: { code?: string; details?: any; message: string; type: string },
- ) => void;
-
- /**
- * Get operation's AbortSignal (for passing to async operations like fetch)
- */
- getOperationAbortSignal: (operationId: string) => AbortSignal;
-
- /**
- * Get conversation context from operation or fallback to global state
- * This is a helper method that can be used by other slices
- *
- * Returns full MessageMapKeyInput for consistent key generation
- *
- * Migration Note:
- * - Only agentId is used for message association
- * - Backend handles sessionId mapping internally based on agentId
- */
- internal_getConversationContext: (context?: { operationId?: string }) => MessageMapKeyInput;
-
- /**
- * Register cancel handler for an operation
- * The handler will be called when the operation is cancelled
- */
- onOperationCancel: (
- operationId: string,
- handler: (context: OperationCancelContext) => void | Promise<void>,
- ) => void;
-
- /**
- * Register an afterCompletion callback for an operation
- * The callback will be executed after the AgentRuntime completes
- * Used to avoid race conditions with message updates
- */
- registerAfterCompletionCallback: (operationId: string, callback: AfterCompletionCallback) => void;
-
- /**
- * Start an operation (supports auto-inheriting context from parent operation)
- */
- startOperation: (params: {
- context?: Partial<OperationContext>;
- description?: string;
- label?: string;
- metadata?: Partial<OperationMetadata>;
- operationId?: string;
- parentOperationId?: string;
- type: OperationType;
- }) => { abortController: AbortController; operationId: string };
-
- /**
- * Update operation metadata
- */
- updateOperationMetadata: (operationId: string, metadata: Partial<OperationMetadata>) => void;
-
- /**
- * Update operation progress
- */
- updateOperationProgress: (operationId: string, current: number, total?: number) => void;
-
- /**
- * Update operation status
- */
- updateOperationStatus: (
- operationId: string,
- status: OperationStatus,
- metadata?: Partial<OperationMetadata>,
- ) => void;
-}
-export const operationActions: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- OperationActions
-> = (set, get) => ({
- internal_getConversationContext: (context) => {
+type Setter = StoreSetter<ChatStore>;
+export const operationActions = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new OperationActionsImpl(set, get, _api);
+
+export class OperationActionsImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_getConversationContext = (context?: { operationId?: string }): MessageMapKeyInput => {
if (context?.operationId) {
- const operation = get().operations[context.operationId];
+ const operation = this.#get().operations[context.operationId];
if (!operation) {
log(
'[internal_getConversationContext] ERROR: Operation not found: %s',
@@ -161,10 +64,10 @@ export const operationActions: StateCreator<
}
// Fallback to global state
- const agentId = get().activeAgentId;
- const groupId = get().activeGroupId;
- const topicId = get().activeTopicId;
- const threadId = get().activeThreadId;
+ const agentId = this.#get().activeAgentId;
+ const groupId = this.#get().activeGroupId;
+ const topicId = this.#get().activeTopicId;
+ const threadId = this.#get().activeThreadId;
log('[internal_getConversationContext] use global state: ', {
agentId,
topicId,
@@ -172,9 +75,17 @@ export const operationActions: StateCreator<
groupId,
});
return { agentId, topicId, threadId, groupId };
- },
+ };
- startOperation: (params) => {
+ startOperation = (params: {
+ context?: Partial<OperationContext>;
+ description?: string;
+ label?: string;
+ metadata?: Partial<OperationMetadata>;
+ operationId?: string;
+ parentOperationId?: string;
+ type: OperationType;
+ }): { abortController: AbortController; operationId: string } => {
const {
type,
context: partialContext,
@@ -191,7 +102,7 @@ export const operationActions: StateCreator<
let context: OperationContext = partialContext || {};
if (parentOperationId) {
- const parentOp = get().operations[parentOperationId];
+ const parentOp = this.#get().operations[parentOperationId];
if (parentOp) {
// Inherit parent's context, allow partial override
context = { ...parentOp.context, ...partialContext };
@@ -220,7 +131,7 @@ export const operationActions: StateCreator<
description,
};
- set(
+ this.#set(
produce((state: ChatStore) => {
// Add to operations map
state.operations[operationId] = operation;
@@ -272,14 +183,14 @@ export const operationActions: StateCreator<
// Only cleanup for top-level operations (no parent) to avoid excessive cleanup calls
if (!parentOperationId) {
// Clean up operations completed more than 30 seconds ago
- get().cleanupCompletedOperations(30_000);
+ this.#get().cleanupCompletedOperations(30_000);
}
return { operationId, abortController };
- },
+ };
- updateOperationMetadata: (operationId, metadata) => {
- const operation = get().operations[operationId];
+ updateOperationMetadata = (operationId: string, metadata: Partial<OperationMetadata>): void => {
+ const operation = this.#get().operations[operationId];
if (metadata.isAborting) {
log(
'[updateOperationMetadata] Setting isAborting=true for operation %s (type=%s)',
@@ -288,7 +199,7 @@ export const operationActions: StateCreator<
);
}
- set(
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) return;
@@ -301,10 +212,14 @@ export const operationActions: StateCreator<
false,
n(`updateOperationMetadata/${operationId}`),
);
- },
+ };
- updateOperationStatus: (operationId, status, metadata) => {
- set(
+ updateOperationStatus = (
+ operationId: string,
+ status: OperationStatus,
+ metadata?: Partial<OperationMetadata>,
+ ): void => {
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) return;
@@ -321,10 +236,10 @@ export const operationActions: StateCreator<
false,
n(`updateOperationStatus/${operationId}/${status}`),
);
- },
+ };
- updateOperationProgress: (operationId, current, total) => {
- set(
+ updateOperationProgress = (operationId: string, current: number, total?: number): void => {
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) return;
@@ -338,10 +253,10 @@ export const operationActions: StateCreator<
false,
n(`updateOperationProgress/${operationId}`),
);
- },
+ };
- completeOperation: (operationId, metadata) => {
- const operation = get().operations[operationId];
+ completeOperation = (operationId: string, metadata?: Partial<OperationMetadata>): void => {
+ const operation = this.#get().operations[operationId];
if (operation) {
log(
'[completeOperation] operation %s (type=%s) completed, duration=%dms',
@@ -351,7 +266,7 @@ export const operationActions: StateCreator<
);
}
- set(
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) return;
@@ -371,18 +286,21 @@ export const operationActions: StateCreator<
false,
n(`completeOperation/${operationId}`),
);
- },
+ };
- getOperationAbortSignal: (operationId) => {
- const operation = get().operations[operationId];
+ getOperationAbortSignal = (operationId: string): AbortSignal => {
+ const operation = this.#get().operations[operationId];
if (!operation) {
throw new Error(`[getOperationAbortSignal] Operation not found: ${operationId}`);
}
return operation.abortController.signal;
- },
+ };
- onOperationCancel: (operationId, handler) => {
- set(
+ onOperationCancel = (
+ operationId: string,
+ handler: (context: OperationCancelContext) => void | Promise<void>,
+ ): void => {
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) {
@@ -400,10 +318,13 @@ export const operationActions: StateCreator<
false,
n(`onOperationCancel/${operationId}`),
);
- },
+ };
- registerAfterCompletionCallback: (operationId, callback) => {
- set(
+ registerAfterCompletionCallback = (
+ operationId: string,
+ callback: AfterCompletionCallback,
+ ): void => {
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) {
@@ -434,10 +355,10 @@ export const operationActions: StateCreator<
false,
n(`registerAfterCompletionCallback/${operationId}`),
);
- },
+ };
- cancelOperation: (operationId, reason = 'User cancelled') => {
- const operation = get().operations[operationId];
+ cancelOperation = (operationId: string, reason: string = 'User cancelled'): void => {
+ const operation = this.#get().operations[operationId];
if (!operation) {
log('[cancelOperation] operation not found: %s', operationId);
return;
@@ -466,7 +387,7 @@ export const operationActions: StateCreator<
// 2. Set isAborting flag immediately for execAgentRuntime operations
// This ensures UI (loading button) responds instantly to user cancellation
if (operation.type === 'execAgentRuntime') {
- get().updateOperationMetadata(operationId, { isAborting: true });
+ this.#get().updateOperationMetadata(operationId, { isAborting: true });
}
// 3. Call cancel handler if registered
@@ -493,7 +414,7 @@ export const operationActions: StateCreator<
}
// 4. Update status
- set(
+ this.#set(
produce((state: ChatStore) => {
const op = state.operations[operationId];
if (!op) return;
@@ -512,13 +433,16 @@ export const operationActions: StateCreator<
if (operation.childOperationIds && operation.childOperationIds.length > 0) {
log('[cancelOperation] cancelling %d child operations', operation.childOperationIds.length);
operation.childOperationIds.forEach((childId) => {
- get().cancelOperation(childId, 'Parent operation cancelled');
+ this.#get().cancelOperation(childId, 'Parent operation cancelled');
});
}
- },
+ };
- failOperation: (operationId, error) => {
- const operation = get().operations[operationId];
+ failOperation = (
+ operationId: string,
+ error: { code?: string; details?: any; message: string; type: string },
+ ): void => {
+ const operation = this.#get().operations[operationId];
if (operation) {
log(
'[failOperation] operation %s (type=%s) failed: %s',
@@ -528,7 +452,7 @@ export const operationActions: StateCreator<
);
}
- set(
+ this.#set(
produce((state: ChatStore) => {
const operation = state.operations[operationId];
if (!operation) return;
@@ -542,10 +466,10 @@ export const operationActions: StateCreator<
false,
n(`failOperation/${operationId}`),
);
- },
+ };
- cancelOperations: (filter, reason = 'Batch cancelled') => {
- const operations = Object.values(get().operations);
+ cancelOperations = (filter: OperationFilter, reason: string = 'Batch cancelled'): string[] => {
+ const operations = Object.values(this.#get().operations);
const matchedIds: string[] = [];
operations.forEach((op) => {
@@ -592,29 +516,29 @@ export const operationActions: StateCreator<
// Cancel all matched operations
matchedIds.forEach((id) => {
- get().cancelOperation(id, reason);
+ this.#get().cancelOperation(id, reason);
});
return matchedIds;
- },
+ };
- cancelAllOperations: (reason = 'Cancel all operations') => {
- const operations = Object.values(get().operations);
+ cancelAllOperations = (reason: string = 'Cancel all operations'): void => {
+ const operations = Object.values(this.#get().operations);
operations.forEach((op) => {
if (op.status === 'running') {
- get().cancelOperation(op.id, reason);
+ this.#get().cancelOperation(op.id, reason);
}
});
- },
+ };
- cleanupCompletedOperations: (olderThan = 60_000) => {
+ cleanupCompletedOperations = (olderThan: number = 60_000): number => {
// Default: cleanup operations completed more than 1 minute ago
const now = Date.now();
// Collect operations to delete first
const operationsToDelete: string[] = [];
- Object.values(get().operations).forEach((op) => {
+ Object.values(this.#get().operations).forEach((op) => {
const isCompleted =
op.status === 'completed' || op.status === 'cancelled' || op.status === 'failed';
const isOld = op.metadata.endTime && now - op.metadata.endTime > olderThan;
@@ -626,7 +550,7 @@ export const operationActions: StateCreator<
if (operationsToDelete.length === 0) return 0;
- set(
+ this.#set(
produce((state: ChatStore) => {
// Delete operations and update indexes
operationsToDelete.forEach((operationId) => {
@@ -692,10 +616,10 @@ export const operationActions: StateCreator<
log('[cleanupCompletedOperations] cleaned up %d operations', operationsToDelete.length);
return operationsToDelete.length;
- },
+ };
- associateMessageWithOperation: (messageId, operationId) => {
- set(
+ associateMessageWithOperation = (messageId: string, operationId: string): void => {
+ this.#set(
produce((state: ChatStore) => {
// Update messageOperationMap (for single operation lookup)
state.messageOperationMap[messageId] = operationId;
@@ -711,5 +635,7 @@ export const operationActions: StateCreator<
false,
n(`associateMessageWithOperation/${messageId}/${operationId}`),
);
- },
-});
+ };
+}
+
+export type OperationActions = Pick<OperationActionsImpl, keyof OperationActionsImpl>;
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index ecc723d558a..bd743d90076 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -22,7 +22,7 @@ export type OperationType =
| 'createAssistantMessage' // Create assistant message (sub-operation of execAgentRuntime)
// === LLM execution (sub-operations) ===
| 'callLLM' // Call LLM streaming response (sub-operation of execAgentRuntime)
- // === (sub-operations) ===
+ // === (sub-operations) = ==
| 'reasoning' // AI reasoning process (child operation)
// === RAG and retrieval ===
diff --git a/src/store/chat/slices/plugin/actions/exector.ts b/src/store/chat/slices/plugin/actions/exector.ts
index d60c36bff24..b34f111421c 100644
--- a/src/store/chat/slices/plugin/actions/exector.ts
+++ b/src/store/chat/slices/plugin/actions/exector.ts
@@ -62,7 +62,7 @@ export const klavisExecutor: RemoteToolExecutor = async (p) => {
return createFailedResult('Klavis tool returned empty result');
};
-export const lobehubSkillExecutor: RemoteToolExecutor = async (p) => {
+export const lobehubSkillExecutor: RemoteToolExecutor = async (p: any) => {
// payload.identifier is the provider id (e.g., 'linear', 'microsoft')
const provider = p.identifier;
diff --git a/src/store/chat/slices/plugin/actions/index.ts b/src/store/chat/slices/plugin/actions/index.ts
index 20eee9566cc..a838d229910 100644
--- a/src/store/chat/slices/plugin/actions/index.ts
+++ b/src/store/chat/slices/plugin/actions/index.ts
@@ -1,29 +1,27 @@
import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { flattenActions } from '@/store/utils/flattenActions';
-import { type PluginInternalsAction, pluginInternals } from './internals';
+import { type PluginInternalsAction, PluginInternalsActionImpl } from './internals';
import {
type PluginOptimisticUpdateAction,
- pluginOptimisticUpdate,
+ PluginOptimisticUpdateActionImpl,
} from './optimisticUpdate';
-import { type PluginTypesAction, pluginTypes } from './pluginTypes';
-import { type PluginPublicApiAction, pluginPublicApi } from './publicApi';
-import { type PluginWorkflowAction, pluginWorkflow } from './workflow';
+import { type PluginTypesAction, PluginTypesActionImpl } from './pluginTypes';
+import { type PluginPublicApiAction, PluginPublicApiActionImpl } from './publicApi';
+import { type PluginWorkflowAction, PluginWorkflowActionImpl } from './workflow';
+
+export type ChatPluginAction = PluginPublicApiAction &
+ PluginOptimisticUpdateAction &
+ PluginTypesAction &
+ PluginWorkflowAction &
+ PluginInternalsAction;
/**
* Combined plugin action interface
* Aggregates all plugin-related actions
*/
-export interface ChatPluginAction
- extends
- PluginPublicApiAction,
- PluginOptimisticUpdateAction,
- PluginTypesAction,
- PluginWorkflowAction,
- PluginInternalsAction {
- /**/
-}
/**
* Combined plugin action creator
@@ -34,10 +32,15 @@ export const chatPlugin: StateCreator<
[['zustand/devtools', never]],
[],
ChatPluginAction
-> = (...params) => ({
- ...pluginPublicApi(...params),
- ...pluginOptimisticUpdate(...params),
- ...pluginTypes(...params),
- ...pluginWorkflow(...params),
- ...pluginInternals(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatPluginAction>
+ >
+) =>
+ flattenActions<ChatPluginAction>([
+ new PluginPublicApiActionImpl(...params),
+ new PluginOptimisticUpdateActionImpl(...params),
+ new PluginTypesActionImpl(...params),
+ new PluginWorkflowActionImpl(...params),
+ new PluginInternalsActionImpl(...params),
+ ]);
diff --git a/src/store/chat/slices/plugin/actions/internals.ts b/src/store/chat/slices/plugin/actions/internals.ts
index 3c07b91571f..36fefd17d7b 100644
--- a/src/store/chat/slices/plugin/actions/internals.ts
+++ b/src/store/chat/slices/plugin/actions/internals.ts
@@ -2,7 +2,6 @@
import { ToolArgumentsRepairer, ToolNameResolver } from '@lobechat/context-engine';
import { type ChatToolPayload, type MessageToolCall } from '@lobechat/types';
import { type LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
-import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
import { useToolStore } from '@/store/tool';
@@ -11,26 +10,29 @@ import {
lobehubSkillStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { type StoreSetter } from '@/store/types';
import { builtinTools } from '@/tools';
/**
* Internal utility methods and runtime state management
* These are building blocks used by other actions
*/
-export interface PluginInternalsAction {
- /**
- * Transform tool calls from runtime format to storage format
- */
- internal_transformToolCalls: (toolCalls: MessageToolCall[]) => ChatToolPayload[];
-}
-export const pluginInternals: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- PluginInternalsAction
-> = () => ({
- internal_transformToolCalls: (toolCalls) => {
+type Setter = StoreSetter<ChatStore>;
+export const pluginInternals = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new PluginInternalsActionImpl(set, get, _api);
+
+export class PluginInternalsActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ internal_transformToolCalls = (toolCalls: MessageToolCall[]): ChatToolPayload[] => {
const toolNameResolver = new ToolNameResolver();
// Build manifests map from tool store
@@ -91,5 +93,10 @@ export const pluginInternals: StateCreator<
source: sourceMap[payload.identifier],
};
});
- },
-});
+ };
+}
+
+export type PluginInternalsAction = Pick<
+ PluginInternalsActionImpl,
+ keyof PluginInternalsActionImpl
+>;
diff --git a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
index d28cdc5af32..47d1f5e71d9 100644
--- a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
+++ b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
@@ -6,11 +6,11 @@ import {
type MessagePluginItem,
} from '@lobechat/types';
import isEqual from 'fast-deep-equal';
-import { type StateCreator } from 'zustand/vanilla';
import { messageService } from '@/services/message';
import { type OptimisticUpdateContext } from '@/store/chat/slices/message/actions/optimisticUpdate';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { merge } from '@/utils/merge';
import { safeParseJSON } from '@/utils/safeParseJSON';
@@ -34,92 +34,30 @@ export interface UpdateToolMessageParams {
* Optimistic update operations for plugin-related data
* All methods follow the pattern: update frontend first, then persist to database
*/
-export interface PluginOptimisticUpdateAction {
- /**
- * Update plugin state with optimistic update
- */
- optimisticUpdatePluginState: (
- id: string,
- value: any,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
- /**
- * Update plugin arguments with optimistic update
- */
- optimisticUpdatePluginArguments: <T = any>(
- id: string,
- value: T,
- replace?: boolean,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * Update plugin with optimistic update (generic method for any plugin field)
- */
- optimisticUpdatePlugin: (
- id: string,
- value: Partial<MessagePluginItem>,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
+type Setter = StoreSetter<ChatStore>;
+export const pluginOptimisticUpdate = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new PluginOptimisticUpdateActionImpl(set, get, _api);
- /**
- * Add tool to assistant message with optimistic update
- */
- optimisticAddToolToAssistantMessage: (
- id: string,
- tool: ChatToolPayload,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * Remove tool from assistant message with optimistic update
- */
- optimisticRemoveToolFromAssistantMessage: (
- id: string,
- tool_call_id?: string,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * Update plugin error with optimistic update
- */
- optimisticUpdatePluginError: (
- id: string,
- error: ChatMessageError,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
+export class PluginOptimisticUpdateActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
- /**
- * Use the optimistic update value to update the message tools to database
- */
- internal_refreshToUpdateMessageTools: (
- id: string,
- context?: OptimisticUpdateContext,
- ) => Promise<void>;
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- /**
- * Batch update tool message content, state, and error in a single call
- * This is optimized for builtin tool executors to reduce multiple update calls
- */
- optimisticUpdateToolMessage: (
+ optimisticUpdatePluginState = async (
id: string,
- params: UpdateToolMessageParams,
+ value: any,
context?: OptimisticUpdateContext,
- ) => Promise<void>;
-}
-
-export const pluginOptimisticUpdate: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- PluginOptimisticUpdateAction
-> = (set, get) => ({
- optimisticUpdatePluginState: async (id, value, context) => {
- const { replaceMessages, internal_getConversationContext } = get();
+ ): Promise<void> => {
+ const { replaceMessages, internal_getConversationContext } = this.#get();
// optimistic update
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{ id, type: 'updateMessage', value: { pluginState: value } },
context,
);
@@ -130,16 +68,21 @@ export const pluginOptimisticUpdate: StateCreator<
if (result?.success && result.messages) {
replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticUpdatePluginArguments: async (id, value, replace = false, context) => {
- const { refreshMessages } = get();
- const toolMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
+ optimisticUpdatePluginArguments = async <T = any>(
+ id: string,
+ value: T,
+ replace = false,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { refreshMessages } = this.#get();
+ const toolMessage = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!toolMessage || !toolMessage?.tool_call_id) return;
let assistantMessage = displayMessageSelectors.getDisplayMessageById(
toolMessage?.parentId || '',
- )(get());
+ )(this.#get());
const prevArguments = toolMessage?.plugin?.arguments;
const prevJson = safeParseJSON(prevArguments || '');
@@ -147,14 +90,14 @@ export const pluginOptimisticUpdate: StateCreator<
if (isEqual(prevJson, nextValue)) return;
// optimistic update
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{ id, type: 'updateMessagePlugin', value: { arguments: JSON.stringify(nextValue) } },
context,
);
// 同样需要更新 assistantMessage 的 pluginArguments
if (assistantMessage) {
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{
id: assistantMessage.id,
type: 'updateMessageTools',
@@ -163,12 +106,14 @@ export const pluginOptimisticUpdate: StateCreator<
},
context,
);
- assistantMessage = displayMessageSelectors.getDisplayMessageById(assistantMessage?.id)(get());
+ assistantMessage = displayMessageSelectors.getDisplayMessageById(assistantMessage?.id)(
+ this.#get(),
+ );
}
const updateAssistantMessage = async () => {
if (!assistantMessage) return;
- await messageService.updateMessage(assistantMessage!.id, {
+ await messageService.updateMessage(assistantMessage.id, {
tools: assistantMessage?.tools,
});
};
@@ -179,13 +124,17 @@ export const pluginOptimisticUpdate: StateCreator<
]);
await refreshMessages();
- },
+ };
- optimisticUpdatePlugin: async (id, value, context) => {
- const { replaceMessages, internal_getConversationContext } = get();
+ optimisticUpdatePlugin = async (
+ id: string,
+ value: Partial<MessagePluginItem>,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { replaceMessages, internal_getConversationContext } = this.#get();
// optimistic update
- get().internal_dispatchMessage(
+ this.#get().internal_dispatchMessage(
{
id,
type: 'updateMessagePlugin',
@@ -200,13 +149,17 @@ export const pluginOptimisticUpdate: StateCreator<
if (result?.success && result.messages) {
replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticAddToolToAssistantMessage: async (id, tool, context) => {
- const assistantMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
+ optimisticAddToolToAssistantMessage = async (
+ id: string,
+ tool: ChatToolPayload,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const assistantMessage = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!assistantMessage) return;
- const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = get();
+ const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = this.#get();
internal_dispatchMessage(
{
type: 'addMessageTool',
@@ -217,40 +170,51 @@ export const pluginOptimisticUpdate: StateCreator<
);
await internal_refreshToUpdateMessageTools(id, context);
- },
+ };
- optimisticRemoveToolFromAssistantMessage: async (id, tool_call_id, context) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ optimisticRemoveToolFromAssistantMessage = async (
+ id: string,
+ tool_call_id?: string,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message || !tool_call_id) return;
- const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = get();
+ const { internal_dispatchMessage, internal_refreshToUpdateMessageTools } = this.#get();
// optimistic update
internal_dispatchMessage({ type: 'deleteMessageTool', tool_call_id, id: message.id }, context);
// update the message tools
await internal_refreshToUpdateMessageTools(id, context);
- },
+ };
- optimisticUpdatePluginError: async (id, error, context) => {
- const { replaceMessages, internal_getConversationContext } = get();
+ optimisticUpdatePluginError = async (
+ id: string,
+ error: ChatMessageError,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { replaceMessages, internal_getConversationContext } = this.#get();
- get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } }, context);
+ this.#get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } }, context);
const ctx = internal_getConversationContext(context);
const result = await messageService.updateMessage(id, { error }, ctx);
if (result?.success && result.messages) {
replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- internal_refreshToUpdateMessageTools: async (id, context) => {
+ internal_refreshToUpdateMessageTools = async (
+ id: string,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
const { dbMessageSelectors } = await import('../../message/selectors');
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message || !message.tools) return;
const { internal_toggleMessageLoading, replaceMessages, internal_getConversationContext } =
- get();
+ this.#get();
const ctx = internal_getConversationContext(context);
@@ -261,10 +225,15 @@ export const pluginOptimisticUpdate: StateCreator<
if (result?.success && result.messages) {
replaceMessages(result.messages, { context: ctx });
}
- },
+ };
- optimisticUpdateToolMessage: async (id, params, context) => {
- const { replaceMessages, internal_getConversationContext, internal_dispatchMessage } = get();
+ optimisticUpdateToolMessage = async (
+ id: string,
+ params: UpdateToolMessageParams,
+ context?: OptimisticUpdateContext,
+ ): Promise<void> => {
+ const { replaceMessages, internal_getConversationContext, internal_dispatchMessage } =
+ this.#get();
const { content, metadata, pluginState, pluginError } = params;
@@ -294,5 +263,10 @@ export const pluginOptimisticUpdate: StateCreator<
if (result?.success && result.messages) {
replaceMessages(result.messages, { context: ctx });
}
- },
-});
+ };
+}
+
+export type PluginOptimisticUpdateAction = Pick<
+ PluginOptimisticUpdateActionImpl,
+ keyof PluginOptimisticUpdateActionImpl
+>;
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 2a13061e958..448c3911bfa 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -3,7 +3,6 @@ import { type ChatToolPayload, type RuntimeStepContext } from '@lobechat/types';
import { PluginErrorType } from '@lobehub/chat-plugin-sdk';
import debug from 'debug';
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { type MCPToolCallResult } from '@/libs/mcp';
import { truncateToolResult } from '@/server/utils/truncateToolResult';
@@ -14,6 +13,7 @@ import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation';
import { type ChatStore } from '@/store/chat/store';
import { useToolStore } from '@/store/tool';
import { hasExecutor } from '@/store/tool/slices/builtin/executors';
+import { type StoreSetter } from '@/store/types';
import { safeParseJSON } from '@/utils/safeParseJSON';
import { dbMessageSelectors } from '../../message/selectors';
@@ -25,85 +25,34 @@ const log = debug('lobe-store:plugin-types');
* Plugin type-specific implementations
* Each method handles a specific type of plugin invocation
*/
-export interface PluginTypesAction {
- /**
- * Invoke builtin tool
- *
- * @param id - Tool message ID
- * @param payload - Tool call payload
- * @param stepContext - Optional step context with dynamic state like GTD todos
- * @returns The tool execution result (including stop flag for flow control)
- */
- invokeBuiltinTool: (
+
+type Setter = StoreSetter<ChatStore>;
+export const pluginTypes = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new PluginTypesActionImpl(set, get, _api);
+
+export class PluginTypesActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ invokeBuiltinTool = async (
id: string,
payload: ChatToolPayload,
stepContext?: RuntimeStepContext,
- ) => Promise<any>;
-
- /**
- * Invoke default type plugin (returns data)
- */
- invokeDefaultTypePlugin: (id: string, payload: any) => Promise<string | undefined>;
-
- /**
- * Invoke Klavis type plugin
- */
- invokeKlavisTypePlugin: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
-
- /**
- * Invoke LobeHub Skill type plugin
- */
- invokeLobehubSkillTypePlugin: (
- id: string,
- payload: ChatToolPayload,
- ) => Promise<string | undefined>;
-
- /**
- * Invoke markdown type plugin
- */
- invokeMarkdownTypePlugin: (id: string, payload: ChatToolPayload) => Promise<void>;
-
- /**
- * Invoke MCP type plugin
- */
- invokeMCPTypePlugin: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
-
- /**
- * Invoke standalone type plugin
- */
- invokeStandaloneTypePlugin: (id: string, payload: ChatToolPayload) => Promise<void>;
-
- /**
- * Internal method to call plugin API
- */
- internal_callPluginApi: (id: string, payload: ChatToolPayload) => Promise<string | undefined>;
-
- /**
- * Internal unified method to invoke remote tool plugins (Klavis, LobeHub Skill, etc.)
- */
- internal_invokeRemoteToolPlugin: (
- id: string,
- payload: ChatToolPayload,
- executor: RemoteToolExecutor,
- logPrefix: string,
- ) => Promise<string | undefined>;
-}
-
-export const pluginTypes: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- PluginTypesAction
-> = (set, get) => ({
- invokeBuiltinTool: async (id, payload, stepContext) => {
+ ): Promise<any> => {
// Check if this is a Klavis tool by source field
if (payload.source === 'klavis') {
- return await get().invokeKlavisTypePlugin(id, payload);
+ return await this.#get().invokeKlavisTypePlugin(id, payload);
}
// Check if this is a LobeHub Skill tool by source field
if (payload.source === 'lobehubSkill') {
- return await get().invokeLobehubSkillTypePlugin(id, payload);
+ return await this.#get().invokeLobehubSkillTypePlugin(id, payload);
}
const params = safeParseJSON(payload.arguments);
@@ -111,11 +60,11 @@ export const pluginTypes: StateCreator<
// Check if there's a registered executor in Tool Store (new architecture)
if (hasExecutor(payload.identifier, payload.apiName)) {
- const { optimisticUpdateToolMessage, registerAfterCompletionCallback } = get();
+ const { optimisticUpdateToolMessage, registerAfterCompletionCallback } = this.#get();
// Get operation context
- const operationId = get().messageOperationMap[id];
- const operation = operationId ? get().operations[operationId] : undefined;
+ const operationId = this.#get().messageOperationMap[id];
+ const operation = operationId ? this.#get().operations[operationId] : undefined;
const context = operationId ? { operationId } : undefined;
// Get agent ID, group ID, and topic ID from operation context
@@ -127,7 +76,7 @@ export const pluginTypes: StateCreator<
// This is needed because AgentBuilderProvider uses a separate scope for messages
// but the tools need the correct agentId for execution
if (payload.identifier === 'lobe-agent-builder') {
- const activeAgentId = get().activeAgentId;
+ const activeAgentId = this.#get().activeAgentId;
if (activeAgentId) {
agentId = activeAgentId;
}
@@ -142,7 +91,7 @@ export const pluginTypes: StateCreator<
}
// Get group orchestration callbacks if available (for group management tools)
- const groupOrchestration = get().getGroupOrchestrationCallbacks?.();
+ const groupOrchestration = this.#get().getGroupOrchestrationCallbacks?.();
// Find root execAgentRuntime operation for registering afterCompletion callbacks
// Navigate up the operation tree to find the root runtime operation
@@ -156,7 +105,7 @@ export const pluginTypes: StateCreator<
}
// Move up to parent operation
const parentId = currentOp.parentOperationId;
- currentOp = parentId ? get().operations[parentId] : undefined;
+ currentOp = parentId ? this.#get().operations[parentId] : undefined;
}
}
@@ -228,50 +177,56 @@ export const pluginTypes: StateCreator<
`[invokeBuiltinTool] No executor found for: ${payload.identifier}/${payload.apiName}`,
);
return;
- },
+ };
- invokeDefaultTypePlugin: async (id, payload) => {
- const { internal_callPluginApi } = get();
+ invokeDefaultTypePlugin = async (id: string, payload: any): Promise<string | undefined> => {
+ const { internal_callPluginApi } = this.#get();
const data = await internal_callPluginApi(id, payload);
if (!data) return;
return data;
- },
+ };
- invokeKlavisTypePlugin: async (id, payload) => {
- return get().internal_invokeRemoteToolPlugin(
+ invokeKlavisTypePlugin = async (
+ id: string,
+ payload: ChatToolPayload,
+ ): Promise<string | undefined> => {
+ return this.#get().internal_invokeRemoteToolPlugin(
id,
payload,
klavisExecutor,
'invokeKlavisTypePlugin',
);
- },
+ };
- invokeLobehubSkillTypePlugin: async (id, payload) => {
- return get().internal_invokeRemoteToolPlugin(
+ invokeLobehubSkillTypePlugin = async (
+ id: string,
+ payload: ChatToolPayload,
+ ): Promise<string | undefined> => {
+ return this.#get().internal_invokeRemoteToolPlugin(
id,
payload,
lobehubSkillExecutor,
'invokeLobehubSkillTypePlugin',
);
- },
+ };
- invokeMarkdownTypePlugin: async (id, payload) => {
- const { internal_callPluginApi } = get();
+ invokeMarkdownTypePlugin = async (id: string, payload: ChatToolPayload): Promise<void> => {
+ const { internal_callPluginApi } = this.#get();
await internal_callPluginApi(id, payload);
- },
+ };
- invokeStandaloneTypePlugin: async (id, payload) => {
+ invokeStandaloneTypePlugin = async (id: string, payload: ChatToolPayload): Promise<void> => {
const result = await useToolStore.getState().validatePluginSettings(payload.identifier);
if (!result) return;
// if the plugin settings is not valid, then set the message with error type
if (!result.valid) {
// Get message to extract agentId/topicId
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
const updateResult = await messageService.updateMessageError(
id,
{
@@ -289,23 +244,26 @@ export const pluginTypes: StateCreator<
);
if (updateResult?.success && updateResult.messages) {
- get().replaceMessages(updateResult.messages, {
+ this.#get().replaceMessages(updateResult.messages, {
context: { agentId: message?.agentId || '', topicId: message?.topicId },
});
}
return;
}
- },
+ };
- invokeMCPTypePlugin: async (id, payload) => {
+ invokeMCPTypePlugin = async (
+ id: string,
+ payload: ChatToolPayload,
+ ): Promise<string | undefined> => {
let data: MCPToolCallResult | undefined;
// Get message to extract agentId/topicId
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
// Get abort controller from operation
- const operationId = get().messageOperationMap[id];
- const operation = operationId ? get().operations[operationId] : undefined;
+ const operationId = this.#get().messageOperationMap[id];
+ const operation = operationId ? this.#get().operations[operationId] : undefined;
const abortController = operation?.abortController;
log(
@@ -336,7 +294,7 @@ export const pluginTypes: StateCreator<
topicId: message?.topicId,
});
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, {
+ this.#get().replaceMessages(result.messages, {
context: { agentId: message?.agentId || '', topicId: message?.topicId },
});
}
@@ -354,7 +312,7 @@ export const pluginTypes: StateCreator<
const context = operationId ? { operationId } : undefined;
// Use optimisticUpdateToolMessage to update content and state/error in a single call
- await get().optimisticUpdateToolMessage(
+ await this.#get().optimisticUpdateToolMessage(
id,
{
content: truncatedContent,
@@ -365,17 +323,22 @@ export const pluginTypes: StateCreator<
);
return truncatedContent;
- },
+ };
- internal_invokeRemoteToolPlugin: async (id, payload, executor, logPrefix) => {
+ internal_invokeRemoteToolPlugin = async (
+ id: string,
+ payload: ChatToolPayload,
+ executor: RemoteToolExecutor,
+ logPrefix: string,
+ ): Promise<string | undefined> => {
let data: MCPToolCallResult | undefined;
// Get message to extract sessionId/topicId
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
// Get abort controller from operation
- const operationId = get().messageOperationMap[id];
- const operation = operationId ? get().operations[operationId] : undefined;
+ const operationId = this.#get().messageOperationMap[id];
+ const operation = operationId ? this.#get().operations[operationId] : undefined;
const abortController = operation?.abortController;
log(
@@ -402,7 +365,7 @@ export const pluginTypes: StateCreator<
topicId: message?.topicId,
});
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, {
+ this.#get().replaceMessages(result.messages, {
context: {
agentId: message?.agentId,
topicId: message?.topicId,
@@ -418,7 +381,7 @@ export const pluginTypes: StateCreator<
const context = operationId ? { operationId } : undefined;
// Use optimisticUpdateToolMessage to update content and state/error in a single call
- await get().optimisticUpdateToolMessage(
+ await this.#get().optimisticUpdateToolMessage(
id,
{
content: data.content,
@@ -429,18 +392,21 @@ export const pluginTypes: StateCreator<
);
return data.content;
- },
+ };
- internal_callPluginApi: async (id, payload) => {
- const { optimisticUpdateMessageContent } = get();
+ internal_callPluginApi = async (
+ id: string,
+ payload: ChatToolPayload,
+ ): Promise<string | undefined> => {
+ const { optimisticUpdateMessageContent } = this.#get();
let data: string;
// Get message to extract agentId/topicId
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
// Get abort controller from operation
- const operationId = get().messageOperationMap[id];
- const operation = operationId ? get().operations[operationId] : undefined;
+ const operationId = this.#get().messageOperationMap[id];
+ const operation = operationId ? this.#get().operations[operationId] : undefined;
const abortController = operation?.abortController;
log(
@@ -479,7 +445,7 @@ export const pluginTypes: StateCreator<
topicId: message?.topicId,
});
if (result?.success && result.messages) {
- get().replaceMessages(result.messages, {
+ this.#get().replaceMessages(result.messages, {
context: { agentId: message?.agentId || '', topicId: message?.topicId },
});
}
@@ -496,5 +462,7 @@ export const pluginTypes: StateCreator<
await optimisticUpdateMessageContent(id, data, undefined, context);
return data;
- },
-});
+ };
+}
+
+export type PluginTypesAction = Pick<PluginTypesActionImpl, keyof PluginTypesActionImpl>;
diff --git a/src/store/chat/slices/plugin/actions/publicApi.ts b/src/store/chat/slices/plugin/actions/publicApi.ts
index 52bdf0ac8c9..43a321d92a3 100644
--- a/src/store/chat/slices/plugin/actions/publicApi.ts
+++ b/src/store/chat/slices/plugin/actions/publicApi.ts
@@ -1,9 +1,9 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { type ChatToolPayload, type RuntimeStepContext, type UIChatMessage } from '@lobechat/types';
import i18n from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { type OptimisticUpdateContext } from '../../message/actions/optimisticUpdate';
import { displayMessageSelectors } from '../../message/selectors';
@@ -12,85 +12,59 @@ import { displayMessageSelectors } from '../../message/selectors';
* Public API for plugin operations
* These methods are called by UI components or other business scenarios
*/
-export interface PluginPublicApiAction {
- /**
- * Fill plugin message content and optionally trigger AI message
- * @param id - message id
- * @param content - content to fill
- * @param triggerAiMessage - whether to trigger AI message
- * @param context - Optional context for optimistic update (required for Group mode)
- */
- fillPluginMessageContent: (
+
+type Setter = StoreSetter<ChatStore>;
+export const pluginPublicApi = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new PluginPublicApiActionImpl(set, get, _api);
+
+export class PluginPublicApiActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ fillPluginMessageContent = async (
id: string,
content: string,
triggerAiMessage?: boolean,
context?: OptimisticUpdateContext,
- ) => Promise<void>;
-
- /**
- * Re-invoke a tool message (retry failed plugin call)
- */
- reInvokeToolMessage: (id: string) => Promise<void>;
-
- /**
- * Summary plugin content using AI
- */
- summaryPluginContent: (id: string) => Promise<void>;
-
- /**
- * Invoke different type of plugin based on payload type
- * This is the unified entry point for plugin invocation
- *
- * @param id - Tool message ID
- * @param payload - Tool call payload
- * @param stepContext - Optional step context with dynamic state like GTD todos
- */
- internal_invokeDifferentTypePlugin: (
- id: string,
- payload: ChatToolPayload,
- stepContext?: RuntimeStepContext,
- ) => Promise<any>;
-}
-
-export const pluginPublicApi: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- PluginPublicApiAction
-> = (set, get) => ({
- fillPluginMessageContent: async (id, content, triggerAiMessage, context) => {
- const { triggerAIMessage, optimisticUpdateMessageContent } = get();
+ ): Promise<void> => {
+ const { triggerAIMessage, optimisticUpdateMessageContent } = this.#get();
await optimisticUpdateMessageContent(id, content, undefined, context);
if (triggerAiMessage) await triggerAIMessage({ parentId: id });
- },
+ };
- reInvokeToolMessage: async (id) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ reInvokeToolMessage = async (id: string): Promise<void> => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message || message.role !== 'tool' || !message.plugin) return;
// Get operationId from messageOperationMap
- const operationId = get().messageOperationMap[id];
+ const operationId = this.#get().messageOperationMap[id];
const context = operationId ? { operationId } : undefined;
// if there is error content, then clear the error
if (!!message.pluginError) {
- get().optimisticUpdateMessagePluginError(id, null, context);
+ this.#get().optimisticUpdateMessagePluginError(id, null, context);
}
const payload: ChatToolPayload = { ...message.plugin, id: message.tool_call_id! };
- await get().internal_invokeDifferentTypePlugin(id, payload);
- },
+ await this.#get().internal_invokeDifferentTypePlugin(id, payload);
+ };
- summaryPluginContent: async (id) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
+ summaryPluginContent = async (id: string): Promise<void> => {
+ const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message || message.role !== 'tool') return;
- const { activeAgentId, activeTopicId, activeThreadId } = get();
+ const { activeAgentId, activeTopicId, activeThreadId } = this.#get();
- await get().internal_execAgentRuntime({
+ await this.#get().internal_execAgentRuntime({
context: {
agentId: activeAgentId,
topicId: activeTopicId,
@@ -112,31 +86,40 @@ export const pluginPublicApi: StateCreator<
parentMessageId: message.id,
parentMessageType: 'assistant',
});
- },
+ };
- internal_invokeDifferentTypePlugin: async (id, payload, stepContext) => {
+ internal_invokeDifferentTypePlugin = async (
+ id: string,
+ payload: ChatToolPayload,
+ stepContext?: RuntimeStepContext,
+ ): Promise<any> => {
switch (payload.type) {
case 'standalone': {
- return await get().invokeStandaloneTypePlugin(id, payload);
+ return await this.#get().invokeStandaloneTypePlugin(id, payload);
}
case 'markdown': {
- return await get().invokeMarkdownTypePlugin(id, payload);
+ return await this.#get().invokeMarkdownTypePlugin(id, payload);
}
case 'builtin': {
// Pass stepContext to builtin tools for dynamic state access
- return await get().invokeBuiltinTool(id, payload, stepContext);
+ return await this.#get().invokeBuiltinTool(id, payload, stepContext);
}
// @ts-ignore
case 'mcp': {
- return await get().invokeMCPTypePlugin(id, payload);
+ return await this.#get().invokeMCPTypePlugin(id, payload);
}
default: {
- return await get().invokeDefaultTypePlugin(id, payload);
+ return await this.#get().invokeDefaultTypePlugin(id, payload);
}
}
- },
-});
+ };
+}
+
+export type PluginPublicApiAction = Pick<
+ PluginPublicApiActionImpl,
+ keyof PluginPublicApiActionImpl
+>;
diff --git a/src/store/chat/slices/plugin/actions/workflow.ts b/src/store/chat/slices/plugin/actions/workflow.ts
index 0b87f2c4cfe..f8bdf899540 100644
--- a/src/store/chat/slices/plugin/actions/workflow.ts
+++ b/src/store/chat/slices/plugin/actions/workflow.ts
@@ -1,9 +1,9 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { type CreateMessageParams } from '@lobechat/types';
-import { type StateCreator } from 'zustand/vanilla';
import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { dbMessageSelectors, displayMessageSelectors } from '../../message/selectors';
import { threadSelectors } from '../../thread/selectors';
@@ -12,54 +12,56 @@ import { threadSelectors } from '../../thread/selectors';
* Workflow orchestration actions
* Handle complex business flows involving multiple steps
*/
-export interface PluginWorkflowAction {
- /**
- * Create an assistant message by plugin result
- */
- createAssistantMessageByPlugin: (content: string, parentId: string) => Promise<void>;
- /**
- * Trigger AI message after tool calls
- */
- triggerAIMessage: (params: {
- parentId?: string;
- traceId?: string;
- threadId?: string;
- inPortalThread?: boolean;
- inSearchWorkflow?: boolean;
- }) => Promise<void>;
-}
+type Setter = StoreSetter<ChatStore>;
+export const pluginWorkflow = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new PluginWorkflowActionImpl(set, get, _api);
+
+export class PluginWorkflowActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const pluginWorkflow: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- PluginWorkflowAction
-> = (set, get) => ({
- createAssistantMessageByPlugin: async (content, parentId) => {
+ createAssistantMessageByPlugin = async (content: string, parentId: string): Promise<void> => {
// Get parent message to extract agentId/topicId
- const parentMessage = dbMessageSelectors.getDbMessageById(parentId)(get());
+ const parentMessage = dbMessageSelectors.getDbMessageById(parentId)(this.#get());
const newMessage: CreateMessageParams = {
content,
parentId,
role: 'assistant',
- agentId: parentMessage?.agentId ?? get().activeAgentId,
- topicId: parentMessage?.topicId !== undefined ? parentMessage.topicId : get().activeTopicId,
+ agentId: parentMessage?.agentId ?? this.#get().activeAgentId,
+ topicId:
+ parentMessage?.topicId !== undefined ? parentMessage.topicId : this.#get().activeTopicId,
};
const result = await messageService.createMessage(newMessage);
- get().replaceMessages(result.messages, {
+ this.#get().replaceMessages(result.messages, {
context: { agentId: newMessage.agentId, topicId: newMessage.topicId },
});
- },
+ };
- triggerAIMessage: async ({ parentId, threadId, inPortalThread, inSearchWorkflow }) => {
- const { internal_execAgentRuntime, activeAgentId, activeTopicId } = get();
+ triggerAIMessage = async ({
+ parentId,
+ threadId,
+ inPortalThread,
+ inSearchWorkflow,
+ }: {
+ parentId?: string;
+ threadId?: string;
+ inPortalThread?: boolean;
+ inSearchWorkflow?: boolean;
+ } = {}): Promise<void> => {
+ const { internal_execAgentRuntime, activeAgentId, activeTopicId } = this.#get();
const chats = inPortalThread
- ? threadSelectors.portalAIChatsWithHistoryConfig(get())
- : displayMessageSelectors.mainAIChatsWithHistoryConfig(get());
+ ? threadSelectors.portalAIChatsWithHistoryConfig(this.#get())
+ : displayMessageSelectors.mainAIChatsWithHistoryConfig(this.#get());
await internal_execAgentRuntime({
context: {
@@ -73,5 +75,7 @@ export const pluginWorkflow: StateCreator<
inPortalThread,
inSearchWorkflow,
});
- },
-});
+ };
+}
+
+export type PluginWorkflowAction = Pick<PluginWorkflowActionImpl, keyof PluginWorkflowActionImpl>;
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index bc94d288927..9c5751735a4 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -1,99 +1,81 @@
-import { type StateCreator } from 'zustand/vanilla';
-
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { type PortalArtifact } from '@/types/artifact';
import { type PortalFile, type PortalViewData, PortalViewType } from './initialState';
-export interface ChatPortalAction {
- // ============== Core Stack Operations ==============
- clearPortalStack: () => void;
- // ============== Convenience Methods ==============
- closeArtifact: () => void;
- closeDocument: () => void;
- closeFilePreview: () => void;
- closeMessageDetail: () => void;
- closeNotebook: () => void;
-
- closeToolUI: () => void;
- goBack: () => void;
- goHome: () => void;
- openArtifact: (artifact: PortalArtifact) => void;
- openDocument: (documentId: string) => void;
- openFilePreview: (file: PortalFile) => void;
- openMessageDetail: (messageId: string) => void;
- openNotebook: () => void;
- openToolUI: (messageId: string, identifier: string) => void;
- popPortalView: () => void;
- pushPortalView: (view: PortalViewData) => void;
- replacePortalView: (view: PortalViewData) => void;
- toggleNotebook: (open?: boolean) => void;
-}
-
// Helper to get current view type from stack
const getCurrentViewType = (portalStack: PortalViewData[]): PortalViewType | null => {
const top = portalStack.at(-1);
return top?.type ?? null;
};
-export const chatPortalSlice: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatPortalAction
-> = (set, get) => ({
- clearPortalStack: () => {
- set({ portalStack: [], showPortal: false }, false, 'clearPortalStack');
- },
-
- closeArtifact: () => {
- const { portalStack } = get();
+type Setter = StoreSetter<ChatStore>;
+export const chatPortalSlice = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatPortalActionImpl(set, get, _api);
+
+export class ChatPortalActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ clearPortalStack = (): void => {
+ this.#set({ portalStack: [], showPortal: false }, false, 'clearPortalStack');
+ };
+
+ closeArtifact = (): void => {
+ const { portalStack } = this.#get();
if (getCurrentViewType(portalStack) === PortalViewType.Artifact) {
- get().popPortalView();
+ this.#get().popPortalView();
}
- },
+ };
- closeDocument: () => {
- const { portalStack } = get();
+ closeDocument = (): void => {
+ const { portalStack } = this.#get();
if (getCurrentViewType(portalStack) === PortalViewType.Document) {
- get().popPortalView();
+ this.#get().popPortalView();
}
- },
+ };
- closeFilePreview: () => {
- const { portalStack } = get();
+ closeFilePreview = (): void => {
+ const { portalStack } = this.#get();
if (getCurrentViewType(portalStack) === PortalViewType.FilePreview) {
- get().popPortalView();
+ this.#get().popPortalView();
}
- },
+ };
- closeMessageDetail: () => {
- const { portalStack } = get();
+ closeMessageDetail = (): void => {
+ const { portalStack } = this.#get();
if (getCurrentViewType(portalStack) === PortalViewType.MessageDetail) {
- get().popPortalView();
+ this.#get().popPortalView();
}
- },
+ };
- closeNotebook: () => {
- const { portalStack } = get();
+ closeNotebook = (): void => {
+ const { portalStack } = this.#get();
if (getCurrentViewType(portalStack) === PortalViewType.Notebook) {
- get().popPortalView();
+ this.#get().popPortalView();
}
- },
+ };
- closeToolUI: () => {
- const { portalStack } = get();
+ closeToolUI = (): void => {
+ const { portalStack } = this.#get();
if (getCurrentViewType(portalStack) === PortalViewType.ToolUI) {
- get().popPortalView();
+ this.#get().popPortalView();
}
- },
+ };
- goBack: () => {
- get().popPortalView();
- },
+ goBack = (): void => {
+ this.#get().popPortalView();
+ };
- goHome: () => {
- set(
+ goHome = (): void => {
+ this.#set(
{
portalStack: [{ type: PortalViewType.Home }],
showPortal: true,
@@ -101,52 +83,50 @@ export const chatPortalSlice: StateCreator<
false,
'goHome',
);
- },
+ };
- // ============== Convenience Methods (using stack operations) ==============
- openArtifact: (artifact) => {
- get().pushPortalView({ artifact, type: PortalViewType.Artifact });
- },
+ openArtifact = (artifact: PortalArtifact): void => {
+ this.#get().pushPortalView({ artifact, type: PortalViewType.Artifact });
+ };
- openDocument: (documentId) => {
- get().pushPortalView({ documentId, type: PortalViewType.Document });
- },
+ openDocument = (documentId: string): void => {
+ this.#get().pushPortalView({ documentId, type: PortalViewType.Document });
+ };
- openFilePreview: (file) => {
- get().pushPortalView({ file, type: PortalViewType.FilePreview });
- },
+ openFilePreview = (file: PortalFile): void => {
+ this.#get().pushPortalView({ file, type: PortalViewType.FilePreview });
+ };
- openMessageDetail: (messageId) => {
- get().pushPortalView({ messageId, type: PortalViewType.MessageDetail });
- },
+ openMessageDetail = (messageId: string): void => {
+ this.#get().pushPortalView({ messageId, type: PortalViewType.MessageDetail });
+ };
- openNotebook: () => {
- get().pushPortalView({ type: PortalViewType.Notebook });
- },
+ openNotebook = (): void => {
+ this.#get().pushPortalView({ type: PortalViewType.Notebook });
+ };
- openToolUI: (messageId, identifier) => {
- get().pushPortalView({ identifier, messageId, type: PortalViewType.ToolUI });
- },
+ openToolUI = (messageId: string, identifier: string): void => {
+ this.#get().pushPortalView({ identifier, messageId, type: PortalViewType.ToolUI });
+ };
- popPortalView: () => {
- const { portalStack } = get();
+ popPortalView = (): void => {
+ const { portalStack } = this.#get();
if (portalStack.length <= 1) {
// Stack empty or only one item, clear stack and close portal
- set({ portalStack: [], showPortal: false }, false, 'popPortalView/close');
+ this.#set({ portalStack: [], showPortal: false }, false, 'popPortalView/close');
} else {
- set({ portalStack: portalStack.slice(0, -1) }, false, 'popPortalView');
+ this.#set({ portalStack: portalStack.slice(0, -1) }, false, 'popPortalView');
}
- },
+ };
- // ============== Core Stack Operations ==============
- pushPortalView: (view) => {
- const { portalStack } = get();
+ pushPortalView = (view: PortalViewData): void => {
+ const { portalStack } = this.#get();
const top = portalStack.at(-1);
// If top of stack is same type, replace instead of push (avoid duplicates)
if (top?.type === view.type) {
- set(
+ this.#set(
{
portalStack: [...portalStack.slice(0, -1), view],
showPortal: true,
@@ -155,7 +135,7 @@ export const chatPortalSlice: StateCreator<
'pushPortalView/replace',
);
} else {
- set(
+ this.#set(
{
portalStack: [...portalStack, view],
showPortal: true,
@@ -164,15 +144,15 @@ export const chatPortalSlice: StateCreator<
'pushPortalView',
);
}
- },
+ };
- replacePortalView: (view) => {
- const { portalStack } = get();
+ replacePortalView = (view: PortalViewData): void => {
+ const { portalStack } = this.#get();
if (portalStack.length === 0) {
- set({ portalStack: [view], showPortal: true }, false, 'replacePortalView/push');
+ this.#set({ portalStack: [view], showPortal: true }, false, 'replacePortalView/push');
} else {
- set(
+ this.#set(
{
portalStack: [...portalStack.slice(0, -1), view],
showPortal: true,
@@ -181,17 +161,19 @@ export const chatPortalSlice: StateCreator<
'replacePortalView',
);
}
- },
+ };
- toggleNotebook: (open) => {
- const { portalStack } = get();
+ toggleNotebook = (open?: boolean): void => {
+ const { portalStack } = this.#get();
const isCurrentlyNotebook = getCurrentViewType(portalStack) === PortalViewType.Notebook;
const shouldOpen = open ?? !isCurrentlyNotebook;
if (shouldOpen) {
- get().openNotebook();
+ this.#get().openNotebook();
} else {
- get().closeNotebook();
+ this.#get().closeNotebook();
}
- },
-});
+ };
+}
+
+export type ChatPortalAction = Pick<ChatPortalActionImpl, keyof ChatPortalActionImpl>;
diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.ts
index 3e47fd57062..001e1576bb6 100644
--- a/src/store/chat/slices/thread/action.test.ts
+++ b/src/store/chat/slices/thread/action.test.ts
@@ -353,7 +353,9 @@ describe('thread action', () => {
(threadService.removeThread as Mock).mockResolvedValue(undefined);
- const refreshThreadsSpy = vi.spyOn(result.current, 'refreshThreads').mockResolvedValue();
+ const refreshThreadsSpy = vi
+ .spyOn(result.current, 'refreshThreads')
+ .mockResolvedValue(undefined);
await act(async () => {
await result.current.removeThread('thread-id');
@@ -371,7 +373,7 @@ describe('thread action', () => {
});
(threadService.removeThread as Mock).mockResolvedValue(undefined);
- vi.spyOn(result.current, 'refreshThreads').mockResolvedValue();
+ vi.spyOn(result.current, 'refreshThreads').mockResolvedValue(undefined);
await act(async () => {
await result.current.removeThread('thread-id');
@@ -388,7 +390,7 @@ describe('thread action', () => {
});
(threadService.removeThread as Mock).mockResolvedValue(undefined);
- vi.spyOn(result.current, 'refreshThreads').mockResolvedValue();
+ vi.spyOn(result.current, 'refreshThreads').mockResolvedValue(undefined);
await act(async () => {
await result.current.removeThread('different-thread-id');
@@ -404,7 +406,7 @@ describe('thread action', () => {
const internalUpdateSpy = vi
.spyOn(result.current, 'internal_updateThread')
- .mockResolvedValue();
+ .mockResolvedValue(undefined);
await act(async () => {
await result.current.updateThreadTitle('thread-id', 'New Title');
@@ -462,7 +464,7 @@ describe('thread action', () => {
const internalUpdateSpy = vi
.spyOn(result.current, 'internal_updateThread')
- .mockResolvedValue();
+ .mockResolvedValue(undefined);
await act(async () => {
await result.current.summaryThreadTitle('thread-id', messages);
@@ -507,7 +509,7 @@ describe('thread action', () => {
},
);
- vi.spyOn(result.current, 'internal_updateThread').mockResolvedValue();
+ vi.spyOn(result.current, 'internal_updateThread').mockResolvedValue(undefined);
await act(async () => {
await result.current.summaryThreadTitle('thread-id', []);
@@ -545,7 +547,7 @@ describe('thread action', () => {
await onError?.();
});
- vi.spyOn(result.current, 'internal_updateThread').mockResolvedValue();
+ vi.spyOn(result.current, 'internal_updateThread').mockResolvedValue(undefined);
await act(async () => {
await result.current.summaryThreadTitle('thread-id', []);
@@ -646,7 +648,7 @@ describe('thread action', () => {
(threadService.updateThread as Mock).mockResolvedValue(undefined);
const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchThread');
- const refreshSpy = vi.spyOn(result.current, 'refreshThreads').mockResolvedValue();
+ const refreshSpy = vi.spyOn(result.current, 'refreshThreads').mockResolvedValue(undefined);
const loadingSpy = vi.spyOn(result.current, 'internal_updateThreadLoading');
await act(async () => {
diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.ts
index 9d2af644f19..62519a17c0c 100644
--- a/src/store/chat/slices/thread/action.ts
+++ b/src/store/chat/slices/thread/action.ts
@@ -10,7 +10,6 @@ import {
} from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { chatService } from '@/services/chat';
@@ -18,6 +17,7 @@ import { threadService } from '@/services/thread';
import { threadSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors } from '@/store/user/selectors';
import { merge } from '@/utils/merge';
@@ -31,48 +31,31 @@ import { genParentMessages } from './selectors';
const n = setNamespace('thd');
const SWR_USE_FETCH_THREADS = 'SWR_USE_FETCH_THREADS';
-export interface ChatThreadAction {
- // update
- updateThreadInputMessage: (message: string) => void;
- refreshThreads: () => Promise<void>;
- createThread: (params: {
- message: CreateMessageParams;
- sourceMessageId: string;
- topicId: string;
- type: IThreadType;
- }) => Promise<{ threadId: string; messageId: string }>;
- openThreadCreator: (messageId: string) => void;
- openThreadInPortal: (threadId: string, sourceMessageId?: string | null) => void;
- closeThreadPortal: () => void;
- useFetchThreads: (enable: boolean, topicId?: string) => SWRResponse<ThreadItem[]>;
- summaryThreadTitle: (threadId: string, messages: UIChatMessage[]) => Promise<void>;
- updateThreadTitle: (id: string, title: string) => Promise<void>;
- removeThread: (id: string) => Promise<void>;
- switchThread: (id: string) => void;
-
- internal_updateThreadTitleInSummary: (id: string, title: string) => void;
- internal_updateThreadLoading: (id: string, loading: boolean) => void;
- internal_updateThread: (id: string, data: Partial<ThreadItem>) => Promise<void>;
- internal_dispatchThread: (payload: ThreadDispatch, action?: any) => void;
-}
+type Setter = StoreSetter<ChatStore>;
+export const chatThreadMessage = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatThreadActionImpl(set, get, _api);
-export const chatThreadMessage: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatThreadAction
-> = (set, get) => ({
- updateThreadInputMessage: (message) => {
- if (isEqual(message, get().threadInputMessage)) return;
+export class ChatThreadActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
- set({ threadInputMessage: message }, false, n(`updateThreadInputMessage`, message));
- },
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- openThreadCreator: (messageId) => {
- const { activeAgentId, activeTopicId, newThreadMode, replaceMessages } = get();
+ updateThreadInputMessage = (message: string): void => {
+ if (isEqual(message, this.#get().threadInputMessage)) return;
+
+ this.#set({ threadInputMessage: message }, false, n(`updateThreadInputMessage`, message));
+ };
+
+ openThreadCreator = (messageId: string): void => {
+ const { activeAgentId, activeTopicId, newThreadMode, replaceMessages } = this.#get();
// Get parent messages up to and including the source message
- const displayMessages = displayMessageSelectors.activeDisplayMessages(get());
+ const displayMessages = displayMessageSelectors.activeDisplayMessages(this.#get());
// Filter out messages that have threadId (they belong to other threads)
const mainMessages = displayMessages.filter((m) => !m.threadId);
const parentMessages = genParentMessages(mainMessages, messageId, newThreadMode);
@@ -89,38 +72,50 @@ export const chatThreadMessage: StateCreator<
replaceMessages(parentMessages, { action: 'initThreadMessages', context });
}
- set(
+ this.#set(
{ threadStartMessageId: messageId, portalThreadId: undefined, startToForkThread: true },
false,
'openThreadCreator',
);
// Push Thread view to portal stack instead of togglePortal
- get().pushPortalView({ type: PortalViewType.Thread, startMessageId: messageId });
- },
- openThreadInPortal: (threadId, sourceMessageId) => {
- set(
+ this.#get().pushPortalView({ type: PortalViewType.Thread, startMessageId: messageId });
+ };
+
+ openThreadInPortal = (threadId: string, sourceMessageId?: string | null): void => {
+ this.#set(
{ portalThreadId: threadId, threadStartMessageId: sourceMessageId, startToForkThread: false },
false,
'openThreadInPortal',
);
// Push Thread view to portal stack with threadId
- get().pushPortalView({
+ this.#get().pushPortalView({
type: PortalViewType.Thread,
threadId,
startMessageId: sourceMessageId ?? undefined,
});
- },
+ };
- closeThreadPortal: () => {
- set(
+ closeThreadPortal = (): void => {
+ this.#set(
{ threadStartMessageId: undefined, portalThreadId: undefined, startToForkThread: undefined },
false,
'closeThreadPortal',
);
- get().clearPortalStack();
- },
- createThread: async ({ message, sourceMessageId, topicId, type }) => {
- set({ isCreatingThread: true }, false, n('creatingThread/start'));
+ this.#get().clearPortalStack();
+ };
+
+ createThread = async ({
+ message,
+ sourceMessageId,
+ topicId,
+ type,
+ }: {
+ message: CreateMessageParams;
+ sourceMessageId: string;
+ topicId: string;
+ type: IThreadType;
+ }): Promise<{ threadId: string; messageId: string }> => {
+ this.#set({ isCreatingThread: true }, false, n('creatingThread/start'));
const data = await threadService.createThreadWithMessage({
topicId,
@@ -128,55 +123,59 @@ export const chatThreadMessage: StateCreator<
type,
message,
});
- set({ isCreatingThread: false }, false, n('creatingThread/end'));
+ this.#set({ isCreatingThread: false }, false, n('creatingThread/end'));
return data;
- },
+ };
- useFetchThreads: (enable, topicId) =>
- useClientDataSWR<ThreadItem[]>(
+ useFetchThreads = (enable: boolean, topicId?: string): SWRResponse<ThreadItem[]> => {
+ return useClientDataSWR<ThreadItem[]>(
enable && !!topicId ? [SWR_USE_FETCH_THREADS, topicId] : null,
async ([, topicId]: [string, string]) => threadService.getThreads(topicId),
{
onSuccess: (threads) => {
- const nextMap = { ...get().threadMaps, [topicId!]: threads };
+ const nextMap = { ...this.#get().threadMaps, [topicId!]: threads };
// no need to update map if the threads have been init and the map is the same
- if (get().threadsInit && isEqual(nextMap, get().threadMaps)) return;
+ if (this.#get().threadsInit && isEqual(nextMap, this.#get().threadMaps)) return;
- set(
+ this.#set(
{ threadMaps: nextMap, threadsInit: true },
false,
n('useFetchThreads(success)', { topicId }),
);
},
},
- ),
+ );
+ };
- refreshThreads: async () => {
- const topicId = get().activeTopicId;
+ refreshThreads = async (): Promise<void> => {
+ const topicId = this.#get().activeTopicId;
if (!topicId) return;
return mutate([SWR_USE_FETCH_THREADS, topicId]);
- },
- removeThread: async (id) => {
+ };
+
+ removeThread = async (id: string): Promise<void> => {
await threadService.removeThread(id);
- await get().refreshThreads();
+ await this.#get().refreshThreads();
- if (get().activeThreadId === id) {
- set({ activeThreadId: undefined });
+ if (this.#get().activeThreadId === id) {
+ this.#set({ activeThreadId: undefined });
}
- },
- switchThread: async (id) => {
- set({ activeThreadId: id }, false, n('toggleTopic'));
- },
- updateThreadTitle: async (id, title) => {
- await get().internal_updateThread(id, { title });
- },
-
- summaryThreadTitle: async (threadId, messages) => {
- const { internal_updateThreadTitleInSummary, internal_updateThreadLoading } = get();
- const portalThread = threadSelectors.currentPortalThread(get());
+ };
+
+ switchThread = async (id: string): Promise<void> => {
+ this.#set({ activeThreadId: id }, false, n('toggleTopic'));
+ };
+
+ updateThreadTitle = async (id: string, title: string): Promise<void> => {
+ await this.#get().internal_updateThread(id, { title });
+ };
+
+ summaryThreadTitle = async (threadId: string, messages: UIChatMessage[]): Promise<void> => {
+ const { internal_updateThreadTitleInSummary, internal_updateThreadLoading } = this.#get();
+ const portalThread = threadSelectors.currentPortalThread(this.#get());
if (!portalThread) return;
internal_updateThreadTitleInSummary(threadId, LOADING_FLAT);
@@ -189,7 +188,7 @@ export const chatThreadMessage: StateCreator<
internal_updateThreadTitleInSummary(threadId, portalThread.title);
},
onFinish: async (text) => {
- await get().internal_updateThread(threadId, { title: text });
+ await this.#get().internal_updateThread(threadId, { title: text });
},
onLoadingChange: (loading) => {
internal_updateThreadLoading(threadId, loading);
@@ -205,18 +204,17 @@ export const chatThreadMessage: StateCreator<
},
params: merge(threadConfig, chainSummaryTitle(messages, globalHelpers.getCurrentLanguage())),
});
- },
+ };
- // Internal process method of the topics
- internal_updateThreadTitleInSummary: (id, title) => {
- get().internal_dispatchThread(
+ internal_updateThreadTitleInSummary = (id: string, title: string): void => {
+ this.#get().internal_dispatchThread(
{ type: 'updateThread', id, value: { title } },
'updateThreadTitleInSummary',
);
- },
+ };
- internal_updateThreadLoading: (id, loading) => {
- set(
+ internal_updateThreadLoading = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading) return { threadLoadingIds: [...state.threadLoadingIds, id] };
@@ -225,24 +223,26 @@ export const chatThreadMessage: StateCreator<
false,
n('updateThreadLoading'),
);
- },
+ };
- internal_updateThread: async (id, data) => {
- get().internal_dispatchThread({ type: 'updateThread', id, value: data });
+ internal_updateThread = async (id: string, data: Partial<ThreadItem>): Promise<void> => {
+ this.#get().internal_dispatchThread({ type: 'updateThread', id, value: data });
- get().internal_updateThreadLoading(id, true);
+ this.#get().internal_updateThreadLoading(id, true);
await threadService.updateThread(id, data);
- await get().refreshThreads();
- get().internal_updateThreadLoading(id, false);
- },
+ await this.#get().refreshThreads();
+ this.#get().internal_updateThreadLoading(id, false);
+ };
- internal_dispatchThread: (payload, action) => {
- const nextThreads = threadReducer(threadSelectors.currentTopicThreads(get()), payload);
- const nextMap = { ...get().threadMaps, [get().activeTopicId!]: nextThreads };
+ internal_dispatchThread = (payload: ThreadDispatch, action?: any): void => {
+ const nextThreads = threadReducer(threadSelectors.currentTopicThreads(this.#get()), payload);
+ const nextMap = { ...this.#get().threadMaps, [this.#get().activeTopicId!]: nextThreads };
// no need to update map if is the same
- if (isEqual(nextMap, get().threadMaps)) return;
+ if (isEqual(nextMap, this.#get().threadMaps)) return;
+
+ this.#set({ threadMaps: nextMap }, false, action ?? n(`dispatchThread/${payload.type}`));
+ };
+}
- set({ threadMaps: nextMap }, false, action ?? n(`dispatchThread/${payload.type}`));
- },
-});
+export type ChatThreadAction = Pick<ChatThreadActionImpl, keyof ChatThreadActionImpl>;
diff --git a/src/store/chat/slices/thread/reducer.ts b/src/store/chat/slices/thread/reducer.ts
index 514391f15af..885ade35c89 100644
--- a/src/store/chat/slices/thread/reducer.ts
+++ b/src/store/chat/slices/thread/reducer.ts
@@ -2,16 +2,16 @@ import { produce } from 'immer';
import { type ThreadItem } from '@/types/topic';
-interface UpdateThreadAction {
+type UpdateThreadAction = {
id: string;
type: 'updateThread';
value: Partial<ThreadItem>;
-}
+};
-interface DeleteThreadAction {
+type DeleteThreadAction = {
id: string;
type: 'deleteThread';
-}
+};
export type ThreadDispatch = UpdateThreadAction | DeleteThreadAction;
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 0dddaeed736..198d1f6111f 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -11,7 +11,6 @@ import {
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { message } from '@/components/AntdStaticMethods';
import { LOADING_FLAT } from '@/const/message';
@@ -23,6 +22,7 @@ import type { ChatStore } from '@/store/chat';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { useGlobalStore } from '@/store/global';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors } from '@/store/user/selectors';
import { type ChatTopic, type CreateTopicParams } from '@/types/topic';
@@ -66,95 +66,30 @@ export interface SwitchTopicOptions {
skipRefreshMessage?: boolean;
}
-export interface ChatTopicAction {
- closeAllTopicsDrawer: () => void;
- favoriteTopic: (id: string, favState: boolean) => Promise<void>;
- importTopic: (data: string) => Promise<string | undefined>;
- loadMoreTopics: () => Promise<void>;
- openAllTopicsDrawer: () => void;
- openNewTopicOrSaveTopic: () => Promise<void>;
- refreshTopic: () => Promise<void>;
- removeAllTopics: () => Promise<void>;
- removeSessionTopics: () => Promise<void>;
- removeGroupTopics: (groupId: string) => Promise<void>;
- removeTopic: (id: string) => Promise<void>;
- removeUnstarredTopic: () => Promise<void>;
- saveToTopic: (sessionId?: string) => Promise<string | undefined>;
- createTopic: (sessionId?: string) => Promise<string | undefined>;
-
- autoRenameTopicTitle: (id: string) => Promise<void>;
- duplicateTopic: (id: string) => Promise<void>;
- summaryTopicTitle: (topicId: string, messages: UIChatMessage[]) => Promise<void>;
- /**
- * Switch to a topic or create new topic state
- * @param id - Topic ID to switch to, or null to switch to "new" state (clears _new key data)
- * @param options - Options object for configuring the switch behavior
- */
- switchTopic: (id?: string | null, options?: SwitchTopicOptions) => Promise<void>;
- /**
- * Update topic metadata
- * @param id - Topic ID to update
- * @param metadata - Partial metadata to merge with existing metadata
- */
- updateTopicMetadata: (id: string, metadata: Partial<ChatTopicMetadata>) => Promise<void>;
- updateTopicTitle: (id: string, title: string) => Promise<void>;
- useFetchTopics: (
- enable: boolean,
- params: {
- agentId?: string;
- excludeTriggers?: string[];
- groupId?: string;
- isInbox?: boolean;
- pageSize?: number;
- },
- ) => SWRResponse<{ items: ChatTopic[]; total: number }>;
- useSearchTopics: (
- keywords: string | undefined,
- params: {
- agentId?: string;
- groupId?: string;
- },
- ) => SWRResponse<ChatTopic[]>;
-
- internal_updateTopicTitleInSummary: (id: string, title: string) => void;
- internal_updateTopicLoading: (id: string, loading: boolean) => void;
- internal_createTopic: (params: CreateTopicParams) => Promise<string>;
- internal_updateTopic: (id: string, data: Partial<ChatTopic>) => Promise<void>;
- internal_dispatchTopic: (payload: ChatTopicDispatch, action?: any) => void;
- internal_updateTopics: (
- agentId: string,
- params: {
- append?: boolean;
- currentPage?: number;
- groupId?: string;
- items: ChatTopic[];
- pageSize: number;
- total: number;
- },
- ) => void;
- /**
- * Update TopicData properties (loading states, pagination, etc.)
- */
- internal_updateTopicData: (key: string, data: Partial<TopicData>) => void;
-}
+type Setter = StoreSetter<ChatStore>;
+export const chatTopic = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatTopicActionImpl(set, get, _api);
+
+export class ChatTopicActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ closeAllTopicsDrawer = (): void => {
+ this.#set({ allTopicsDrawerOpen: false }, false, n('closeAllTopicsDrawer'));
+ };
-export const chatTopic: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatTopicAction
-> = (set, get) => ({
- closeAllTopicsDrawer: () => {
- set({ allTopicsDrawerOpen: false }, false, n('closeAllTopicsDrawer'));
- },
-
- openAllTopicsDrawer: () => {
- set({ allTopicsDrawerOpen: true }, false, n('openAllTopicsDrawer'));
- },
-
- // create
- openNewTopicOrSaveTopic: async () => {
- const { switchTopic, saveToTopic, refreshMessages, activeTopicId } = get();
+ openAllTopicsDrawer = (): void => {
+ this.#set({ allTopicsDrawerOpen: true }, false, n('openAllTopicsDrawer'));
+ };
+
+ openNewTopicOrSaveTopic = async (): Promise<void> => {
+ const { switchTopic, saveToTopic, refreshMessages, activeTopicId } = this.#get();
const hasTopic = !!activeTopicId;
if (hasTopic) switchTopic(null);
@@ -162,30 +97,30 @@ export const chatTopic: StateCreator<
await saveToTopic();
refreshMessages();
}
- },
+ };
- createTopic: async (sessionId) => {
- const { activeAgentId, internal_createTopic } = get();
+ createTopic = async (sessionId?: string): Promise<string | undefined> => {
+ const { activeAgentId, internal_createTopic } = this.#get();
- const messages = displayMessageSelectors.activeDisplayMessages(get());
+ const messages = displayMessageSelectors.activeDisplayMessages(this.#get());
- set({ creatingTopic: true }, false, n('creatingTopic/start'));
+ this.#set({ creatingTopic: true }, false, n('creatingTopic/start'));
const topicId = await internal_createTopic({
title: t('defaultTitle', { ns: 'topic' }),
messages: messages.map((m) => m.id),
sessionId: sessionId || activeAgentId,
});
- set({ creatingTopic: false }, false, n('creatingTopic/end'));
+ this.#set({ creatingTopic: false }, false, n('creatingTopic/end'));
return topicId;
- },
+ };
- saveToTopic: async (sessionId) => {
+ saveToTopic = async (sessionId?: string): Promise<string | undefined> => {
// if there is no message, stop
- const messages = displayMessageSelectors.activeDisplayMessages(get());
+ const messages = displayMessageSelectors.activeDisplayMessages(this.#get());
if (messages.length === 0) return;
- const { activeAgentId, summaryTopicTitle, internal_createTopic } = get();
+ const { activeAgentId, summaryTopicTitle, internal_createTopic } = this.#get();
// 1. create topic and bind these messages
const topicId = await internal_createTopic({
@@ -194,18 +129,18 @@ export const chatTopic: StateCreator<
sessionId: sessionId || activeAgentId,
});
- get().internal_updateTopicLoading(topicId, true);
+ this.#get().internal_updateTopicLoading(topicId, true);
// 2. auto summary topic Title
// we don't need to wait for summary, just let it run async
summaryTopicTitle(topicId, messages);
return topicId;
- },
+ };
- duplicateTopic: async (id) => {
- const { refreshTopic, switchTopic } = get();
+ duplicateTopic = async (id: string): Promise<void> => {
+ const { refreshTopic, switchTopic } = this.#get();
- const topic = topicSelectors.getTopicById(id)(get());
+ const topic = topicSelectors.getTopicById(id)(this.#get());
if (!topic) return;
const newTitle = t('duplicateTitle', { ns: 'chat', title: topic?.title });
@@ -222,10 +157,10 @@ export const chatTopic: StateCreator<
message.success(t('duplicateSuccess', { ns: 'topic' }));
await switchTopic(newTopicId);
- },
+ };
- importTopic: async (data) => {
- const { activeAgentId, activeGroupId, refreshTopic, switchTopic } = get();
+ importTopic = async (data: string): Promise<string | undefined> => {
+ const { activeAgentId, activeGroupId, refreshTopic, switchTopic } = this.#get();
if (!activeAgentId) return;
@@ -255,11 +190,11 @@ export const chatTopic: StateCreator<
console.error('[importTopic] Failed:', error);
return undefined;
}
- },
- // update
- summaryTopicTitle: async (topicId, messages) => {
- const { internal_updateTopicTitleInSummary, internal_updateTopicLoading } = get();
- const topic = topicSelectors.getTopicById(topicId)(get());
+ };
+
+ summaryTopicTitle = async (topicId: string, messages: UIChatMessage[]): Promise<void> => {
+ const { internal_updateTopicTitleInSummary, internal_updateTopicLoading } = this.#get();
+ const topic = topicSelectors.getTopicById(topicId)(this.#get());
if (!topic) return;
internal_updateTopicTitleInSummary(topicId, LOADING_FLAT);
@@ -275,7 +210,7 @@ export const chatTopic: StateCreator<
internal_updateTopicTitleInSummary(topicId, topic.title);
},
onFinish: async (text) => {
- await get().internal_updateTopic(topicId, { title: text });
+ await this.#get().internal_updateTopic(topicId, { title: text });
},
onLoadingChange: (loading) => {
internal_updateTopicLoading(topicId, loading);
@@ -290,12 +225,16 @@ export const chatTopic: StateCreator<
internal_updateTopicTitleInSummary(topicId, output);
},
params: merge(topicConfig, chainSummaryTitle(messages, globalHelpers.getCurrentLanguage())),
- trace: get().getCurrentTracePayload({ traceName: TraceNameMap.SummaryTopicTitle, topicId }),
+ trace: this.#get().getCurrentTracePayload({
+ traceName: TraceNameMap.SummaryTopicTitle,
+ topicId,
+ }),
});
- },
- favoriteTopic: async (id, favorite) => {
- const { activeAgentId } = get();
- await get().internal_updateTopic(id, { favorite });
+ };
+
+ favoriteTopic = async (id: string, favorite: boolean): Promise<void> => {
+ const { activeAgentId } = this.#get();
+ await this.#get().internal_updateTopic(id, { favorite });
if (!activeAgentId) return;
@@ -324,41 +263,56 @@ export const chatTopic: StateCreator<
},
{ revalidate: false },
);
- },
+ };
- updateTopicMetadata: async (id, metadata) => {
- const topic = topicSelectors.getTopicById(id)(get());
+ updateTopicMetadata = async (id: string, metadata: Partial<ChatTopicMetadata>): Promise<void> => {
+ const topic = topicSelectors.getTopicById(id)(this.#get());
if (!topic) return;
// Optimistic update with merged metadata
const mergedMetadata = { ...topic.metadata, ...metadata };
- get().internal_dispatchTopic({ type: 'updateTopic', id, value: { metadata: mergedMetadata } });
+ this.#get().internal_dispatchTopic({
+ type: 'updateTopic',
+ id,
+ value: { metadata: mergedMetadata },
+ });
- get().internal_updateTopicLoading(id, true);
+ this.#get().internal_updateTopicLoading(id, true);
await topicService.updateTopicMetadata(id, metadata);
- await get().refreshTopic();
- get().internal_updateTopicLoading(id, false);
- },
+ await this.#get().refreshTopic();
+ this.#get().internal_updateTopicLoading(id, false);
+ };
- updateTopicTitle: async (id, title) => {
- await get().internal_updateTopic(id, { title });
- },
+ updateTopicTitle = async (id: string, title: string): Promise<void> => {
+ await this.#get().internal_updateTopic(id, { title });
+ };
- autoRenameTopicTitle: async (id) => {
- const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = get();
+ autoRenameTopicTitle = async (id: string): Promise<void> => {
+ const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = this.#get();
internal_updateTopicLoading(id, true);
const messages = await messageService.getMessages({ agentId, topicId: id });
await summaryTopicTitle(id, messages);
internal_updateTopicLoading(id, false);
- },
+ };
- // query
- useFetchTopics: (
- enable,
- { agentId, excludeTriggers, groupId, pageSize: customPageSize, isInbox },
- ) => {
+ useFetchTopics = (
+ enable: boolean,
+ {
+ agentId,
+ excludeTriggers,
+ groupId,
+ pageSize: customPageSize,
+ isInbox,
+ }: {
+ agentId?: string;
+ excludeTriggers?: string[];
+ groupId?: string;
+ isInbox?: boolean;
+ pageSize?: number;
+ } = {},
+ ): SWRResponse<{ items: ChatTopic[]; total: number }> => {
const pageSize = customPageSize || 20;
const effectiveExcludeTriggers =
excludeTriggers && excludeTriggers.length > 0 ? excludeTriggers : undefined;
@@ -382,7 +336,7 @@ export const chatTopic: StateCreator<
// agentId, groupId, isInbox, pageSize come from the outer scope closure
if (!agentId && !groupId) return { items: [], total: 0 };
- const currentData = get().topicDataMap[containerKey];
+ const currentData = this.#get().topicDataMap[containerKey];
const lastPageSize = currentData?.pageSize;
const hasExistingItems = (currentData?.items?.length || 0) > 0;
@@ -391,7 +345,7 @@ export const chatTopic: StateCreator<
const isExpanding =
hasExistingItems && typeof lastPageSize === 'number' && pageSize > lastPageSize;
if (isExpanding) {
- get().internal_updateTopicData(containerKey, { isExpandingPageSize: true });
+ this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: true });
}
const result = await topicService.getTopics({
@@ -405,7 +359,7 @@ export const chatTopic: StateCreator<
// Reset expanding state after fetch completes
if (isExpanding) {
- get().internal_updateTopicData(containerKey, { isExpandingPageSize: false });
+ this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: false });
}
return result;
@@ -418,15 +372,15 @@ export const chatTopic: StateCreator<
const { items: topics, total: totalCount } = result;
const hasMore = topics.length >= pageSize;
- const currentData = get().topicDataMap[containerKey];
+ const currentData = this.#get().topicDataMap[containerKey];
// no need to update map if the current key's data exists and is the same
if (currentData && isEqual(topics, currentData.items)) return;
- set(
+ this.#set(
{
topicDataMap: {
- ...get().topicDataMap,
+ ...this.#get().topicDataMap,
[containerKey]: {
currentPage: 0,
excludeTriggers: effectiveExcludeTriggers,
@@ -444,10 +398,10 @@ export const chatTopic: StateCreator<
},
},
);
- },
+ };
- loadMoreTopics: async () => {
- const { activeAgentId, activeGroupId, topicDataMap } = get();
+ loadMoreTopics = async (): Promise<void> => {
+ const { activeAgentId, activeGroupId, topicDataMap } = this.#get();
const key = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
const currentData = topicDataMap[key];
@@ -456,7 +410,7 @@ export const chatTopic: StateCreator<
const currentPage = currentData?.currentPage || 0;
const nextPage = currentPage + 1;
- set(
+ this.#set(
{
topicDataMap: {
...topicDataMap,
@@ -481,10 +435,10 @@ export const chatTopic: StateCreator<
const currentTopics = currentData?.items || [];
const hasMore = result.items.length >= pageSize;
- set(
+ this.#set(
{
topicDataMap: {
- ...get().topicDataMap,
+ ...this.#get().topicDataMap,
[key]: {
currentPage: nextPage,
excludeTriggers,
@@ -500,38 +454,49 @@ export const chatTopic: StateCreator<
n('loadMoreTopics(success)'),
);
} catch {
- set(
+ this.#set(
{
topicDataMap: {
- ...get().topicDataMap,
- [key]: { ...get().topicDataMap[key]!, isLoadingMore: false },
+ ...this.#get().topicDataMap,
+ [key]: { ...this.#get().topicDataMap[key]!, isLoadingMore: false },
},
},
false,
n('loadMoreTopics(error)'),
);
}
- },
- useSearchTopics: (keywords, { agentId, groupId }) =>
- useSWR<ChatTopic[]>(
+ };
+
+ useSearchTopics = (
+ keywords: string | undefined,
+ {
+ agentId,
+ groupId,
+ }: {
+ agentId?: string;
+ groupId?: string;
+ } = {},
+ ): SWRResponse<ChatTopic[]> => {
+ return useSWR<ChatTopic[]>(
keywords ? [SWR_USE_SEARCH_TOPIC, keywords, agentId, groupId] : null,
([, keywords, agentId, groupId]: [string, string, string | undefined, string | undefined]) =>
topicService.searchTopics(keywords, agentId, groupId),
{
onSuccess: (data) => {
- set(
+ this.#set(
{ searchTopics: data, isSearchingTopic: false },
false,
n('useSearchTopics(success)', { keywords }),
);
},
},
- ),
+ );
+ };
- switchTopic: async (id, options) => {
+ switchTopic = async (id?: string | null, options?: SwitchTopicOptions): Promise<void> => {
const opts = options ?? {};
- const { activeAgentId, activeGroupId } = get();
+ const { activeAgentId, activeGroupId } = this.#get();
// Clear the _new key data in the following cases:
// 1. When id is null or undefined (switching to empty topic state)
@@ -544,7 +509,7 @@ export const chatTopic: StateCreator<
// Determine scope: use explicit scope from options, or infer from activeGroupId
const scope = opts.scope ?? (activeGroupId ? 'group' : 'main');
- get().replaceMessages([], {
+ this.#get().replaceMessages([], {
context: {
agentId: activeAgentId,
groupId: activeGroupId,
@@ -555,18 +520,18 @@ export const chatTopic: StateCreator<
});
}
- set(
+ this.#set(
{ activeTopicId: !id ? (null as any) : id, activeThreadId: undefined },
false,
n('toggleTopic'),
);
if (opts.skipRefreshMessage) return;
- await get().refreshMessages();
- },
- // delete
- removeSessionTopics: async () => {
- const { switchTopic, activeAgentId, refreshTopic } = get();
+ await this.#get().refreshMessages();
+ };
+
+ removeSessionTopics = async (): Promise<void> => {
+ const { switchTopic, activeAgentId, refreshTopic } = this.#get();
if (!activeAgentId) return;
await topicService.removeTopicsByAgentId(activeAgentId);
@@ -574,14 +539,14 @@ export const chatTopic: StateCreator<
// switch to default topic
switchTopic(null);
- },
+ };
- removeGroupTopics: async (groupId: string) => {
- const { switchTopic, refreshTopic } = get();
+ removeGroupTopics = async (groupId: string): Promise<void> => {
+ const { switchTopic, refreshTopic } = this.#get();
// Get topics for this specific group from the topic map using topicMapKey
const key = topicMapKey({ groupId });
- const groupTopics = get().topicDataMap[key]?.items || [];
+ const groupTopics = this.#get().topicDataMap[key]?.items || [];
const topicIds = groupTopics.map((t) => t.id);
if (topicIds.length > 0) {
@@ -592,15 +557,17 @@ export const chatTopic: StateCreator<
// switch to default topic
switchTopic(null);
- },
- removeAllTopics: async () => {
- const { refreshTopic } = get();
+ };
+
+ removeAllTopics = async (): Promise<void> => {
+ const { refreshTopic } = this.#get();
await topicService.removeAllTopic();
await refreshTopic();
- },
- removeTopic: async (id) => {
- const { activeAgentId, activeGroupId, activeTopicId, switchTopic, refreshTopic } = get();
+ };
+
+ removeTopic = async (id: string): Promise<void> => {
+ const { activeAgentId, activeGroupId, activeTopicId, switchTopic, refreshTopic } = this.#get();
// Allow deletion when either agentId or groupId is active
if (!activeAgentId && !activeGroupId) return;
@@ -610,37 +577,38 @@ export const chatTopic: StateCreator<
// switch back to default topic
if (activeTopicId === id) switchTopic(null);
- },
- removeUnstarredTopic: async () => {
- const { refreshTopic, switchTopic } = get();
- const topics = topicSelectors.currentUnFavTopics(get());
+ };
+
+ removeUnstarredTopic = async (): Promise<void> => {
+ const { refreshTopic, switchTopic } = this.#get();
+ const topics = topicSelectors.currentUnFavTopics(this.#get());
await topicService.batchRemoveTopics(topics.map((t) => t.id));
await refreshTopic();
// Switch to default topic
switchTopic(null);
- },
+ };
- // Internal process method of the topics
- internal_updateTopicTitleInSummary: (id, title) => {
- get().internal_dispatchTopic(
+ internal_updateTopicTitleInSummary = (id: string, title: string): void => {
+ this.#get().internal_dispatchTopic(
{ type: 'updateTopic', id, value: { title } },
'updateTopicTitleInSummary',
);
- },
- refreshTopic: async () => {
- const { activeAgentId, activeGroupId } = get();
+ };
+
+ refreshTopic = async (): Promise<void> => {
+ const { activeAgentId, activeGroupId } = this.#get();
// Use topicMapKey to generate the same key used in useFetchTopics
// Key format: [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]
const containerKey = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
await mutate(
(key) => Array.isArray(key) && key[0] === SWR_USE_FETCH_TOPIC && key[1] === containerKey,
);
- },
+ };
- internal_updateTopicLoading: (id, loading) => {
- set(
+ internal_updateTopicLoading = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading) return { topicLoadingIds: [...state.topicLoadingIds, id] };
@@ -649,47 +617,48 @@ export const chatTopic: StateCreator<
false,
n('updateTopicLoading'),
);
- },
+ };
- internal_updateTopic: async (id, data) => {
- get().internal_dispatchTopic({ type: 'updateTopic', id, value: data });
+ internal_updateTopic = async (id: string, data: Partial<ChatTopic>): Promise<void> => {
+ this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: data });
- get().internal_updateTopicLoading(id, true);
+ this.#get().internal_updateTopicLoading(id, true);
await topicService.updateTopic(id, data);
- await get().refreshTopic();
- get().internal_updateTopicLoading(id, false);
- },
- internal_createTopic: async (params) => {
+ await this.#get().refreshTopic();
+ this.#get().internal_updateTopicLoading(id, false);
+ };
+
+ internal_createTopic = async (params: CreateTopicParams): Promise<string> => {
const tmpId = Date.now().toString();
- get().internal_dispatchTopic(
+ this.#get().internal_dispatchTopic(
{ type: 'addTopic', value: { ...params, id: tmpId } },
'internal_createTopic',
);
- get().internal_updateTopicLoading(tmpId, true);
+ this.#get().internal_updateTopicLoading(tmpId, true);
const topicId = await topicService.createTopic(params);
- get().internal_updateTopicLoading(tmpId, false);
+ this.#get().internal_updateTopicLoading(tmpId, false);
- get().internal_updateTopicLoading(topicId, true);
- await get().refreshTopic();
- get().internal_updateTopicLoading(topicId, false);
+ this.#get().internal_updateTopicLoading(topicId, true);
+ await this.#get().refreshTopic();
+ this.#get().internal_updateTopicLoading(topicId, false);
return topicId;
- },
+ };
- internal_dispatchTopic: (payload, action) => {
- const { activeAgentId, activeGroupId } = get();
+ internal_dispatchTopic = (payload: ChatTopicDispatch, action?: any): void => {
+ const { activeAgentId, activeGroupId } = this.#get();
const key = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
- const currentData = get().topicDataMap[key];
+ const currentData = this.#get().topicDataMap[key];
const nextItems = topicReducer(currentData?.items, payload);
// no need to update if is the same
if (isEqual(nextItems, currentData?.items)) return;
- set(
+ this.#set(
{
topicDataMap: {
- ...get().topicDataMap,
+ ...this.#get().topicDataMap,
[key]: {
...currentData,
currentPage: currentData?.currentPage ?? 0,
@@ -702,19 +671,29 @@ export const chatTopic: StateCreator<
false,
action ?? n(`dispatchTopic/${payload.type}`),
);
- },
+ };
- internal_updateTopics: (agentId, params) => {
+ internal_updateTopics = (
+ agentId: string,
+ params: {
+ append?: boolean;
+ currentPage?: number;
+ groupId?: string;
+ items: ChatTopic[];
+ pageSize: number;
+ total: number;
+ },
+ ): void => {
const { items, total, pageSize, currentPage = 0, append = false, groupId } = params;
const key = topicMapKey({ agentId, groupId });
- const currentData = get().topicDataMap[key];
+ const currentData = this.#get().topicDataMap[key];
const nextItems = append ? [...(currentData?.items || []), ...items] : items;
- set(
+ this.#set(
{
topicDataMap: {
- ...get().topicDataMap,
+ ...this.#get().topicDataMap,
[key]: {
currentPage,
hasMore: items.length >= pageSize,
@@ -729,16 +708,16 @@ export const chatTopic: StateCreator<
false,
n('internal_updateTopics', { key, append }),
);
- },
+ };
- internal_updateTopicData: (key, data) => {
- const currentData = get().topicDataMap[key];
+ internal_updateTopicData = (key: string, data: Partial<TopicData>): void => {
+ const currentData = this.#get().topicDataMap[key];
if (!currentData) return;
- set(
+ this.#set(
{
topicDataMap: {
- ...get().topicDataMap,
+ ...this.#get().topicDataMap,
[key]: {
...currentData,
...data,
@@ -748,5 +727,7 @@ export const chatTopic: StateCreator<
false,
n('internal_updateTopicData', { key, data }),
);
- },
-});
+ };
+}
+
+export type ChatTopicAction = Pick<ChatTopicActionImpl, keyof ChatTopicActionImpl>;
diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.ts
index e9384b2f91e..8c7730df94c 100644
--- a/src/store/chat/slices/topic/reducer.ts
+++ b/src/store/chat/slices/topic/reducer.ts
@@ -3,21 +3,21 @@ import { produce } from 'immer';
import { type ChatTopic, type CreateTopicParams } from '@/types/topic';
-interface AddChatTopicAction {
+type AddChatTopicAction = {
type: 'addTopic';
value: CreateTopicParams & { id?: string };
-}
+};
-interface UpdateChatTopicAction {
+type UpdateChatTopicAction = {
id: string;
type: 'updateTopic';
value: Partial<ChatTopic>;
-}
+};
-interface DeleteChatTopicAction {
+type DeleteChatTopicAction = {
id: string;
type: 'deleteTopic';
-}
+};
export type ChatTopicDispatch = AddChatTopicAction | UpdateChatTopicAction | DeleteChatTopicAction;
diff --git a/src/store/chat/slices/translate/action.ts b/src/store/chat/slices/translate/action.ts
index 47d3419889a..63a3c1eeb33 100644
--- a/src/store/chat/slices/translate/action.ts
+++ b/src/store/chat/slices/translate/action.ts
@@ -1,45 +1,50 @@
import { chainLangDetect, chainTranslate } from '@lobechat/prompts';
import { type ChatTranslate, TraceNameMap, type TracePayload } from '@lobechat/types';
import { merge } from '@lobechat/utils';
-import { type StateCreator } from 'zustand/vanilla';
import { supportLocales } from '@/locales/resources';
import { chatService } from '@/services/chat';
import { messageService } from '@/services/message';
import { dbMessageSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors } from '@/store/user/selectors';
/**
* chat translate
*/
-export interface ChatTranslateAction {
- clearTranslate: (id: string) => Promise<void>;
- getCurrentTracePayload: (data: Partial<TracePayload>) => TracePayload;
- translateMessage: (id: string, targetLang: string) => Promise<void>;
- updateMessageTranslate: (id: string, data: Partial<ChatTranslate> | false) => Promise<void>;
-}
-export const chatTranslate: StateCreator<
- ChatStore,
- [['zustand/devtools', never]],
- [],
- ChatTranslateAction
-> = (set, get) => ({
- clearTranslate: async (id) => {
- await get().updateMessageTranslate(id, false);
- },
- getCurrentTracePayload: (data) => ({
- sessionId: get().activeAgentId,
- topicId: get().activeTopicId,
- ...data,
- }),
-
- translateMessage: async (id, targetLang) => {
- const { updateMessageTranslate, internal_dispatchMessage } = get();
-
- const message = dbMessageSelectors.getDbMessageById(id)(get());
+type Setter = StoreSetter<ChatStore>;
+export const chatTranslate = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatTranslateActionImpl(set, get, _api);
+
+export class ChatTranslateActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ clearTranslate = async (id: string): Promise<void> => {
+ await this.#get().updateMessageTranslate(id, false);
+ };
+
+ getCurrentTracePayload = (data: Partial<TracePayload>): TracePayload => {
+ return {
+ sessionId: this.#get().activeAgentId,
+ topicId: this.#get().activeTopicId,
+ ...data,
+ };
+ };
+
+ translateMessage = async (id: string, targetLang: string): Promise<void> => {
+ const { updateMessageTranslate, internal_dispatchMessage } = this.#get();
+
+ const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
if (!message) return;
// Get current agent for translation
@@ -49,7 +54,7 @@ export const chatTranslate: StateCreator<
await updateMessageTranslate(id, { content: '', from: '', to: targetLang });
// Create translate operation
- const { operationId } = get().startOperation({
+ const { operationId } = this.#get().startOperation({
context: {
agentId: message.agentId,
messageId: id,
@@ -61,7 +66,7 @@ export const chatTranslate: StateCreator<
});
// Associate message with operation
- get().associateMessageWithOperation(id, operationId);
+ this.#get().associateMessageWithOperation(id, operationId);
try {
let content = '';
@@ -75,14 +80,14 @@ export const chatTranslate: StateCreator<
await updateMessageTranslate(id, { content, from, to: targetLang });
},
params: merge(translationSetting, chainLangDetect(message.content)),
- trace: get().getCurrentTracePayload({ traceName: TraceNameMap.LanguageDetect }),
+ trace: this.#get().getCurrentTracePayload({ traceName: TraceNameMap.LanguageDetect }),
});
// translate to target language
await chatService.fetchPresetTaskResult({
onFinish: async (translatedContent) => {
await updateMessageTranslate(id, { content: translatedContent, from, to: targetLang });
- get().completeOperation(operationId);
+ this.#get().completeOperation(operationId);
},
onMessageHandle: (chunk) => {
switch (chunk.type) {
@@ -102,20 +107,23 @@ export const chatTranslate: StateCreator<
}
},
params: merge(translationSetting, chainTranslate(message.content, targetLang)),
- trace: get().getCurrentTracePayload({ traceName: TraceNameMap.Translator }),
+ trace: this.#get().getCurrentTracePayload({ traceName: TraceNameMap.Translator }),
});
} catch (error) {
- get().failOperation(operationId, {
+ this.#get().failOperation(operationId, {
message: error instanceof Error ? error.message : String(error),
type: 'TranslateError',
});
throw error;
}
- },
+ };
- updateMessageTranslate: async (id, data) => {
+ updateMessageTranslate = async (
+ id: string,
+ data: Partial<ChatTranslate> | false,
+ ): Promise<void> => {
// Optimistic update
- get().internal_dispatchMessage({
+ this.#get().internal_dispatchMessage({
id,
key: 'translate',
type: 'updateMessageExtra',
@@ -124,5 +132,7 @@ export const chatTranslate: StateCreator<
// Persist to database
await messageService.updateMessageTranslate(id, data);
- },
-});
+ };
+}
+
+export type ChatTranslateAction = Pick<ChatTranslateActionImpl, keyof ChatTranslateActionImpl>;
diff --git a/src/store/chat/slices/tts/action.ts b/src/store/chat/slices/tts/action.ts
index 1408a19aecd..ec8f65dabbf 100644
--- a/src/store/chat/slices/tts/action.ts
+++ b/src/store/chat/slices/tts/action.ts
@@ -1,36 +1,41 @@
import { type ChatTTS } from '@lobechat/types';
-import { type StateCreator } from 'zustand/vanilla';
import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
+import { type StoreSetter } from '@/store/types';
/**
* enhance chat action like translate,tts
*/
-export interface ChatTTSAction {
- clearTTS: (id: string) => Promise<void>;
- ttsMessage: (
- id: string,
- state?: { contentMd5?: string; file?: string; voice?: string },
- ) => Promise<void>;
- updateMessageTTS: (id: string, data: Partial<ChatTTS> | false) => Promise<void>;
-}
-export const chatTTS: StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatTTSAction> = (
- set,
- get,
-) => ({
- clearTTS: async (id) => {
- await get().updateMessageTTS(id, false);
- },
+type Setter = StoreSetter<ChatStore>;
+export const chatTTS = (set: Setter, get: () => ChatStore, _api?: unknown) =>
+ new ChatTTSActionImpl(set, get, _api);
+
+export class ChatTTSActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- ttsMessage: async (id, state = {}) => {
- await get().updateMessageTTS(id, state);
- },
+ clearTTS = async (id: string): Promise<void> => {
+ await this.#get().updateMessageTTS(id, false);
+ };
- updateMessageTTS: async (id, data) => {
+ ttsMessage = async (
+ id: string,
+ state: { contentMd5?: string; file?: string; voice?: string } = {},
+ ): Promise<void> => {
+ await this.#get().updateMessageTTS(id, state);
+ };
+
+ updateMessageTTS = async (id: string, data: Partial<ChatTTS> | false): Promise<void> => {
// Optimistic update
- get().internal_dispatchMessage({
+ this.#get().internal_dispatchMessage({
id,
key: 'tts',
type: 'updateMessageExtra',
@@ -39,5 +44,7 @@ export const chatTTS: StateCreator<ChatStore, [['zustand/devtools', never]], [],
// Persist to database
await messageService.updateMessageTTS(id, data);
- },
-});
+ };
+}
+
+export type ChatTTSAction = Pick<ChatTTSActionImpl, keyof ChatTTSActionImpl>;
diff --git a/src/store/chat/store.ts b/src/store/chat/store.ts
index cc4324cca6e..ac5ad7b3f8b 100644
--- a/src/store/chat/store.ts
+++ b/src/store/chat/store.ts
@@ -5,54 +5,56 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type ChatStoreState, initialState } from './initialState';
import { type ChatBuiltinToolAction, chatToolSlice } from './slices/builtinTool/actions';
-import { type ChatPortalAction, chatPortalSlice } from './slices/portal/action';
-import { type ChatTranslateAction, chatTranslate } from './slices/translate/action';
+import { type ChatPortalAction, ChatPortalActionImpl } from './slices/portal/action';
+import { type ChatTranslateAction, ChatTranslateActionImpl } from './slices/translate/action';
import { type ChatMessageAction, chatMessage } from './slices/message/actions';
import { type ChatPluginAction, chatPlugin } from './slices/plugin/actions';
-import { type ChatTopicAction, chatTopic } from './slices/topic/action';
+import { type ChatTopicAction, ChatTopicActionImpl } from './slices/topic/action';
import { type ChatAIChatAction, chatAiChat } from './slices/aiChat/actions';
-import { type ChatTTSAction, chatTTS } from './slices/tts/action';
-import { type ChatThreadAction, chatThreadMessage } from './slices/thread/action';
-import { type OperationActions, operationActions } from './slices/operation/actions';
+import { type ChatTTSAction, ChatTTSActionImpl } from './slices/tts/action';
+import { type ChatThreadAction, ChatThreadActionImpl } from './slices/thread/action';
+import { type OperationActions, OperationActionsImpl } from './slices/operation/actions';
import { type ChatAIAgentAction, chatAiAgent } from './slices/aiAgent/actions';
-export interface ChatStoreAction
- extends
- ChatMessageAction,
- ChatThreadAction,
- ChatAIChatAction,
- ChatTopicAction,
- ChatTranslateAction,
- ChatTTSAction,
- ChatPluginAction,
- ChatBuiltinToolAction,
- ChatPortalAction,
- OperationActions,
- ChatAIAgentAction {}
+export type ChatStoreAction = ChatMessageAction &
+ ChatThreadAction &
+ ChatAIChatAction &
+ ChatTopicAction &
+ ChatTranslateAction &
+ ChatTTSAction &
+ ChatPluginAction &
+ ChatBuiltinToolAction &
+ ChatPortalAction &
+ OperationActions &
+ ChatAIAgentAction;
export type ChatStore = ChatStoreAction & ChatStoreState;
// =============== Aggregate createStoreFn ============ //
-const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (...params) => ({
- ...initialState,
-
- ...chatMessage(...params),
- ...chatThreadMessage(...params),
- ...chatAiChat(...params),
- ...chatTopic(...params),
- ...chatTranslate(...params),
- ...chatTTS(...params),
- ...chatToolSlice(...params),
- ...chatPlugin(...params),
- ...chatPortalSlice(...params),
- ...operationActions(...params),
- ...chatAiAgent(...params),
-
- // cloud
-});
+const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (
+ ...params: Parameters<StateCreator<ChatStore, [['zustand/devtools', never]]>>
+) =>
+ ({
+ ...initialState,
+ ...(flattenActions<ChatStoreAction>([
+ chatMessage(...params),
+ new ChatThreadActionImpl(...params),
+ chatAiChat(...params),
+ new ChatTopicActionImpl(...params),
+ new ChatTranslateActionImpl(...params),
+ new ChatTTSActionImpl(...params),
+ chatToolSlice(...params),
+ chatPlugin(...params),
+ new ChatPortalActionImpl(...params),
+ new OperationActionsImpl(...params),
+ chatAiAgent(...params),
+ ]) as ChatStoreAction),
+ // cloud
+ }) as ChatStore;
// =============== Implement useStore ============ //
const devtools = createDevtools('chat');
diff --git a/src/store/discover/slices/assistant/action.ts b/src/store/discover/slices/assistant/action.ts
index b6b52377df4..23690f41b78 100644
--- a/src/store/discover/slices/assistant/action.ts
+++ b/src/store/discover/slices/assistant/action.ts
@@ -1,10 +1,10 @@
import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import {
type AssistantListResponse,
type AssistantMarketSource,
@@ -13,28 +13,23 @@ import {
type IdentifiersResponse,
} from '@/types/discover';
-export interface AssistantAction {
- useAssistantCategories: (
- params: CategoryListQuery & { source?: AssistantMarketSource },
- ) => SWRResponse<CategoryItem[]>;
- useAssistantDetail: (params: {
- identifier: string;
- source?: AssistantMarketSource;
- version?: string;
- }) => SWRResponse<DiscoverAssistantDetail | undefined>;
- useAssistantIdentifiers: (params?: {
- source?: AssistantMarketSource;
- }) => SWRResponse<IdentifiersResponse>;
- useAssistantList: (params?: AssistantQueryParams) => SWRResponse<AssistantListResponse>;
-}
+type Setter = StoreSetter<DiscoverStore>;
+export const createAssistantSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new AssistantActionImpl(set, get, _api);
+
+export class AssistantActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createAssistantSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- AssistantAction
-> = () => ({
- useAssistantCategories: (params) => {
+ useAssistantCategories = (
+ params: CategoryListQuery & { source?: AssistantMarketSource },
+ ): SWRResponse<CategoryItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['assistant-categories', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -43,9 +38,13 @@ export const createAssistantSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useAssistantDetail: (params) => {
+ useAssistantDetail = (params: {
+ identifier: string;
+ source?: AssistantMarketSource;
+ version?: string;
+ }): SWRResponse<DiscoverAssistantDetail | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['assistant-details', locale, params.identifier, params.version, params.source]
@@ -56,19 +55,22 @@ export const createAssistantSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useAssistantIdentifiers: (params) => {
+ useAssistantIdentifiers = (params?: {
+ source?: AssistantMarketSource;
+ }): SWRResponse<IdentifiersResponse> => {
return useSWR(
- ['assistant-identifiers', params?.source].filter(Boolean).join('-') || 'assistant-identifiers',
+ ['assistant-identifiers', params?.source].filter(Boolean).join('-') ||
+ 'assistant-identifiers',
async () => discoverService.getAssistantIdentifiers(params),
{
revalidateOnFocus: false,
},
);
- },
+ };
- useAssistantList: (params = {}) => {
+ useAssistantList = (params: AssistantQueryParams = {}): SWRResponse<AssistantListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['assistant-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -82,5 +84,7 @@ export const createAssistantSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type AssistantAction = Pick<AssistantActionImpl, keyof AssistantActionImpl>;
diff --git a/src/store/discover/slices/groupAgent/action.ts b/src/store/discover/slices/groupAgent/action.ts
index a4aafcdb4d8..f90ecb51069 100644
--- a/src/store/discover/slices/groupAgent/action.ts
+++ b/src/store/discover/slices/groupAgent/action.ts
@@ -1,10 +1,10 @@
import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import {
type DiscoverGroupAgentDetail,
type GroupAgentListResponse,
@@ -12,23 +12,21 @@ import {
type IdentifiersResponse,
} from '@/types/discover';
-export interface GroupAgentAction {
- useGroupAgentCategories: (params?: CategoryListQuery) => SWRResponse<CategoryItem[]>;
- useGroupAgentDetail: (params: {
- identifier: string;
- version?: string;
- }) => SWRResponse<DiscoverGroupAgentDetail | undefined>;
- useGroupAgentIdentifiers: () => SWRResponse<IdentifiersResponse>;
- useGroupAgentList: (params?: GroupAgentQueryParams) => SWRResponse<GroupAgentListResponse>;
-}
+type Setter = StoreSetter<DiscoverStore>;
+export const createGroupAgentSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new GroupAgentActionImpl(set, get, _api);
+
+export class GroupAgentActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createGroupAgentSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- GroupAgentAction
-> = () => ({
- useGroupAgentCategories: (params = {}) => {
+ useGroupAgentCategories = (params: CategoryListQuery = {}): SWRResponse<CategoryItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['group-agent-categories', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -37,22 +35,23 @@ export const createGroupAgentSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useGroupAgentDetail: (params) => {
+ useGroupAgentDetail = (params: {
+ identifier: string;
+ version?: string;
+ }): SWRResponse<DiscoverGroupAgentDetail | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
- ['group-agent-details', locale, params.identifier, params.version]
- .filter(Boolean)
- .join('-'),
+ ['group-agent-details', locale, params.identifier, params.version].filter(Boolean).join('-'),
async () => discoverService.getGroupAgentDetail(params),
{
revalidateOnFocus: false,
},
);
- },
+ };
- useGroupAgentIdentifiers: () => {
+ useGroupAgentIdentifiers = (): SWRResponse<IdentifiersResponse> => {
return useSWR(
'group-agent-identifiers',
async () => discoverService.getGroupAgentIdentifiers(),
@@ -60,9 +59,9 @@ export const createGroupAgentSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useGroupAgentList: (params = {}) => {
+ useGroupAgentList = (params: GroupAgentQueryParams = {}): SWRResponse<GroupAgentListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['group-agent-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -76,5 +75,7 @@ export const createGroupAgentSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type GroupAgentAction = Pick<GroupAgentActionImpl, keyof GroupAgentActionImpl>;
diff --git a/src/store/discover/slices/mcp/action.ts b/src/store/discover/slices/mcp/action.ts
index 2c814508474..a84056a96b4 100644
--- a/src/store/discover/slices/mcp/action.ts
+++ b/src/store/discover/slices/mcp/action.ts
@@ -1,42 +1,47 @@
import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { useClientDataSWR } from '@/libs/swr';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import {
type DiscoverMcpDetail,
type McpListResponse,
type McpQueryParams,
} from '@/types/discover';
-export interface MCPAction {
- useFetchMcpDetail: (params: {
+type Setter = StoreSetter<DiscoverStore>;
+export const createMCPSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new MCPActionImpl(set, get, _api);
+
+export class MCPActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ useFetchMcpDetail = ({
+ identifier,
+ version,
+ }: {
identifier?: string;
version?: string;
- }) => SWRResponse<DiscoverMcpDetail>;
- useFetchMcpList: (params: McpQueryParams) => SWRResponse<McpListResponse>;
- useMcpCategories: (params: CategoryListQuery) => SWRResponse<CategoryItem[]>;
-}
-
-export const createMCPSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- MCPAction
-> = () => ({
- useFetchMcpDetail: ({ identifier, version }) => {
+ }): SWRResponse<DiscoverMcpDetail> => {
const locale = globalHelpers.getCurrentLanguage();
return useClientDataSWR(
!identifier ? null : ['mcp-detail', locale, identifier, version].filter(Boolean).join('-'),
async () => discoverService.getMcpDetail({ identifier: identifier!, version }),
);
- },
+ };
- useFetchMcpList: (params) => {
+ useFetchMcpList = (params: McpQueryParams): SWRResponse<McpListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useClientDataSWR(
['mcp-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -47,9 +52,9 @@ export const createMCPSlice: StateCreator<
pageSize: params.pageSize ? Number(params.pageSize) : 21,
}),
);
- },
+ };
- useMcpCategories: (params) => {
+ useMcpCategories = (params: CategoryListQuery): SWRResponse<CategoryItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
return useClientDataSWR(
['mcp-categories', locale, ...Object.values(params)].join('-'),
@@ -58,5 +63,7 @@ export const createMCPSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type MCPAction = Pick<MCPActionImpl, keyof MCPActionImpl>;
diff --git a/src/store/discover/slices/model/action.ts b/src/store/discover/slices/model/action.ts
index 29ac832fbd4..75f9a3604c4 100644
--- a/src/store/discover/slices/model/action.ts
+++ b/src/store/discover/slices/model/action.ts
@@ -1,10 +1,10 @@
import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import {
type DiscoverModelDetail,
type IdentifiersResponse,
@@ -12,20 +12,21 @@ import {
type ModelQueryParams,
} from '@/types/discover';
-export interface ModelAction {
- useModelCategories: (params: CategoryListQuery) => SWRResponse<CategoryItem[]>;
- useModelDetail: (params: { identifier: string }) => SWRResponse<DiscoverModelDetail | undefined>;
- useModelIdentifiers: () => SWRResponse<IdentifiersResponse>;
- useModelList: (params?: ModelQueryParams) => SWRResponse<ModelListResponse>;
-}
+type Setter = StoreSetter<DiscoverStore>;
+export const createModelSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new ModelActionImpl(set, get, _api);
+
+export class ModelActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createModelSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- ModelAction
-> = () => ({
- useModelCategories: (params) => {
+ useModelCategories = (params: CategoryListQuery): SWRResponse<CategoryItem[]> => {
return useSWR(
['model-categories', ...Object.values(params)].filter(Boolean).join('-'),
async () => discoverService.getModelCategories(params),
@@ -33,9 +34,11 @@ export const createModelSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useModelDetail: (params) => {
+ useModelDetail = (params: {
+ identifier: string;
+ }): SWRResponse<DiscoverModelDetail | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['model-details', locale, params.identifier].filter(Boolean).join('-'),
@@ -44,15 +47,15 @@ export const createModelSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useModelIdentifiers: () => {
+ useModelIdentifiers = (): SWRResponse<IdentifiersResponse> => {
return useSWR('model-identifiers', async () => discoverService.getModelIdentifiers(), {
revalidateOnFocus: false,
});
- },
+ };
- useModelList: (params = {}) => {
+ useModelList = (params: ModelQueryParams = {}): SWRResponse<ModelListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['model-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -66,5 +69,7 @@ export const createModelSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type ModelAction = Pick<ModelActionImpl, keyof ModelActionImpl>;
diff --git a/src/store/discover/slices/plugin/action.ts b/src/store/discover/slices/plugin/action.ts
index 84fd8eec529..7a369162ac9 100644
--- a/src/store/discover/slices/plugin/action.ts
+++ b/src/store/discover/slices/plugin/action.ts
@@ -6,29 +6,27 @@ import {
} from '@lobechat/types';
import { type CategoryItem, type CategoryListQuery } from '@lobehub/market-sdk';
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
-export interface PluginAction {
- usePluginCategories: (params: CategoryListQuery) => SWRResponse<CategoryItem[]>;
- usePluginDetail: (params: {
- identifier?: string;
- withManifest?: boolean;
- }) => SWRResponse<DiscoverPluginDetail | undefined>;
- usePluginIdentifiers: () => SWRResponse<IdentifiersResponse>;
- usePluginList: (params?: PluginQueryParams) => SWRResponse<PluginListResponse>;
-}
+type Setter = StoreSetter<DiscoverStore>;
+export const createPluginSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new PluginActionImpl(set, get, _api);
+
+export class PluginActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createPluginSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- PluginAction
-> = () => ({
- usePluginCategories: (params) => {
+ usePluginCategories = (params: CategoryListQuery): SWRResponse<CategoryItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['plugin-categories', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -37,9 +35,15 @@ export const createPluginSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- usePluginDetail: ({ identifier, withManifest }) => {
+ usePluginDetail = ({
+ identifier,
+ withManifest,
+ }: {
+ identifier?: string;
+ withManifest?: boolean;
+ }): SWRResponse<DiscoverPluginDetail | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
!identifier
@@ -50,15 +54,15 @@ export const createPluginSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- usePluginIdentifiers: () => {
+ usePluginIdentifiers = (): SWRResponse<IdentifiersResponse> => {
return useSWR('plugin-identifiers', async () => discoverService.getPluginIdentifiers(), {
revalidateOnFocus: false,
});
- },
+ };
- usePluginList: (params = {}) => {
+ usePluginList = (params: PluginQueryParams = {}): SWRResponse<PluginListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['plugin-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -72,5 +76,7 @@ export const createPluginSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type PluginAction = Pick<PluginActionImpl, keyof PluginActionImpl>;
diff --git a/src/store/discover/slices/provider/action.ts b/src/store/discover/slices/provider/action.ts
index d3dfb272b1d..b41ac4c8ca4 100644
--- a/src/store/discover/slices/provider/action.ts
+++ b/src/store/discover/slices/provider/action.ts
@@ -1,9 +1,9 @@
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import {
type DiscoverProviderDetail,
type IdentifiersResponse,
@@ -11,22 +11,24 @@ import {
type ProviderQueryParams,
} from '@/types/discover';
-export interface ProviderAction {
- useProviderDetail: (params: {
+type Setter = StoreSetter<DiscoverStore>;
+export const createProviderSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new ProviderActionImpl(set, get, _api);
+
+export class ProviderActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ useProviderDetail = (params: {
identifier: string;
withReadme?: boolean;
- }) => SWRResponse<DiscoverProviderDetail | undefined>;
- useProviderIdentifiers: () => SWRResponse<IdentifiersResponse>;
- useProviderList: (params?: ProviderQueryParams) => SWRResponse<ProviderListResponse>;
-}
-
-export const createProviderSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- ProviderAction
-> = () => ({
- useProviderDetail: (params) => {
+ }): SWRResponse<DiscoverProviderDetail | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['provider-details', locale, params.identifier].filter(Boolean).join('-'),
@@ -35,15 +37,15 @@ export const createProviderSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useProviderIdentifiers: () => {
+ useProviderIdentifiers = (): SWRResponse<IdentifiersResponse> => {
return useSWR('provider-identifiers', async () => discoverService.getProviderIdentifiers(), {
revalidateOnFocus: false,
});
- },
+ };
- useProviderList: (params = {}) => {
+ useProviderList = (params: ProviderQueryParams = {}): SWRResponse<ProviderListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
['provider-list', locale, ...Object.values(params)].filter(Boolean).join('-'),
@@ -57,5 +59,7 @@ export const createProviderSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type ProviderAction = Pick<ProviderActionImpl, keyof ProviderActionImpl>;
diff --git a/src/store/discover/slices/social/action.ts b/src/store/discover/slices/social/action.ts
index 22fe632d772..6a427735b0d 100644
--- a/src/store/discover/slices/social/action.ts
+++ b/src/store/discover/slices/social/action.ts
@@ -1,5 +1,4 @@
import useSWR, { type SWRResponse, mutate } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import {
type FavoriteAgentItem,
@@ -12,150 +11,125 @@ import {
socialService,
} from '@/services/social';
import { type DiscoverStore } from '@/store/discover';
+import { type StoreSetter } from '@/store/types';
-export interface SocialAction {
- // Favorite actions
- addFavorite: (targetType: SocialTargetType, targetId: number) => Promise<void>;
- // Follow actions
- follow: (followingId: number) => Promise<void>;
+type Setter = StoreSetter<DiscoverStore>;
+export const createSocialSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new SocialActionImpl(set, get, _api);
- removeFavorite: (targetType: SocialTargetType, targetId: number) => Promise<void>;
- // Like actions
- toggleLike: (targetType: SocialTargetType, targetId: number) => Promise<{ liked: boolean }>;
+export class SocialActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
- unfollow: (followingId: number) => Promise<void>;
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- // Favorite queries
- useFavoriteAgents: (
- userId: number | undefined,
- params?: { page?: number; pageSize?: number },
- ) => SWRResponse<PaginatedResponse<FavoriteAgentItem>>;
- useFavoritePlugins: (
- userId: number | undefined,
- params?: { page?: number; pageSize?: number },
- ) => SWRResponse<PaginatedResponse<FavoritePluginItem>>;
- useFollowCounts: (userId: number | undefined) => SWRResponse<FollowCounts>;
- // Follow queries
- useFollowStatus: (userId: number | undefined) => SWRResponse<FollowStatus>;
-
- useFollowers: (
- userId: number | undefined,
- params?: { page?: number; pageSize?: number },
- ) => SWRResponse<PaginatedResponse<FollowUserItem>>;
- useFollowing: (
- userId: number | undefined,
- params?: { page?: number; pageSize?: number },
- ) => SWRResponse<PaginatedResponse<FollowUserItem>>;
-}
-
-export const createSocialSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- SocialAction
-> = () => ({
-
- // Favorite actions
-addFavorite: async (targetType, targetId) => {
+ addFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
await socialService.addFavorite(targetType, targetId);
// Invalidate favorite-related caches
await mutate((key) => typeof key === 'string' && key.startsWith('favorite-'), undefined, {
revalidate: true,
});
- },
+ };
-
-// Follow actions
-follow: async (followingId) => {
+ follow = async (followingId: number): Promise<void> => {
await socialService.follow(followingId);
// Invalidate follow-related caches
await mutate((key) => typeof key === 'string' && key.startsWith('follow-'), undefined, {
revalidate: true,
});
- },
+ };
-
- removeFavorite: async (targetType, targetId) => {
+ removeFavorite = async (targetType: SocialTargetType, targetId: number): Promise<void> => {
await socialService.removeFavorite(targetType, targetId);
// Invalidate favorite-related caches
await mutate((key) => typeof key === 'string' && key.startsWith('favorite-'), undefined, {
revalidate: true,
});
- },
+ };
- // Like actions
-toggleLike: async (targetType, targetId) => {
+ toggleLike = async (
+ targetType: SocialTargetType,
+ targetId: number,
+ ): Promise<{ liked: boolean }> => {
const result = await socialService.toggleLike(targetType, targetId);
// Invalidate like-related caches
await mutate((key) => typeof key === 'string' && key.startsWith('liked-'), undefined, {
revalidate: true,
});
return result;
- },
+ };
-
- unfollow: async (followingId) => {
+ unfollow = async (followingId: number): Promise<void> => {
await socialService.unfollow(followingId);
// Invalidate follow-related caches
await mutate((key) => typeof key === 'string' && key.startsWith('follow-'), undefined, {
revalidate: true,
});
- },
+ };
-
- // Favorite queries
-useFavoriteAgents: (userId, params) => {
+ useFavoriteAgents = (
+ userId: number | undefined,
+ params?: { page?: number; pageSize?: number },
+ ): SWRResponse<PaginatedResponse<FavoriteAgentItem>> => {
return useSWR(
userId ? ['favorite-agents', userId, params?.page, params?.pageSize].join('-') : null,
async () => socialService.getUserFavoriteAgents(userId!, params),
{ revalidateOnFocus: false },
);
- },
-
-
+ };
-useFavoritePlugins: (userId, params) => {
+ useFavoritePlugins = (
+ userId: number | undefined,
+ params?: { page?: number; pageSize?: number },
+ ): SWRResponse<PaginatedResponse<FavoritePluginItem>> => {
return useSWR(
userId ? ['favorite-plugins', userId, params?.page, params?.pageSize].join('-') : null,
async () => socialService.getUserFavoritePlugins(userId!, params),
{ revalidateOnFocus: false },
);
- },
-
-
+ };
-useFollowCounts: (userId) => {
+ useFollowCounts = (userId: number | undefined): SWRResponse<FollowCounts> => {
return useSWR(
userId ? ['follow-counts', userId].join('-') : null,
async () => socialService.getFollowCounts(userId!),
{ revalidateOnFocus: false },
);
- },
+ };
-
-// Follow queries
-useFollowStatus: (userId) => {
+ useFollowStatus = (userId: number | undefined): SWRResponse<FollowStatus> => {
return useSWR(
userId ? ['follow-status', userId].join('-') : null,
async () => socialService.checkFollowStatus(userId!),
{ revalidateOnFocus: false },
);
- },
+ };
-
- useFollowers: (userId, params) => {
+ useFollowers = (
+ userId: number | undefined,
+ params?: { page?: number; pageSize?: number },
+ ): SWRResponse<PaginatedResponse<FollowUserItem>> => {
return useSWR(
userId ? ['followers', userId, params?.page, params?.pageSize].join('-') : null,
async () => socialService.getFollowers(userId!, params),
{ revalidateOnFocus: false },
);
- },
+ };
- useFollowing: (userId, params) => {
+ useFollowing = (
+ userId: number | undefined,
+ params?: { page?: number; pageSize?: number },
+ ): SWRResponse<PaginatedResponse<FollowUserItem>> => {
return useSWR(
userId ? ['following', userId, params?.page, params?.pageSize].join('-') : null,
async () => socialService.getFollowing(userId!, params),
{ revalidateOnFocus: false },
);
- },
-});
+ };
+}
+
+export type SocialAction = Pick<SocialActionImpl, keyof SocialActionImpl>;
diff --git a/src/store/discover/slices/user/action.ts b/src/store/discover/slices/user/action.ts
index 75220e0081b..7c4155a2bc6 100644
--- a/src/store/discover/slices/user/action.ts
+++ b/src/store/discover/slices/user/action.ts
@@ -1,22 +1,26 @@
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { discoverService } from '@/services/discover';
import { type DiscoverStore } from '@/store/discover';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import { type DiscoverUserProfile } from '@/types/discover';
-export interface UserAction {
- useUserProfile: (params: { username: string }) => SWRResponse<DiscoverUserProfile | undefined>;
-}
+type Setter = StoreSetter<DiscoverStore>;
+export const createUserSlice = (set: Setter, get: () => DiscoverStore, _api?: unknown) =>
+ new UserActionImpl(set, get, _api);
+
+export class UserActionImpl {
+ readonly #get: () => DiscoverStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DiscoverStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createUserSlice: StateCreator<
- DiscoverStore,
- [['zustand/devtools', never]],
- [],
- UserAction
-> = () => ({
- useUserProfile: (params) => {
+ useUserProfile = (params: { username: string }): SWRResponse<DiscoverUserProfile | undefined> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR(
params.username ? ['user-profile', locale, params.username].join('-') : null,
@@ -25,5 +29,7 @@ export const createUserSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type UserAction = Pick<UserActionImpl, keyof UserActionImpl>;
diff --git a/src/store/discover/store.ts b/src/store/discover/store.ts
index a2477ba7cfa..342f2b14a91 100644
--- a/src/store/discover/store.ts
+++ b/src/store/discover/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type AssistantAction, createAssistantSlice } from './slices/assistant/action';
import { type GroupAgentAction, createGroupAgentSlice } from './slices/groupAgent/action';
import { type MCPAction, createMCPSlice } from './slices/mcp';
@@ -23,18 +24,28 @@ export type DiscoverStore = MCPAction &
SocialAction &
UserAction;
+type DiscoverStoreAction = MCPAction &
+ AssistantAction &
+ GroupAgentAction &
+ ProviderAction &
+ ModelAction &
+ PluginAction &
+ SocialAction &
+ UserAction;
+
const createStore: StateCreator<DiscoverStore, [['zustand/devtools', never]]> = (
- ...parameters
-) => ({
- ...createMCPSlice(...parameters),
- ...createAssistantSlice(...parameters),
- ...createGroupAgentSlice(...parameters),
- ...createProviderSlice(...parameters),
- ...createModelSlice(...parameters),
- ...createPluginSlice(...parameters),
- ...createSocialSlice(...parameters),
- ...createUserSlice(...parameters),
-});
+ ...parameters: Parameters<StateCreator<DiscoverStore, [['zustand/devtools', never]]>>
+) =>
+ flattenActions<DiscoverStoreAction>([
+ createMCPSlice(...parameters),
+ createAssistantSlice(...parameters),
+ createGroupAgentSlice(...parameters),
+ createProviderSlice(...parameters),
+ createModelSlice(...parameters),
+ createPluginSlice(...parameters),
+ createSocialSlice(...parameters),
+ createUserSlice(...parameters),
+ ]);
// =============== Implement useStore ============ //
diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.ts
index e9cf02a75ed..91b56934ed5 100644
--- a/src/store/document/slices/document/action.ts
+++ b/src/store/document/slices/document/action.ts
@@ -5,10 +5,10 @@ import { type DocumentItem } from '@lobechat/database/schemas';
import { type IEditor } from '@lobehub/editor';
import { debounce } from 'es-toolkit/compat';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type { DocumentStore } from '../../store';
@@ -51,48 +51,27 @@ export interface UseFetchDocumentOptions {
sourceType?: DocumentSourceType;
}
-export interface DocumentAction {
- /**
- * Close a document and remove it from state
- */
- closeDocument: (documentId: string) => void;
- /**
- * Flush any pending debounced save for a document
- */
- flushSave: (documentId?: string) => void;
- /**
- * Initialize a document with editor - stores state only.
- * Content is loaded into editor via onEditorInit when Editor component is ready.
- */
- initDocumentWithEditor: (params: InitDocumentParams) => void;
- /**
- * Trigger a debounced save for the specified document
- */
- triggerDebouncedSave: (documentId: string) => void;
- /**
- * SWR hook to fetch document and initialize in DocumentStore
- */
- useFetchDocument: (
- documentId: string | undefined,
- options?: UseFetchDocumentOptions,
- ) => SWRResponse<DocumentItem | null>;
-}
+type Setter = StoreSetter<DocumentStore>;
+export const createDocumentSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>
+ new DocumentActionImpl(set, get, _api);
-export const createDocumentSlice: StateCreator<
- DocumentStore,
- [['zustand/devtools', never]],
- [],
- DocumentAction
-> = (set, get) => {
- // Store debounced save functions per document - inside store closure so `get` is always correct
- const debouncedSaves = new Map<string, ReturnType<typeof debounce>>();
-
- const getOrCreateDebouncedSave = (documentId: string) => {
- if (!debouncedSaves.has(documentId)) {
+export class DocumentActionImpl {
+ readonly #get: () => DocumentStore;
+ readonly #set: Setter;
+ readonly #debouncedSaves = new Map<string, ReturnType<typeof debounce>>();
+
+ constructor(set: Setter, get: () => DocumentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ #getOrCreateDebouncedSave = (documentId: string) => {
+ if (!this.#debouncedSaves.has(documentId)) {
const debouncedFn = debounce(
async () => {
try {
- await get().performSave(documentId);
+ await this.#get().performSave(documentId);
} catch (error) {
console.error('[DocumentStore] Failed to auto-save:', error);
}
@@ -100,119 +79,142 @@ export const createDocumentSlice: StateCreator<
EDITOR_DEBOUNCE_TIME,
{ leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
);
- debouncedSaves.set(documentId, debouncedFn);
+ this.#debouncedSaves.set(documentId, debouncedFn);
}
- return debouncedSaves.get(documentId)!;
+ return this.#debouncedSaves.get(documentId)!;
};
- const cleanupDebouncedSave = (documentId: string) => {
- const fn = debouncedSaves.get(documentId);
+ #cleanupDebouncedSave = (documentId: string) => {
+ const fn = this.#debouncedSaves.get(documentId);
if (fn) {
fn.cancel();
- debouncedSaves.delete(documentId);
+ this.#debouncedSaves.delete(documentId);
}
};
- return {
- closeDocument: (documentId) => {
- // Flush any pending saves before closing
- const save = debouncedSaves.get(documentId);
- if (save) {
- save.flush();
- cleanupDebouncedSave(documentId);
- }
-
- const { activeDocumentId, internal_dispatchDocument } = get();
-
- // Delete document via reducer
- internal_dispatchDocument({ id: documentId, type: 'deleteDocument' });
-
- // Update activeDocumentId if needed
- if (activeDocumentId === documentId) {
- set({ activeDocumentId: undefined }, false, n('closeDocument:clearActive'));
- }
- },
-
- flushSave: (documentId) => {
- const id = documentId || get().activeDocumentId;
- if (id) {
- const save = debouncedSaves.get(id);
- save?.flush();
- }
- },
-
- initDocumentWithEditor: (params) => {
- const { documentId, sourceType, content, editorData, topicId, autoSave, editor } = params;
-
- const { internal_dispatchDocument } = get();
-
- // Add or update document via reducer
- internal_dispatchDocument({
- id: documentId,
- type: 'addDocument',
- value: {
- autoSave,
- content: content ?? undefined,
- editorData,
- lastSavedContent: content ?? undefined,
- sourceType,
- topicId,
- },
- });
+ /**
+ * Close a document and remove it from state
+ */
+ closeDocument = (documentId: string): void => {
+ // Flush any pending saves before closing
+ const save = this.#debouncedSaves.get(documentId);
+ if (save) {
+ save.flush();
+ this.#cleanupDebouncedSave(documentId);
+ }
- // Update activeDocumentId and editor
- set({ activeDocumentId: documentId, editor }, false, n('initDocumentWithEditor:setActive'));
- },
+ const { activeDocumentId, internal_dispatchDocument } = this.#get();
- triggerDebouncedSave: (documentId) => {
- const save = getOrCreateDebouncedSave(documentId);
- save();
- },
+ // Delete document via reducer
+ internal_dispatchDocument({ id: documentId, type: 'deleteDocument' });
- useFetchDocument: (documentId, options = {}) => {
- const { autoSave = true, editor, sourceType = 'page' } = options;
- const swrKey = documentId && editor ? ['document/editor', documentId] : null;
+ // Update activeDocumentId if needed
+ if (activeDocumentId === documentId) {
+ this.#set({ activeDocumentId: undefined }, false, n('closeDocument:clearActive'));
+ }
+ };
- return useClientDataSWRWithSync<DocumentItem | null>(
- swrKey,
- async () => {
- // documentId is guaranteed to be defined when swrKey is not null
- const document = await documentService.getDocumentById(documentId!);
- if (!document) {
- console.warn(`[useFetchDocument] Document not found: ${documentId}`);
- return null;
+ /**
+ * Flush any pending debounced save for a document
+ */
+ flushSave = (documentId?: string): void => {
+ const id = documentId || this.#get().activeDocumentId;
+ if (id) {
+ const save = this.#debouncedSaves.get(id);
+ save?.flush();
+ }
+ };
+
+ /**
+ * Initialize a document with editor - stores state only.
+ * Content is loaded into editor via onEditorInit when Editor component is ready.
+ */
+ initDocumentWithEditor = (params: InitDocumentParams): void => {
+ const { documentId, sourceType, content, editorData, topicId, autoSave, editor } = params;
+
+ const { internal_dispatchDocument } = this.#get();
+
+ // Add or update document via reducer
+ internal_dispatchDocument({
+ id: documentId,
+ type: 'addDocument',
+ value: {
+ autoSave,
+ content: content ?? undefined,
+ editorData,
+ lastSavedContent: content ?? undefined,
+ sourceType,
+ topicId,
+ },
+ });
+
+ // Update activeDocumentId and editor
+ this.#set(
+ { activeDocumentId: documentId, editor },
+ false,
+ n('initDocumentWithEditor:setActive'),
+ );
+ };
+
+ /**
+ * Trigger a debounced save for the specified document
+ */
+ triggerDebouncedSave = (documentId: string): void => {
+ const save = this.#getOrCreateDebouncedSave(documentId);
+ save();
+ };
+
+ /**
+ * SWR hook to fetch document and initialize in DocumentStore
+ */
+ useFetchDocument = (
+ documentId: string | undefined,
+ options: UseFetchDocumentOptions = {},
+ ): SWRResponse<DocumentItem | null> => {
+ const { autoSave = true, editor, sourceType = 'page' } = options;
+ const swrKey = documentId && editor ? ['document/editor', documentId] : null;
+
+ return useClientDataSWRWithSync<DocumentItem | null>(
+ swrKey,
+ async () => {
+ // documentId is guaranteed to be defined when swrKey is not null
+ const document = await documentService.getDocumentById(documentId!);
+ if (!document) {
+ console.warn(`[useFetchDocument] Document not found: ${documentId}`);
+ return null;
+ }
+
+ return document;
+ },
+ {
+ focusThrottleInterval: 20_000,
+ onData: (document) => {
+ // Both documentId and editor are guaranteed to be defined when this callback is called
+ if (!document || !documentId || !editor) return;
+
+ // Check if this response is still for the current active document
+ // This prevents race conditions when quickly switching between documents
+ const currentActiveId = this.#get().activeDocumentId;
+
+ if (currentActiveId && currentActiveId !== documentId) {
+ // User has already switched to another document, discard this stale response
+ return;
}
- return document;
- },
- {
- focusThrottleInterval: 20_000,
- onData: (document) => {
- // Both documentId and editor are guaranteed to be defined when this callback is called
- if (!document || !documentId || !editor) return;
-
- // Check if this response is still for the current active document
- // This prevents race conditions when quickly switching between documents
- const currentActiveId = get().activeDocumentId;
-
- if (currentActiveId && currentActiveId !== documentId) {
- // User has already switched to another document, discard this stale response
- return;
- }
-
- // Initialize document with editor
- get().initDocumentWithEditor({
- autoSave,
- content: document.content,
- documentId,
- editor,
- editorData: document.editorData,
- sourceType,
- });
- },
- revalidateOnFocus: true,
+ // Initialize document with editor
+ this.#get().initDocumentWithEditor({
+ autoSave,
+ content: document.content,
+ documentId,
+ editor,
+ editorData: document.editorData,
+ sourceType,
+ });
},
- );
- },
+ revalidateOnFocus: true,
+ },
+ );
};
-};
+}
+
+export type DocumentAction = Pick<DocumentActionImpl, keyof DocumentActionImpl>;
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index 1cc0c6be8a7..ba291078b7a 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -3,9 +3,9 @@
import type { IEditor } from '@lobehub/editor/es/types';
import { type EditorState as LobehubEditorState } from '@lobehub/editor/react';
import isEqual from 'fast-deep-equal';
-import { type StateCreator } from 'zustand/vanilla';
import { documentService } from '@/services/document';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type { DocumentStore } from '../../store';
@@ -21,47 +21,22 @@ export interface SaveMetadata {
title?: string;
}
-export interface EditorAction {
- /**
- * Get current content from editor
- */
- getEditorContent: () => { editorData: any; markdown: string } | null;
- /**
- * Handle content change from editor
- */
- handleContentChange: () => void;
- /**
- * Dispatch action to update documents map
- */
- internal_dispatchDocument: (payload: DocumentDispatch, action?: string) => void;
- /**
- * Mark a document as dirty
- */
- markDirty: (documentId: string) => void;
- /**
- * Called when editor is initialized
- */
- onEditorInit: (editor: IEditor) => Promise<void>;
- /**
- * Perform save operation for a document
- * @param documentId - Document ID (defaults to active document)
- * @param metadata - Document metadata (title, emoji) passed from caller
- */
- performSave: (documentId?: string, metadata?: SaveMetadata) => Promise<void>;
- /**
- * Set editor state from useEditorState hook
- */
- setEditorState: (editorState: LobehubEditorState | undefined) => void;
-}
+type Setter = StoreSetter<DocumentStore>;
+export const createEditorSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>
+ new EditorActionImpl(set, get, _api);
+
+export class EditorActionImpl {
+ readonly #get: () => DocumentStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => DocumentStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createEditorSlice: StateCreator<
- DocumentStore,
- [['zustand/devtools', never]],
- [],
- EditorAction
-> = (set, get) => ({
- getEditorContent: () => {
- const { editor } = get();
+ getEditorContent = (): { editorData: any; markdown: string } | null => {
+ const { editor } = this.#get();
if (!editor) return null;
try {
@@ -72,10 +47,10 @@ export const createEditorSlice: StateCreator<
console.error('[DocumentStore] Failed to get editor content:', error);
return null;
}
- },
+ };
- handleContentChange: () => {
- const { editor, activeDocumentId, documents, internal_dispatchDocument } = get();
+ handleContentChange = (): void => {
+ const { editor, activeDocumentId, documents, internal_dispatchDocument } = this.#get();
if (!editor || !activeDocumentId) return;
const doc = documents[activeDocumentId];
@@ -99,35 +74,35 @@ export const createEditorSlice: StateCreator<
// Only trigger auto-save if content actually changed AND autoSave is enabled
if (contentChanged && doc.autoSave !== false) {
- get().triggerDebouncedSave(activeDocumentId);
+ this.#get().triggerDebouncedSave(activeDocumentId);
}
} catch (error) {
console.error('[DocumentStore] Failed to update content:', error);
}
- },
+ };
- internal_dispatchDocument: (payload, action) => {
- const { documents } = get();
+ internal_dispatchDocument = (payload: DocumentDispatch, action?: string): void => {
+ const { documents } = this.#get();
const nextDocuments = documentReducer(documents, payload);
if (isEqual(documents, nextDocuments)) return;
- set(
+ this.#set(
{ documents: nextDocuments },
false,
action ?? n(`dispatchDocument/${payload.type}`, { id: payload.id }),
);
- },
+ };
- markDirty: (documentId) => {
- const { documents, internal_dispatchDocument } = get();
+ markDirty = (documentId: string): void => {
+ const { documents, internal_dispatchDocument } = this.#get();
if (!documents[documentId]) return;
internal_dispatchDocument({ id: documentId, type: 'updateDocument', value: { isDirty: true } });
- },
+ };
- onEditorInit: async (editor) => {
- const { activeDocumentId, documents } = get();
+ onEditorInit = async (editor: IEditor): Promise<void> => {
+ const { activeDocumentId, documents } = this.#get();
if (!editor || !activeDocumentId) return;
const doc = documents[activeDocumentId];
@@ -161,15 +136,15 @@ export const createEditorSlice: StateCreator<
}
}
- set({ editor });
- },
+ this.#set({ editor });
+ };
- performSave: async (documentId, metadata) => {
- const id = documentId || get().activeDocumentId;
+ performSave = async (documentId?: string, metadata?: SaveMetadata): Promise<void> => {
+ const id = documentId || this.#get().activeDocumentId;
if (!id) return;
- const { editor, documents, internal_dispatchDocument } = get();
+ const { editor, documents, internal_dispatchDocument } = this.#get();
const doc = documents[id];
if (!doc || !editor) return;
@@ -208,9 +183,11 @@ export const createEditorSlice: StateCreator<
console.error('[DocumentStore] Failed to save:', error);
internal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'idle' } });
}
- },
+ };
+
+ setEditorState = (editorState: LobehubEditorState | undefined): void => {
+ this.#set({ editorState }, false, n('setEditorState'));
+ };
+}
- setEditorState: (editorState) => {
- set({ editorState }, false, n('setEditorState'));
- },
-});
+export type EditorAction = Pick<EditorActionImpl, keyof EditorActionImpl>;
diff --git a/src/store/document/slices/editor/reducer.ts b/src/store/document/slices/editor/reducer.ts
index ffcc89c8267..31f424a7ed1 100644
--- a/src/store/document/slices/editor/reducer.ts
+++ b/src/store/document/slices/editor/reducer.ts
@@ -4,22 +4,22 @@ import { type EditorContentState, createInitialEditorContentState } from './init
// ============ Action Types ============
-interface AddDocumentAction {
+type AddDocumentAction = {
id: string;
type: 'addDocument';
value: Partial<EditorContentState> & { sourceType: EditorContentState['sourceType'] };
-}
+};
-interface UpdateDocumentAction {
+type UpdateDocumentAction = {
id: string;
type: 'updateDocument';
value: Partial<EditorContentState>;
-}
+};
-interface DeleteDocumentAction {
+type DeleteDocumentAction = {
id: string;
type: 'deleteDocument';
-}
+};
export type DocumentDispatch = AddDocumentAction | UpdateDocumentAction | DeleteDocumentAction;
diff --git a/src/store/document/store.ts b/src/store/document/store.ts
index 208bee33c2e..0efe446ba70 100644
--- a/src/store/document/store.ts
+++ b/src/store/document/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type DocumentAction, createDocumentSlice } from './slices/document';
import {
type EditorAction,
@@ -26,11 +27,13 @@ const initialState: DocumentState = {
};
const createStore: StateCreator<DocumentStore, [['zustand/devtools', never]]> = (
- ...parameters
+ ...parameters: Parameters<StateCreator<DocumentStore, [['zustand/devtools', never]]>>
) => ({
...initialState,
- ...createDocumentSlice(...parameters),
- ...createEditorSlice(...parameters),
+ ...flattenActions<DocumentStoreAction>([
+ createDocumentSlice(...parameters),
+ createEditorSlice(...parameters),
+ ]),
});
const devtools = createDevtools('document');
diff --git a/src/store/electron/actions/app.ts b/src/store/electron/actions/app.ts
index e377f1ff8e2..d031024b4b6 100644
--- a/src/store/electron/actions/app.ts
+++ b/src/store/electron/actions/app.ts
@@ -1,11 +1,11 @@
import { type ElectronAppState } from '@lobechat/electron-client-ipc';
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { useOnlyFetchOnceSWR } from '@/libs/swr';
// Import for type usage
import { electronSystemService } from '@/services/electron/system';
+import { type StoreSetter } from '@/store/types';
import { type LocaleMode } from '@/types/locale';
import { switchLang } from '@/utils/client/switchLang';
import { merge } from '@/utils/merge';
@@ -14,41 +14,38 @@ import type { ElectronStore } from '../store';
// ======== Action Interface ======== //
-export interface ElectronAppAction {
- setConnectionDrawerOpen: (isOpen: boolean) => void;
- updateElectronAppState: (state: ElectronAppState) => void;
+// ======== Action Implementation ======== //
- /**
- * Initializes the basic Electron application state, including system info and special paths.
- * Should be called once when the application starts.
- */
- useInitElectronAppState: () => SWRResponse<ElectronAppState>;
-}
+type Setter = StoreSetter<ElectronStore>;
+export const createElectronAppSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
+ new ElectronAppActionImpl(set, get, _api);
-// ======== Action Implementation ======== //
+export class ElectronAppActionImpl {
+ readonly #get: () => ElectronStore;
+ readonly #set: Setter;
-export const createElectronAppSlice: StateCreator<
- ElectronStore,
- [['zustand/devtools', never]],
- [],
- ElectronAppAction
-> = (set, get) => ({
- setConnectionDrawerOpen: (isOpen: boolean) => {
- set({ isConnectionDrawerOpen: isOpen }, false, 'setConnectionDrawerOpen');
- },
+ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- updateElectronAppState: (state: ElectronAppState) => {
- const prevState = get().appState;
- set({ appState: merge(prevState, state) });
- },
+ setConnectionDrawerOpen = (isOpen: boolean): void => {
+ this.#set({ isConnectionDrawerOpen: isOpen }, false, 'setConnectionDrawerOpen');
+ };
- useInitElectronAppState: () =>
- useOnlyFetchOnceSWR<ElectronAppState>(
+ updateElectronAppState = (state: ElectronAppState): void => {
+ const prevState = this.#get().appState;
+ this.#set({ appState: merge(prevState, state) });
+ };
+
+ useInitElectronAppState = (): SWRResponse<ElectronAppState> => {
+ return useOnlyFetchOnceSWR<ElectronAppState>(
'initElectronAppState',
async () => electronSystemService.getAppState(),
{
onSuccess: (result) => {
- set({ appState: result, isAppStateInit: true }, false, 'initElectronAppState');
+ this.#set({ appState: result, isAppStateInit: true }, false, 'initElectronAppState');
// Update the global agent context manager with relevant paths
// We typically only need paths in the agent context for now.
@@ -68,5 +65,8 @@ export const createElectronAppSlice: StateCreator<
switchLang(locale);
},
},
- ),
-});
+ );
+ };
+}
+
+export type ElectronAppAction = Pick<ElectronAppActionImpl, keyof ElectronAppActionImpl>;
diff --git a/src/store/electron/actions/navigationHistory.ts b/src/store/electron/actions/navigationHistory.ts
index 45f61db78a8..627f1352130 100644
--- a/src/store/electron/actions/navigationHistory.ts
+++ b/src/store/electron/actions/navigationHistory.ts
@@ -1,4 +1,4 @@
-import { type StateCreator } from 'zustand/vanilla';
+import { type StoreSetter } from '@/store/types';
import type { ElectronStore } from '../store';
@@ -38,60 +38,6 @@ export interface NavigationHistoryState {
// ======== Action Interface ======== //
-export interface NavigationHistoryAction {
- /**
- * Check if can go back in history
- */
- canGoBack: () => boolean;
-
- /**
- * Check if can go forward in history
- */
- canGoForward: () => boolean;
-
- /**
- * Get current history entry
- */
- getCurrentEntry: () => HistoryEntry | null;
-
- /**
- * Navigate back in history
- * @returns The target entry or null if cannot go back
- */
- goBack: () => HistoryEntry | null;
-
- /**
- * Navigate forward in history
- * @returns The target entry or null if cannot go forward
- */
- goForward: () => HistoryEntry | null;
-
- /**
- * Push a new entry to history (for normal navigation)
- * Truncates any forward history if not at the end
- */
- pushHistory: (
- entry: Omit<HistoryEntry, 'metadata'> & { metadata?: Partial<HistoryEntry['metadata']> },
- ) => void;
-
- /**
- * Replace current entry in history (for replace navigation)
- */
- replaceHistory: (
- entry: Omit<HistoryEntry, 'metadata'> & { metadata?: Partial<HistoryEntry['metadata']> },
- ) => void;
-
- /**
- * Set current page title (called by PageTitle component)
- */
- setCurrentPageTitle: (title: string) => void;
-
- /**
- * Set the navigating history flag
- */
- setIsNavigatingHistory: (value: boolean) => void;
-}
-
// ======== Initial State ======== //
export const navigationHistoryInitialState: NavigationHistoryState = {
@@ -103,32 +49,43 @@ export const navigationHistoryInitialState: NavigationHistoryState = {
// ======== Action Implementation ======== //
-export const createNavigationHistorySlice: StateCreator<
- ElectronStore,
- [['zustand/devtools', never]],
- [],
- NavigationHistoryAction
-> = (set, get) => ({
- canGoBack: () => {
- const { historyCurrentIndex } = get();
+type Setter = StoreSetter<ElectronStore>;
+export const createNavigationHistorySlice = (
+ set: Setter,
+ get: () => ElectronStore,
+ _api?: unknown,
+) => new NavigationHistoryActionImpl(set, get, _api);
+
+export class NavigationHistoryActionImpl {
+ readonly #get: () => ElectronStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ canGoBack = (): boolean => {
+ const { historyCurrentIndex } = this.#get();
return historyCurrentIndex > 0;
- },
+ };
- canGoForward: () => {
- const { historyCurrentIndex, historyEntries } = get();
+ canGoForward = (): boolean => {
+ const { historyCurrentIndex, historyEntries } = this.#get();
return historyCurrentIndex < historyEntries.length - 1;
- },
+ };
- getCurrentEntry: () => {
- const { historyCurrentIndex, historyEntries } = get();
+ getCurrentEntry = (): HistoryEntry | null => {
+ const { historyCurrentIndex, historyEntries } = this.#get();
if (historyCurrentIndex < 0 || historyCurrentIndex >= historyEntries.length) {
return null;
}
return historyEntries[historyCurrentIndex];
- },
+ };
- goBack: () => {
- const { historyCurrentIndex, historyEntries } = get();
+ goBack = (): HistoryEntry | null => {
+ const { historyCurrentIndex, historyEntries } = this.#get();
if (historyCurrentIndex <= 0) {
return null;
@@ -137,7 +94,7 @@ export const createNavigationHistorySlice: StateCreator<
const newIndex = historyCurrentIndex - 1;
const targetEntry = historyEntries[newIndex];
- set(
+ this.#set(
{
historyCurrentIndex: newIndex,
isNavigatingHistory: true,
@@ -147,10 +104,10 @@ export const createNavigationHistorySlice: StateCreator<
);
return targetEntry;
- },
+ };
- goForward: () => {
- const { historyCurrentIndex, historyEntries } = get();
+ goForward = (): HistoryEntry | null => {
+ const { historyCurrentIndex, historyEntries } = this.#get();
if (historyCurrentIndex >= historyEntries.length - 1) {
return null;
@@ -159,7 +116,7 @@ export const createNavigationHistorySlice: StateCreator<
const newIndex = historyCurrentIndex + 1;
const targetEntry = historyEntries[newIndex];
- set(
+ this.#set(
{
historyCurrentIndex: newIndex,
isNavigatingHistory: true,
@@ -169,10 +126,12 @@ export const createNavigationHistorySlice: StateCreator<
);
return targetEntry;
- },
+ };
- pushHistory: (entry) => {
- const { historyCurrentIndex, historyEntries } = get();
+ pushHistory = (
+ entry: Omit<HistoryEntry, 'metadata'> & { metadata?: Partial<HistoryEntry['metadata']> },
+ ): void => {
+ const { historyCurrentIndex, historyEntries } = this.#get();
// Create full entry with metadata
const fullEntry: HistoryEntry = {
@@ -194,7 +153,7 @@ export const createNavigationHistorySlice: StateCreator<
// Add new entry
newEntries.push(fullEntry);
- set(
+ this.#set(
{
historyCurrentIndex: newEntries.length - 1,
historyEntries: newEntries,
@@ -202,14 +161,16 @@ export const createNavigationHistorySlice: StateCreator<
false,
'pushHistory',
);
- },
+ };
- replaceHistory: (entry) => {
- const { historyCurrentIndex, historyEntries } = get();
+ replaceHistory = (
+ entry: Omit<HistoryEntry, 'metadata'> & { metadata?: Partial<HistoryEntry['metadata']> },
+ ): void => {
+ const { historyCurrentIndex, historyEntries } = this.#get();
// If history is empty, just push
if (historyCurrentIndex < 0 || historyEntries.length === 0) {
- get().pushHistory(entry);
+ this.#get().pushHistory(entry);
return;
}
@@ -228,20 +189,25 @@ export const createNavigationHistorySlice: StateCreator<
const newEntries = [...historyEntries];
newEntries[historyCurrentIndex] = fullEntry;
- set(
+ this.#set(
{
historyEntries: newEntries,
},
false,
'replaceHistory',
);
- },
+ };
+
+ setCurrentPageTitle = (title: string): void => {
+ this.#set({ currentPageTitle: title }, false, 'setCurrentPageTitle');
+ };
- setCurrentPageTitle: (title) => {
- set({ currentPageTitle: title }, false, 'setCurrentPageTitle');
- },
+ setIsNavigatingHistory = (value: boolean): void => {
+ this.#set({ isNavigatingHistory: value }, false, 'setIsNavigatingHistory');
+ };
+}
- setIsNavigatingHistory: (value) => {
- set({ isNavigatingHistory: value }, false, 'setIsNavigatingHistory');
- },
-});
+export type NavigationHistoryAction = Pick<
+ NavigationHistoryActionImpl,
+ keyof NavigationHistoryActionImpl
+>;
diff --git a/src/store/electron/actions/recentPages.ts b/src/store/electron/actions/recentPages.ts
index e918a470fae..8457cae98a2 100644
--- a/src/store/electron/actions/recentPages.ts
+++ b/src/store/electron/actions/recentPages.ts
@@ -1,5 +1,3 @@
-import { type StateCreator } from 'zustand/vanilla';
-
import {
getPinnedPages,
savePinnedPages,
@@ -8,6 +6,7 @@ import {
type CachedPageData,
type PageReference,
} from '@/features/Electron/titlebar/RecentlyViewed/types';
+import { type StoreSetter } from '@/store/types';
import type { ElectronStore } from '../store';
@@ -25,45 +24,6 @@ export interface RecentPagesState {
// ======== Action Interface ======== //
-export interface RecentPagesAction {
- /**
- * Add/update a page reference in recent list (auto-dedupe)
- * @param reference - The page reference to add
- * @param cached - Optional cached display data (title, avatar, etc.)
- */
- addRecentPage: (reference: PageReference, cached?: CachedPageData) => void;
-
- /**
- * Clear all recent pages
- */
- clearRecentPages: () => void;
-
- /**
- * Check if a page is pinned by its ID
- */
- isPagePinned: (id: string) => boolean;
-
- /**
- * Load pinned pages from localStorage (called on init)
- */
- loadPinnedPages: () => void;
-
- /**
- * Add a page to pinned list
- */
- pinPage: (reference: PageReference) => void;
-
- /**
- * Remove a page from recent list by ID
- */
- removeRecentPage: (id: string) => void;
-
- /**
- * Remove a page from pinned list by ID
- */
- unpinPage: (id: string) => void;
-}
-
// ======== Initial State ======== //
export const recentPagesInitialState: RecentPagesState = {
@@ -73,14 +33,22 @@ export const recentPagesInitialState: RecentPagesState = {
// ======== Action Implementation ======== //
-export const createRecentPagesSlice: StateCreator<
- ElectronStore,
- [['zustand/devtools', never]],
- [],
- RecentPagesAction
-> = (set, get) => ({
- addRecentPage: (reference, cached) => {
- const { pinnedPages, recentPages } = get();
+type Setter = StoreSetter<ElectronStore>;
+export const createRecentPagesSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
+ new RecentPagesActionImpl(set, get, _api);
+
+export class RecentPagesActionImpl {
+ readonly #get: () => ElectronStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ addRecentPage = (reference: PageReference, cached?: CachedPageData): void => {
+ const { pinnedPages, recentPages } = this.#get();
const { id } = reference;
// If pinned, update cached data on pinned entry
@@ -92,7 +60,7 @@ export const createRecentPagesSlice: StateCreator<
...updatedPinned[pinnedIndex],
cached: { ...updatedPinned[pinnedIndex].cached, ...cached },
};
- set({ pinnedPages: updatedPinned }, false, 'updatePinnedPageCache');
+ this.#set({ pinnedPages: updatedPinned }, false, 'updatePinnedPageCache');
savePinnedPages(updatedPinned);
}
return;
@@ -119,20 +87,20 @@ export const createRecentPagesSlice: StateCreator<
// Add to front, enforce limit
const newRecent = [newEntry, ...filtered].slice(0, RECENT_PAGES_LIMIT);
- set({ recentPages: newRecent }, false, 'addRecentPage');
- },
+ this.#set({ recentPages: newRecent }, false, 'addRecentPage');
+ };
- clearRecentPages: () => {
- set({ recentPages: [] }, false, 'clearRecentPages');
- },
+ clearRecentPages = (): void => {
+ this.#set({ recentPages: [] }, false, 'clearRecentPages');
+ };
- isPagePinned: (id) => {
- return get().pinnedPages.some((p) => p.id === id);
- },
+ isPagePinned = (id: string): boolean => {
+ return this.#get().pinnedPages.some((p) => p.id === id);
+ };
- loadPinnedPages: () => {
+ loadPinnedPages = (): void => {
const pinned = getPinnedPages();
- const { recentPages } = get();
+ const { recentPages } = this.#get();
const pinnedIds = new Set(pinned.map((p) => p.id));
@@ -140,11 +108,11 @@ export const createRecentPagesSlice: StateCreator<
// This handles the race condition where addRecentPage runs before loadPinnedPages
const filteredRecent = recentPages.filter((p) => !pinnedIds.has(p.id));
- set({ pinnedPages: pinned, recentPages: filteredRecent }, false, 'loadPinnedPages');
- },
+ this.#set({ pinnedPages: pinned, recentPages: filteredRecent }, false, 'loadPinnedPages');
+ };
- pinPage: (reference) => {
- const { pinnedPages, recentPages } = get();
+ pinPage = (reference: PageReference): void => {
+ const { pinnedPages, recentPages } = this.#get();
const { id } = reference;
// Check if already pinned
@@ -167,17 +135,17 @@ export const createRecentPagesSlice: StateCreator<
const newPinned = [...pinnedPages, newEntry];
const newRecent = recentPages.filter((p) => p.id !== id);
- set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'pinPage');
+ this.#set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'pinPage');
savePinnedPages(newPinned);
- },
+ };
- removeRecentPage: (id) => {
- const { recentPages } = get();
- set({ recentPages: recentPages.filter((p) => p.id !== id) }, false, 'removeRecentPage');
- },
+ removeRecentPage = (id: string): void => {
+ const { recentPages } = this.#get();
+ this.#set({ recentPages: recentPages.filter((p) => p.id !== id) }, false, 'removeRecentPage');
+ };
- unpinPage: (id) => {
- const { pinnedPages, recentPages } = get();
+ unpinPage = (id: string): void => {
+ const { pinnedPages, recentPages } = this.#get();
const page = pinnedPages.find((p) => p.id === id);
if (!page) return;
@@ -187,7 +155,9 @@ export const createRecentPagesSlice: StateCreator<
// Add back to recent (at the front)
const newRecent = [page, ...recentPages].slice(0, RECENT_PAGES_LIMIT);
- set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'unpinPage');
+ this.#set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'unpinPage');
savePinnedPages(newPinned);
- },
-});
+ };
+}
+
+export type RecentPagesAction = Pick<RecentPagesActionImpl, keyof RecentPagesActionImpl>;
diff --git a/src/store/electron/actions/settings.ts b/src/store/electron/actions/settings.ts
index e95a1c87a7c..f9a81e06074 100644
--- a/src/store/electron/actions/settings.ts
+++ b/src/store/electron/actions/settings.ts
@@ -1,62 +1,65 @@
-import { type NetworkProxySettings, type ShortcutUpdateResult } from '@lobechat/electron-client-ipc';
+import {
+ type NetworkProxySettings,
+ type ShortcutUpdateResult,
+} from '@lobechat/electron-client-ipc';
import isEqual from 'fast-deep-equal';
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { mutate } from '@/libs/swr';
import { desktopSettingsService } from '@/services/electron/settings';
+import { type StoreSetter } from '@/store/types';
import type { ElectronStore } from '../store';
/**
* Settings actions
*/
-export interface ElectronSettingsAction {
- refreshDesktopHotkeys: () => Promise<void>;
- refreshProxySettings: () => Promise<void>;
- setProxySettings: (params: Partial<NetworkProxySettings>) => Promise<void>;
- updateDesktopHotkey: (id: string, accelerator: string) => Promise<ShortcutUpdateResult>;
- useFetchDesktopHotkeys: () => SWRResponse;
- useGetProxySettings: () => SWRResponse;
-}
const ELECTRON_PROXY_SETTINGS_KEY = 'electron:getProxySettings';
const ELECTRON_DESKTOP_HOTKEYS_KEY = 'electron:getDesktopHotkeys';
-export const settingsSlice: StateCreator<
- ElectronStore,
- [['zustand/devtools', never]],
- [],
- ElectronSettingsAction
-> = (set, get) => ({
- refreshDesktopHotkeys: async () => {
+type Setter = StoreSetter<ElectronStore>;
+export const settingsSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
+ new ElectronSettingsActionImpl(set, get, _api);
+
+export class ElectronSettingsActionImpl {
+ readonly #get: () => ElectronStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ refreshDesktopHotkeys = async (): Promise<void> => {
await mutate(ELECTRON_DESKTOP_HOTKEYS_KEY);
- },
+ };
- refreshProxySettings: async () => {
+ refreshProxySettings = async (): Promise<void> => {
await mutate(ELECTRON_PROXY_SETTINGS_KEY);
- },
+ };
- setProxySettings: async (values) => {
+ setProxySettings = async (values: Partial<NetworkProxySettings>): Promise<void> => {
try {
// Update settings
await desktopSettingsService.setSettings(values);
// Refresh state
- await get().refreshProxySettings();
+ await this.#get().refreshProxySettings();
} catch (error) {
console.error('Proxy settings update failed:', error);
}
- },
+ };
- updateDesktopHotkey: async (id, accelerator) => {
+ updateDesktopHotkey = async (id: string, accelerator: string): Promise<ShortcutUpdateResult> => {
try {
// Update hotkey configuration
const result = await desktopSettingsService.updateDesktopHotkey(id, accelerator);
// If update successful, refresh state
if (result.success) {
- await get().refreshDesktopHotkeys();
+ await this.#get().refreshDesktopHotkeys();
}
return result;
@@ -67,31 +70,38 @@ export const settingsSlice: StateCreator<
success: false,
};
}
- },
+ };
- useFetchDesktopHotkeys: () =>
- useSWR<Record<string, string>>(
+ useFetchDesktopHotkeys = (): SWRResponse => {
+ return useSWR<Record<string, string>>(
ELECTRON_DESKTOP_HOTKEYS_KEY,
async () => desktopSettingsService.getDesktopHotkeys(),
{
onSuccess: (data) => {
- if (!isEqual(data, get().desktopHotkeys)) {
- set({ desktopHotkeys: data, isDesktopHotkeysInit: true });
+ if (!isEqual(data, this.#get().desktopHotkeys)) {
+ this.#set({ desktopHotkeys: data, isDesktopHotkeysInit: true });
}
},
},
- ),
+ );
+ };
- useGetProxySettings: () =>
- useSWR<NetworkProxySettings>(
+ useGetProxySettings = (): SWRResponse => {
+ return useSWR<NetworkProxySettings>(
ELECTRON_PROXY_SETTINGS_KEY,
async () => desktopSettingsService.getProxySettings(),
{
onSuccess: (data) => {
- if (!isEqual(data, get().proxySettings)) {
- set({ proxySettings: data });
+ if (!isEqual(data, this.#get().proxySettings)) {
+ this.#set({ proxySettings: data });
}
},
},
- ),
-});
+ );
+ };
+}
+
+export type ElectronSettingsAction = Pick<
+ ElectronSettingsActionImpl,
+ keyof ElectronSettingsActionImpl
+>;
diff --git a/src/store/electron/actions/sync.ts b/src/store/electron/actions/sync.ts
index cf532dc5985..3cd4c3a8acc 100644
--- a/src/store/electron/actions/sync.ts
+++ b/src/store/electron/actions/sync.ts
@@ -1,10 +1,10 @@
import { type DataSyncConfig } from '@lobechat/electron-client-ipc';
import isEqual from 'fast-deep-equal';
import useSWR, { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { mutate } from '@/libs/swr';
import { remoteServerService } from '@/services/electron/remoteServer';
+import { type StoreSetter } from '@/store/types';
import { initialState } from '../initialState';
import type { ElectronStore } from '../store';
@@ -12,32 +12,32 @@ import type { ElectronStore } from '../store';
/**
* Remote server actions
*/
-export interface ElectronRemoteServerAction {
- clearRemoteServerSyncError: () => void;
- connectRemoteServer: (params: DataSyncConfig) => Promise<void>;
- disconnectRemoteServer: () => Promise<void>;
- refreshServerConfig: () => Promise<void>;
- refreshUserData: () => Promise<void>;
- useDataSyncConfig: () => SWRResponse;
-}
const REMOTE_SERVER_CONFIG_KEY = 'electron:getRemoteServerConfig';
-export const remoteSyncSlice: StateCreator<
- ElectronStore,
- [['zustand/devtools', never]],
- [],
- ElectronRemoteServerAction
-> = (set, get) => ({
- clearRemoteServerSyncError: () => {
- set({ remoteServerSyncError: undefined }, false, 'clearRemoteServerSyncError');
- },
-
- connectRemoteServer: async (values) => {
+type Setter = StoreSetter<ElectronStore>;
+export const remoteSyncSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>
+ new ElectronRemoteServerActionImpl(set, get, _api);
+
+export class ElectronRemoteServerActionImpl {
+ readonly #get: () => ElectronStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ clearRemoteServerSyncError = (): void => {
+ this.#set({ remoteServerSyncError: undefined }, false, 'clearRemoteServerSyncError');
+ };
+
+ connectRemoteServer = async (values: DataSyncConfig): Promise<void> => {
if (values.storageMode === 'selfHost' && !values.remoteServerUrl) return;
- set({ isConnectingServer: true });
- get().clearRemoteServerSyncError();
+ this.#set({ isConnectingServer: true });
+ this.#get().clearRemoteServerSyncError();
try {
// Get current configuration
const config = await remoteServerService.getRemoteServerConfig();
@@ -53,46 +53,46 @@ export const remoteSyncSlice: StateCreator<
if (!result.success) {
console.error('Authorization request failed:', result.error);
- set({
+ this.#set({
remoteServerSyncError: { message: result.error, type: 'AUTH_ERROR' },
});
}
// Refresh state
- await get().refreshServerConfig();
+ await this.#get().refreshServerConfig();
} catch (error) {
console.error('Remote server configuration error:', error);
- set({
+ this.#set({
remoteServerSyncError: { message: (error as Error).message, type: 'CONFIG_ERROR' },
});
} finally {
- set({ isConnectingServer: false });
+ this.#set({ isConnectingServer: false });
}
- },
+ };
- disconnectRemoteServer: async () => {
- set({ isConnectingServer: false });
- get().clearRemoteServerSyncError();
+ disconnectRemoteServer = async (): Promise<void> => {
+ this.#set({ isConnectingServer: false });
+ this.#get().clearRemoteServerSyncError();
try {
await remoteServerService.setRemoteServerConfig({ active: false, storageMode: 'cloud' });
// Update form URL to empty
- set({ dataSyncConfig: initialState.dataSyncConfig });
+ this.#set({ dataSyncConfig: initialState.dataSyncConfig });
// Refresh state
- await get().refreshServerConfig();
+ await this.#get().refreshServerConfig();
} catch (error) {
console.error('Disconnect failed:', error);
- set({
+ this.#set({
remoteServerSyncError: { message: (error as Error).message, type: 'DISCONNECT_ERROR' },
});
} finally {
- set({ isConnectingServer: false });
+ this.#set({ isConnectingServer: false });
}
- },
+ };
- refreshServerConfig: async () => {
+ refreshServerConfig = async (): Promise<void> => {
await mutate(REMOTE_SERVER_CONFIG_KEY);
- },
+ };
- refreshUserData: async () => {
+ refreshUserData = async (): Promise<void> => {
const { getSessionStoreState } = await import('@/store/session');
const { getChatStoreState } = await import('@/store/chat');
const { getUserStoreState } = await import('@/store/user');
@@ -101,10 +101,10 @@ export const remoteSyncSlice: StateCreator<
await getChatStoreState().refreshMessages();
await getChatStoreState().refreshTopic();
await getUserStoreState().refreshUserState();
- },
+ };
- useDataSyncConfig: () =>
- useSWR<DataSyncConfig>(
+ useDataSyncConfig = (): SWRResponse => {
+ return useSWR<DataSyncConfig>(
REMOTE_SERVER_CONFIG_KEY,
async () => {
try {
@@ -116,13 +116,19 @@ export const remoteSyncSlice: StateCreator<
},
{
onSuccess: (data) => {
- if (!isEqual(data, get().dataSyncConfig)) {
- get().refreshUserData();
+ if (!isEqual(data, this.#get().dataSyncConfig)) {
+ this.#get().refreshUserData();
}
- set({ dataSyncConfig: data, isInitRemoteServerConfig: true });
+ this.#set({ dataSyncConfig: data, isInitRemoteServerConfig: true });
},
suspense: false,
},
- ),
-});
+ );
+ };
+}
+
+export type ElectronRemoteServerAction = Pick<
+ ElectronRemoteServerActionImpl,
+ keyof ElectronRemoteServerActionImpl
+>;
diff --git a/src/store/electron/store.ts b/src/store/electron/store.ts
index ae768e3a589..de5db2284e8 100644
--- a/src/store/electron/store.ts
+++ b/src/store/electron/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type ElectronAppAction, createElectronAppSlice } from './actions/app';
import {
type NavigationHistoryAction,
@@ -26,15 +27,23 @@ export interface ElectronStore
/* empty */
}
+type ElectronStoreAction = ElectronRemoteServerAction &
+ ElectronAppAction &
+ ElectronSettingsAction &
+ NavigationHistoryAction &
+ RecentPagesAction;
+
const createStore: StateCreator<ElectronStore, [['zustand/devtools', never]]> = (
- ...parameters
+ ...parameters: Parameters<StateCreator<ElectronStore, [['zustand/devtools', never]]>>
) => ({
...initialState,
- ...remoteSyncSlice(...parameters),
- ...createElectronAppSlice(...parameters),
- ...settingsSlice(...parameters),
- ...createNavigationHistorySlice(...parameters),
- ...createRecentPagesSlice(...parameters),
+ ...flattenActions<ElectronStoreAction>([
+ remoteSyncSlice(...parameters),
+ createElectronAppSlice(...parameters),
+ settingsSlice(...parameters),
+ createNavigationHistorySlice(...parameters),
+ createRecentPagesSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/file/initialState.ts b/src/store/file/initialState.ts
index 15c7e380807..156fb01ba9b 100644
--- a/src/store/file/initialState.ts
+++ b/src/store/file/initialState.ts
@@ -2,15 +2,18 @@ import { type ImageFileState, initialImageFileState } from './slices/chat';
import { type FileChunkState, initialFileChunkState } from './slices/chunk';
import { type DocumentState, initialDocumentState } from './slices/document';
import { type FileManagerState, initialFileManagerState } from './slices/fileManager';
+import { type ResourceState, initialResourceState } from './slices/resource/initialState';
export type FilesStoreState = ImageFileState &
DocumentState &
FileManagerState &
- FileChunkState;
+ FileChunkState &
+ ResourceState;
export const initialState: FilesStoreState = {
...initialImageFileState,
...initialDocumentState,
...initialFileManagerState,
...initialFileChunkState,
+ ...initialResourceState,
};
diff --git a/src/store/file/reducers/uploadFileList.ts b/src/store/file/reducers/uploadFileList.ts
index 2869bff87ba..72c2ade909a 100644
--- a/src/store/file/reducers/uploadFileList.ts
+++ b/src/store/file/reducers/uploadFileList.ts
@@ -1,6 +1,10 @@
import { produce } from 'immer';
-import { type FileUploadState, type FileUploadStatus, type UploadFileItem } from '@/types/files/upload';
+import {
+ type FileUploadState,
+ type FileUploadStatus,
+ type UploadFileItem,
+} from '@/types/files/upload';
interface AddFile {
atStart?: boolean;
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index f473260ba29..73ef48e372c 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -1,6 +1,5 @@
import { type ChatContextContent } from '@lobechat/types';
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { notification } from '@/components/AntdStaticMethods';
import { FILE_UPLOAD_BLACKLIST } from '@/const/file';
@@ -11,6 +10,7 @@ import {
type UploadFileListDispatch,
uploadFileListReducer,
} from '@/store/file/reducers/uploadFileList';
+import { type StoreSetter } from '@/store/types';
import { type FileListItem } from '@/types/files';
import { type UploadFileItem } from '@/types/files/upload';
import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
@@ -21,62 +21,59 @@ import { type FileStore } from '../../store';
const n = setNamespace('chat');
-export interface FileAction {
- addChatContextSelection: (context: ChatContextContent) => void;
- clearChatContextSelections: () => void;
- clearChatUploadFileList: () => void;
- dispatchChatUploadFileList: (payload: UploadFileListDispatch) => void;
- removeChatContextSelection: (id: string) => void;
- removeChatUploadFile: (id: string) => Promise<void>;
- startAsyncTask: (
- fileId: string,
- runner: (id: string) => Promise<string>,
- onFileItemChange: (fileItem: FileListItem) => void,
- ) => Promise<void>;
- uploadChatFiles: (files: File[]) => Promise<void>;
-}
+type Setter = StoreSetter<FileStore>;
+export const createFileSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
+ new FileActionImpl(set, get, _api);
+
+export class FileActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createFileSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- FileAction
-> = (set, get) => ({
- addChatContextSelection: (context) => {
- const current = get().chatContextSelections;
+ addChatContextSelection = (context: ChatContextContent): void => {
+ const current = this.#get().chatContextSelections;
const next = [context, ...current.filter((item) => item.id !== context.id)];
- set({ chatContextSelections: next }, false, n('addChatContextSelection'));
- },
+ this.#set({ chatContextSelections: next }, false, n('addChatContextSelection'));
+ };
- clearChatContextSelections: () => {
- set({ chatContextSelections: [] }, false, n('clearChatContextSelections'));
- },
+ clearChatContextSelections = (): void => {
+ this.#set({ chatContextSelections: [] }, false, n('clearChatContextSelections'));
+ };
- clearChatUploadFileList: () => {
- set({ chatUploadFileList: [] }, false, n('clearChatUploadFileList'));
- },
+ clearChatUploadFileList = (): void => {
+ this.#set({ chatUploadFileList: [] }, false, n('clearChatUploadFileList'));
+ };
- dispatchChatUploadFileList: (payload) => {
- const nextValue = uploadFileListReducer(get().chatUploadFileList, payload);
- if (nextValue === get().chatUploadFileList) return;
+ dispatchChatUploadFileList = (payload: UploadFileListDispatch): void => {
+ const nextValue = uploadFileListReducer(this.#get().chatUploadFileList, payload);
+ if (nextValue === this.#get().chatUploadFileList) return;
- set({ chatUploadFileList: nextValue }, false, `dispatchChatFileList/${payload.type}`);
- },
+ this.#set({ chatUploadFileList: nextValue }, false, `dispatchChatFileList/${payload.type}`);
+ };
- removeChatContextSelection: (id) => {
- const next = get().chatContextSelections.filter((item) => item.id !== id);
- set({ chatContextSelections: next }, false, n('removeChatContextSelection'));
- },
+ removeChatContextSelection = (id: string): void => {
+ const next = this.#get().chatContextSelections.filter((item) => item.id !== id);
+ this.#set({ chatContextSelections: next }, false, n('removeChatContextSelection'));
+ };
- removeChatUploadFile: async (id) => {
- const { dispatchChatUploadFileList } = get();
+ removeChatUploadFile = async (id: string): Promise<void> => {
+ const { dispatchChatUploadFileList } = this.#get();
dispatchChatUploadFileList({ id, type: 'removeFile' });
await fileService.removeFile(id);
- },
+ };
- startAsyncTask: async (id, runner, onFileItemUpdate) => {
+ startAsyncTask = async (
+ id: string,
+ runner: (id: string) => Promise<string>,
+ onFileItemUpdate: (fileItem: FileListItem) => void,
+ ): Promise<void> => {
await runner(id);
let isFinished = false;
@@ -108,10 +105,10 @@ export const createFileSlice: StateCreator<
isFinished = true;
}
}
- },
+ };
- uploadChatFiles: async (rawFiles) => {
- const { dispatchChatUploadFileList } = get();
+ uploadChatFiles = async (rawFiles: File[]): Promise<void> => {
+ const { dispatchChatUploadFileList } = this.#get();
// 0. skip file in blacklist
const files = rawFiles.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));
// 1. add files with base64
@@ -141,7 +138,7 @@ export const createFileSlice: StateCreator<
let fileResult: { id: string; url: string } | undefined;
try {
- fileResult = await get().uploadWithProgress({
+ fileResult = await this.#get().uploadWithProgress({
file,
onStatusUpdate: dispatchChatUploadFileList,
});
@@ -173,5 +170,7 @@ export const createFileSlice: StateCreator<
});
await Promise.all(pools);
- },
-});
+ };
+}
+
+export type FileAction = Pick<FileActionImpl, keyof FileActionImpl>;
diff --git a/src/store/file/slices/chunk/action.ts b/src/store/file/slices/chunk/action.ts
index c44680afddd..908bf7c0d80 100644
--- a/src/store/file/slices/chunk/action.ts
+++ b/src/store/file/slices/chunk/action.ts
@@ -1,36 +1,39 @@
-import { type StateCreator } from 'zustand/vanilla';
-
import { ragService } from '@/services/rag';
+import { type StoreSetter } from '@/store/types';
import { type FileStore } from '../../store';
-export interface FileChunkAction {
- closeChunkDrawer: () => void;
- highlightChunks: (ids: string[]) => void;
+type Setter = StoreSetter<FileStore>;
+export const createFileChunkSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
+ new FileChunkActionImpl(set, get, _api);
- openChunkDrawer: (id: string) => void;
- semanticSearch: (text: string, fileId: string) => Promise<void>;
-}
+export class FileChunkActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ closeChunkDrawer = (): void => {
+ this.#set({ chunkDetailId: null, isSimilaritySearch: false, similaritySearchChunks: [] });
+ };
-export const createFileChunkSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- FileChunkAction
-> = (set) => ({
- closeChunkDrawer: () => {
- set({ chunkDetailId: null, isSimilaritySearch: false, similaritySearchChunks: [] });
- },
- highlightChunks: (ids) => {
- set({ highlightChunkIds: ids });
- },
- openChunkDrawer: (id) => {
- set({ chunkDetailId: id });
- },
-
- semanticSearch: async (text, fileId) => {
- set({ isSimilaritySearching: true });
+ highlightChunks = (ids: string[]): void => {
+ this.#set({ highlightChunkIds: ids });
+ };
+
+ openChunkDrawer = (id: string): void => {
+ this.#set({ chunkDetailId: id });
+ };
+
+ semanticSearch = async (text: string, fileId: string): Promise<void> => {
+ this.#set({ isSimilaritySearching: true });
const data = await ragService.semanticSearch(text, [fileId]);
- set({ isSimilaritySearching: false, similaritySearchChunks: data });
- },
-});
+ this.#set({ isSimilaritySearching: false, similaritySearchChunks: data });
+ };
+}
+
+export type FileChunkAction = Pick<FileChunkActionImpl, keyof FileChunkActionImpl>;
diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.ts
index f08c45b2be1..36bbc7352f3 100644
--- a/src/store/file/slices/document/action.ts
+++ b/src/store/file/slices/document/action.ts
@@ -1,10 +1,10 @@
import { createNanoId } from '@lobechat/utils';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
import { useGlobalStore } from '@/store/global';
+import { type StoreSetter } from '@/store/types';
import { DocumentSourceType, type LobeDocument } from '@/types/document';
import { setNamespace } from '@/utils/storeDebug';
@@ -27,84 +27,31 @@ const isAllowedDocument = (page: { fileType: string; sourceType: string }) => {
);
};
-export interface DocumentAction {
- /**
- * Create a new document with markdown content (not optimistic, waits for server response)
- * Returns the created document
- */
- createDocument: (params: {
+type Setter = StoreSetter<FileStore>;
+export const createDocumentSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
+ new DocumentActionImpl(set, get, _api);
+
+export class DocumentActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ createDocument = async ({
+ title,
+ content,
+ knowledgeBaseId,
+ parentId,
+ }: {
content: string;
knowledgeBaseId?: string;
parentId?: string;
title: string;
- }) => Promise<{ [key: string]: any; id: string }>;
- /**
- * Create a new folder
- * Returns the created folder's ID
- */
- createFolder: (name: string, parentId?: string, knowledgeBaseId?: string) => Promise<string>;
- /**
- * Create a new optimistic document immediately in local map
- * Returns the temporary ID for the new document
- */
- createOptimisticDocument: (title?: string) => string;
- /**
- * Duplicate an existing document
- * Returns the created document
- */
- duplicateDocument: (documentId: string) => Promise<{ [key: string]: any; id: string }>;
- /**
- * Fetch full document detail by ID and update local map
- */
- fetchDocumentDetail: (documentId: string) => Promise<void>;
- /**
- * Fetch documents from the server with pagination
- */
- fetchDocuments: (params: { pageOnly?: boolean }) => Promise<void>;
- /**
- * Get documents from local optimistic map merged with server data
- */
- getOptimisticDocuments: () => LobeDocument[];
- /**
- * Load more documents (next page)
- */
- loadMoreDocuments: () => Promise<void>;
- /**
- * Remove a document (deletes from documents table)
- */
- removeDocument: (documentId: string) => Promise<void>;
- /**
- * Remove a temp document from local map
- */
- removeTempDocument: (tempId: string) => void;
- /**
- * Replace a temp document with real document data (for smooth UX when creating documents)
- */
- replaceTempDocumentWithReal: (tempId: string, realDocument: LobeDocument) => void;
- /**
- * Update document directly (no optimistic update)
- */
- updateDocument: (documentId: string, updates: Partial<LobeDocument>) => Promise<void>;
- /**
- * Optimistically update document in local map and queue for DB sync
- */
- updateDocumentOptimistically: (
- documentId: string,
- updates: Partial<LobeDocument>,
- ) => Promise<void>;
- /**
- * SWR hook to fetch document detail with caching and auto-sync to store
- */
- useFetchDocumentDetail: (documentId: string | undefined) => SWRResponse<LobeDocument | null>;
-}
-
-export const createDocumentSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- DocumentAction
-> = (set, get) => ({
- createDocument: async ({ title, content, knowledgeBaseId, parentId }) => {
+ }): Promise<{ [key: string]: any; id: string }> => {
const now = Date.now();
// Create page with markdown content, leave editorData as empty JSON object
@@ -125,9 +72,13 @@ export const createDocumentSlice: StateCreator<
// without triggering the loading skeleton
return newPage;
- },
+ };
- createFolder: async (name, parentId, knowledgeBaseId) => {
+ createFolder = async (
+ name: string,
+ parentId?: string,
+ knowledgeBaseId?: string,
+ ): Promise<string> => {
const now = Date.now();
// Generate random 8-character slug (A-Z, a-z, 0-9)
@@ -152,10 +103,10 @@ export const createDocumentSlice: StateCreator<
await revalidateResources();
return folder.id;
- },
+ };
- createOptimisticDocument: (title = 'Untitled') => {
- const { localDocumentMap } = get();
+ createOptimisticDocument = (title: string = 'Untitled'): string => {
+ const { localDocumentMap } = this.#get();
// Generate temporary ID with prefix to identify optimistic pages
const tempId = `temp-document-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
@@ -180,12 +131,12 @@ export const createDocumentSlice: StateCreator<
// Add to local map
const newMap = new Map(localDocumentMap);
newMap.set(tempId, newPage);
- set({ localDocumentMap: newMap }, false, n('createOptimisticDocument'));
+ this.#set({ localDocumentMap: newMap }, false, n('createOptimisticDocument'));
return tempId;
- },
+ };
- duplicateDocument: async (documentId) => {
+ duplicateDocument = async (documentId: string): Promise<{ [key: string]: any; id: string }> => {
// Fetch the source page
const sourcePage = await documentService.getDocumentById(documentId);
@@ -211,7 +162,7 @@ export const createDocumentSlice: StateCreator<
});
// Add the new page to local map immediately for instant UI update
- const { localDocumentMap } = get();
+ const { localDocumentMap } = this.#get();
const newMap = new Map(localDocumentMap);
const editorPage: LobeDocument = {
content: newPage.content || null,
@@ -232,15 +183,15 @@ export const createDocumentSlice: StateCreator<
updatedAt: newPage.updatedAt ? new Date(newPage.updatedAt) : new Date(),
};
newMap.set(newPage.id, editorPage);
- set({ localDocumentMap: newMap }, false, n('duplicateDocument'));
+ this.#set({ localDocumentMap: newMap }, false, n('duplicateDocument'));
// Don't refresh pages here - we've already added it to the local map
// This prevents the loading skeleton from appearing
return newPage;
- },
+ };
- fetchDocumentDetail: async (documentId) => {
+ fetchDocumentDetail = async (documentId: string): Promise<void> => {
try {
const document = await documentService.getDocumentById(documentId);
@@ -250,7 +201,7 @@ export const createDocumentSlice: StateCreator<
}
// Update local map with full document details including editorData
- const { localDocumentMap } = get();
+ const { localDocumentMap } = this.#get();
const newMap = new Map(localDocumentMap);
const fullDocument: LobeDocument = {
@@ -273,14 +224,14 @@ export const createDocumentSlice: StateCreator<
};
newMap.set(documentId, fullDocument);
- set({ localDocumentMap: newMap }, false, n('fetchDocumentDetail'));
+ this.#set({ localDocumentMap: newMap }, false, n('fetchDocumentDetail'));
} catch (error) {
console.error('[fetchDocumentDetail] Failed to fetch document:', error);
}
- },
+ };
- fetchDocuments: async ({ pageOnly = false }) => {
- set({ isDocumentListLoading: true }, false, n('fetchDocuments/start'));
+ fetchDocuments = async ({ pageOnly = false }: { pageOnly?: boolean }): Promise<void> => {
+ this.#set({ isDocumentListLoading: true }, false, n('fetchDocuments/start'));
try {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
@@ -304,7 +255,7 @@ export const createDocumentSlice: StateCreator<
const hasMore = result.items.length >= pageSize;
- set(
+ this.#set(
{
currentPage: 0,
documentQueryFilter: queryFilters,
@@ -318,7 +269,7 @@ export const createDocumentSlice: StateCreator<
);
// Sync with local map: remove temp pages that now exist on server
- const { localDocumentMap } = get();
+ const { localDocumentMap } = this.#get();
const newMap = new Map(localDocumentMap);
for (const [id] of localDocumentMap.entries()) {
@@ -327,16 +278,16 @@ export const createDocumentSlice: StateCreator<
}
}
- set({ localDocumentMap: newMap }, false, n('fetchDocuments/syncLocalMap'));
+ this.#set({ localDocumentMap: newMap }, false, n('fetchDocuments/syncLocalMap'));
} catch (error) {
console.error('Failed to fetch pages:', error);
- set({ isDocumentListLoading: false }, false, n('fetchDocuments/error'));
+ this.#set({ isDocumentListLoading: false }, false, n('fetchDocuments/error'));
throw error;
}
- },
+ };
- getOptimisticDocuments: () => {
- const { localDocumentMap, documents } = get();
+ getOptimisticDocuments = (): LobeDocument[] => {
+ const { localDocumentMap, documents } = this.#get();
// Track which pages we've added
const addedIds = new Set<string>();
@@ -361,16 +312,17 @@ export const createDocumentSlice: StateCreator<
}
return result;
- },
+ };
- loadMoreDocuments: async () => {
- const { currentPage, isLoadingMoreDocuments, hasMoreDocuments, documentQueryFilter } = get();
+ loadMoreDocuments = async (): Promise<void> => {
+ const { currentPage, isLoadingMoreDocuments, hasMoreDocuments, documentQueryFilter } =
+ this.#get();
if (isLoadingMoreDocuments || !hasMoreDocuments) return;
const nextPage = currentPage + 1;
- set({ isLoadingMoreDocuments: true }, false, n('loadMoreDocuments/start'));
+ this.#set({ isLoadingMoreDocuments: true }, false, n('loadMoreDocuments/start'));
try {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
@@ -387,10 +339,10 @@ export const createDocumentSlice: StateCreator<
const hasMore = result.items.length >= pageSize;
- set(
+ this.#set(
{
currentPage: nextPage,
- documents: [...get().documents, ...newPages],
+ documents: [...this.#get().documents, ...newPages],
documentsTotal: result.total,
hasMoreDocuments: hasMore,
isLoadingMoreDocuments: false,
@@ -400,20 +352,20 @@ export const createDocumentSlice: StateCreator<
);
} catch (error) {
console.error('Failed to load more pages:', error);
- set({ isLoadingMoreDocuments: false }, false, n('loadMoreDocuments/error'));
+ this.#set({ isLoadingMoreDocuments: false }, false, n('loadMoreDocuments/error'));
}
- },
+ };
- removeDocument: async (documentId) => {
+ removeDocument = async (documentId: string): Promise<void> => {
// Remove from local optimistic map first (optimistic update)
- const { localDocumentMap, documents } = get();
+ const { localDocumentMap, documents } = this.#get();
const newMap = new Map(localDocumentMap);
newMap.delete(documentId);
// Also remove from documents array to update the list immediately
const newDocuments = documents.filter((doc) => doc.id !== documentId);
- set(
+ this.#set(
{ documents: newDocuments, localDocumentMap: newMap },
false,
n('removeDocument/optimistic'),
@@ -427,7 +379,7 @@ export const createDocumentSlice: StateCreator<
console.error('Failed to delete document:', error);
// Restore the document in local map and documents array on error
const restoredMap = new Map(localDocumentMap);
- set(
+ this.#set(
{
documents,
localDocumentMap: restoredMap,
@@ -437,17 +389,17 @@ export const createDocumentSlice: StateCreator<
);
throw error;
}
- },
+ };
- removeTempDocument: (tempId) => {
- const { localDocumentMap } = get();
+ removeTempDocument = (tempId: string): void => {
+ const { localDocumentMap } = this.#get();
const newMap = new Map(localDocumentMap);
newMap.delete(tempId);
- set({ localDocumentMap: newMap }, false, n('removeTempDocument'));
- },
+ this.#set({ localDocumentMap: newMap }, false, n('removeTempDocument'));
+ };
- replaceTempDocumentWithReal: (tempId, realPage) => {
- const { localDocumentMap } = get();
+ replaceTempDocumentWithReal = (tempId: string, realPage: LobeDocument): void => {
+ const { localDocumentMap } = this.#get();
const newMap = new Map(localDocumentMap);
// Remove temp page
@@ -456,10 +408,10 @@ export const createDocumentSlice: StateCreator<
// Add real page with same position
newMap.set(realPage.id, realPage);
- set({ localDocumentMap: newMap }, false, n('replaceTempDocumentWithReal'));
- },
+ this.#set({ localDocumentMap: newMap }, false, n('replaceTempDocumentWithReal'));
+ };
- updateDocument: async (id, updates) => {
+ updateDocument = async (id: string, updates: Partial<LobeDocument>): Promise<void> => {
await documentService.updateDocument({
content: updates.content ?? undefined,
editorData: updates.editorData
@@ -476,10 +428,13 @@ export const createDocumentSlice: StateCreator<
// Refetch resource list to show updated document
const { revalidateResources } = await import('../resource/hooks');
await revalidateResources();
- },
+ };
- updateDocumentOptimistically: async (documentId, updates) => {
- const { localDocumentMap, documents } = get();
+ updateDocumentOptimistically = async (
+ documentId: string,
+ updates: Partial<LobeDocument>,
+ ): Promise<void> => {
+ const { localDocumentMap, documents } = this.#get();
// Find the page either in local map or documents state
let existingPage = localDocumentMap.get(documentId);
@@ -515,7 +470,7 @@ export const createDocumentSlice: StateCreator<
// Update local map immediately for optimistic UI
const newMap = new Map(localDocumentMap);
newMap.set(documentId, updatedPage);
- set({ localDocumentMap: newMap }, false, n('updateDocumentOptimistically'));
+ this.#set({ localDocumentMap: newMap }, false, n('updateDocumentOptimistically'));
// Queue background sync to DB
try {
@@ -543,11 +498,11 @@ export const createDocumentSlice: StateCreator<
} else {
revertMap.delete(documentId);
}
- set({ localDocumentMap: revertMap }, false, n('revertOptimisticUpdate'));
+ this.#set({ localDocumentMap: revertMap }, false, n('revertOptimisticUpdate'));
}
- },
+ };
- useFetchDocumentDetail: (documentId) => {
+ useFetchDocumentDetail = (documentId: string | undefined): SWRResponse<LobeDocument | null> => {
const swrKey = documentId ? ['documentDetail', documentId] : null;
return useClientDataSWRWithSync<LobeDocument | null>(
@@ -589,13 +544,15 @@ export const createDocumentSlice: StateCreator<
if (!document) return;
// Auto-sync to localDocumentMap
- const { localDocumentMap } = get();
+ const { localDocumentMap } = this.#get();
const newMap = new Map(localDocumentMap);
newMap.set(documentId!, document);
- set({ localDocumentMap: newMap }, false, n('useFetchDocumentDetail/onData'));
+ this.#set({ localDocumentMap: newMap }, false, n('useFetchDocumentDetail/onData'));
},
revalidateOnFocus: true, // 5 seconds
},
);
- },
-});
+ };
+}
+
+export type DocumentAction = Pick<DocumentActionImpl, keyof DocumentActionImpl>;
diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.ts
index a95ff1b3a56..8100bc2059f 100644
--- a/src/store/file/slices/fileManager/action.ts
+++ b/src/store/file/slices/fileManager/action.ts
@@ -7,7 +7,6 @@ import {
import { t } from 'i18next';
import pMap from 'p-map';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { message } from '@/components/AntdStaticMethods';
import { FILE_UPLOAD_BLACKLIST, MAX_UPLOAD_FILE_COUNT } from '@/const/file';
@@ -19,6 +18,7 @@ import {
type UploadFileListDispatch,
uploadFileListReducer,
} from '@/store/file/reducers/uploadFileList';
+import { type StoreSetter } from '@/store/types';
import { type FileListItem, type QueryFileListParams } from '@/types/files';
import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import { unzipFile } from '@/utils/unzipFile';
@@ -27,6 +27,7 @@ import { type FileStore } from '../../store';
import { fileManagerSelectors } from './selectors';
const serverFileService = new FileService();
+const FETCH_ALL_KNOWLEDGE_KEY = 'useFetchKnowledgeItems';
export interface FolderCrumb {
id: string;
@@ -34,55 +35,22 @@ export interface FolderCrumb {
slug: string;
}
-export interface FileManageAction {
- cancelUpload: (id: string) => void;
- dispatchDockFileList: (payload: UploadFileListDispatch) => void;
- embeddingChunks: (fileIds: string[]) => Promise<void>;
- loadMoreKnowledgeItems: () => Promise<void>;
- moveFileToFolder: (fileId: string, parentId: string | null) => Promise<void>;
- parseFilesToChunks: (ids: string[], params?: { skipExist?: boolean }) => Promise<void>;
- pushDockFileList: (files: File[], knowledgeBaseId?: string, parentId?: string) => Promise<void>;
-
- reEmbeddingChunks: (id: string) => Promise<void>;
- reParseFile: (id: string) => Promise<void>;
- /**
- * @deprecated Use fetchResources(queryParams) from resource slice instead
- * This method is kept for backward compatibility with non-ResourceManager code
- */
- refreshFileList: () => Promise<void>;
- removeAllFiles: () => Promise<void>;
- removeFileItem: (id: string) => Promise<void>;
- removeFiles: (ids: string[]) => Promise<void>;
- renameFolder: (folderId: string, newName: string) => Promise<void>;
-
- setCurrentFolderId: (folderId: string | null | undefined) => void;
- setPendingRenameItemId: (id: string | null) => void;
- setUploadDockExpanded: (expanded: boolean) => void;
-
- toggleEmbeddingIds: (ids: string[], loading?: boolean) => void;
- toggleParsingIds: (ids: string[], loading?: boolean) => void;
-
- uploadFolderWithStructure: (
- files: File[],
- knowledgeBaseId?: string,
- currentFolderId?: string,
- ) => Promise<void>;
+type Setter = StoreSetter<FileStore>;
+export const createFileManageSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
+ new FileManageActionImpl(set, get, _api);
- useFetchFolderBreadcrumb: (slug?: string | null) => SWRResponse<FolderCrumb[]>;
- useFetchKnowledgeItem: (id?: string) => SWRResponse<FileListItem | undefined>;
- useFetchKnowledgeItems: (params: QueryFileListParams) => SWRResponse<FileListItem[]>;
-}
+export class FileManageActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
-const FETCH_ALL_KNOWLEDGE_KEY = 'useFetchKnowledgeItems';
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createFileManageSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- FileManageAction
-> = (set, get) => ({
- cancelUpload: (id) => {
- const { dockUploadFileList, dispatchDockFileList } = get();
+ cancelUpload = (id: string): void => {
+ const { dockUploadFileList, dispatchDockFileList } = this.#get();
const uploadItem = dockUploadFileList.find((item) => item.id === id);
if (uploadItem?.abortController) {
@@ -95,16 +63,18 @@ export const createFileManageSlice: StateCreator<
status: 'cancelled',
type: 'updateFileStatus',
});
- },
- dispatchDockFileList: (payload: UploadFileListDispatch) => {
- const nextValue = uploadFileListReducer(get().dockUploadFileList, payload);
- if (nextValue === get().dockUploadFileList) return;
-
- set({ dockUploadFileList: nextValue }, false, `dispatchDockFileList/${payload.type}`);
- },
- embeddingChunks: async (fileIds: string[]) => {
+ };
+
+ dispatchDockFileList = (payload: UploadFileListDispatch): void => {
+ const nextValue = uploadFileListReducer(this.#get().dockUploadFileList, payload);
+ if (nextValue === this.#get().dockUploadFileList) return;
+
+ this.#set({ dockUploadFileList: nextValue }, false, `dispatchDockFileList/${payload.type}`);
+ };
+
+ embeddingChunks = async (fileIds: string[]): Promise<void> => {
// toggle file ids
- get().toggleEmbeddingIds(fileIds);
+ this.#get().toggleEmbeddingIds(fileIds);
// parse files
const pools = fileIds.map(async (id) => {
@@ -116,12 +86,12 @@ export const createFileManageSlice: StateCreator<
});
await Promise.all(pools);
- await get().refreshFileList();
- get().toggleEmbeddingIds(fileIds, false);
- },
+ await this.#get().refreshFileList();
+ this.#get().toggleEmbeddingIds(fileIds, false);
+ };
- loadMoreKnowledgeItems: async () => {
- const { queryListParams, fileList, fileListOffset, fileListHasMore } = get();
+ loadMoreKnowledgeItems = async (): Promise<void> => {
+ const { queryListParams, fileList, fileListOffset, fileListHasMore } = this.#get();
// Don't load if there's no more data or no params
if (!fileListHasMore || !queryListParams) return;
@@ -139,7 +109,7 @@ export const createFileManageSlice: StateCreator<
const updatedFileList = [...fileList, ...newItems];
// Update Zustand store
- set({
+ this.#set({
fileList: updatedFileList,
fileListHasMore: response.hasMore,
fileListOffset: fileListOffset + newItems.length,
@@ -152,9 +122,9 @@ export const createFileManageSlice: StateCreator<
} catch (error) {
console.error('Failed to load more knowledge items:', error);
}
- },
+ };
- moveFileToFolder: async (fileId, parentId) => {
+ moveFileToFolder = async (fileId: string, parentId: string | null): Promise<void> => {
// Optimistically update all file list caches
await mutate(
(key) => Array.isArray(key) && key[0] === FETCH_ALL_KNOWLEDGE_KEY,
@@ -172,11 +142,12 @@ export const createFileManageSlice: StateCreator<
await fileService.updateFile(fileId, { parentId });
// Revalidate to get fresh data from server
- await get().refreshFileList();
- },
- parseFilesToChunks: async (ids: string[], params) => {
+ await this.#get().refreshFileList();
+ };
+
+ parseFilesToChunks = async (ids: string[], params?: { skipExist?: boolean }): Promise<void> => {
// toggle file ids
- get().toggleParsingIds(ids);
+ this.#get().toggleParsingIds(ids);
// parse files
const pools = ids.map(async (id) => {
@@ -188,12 +159,16 @@ export const createFileManageSlice: StateCreator<
});
await Promise.all(pools);
- await get().refreshFileList();
- get().toggleParsingIds(ids, false);
- },
+ await this.#get().refreshFileList();
+ this.#get().toggleParsingIds(ids, false);
+ };
- pushDockFileList: async (rawFiles, knowledgeBaseId, parentId) => {
- const { dispatchDockFileList } = get();
+ pushDockFileList = async (
+ rawFiles: File[],
+ knowledgeBaseId?: string,
+ parentId?: string,
+ ): Promise<void> => {
+ const { dispatchDockFileList } = this.#get();
// 0. Process ZIP files and extract their contents
const filesToUpload: File[] = [];
@@ -237,7 +212,7 @@ export const createFileManageSlice: StateCreator<
const uploadResults = await pMap(
uploadFiles,
async (uploadFileItem) => {
- const result = await get().uploadWithProgress({
+ const result = await this.#get().uploadWithProgress({
abortController: uploadFileItem.abortController,
file: uploadFileItem.file,
knowledgeBaseId,
@@ -258,7 +233,7 @@ export const createFileManageSlice: StateCreator<
);
// Refresh file list to show newly uploaded files
- await get().refreshFileList();
+ await this.#get().refreshFileList();
// 5. auto-embed files that support chunking
const fileIdsToEmbed = uploadResults
@@ -266,36 +241,39 @@ export const createFileManageSlice: StateCreator<
.map(({ fileId }) => fileId!);
if (fileIdsToEmbed.length > 0) {
- await get().parseFilesToChunks(fileIdsToEmbed, { skipExist: false });
+ await this.#get().parseFilesToChunks(fileIdsToEmbed, { skipExist: false });
}
- },
- reEmbeddingChunks: async (id) => {
- if (fileManagerSelectors.isCreatingChunkEmbeddingTask(id)(get())) return;
+ };
+
+ reEmbeddingChunks = async (id: string): Promise<void> => {
+ if (fileManagerSelectors.isCreatingChunkEmbeddingTask(id)(this.#get())) return;
// toggle file ids
- get().toggleEmbeddingIds([id]);
+ this.#get().toggleEmbeddingIds([id]);
await serverFileService.removeFileAsyncTask(id, 'embedding');
- await get().refreshFileList();
+ await this.#get().refreshFileList();
await ragService.createEmbeddingChunksTask(id);
- await get().refreshFileList();
+ await this.#get().refreshFileList();
+
+ this.#get().toggleEmbeddingIds([id], false);
+ };
- get().toggleEmbeddingIds([id], false);
- },
- reParseFile: async (id) => {
+ reParseFile = async (id: string): Promise<void> => {
// toggle file ids
- get().toggleParsingIds([id]);
+ this.#get().toggleParsingIds([id]);
await ragService.retryParseFile(id);
- await get().refreshFileList();
+ await this.#get().refreshFileList();
- get().toggleParsingIds([id], false);
- },
- refreshFileList: async () => {
+ this.#get().toggleParsingIds([id], false);
+ };
+
+ refreshFileList = async (): Promise<void> => {
// Invalidate all queries that start with FETCH_ALL_KNOWLEDGE_KEY
// This ensures all file lists (explorer, tree, etc.) are refreshed
// Note: We don't pass data as undefined to avoid clearing the cache,
@@ -312,22 +290,23 @@ export const createFileManageSlice: StateCreator<
// so uploaded files appear immediately in the Explorer without a full refresh.
const { revalidateResources } = await import('../resource/hooks');
await revalidateResources();
- },
- removeAllFiles: async () => {
+ };
+
+ removeAllFiles = async (): Promise<void> => {
await fileService.removeAllFiles();
- },
+ };
- removeFileItem: async (id) => {
+ removeFileItem = async (id: string): Promise<void> => {
await fileService.removeFile(id);
- await get().refreshFileList();
- },
+ await this.#get().refreshFileList();
+ };
- removeFiles: async (ids) => {
+ removeFiles = async (ids: string[]): Promise<void> => {
await fileService.removeFiles(ids);
- await get().refreshFileList();
- },
+ await this.#get().refreshFileList();
+ };
- renameFolder: async (folderId, newName) => {
+ renameFolder = async (folderId: string, newName: string): Promise<void> => {
// Optimistically update all file list caches
await mutate(
(key) => Array.isArray(key) && key[0] === FETCH_ALL_KNOWLEDGE_KEY,
@@ -348,26 +327,26 @@ export const createFileManageSlice: StateCreator<
await documentService.updateDocument({ id: folderId, title: newName });
// Revalidate to get fresh data from server
- await get().refreshFileList();
- },
+ await this.#get().refreshFileList();
+ };
- setCurrentFolderId: (folderId) => {
- set({ currentFolderId: folderId }, false, 'setCurrentFolderId');
- },
+ setCurrentFolderId = (folderId: string | null | undefined): void => {
+ this.#set({ currentFolderId: folderId }, false, 'setCurrentFolderId');
+ };
- setPendingRenameItemId: (id) => {
- set({ pendingRenameItemId: id }, false, 'setPendingRenameItemId');
- },
+ setPendingRenameItemId = (id: string | null): void => {
+ this.#set({ pendingRenameItemId: id }, false, 'setPendingRenameItemId');
+ };
- setUploadDockExpanded: (expanded) => {
- set({ uploadDockExpanded: expanded }, false, 'setUploadDockExpanded');
- },
+ setUploadDockExpanded = (expanded: boolean): void => {
+ this.#set({ uploadDockExpanded: expanded }, false, 'setUploadDockExpanded');
+ };
- toggleEmbeddingIds: (ids, loading) => {
- set((state) => {
+ toggleEmbeddingIds = (ids: string[], loading?: boolean): void => {
+ this.#set((state) => {
const nextValue = new Set(state.creatingEmbeddingTaskIds);
- ids.forEach((id) => {
+ ids.forEach((id: string) => {
if (typeof loading === 'undefined') {
if (nextValue.has(id)) nextValue.delete(id);
else nextValue.add(id);
@@ -379,12 +358,13 @@ export const createFileManageSlice: StateCreator<
return { creatingEmbeddingTaskIds: Array.from(nextValue.values()) };
});
- },
- toggleParsingIds: (ids, loading) => {
- set((state) => {
+ };
+
+ toggleParsingIds = (ids: string[], loading?: boolean): void => {
+ this.#set((state) => {
const nextValue = new Set(state.creatingChunkingTaskIds);
- ids.forEach((id) => {
+ ids.forEach((id: string) => {
if (typeof loading === 'undefined') {
if (nextValue.has(id)) nextValue.delete(id);
else nextValue.add(id);
@@ -396,10 +376,14 @@ export const createFileManageSlice: StateCreator<
return { creatingChunkingTaskIds: Array.from(nextValue.values()) };
});
- },
+ };
- uploadFolderWithStructure: async (files, knowledgeBaseId, currentFolderId) => {
- const { dispatchDockFileList } = get();
+ uploadFolderWithStructure = async (
+ files: File[],
+ knowledgeBaseId?: string,
+ currentFolderId?: string,
+ ): Promise<void> => {
+ const { dispatchDockFileList } = this.#get();
// 1. Build folder tree from file paths
const { filesByFolder, folders } = buildFolderTree(files);
@@ -473,7 +457,7 @@ export const createFileManageSlice: StateCreator<
}
// Refresh file list to show the new folders
- await get().refreshFileList();
+ await this.#get().refreshFileList();
// 5. Prepare all file uploads with their target folder IDs
const allUploads: Array<{ file: File; parentId: string | undefined }> = [];
@@ -506,7 +490,7 @@ export const createFileManageSlice: StateCreator<
const uploadResults = await pMap(
validUploads,
async ({ file, parentId }) => {
- const result = await get().uploadWithProgress({
+ const result = await this.#get().uploadWithProgress({
file,
knowledgeBaseId,
onStatusUpdate: dispatchDockFileList,
@@ -522,7 +506,7 @@ export const createFileManageSlice: StateCreator<
);
// Refresh the file list once after all uploads are complete
- await get().refreshFileList();
+ await this.#get().refreshFileList();
// 9. Auto-embed files that support chunking
const fileIdsToEmbed = uploadResults
@@ -530,7 +514,7 @@ export const createFileManageSlice: StateCreator<
.map(({ fileId }) => fileId!);
if (fileIdsToEmbed.length > 0) {
- await get().parseFilesToChunks(fileIdsToEmbed, { skipExist: false });
+ await this.#get().parseFilesToChunks(fileIdsToEmbed, { skipExist: false });
}
} catch (error) {
// Dismiss toast on error
@@ -539,25 +523,30 @@ export const createFileManageSlice: StateCreator<
}
throw error;
}
- },
+ };
- useFetchFolderBreadcrumb: (slug) =>
- useClientDataSWR<FolderCrumb[]>(!slug ? null : ['useFetchFolderBreadcrumb', slug], async () => {
- const response = await serverFileService.getFolderBreadcrumb(slug!);
- return response;
- }),
+ useFetchFolderBreadcrumb = (slug?: string | null): SWRResponse<FolderCrumb[]> => {
+ return useClientDataSWR<FolderCrumb[]>(
+ !slug ? null : ['useFetchFolderBreadcrumb', slug],
+ async () => {
+ const response = await serverFileService.getFolderBreadcrumb(slug!);
+ return response;
+ },
+ );
+ };
- useFetchKnowledgeItem: (id) =>
- useClientDataSWR<FileListItem | undefined>(
+ useFetchKnowledgeItem = (id?: string): SWRResponse<FileListItem | undefined> => {
+ return useClientDataSWR<FileListItem | undefined>(
!id ? null : ['useFetchKnowledgeItem', id],
async () => {
const response = await serverFileService.getKnowledgeItem(id!);
return response ?? undefined;
},
- ),
+ );
+ };
- useFetchKnowledgeItems: (params) =>
- useClientDataSWR<FileListItem[]>([FETCH_ALL_KNOWLEDGE_KEY, params], async () => {
+ useFetchKnowledgeItems = (params: QueryFileListParams): SWRResponse<FileListItem[]> => {
+ return useClientDataSWR<FileListItem[]>([FETCH_ALL_KNOWLEDGE_KEY, params], async () => {
const response = await serverFileService.getKnowledgeItems({
...params,
limit: params.limit ?? 50,
@@ -565,7 +554,7 @@ export const createFileManageSlice: StateCreator<
});
// Update store immediately with response data (no duplicate fetch!)
- set({
+ this.#set({
fileList: response.items,
fileListHasMore: response.hasMore,
fileListOffset: response.items.length,
@@ -573,5 +562,8 @@ export const createFileManageSlice: StateCreator<
});
return response.items;
- }),
-});
+ });
+ };
+}
+
+export type FileManageAction = Pick<FileManageActionImpl, keyof FileManageActionImpl>;
diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.ts
index 69cc3360054..eac5dc2b77b 100644
--- a/src/store/file/slices/resource/action.ts
+++ b/src/store/file/slices/resource/action.ts
@@ -1,7 +1,7 @@
import debug from 'debug';
-import type { StateCreator } from 'zustand/vanilla';
import { resourceService } from '@/services/resource';
+import { type StoreSetter } from '@/store/types';
import type { CreateResourceParams, ResourceItem, UpdateResourceParams } from '@/types/resource';
import type { FileStore } from '../../store';
@@ -10,72 +10,29 @@ import { ResourceSyncEngine } from './syncEngine';
const log = debug('resource-manager:action');
-/**
- * Resource slice actions
- */
-export interface ResourceAction {
- /**
- * Clear all resources and reset state
- */
- clearResources: () => void;
-
- /**
- * Create a new resource with optimistic update
- * Returns temp ID for immediate UI feedback
- */
- createResource: (params: CreateResourceParams) => Promise<string>;
-
- /**
- * Create a new resource and wait for sync to complete
- * Returns real ID from server (useful for auto-rename after creation)
- */
- createResourceAndSync: (params: CreateResourceParams) => Promise<string>;
-
- /**
- * Delete a resource with optimistic update
- */
- deleteResource: (id: string) => Promise<void>;
-
- /**
- * Flush pending sync operations immediately
- */
- flushSync: () => Promise<void>;
-
- /**
- * Load more resources (pagination)
- */
- loadMoreResources: () => Promise<void>;
+let syncEngineInstance: ResourceSyncEngine | null = null;
- /**
- * Move a resource to a different parent folder
- */
- moveResource: (id: string, parentId: string | null) => Promise<void>;
+type Setter = StoreSetter<FileStore>;
+export const createResourceSlice = (set: Setter, get: () => FileStore, _api?: unknown) => ({
+ ...initialResourceState,
+ ...new ResourceActionImpl(set, get, _api),
+});
- /**
- * Retry a failed sync operation
- */
- retrySync: (resourceId: string) => Promise<void>;
+export class ResourceActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
- /**
- * Update a resource with optimistic update
- */
- updateResource: (id: string, updates: UpdateResourceParams) => Promise<void>;
-}
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-let syncEngineInstance: ResourceSyncEngine | null = null;
-
-export const createResourceSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- ResourceAction & ResourceState
-> = (set, get) => {
- // Initialize sync engine (singleton per store instance)
- const getSyncEngine = () => {
+ #getSyncEngine = () => {
if (!syncEngineInstance) {
syncEngineInstance = new ResourceSyncEngine(
() => {
- const state = get();
+ const state = this.#get();
return {
resourceList: state.resourceList || [],
resourceMap: state.resourceMap || new Map(),
@@ -84,351 +41,364 @@ export const createResourceSlice: StateCreator<
};
},
(partial) => {
- set(partial as any, false, 'syncEngine/update');
+ this.#set(partial as any, false, 'syncEngine/update');
},
);
}
return syncEngineInstance;
};
- return {
- ...initialResourceState,
-
- clearResources: () => {
- set(
- {
- hasMore: false,
- offset: 0,
- queryParams: undefined,
- resourceList: [],
- resourceMap: new Map(),
- syncQueue: [],
- total: 0,
- },
- false,
- 'clearResources',
- );
- },
-
- createResource: async (params) => {
- const tempId = `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
-
- // 1. Create optimistic resource
- const optimisticResource: ResourceItem = {
- _optimistic: { isPending: true, retryCount: 0 },
- createdAt: new Date(),
- fileType: params.fileType,
- id: tempId,
- knowledgeBaseId: params.knowledgeBaseId,
- name: 'title' in params ? params.title : params.name,
- parentId: params.parentId,
- size: 'size' in params ? params.size : 0,
- sourceType: params.sourceType,
- updatedAt: new Date(),
- ...(params.sourceType === 'file'
- ? {
- url: 'url' in params ? params.url : '',
- }
- : {
- content: 'content' in params ? params.content : '',
- editorData: 'editorData' in params ? params.editorData : {},
- slug: 'slug' in params ? params.slug : undefined,
- title: 'title' in params ? params.title : 'Untitled',
- }),
- metadata: params.metadata,
- };
-
- // 2. Update store immediately (UI instant feedback)
- const { resourceMap, resourceList } = get();
- const newMap = new Map(resourceMap);
- newMap.set(tempId, optimisticResource);
-
- set(
- {
- resourceList: [optimisticResource, ...resourceList],
- resourceMap: newMap,
- },
- false,
- 'createResource/optimistic',
- );
-
- // 3. Enqueue sync (background)
- const syncEngine = getSyncEngine();
- syncEngine.enqueue({
- id: `sync-${tempId}`,
- payload: params,
- resourceId: tempId,
- retryCount: 0,
- timestamp: new Date(),
- type: 'create',
- });
-
- return tempId;
- },
-
- createResourceAndSync: async (params) => {
- const tempId = `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
-
- // 1. Create optimistic resource
- const optimisticResource: ResourceItem = {
- _optimistic: { isPending: true, retryCount: 0 },
- createdAt: new Date(),
- fileType: params.fileType,
- id: tempId,
- knowledgeBaseId: params.knowledgeBaseId,
- name: 'title' in params ? params.title : params.name,
- parentId: params.parentId,
- size: 'size' in params ? params.size : 0,
- sourceType: params.sourceType,
- updatedAt: new Date(),
- ...(params.sourceType === 'file'
- ? {
- url: 'url' in params ? params.url : '',
- }
- : {
- content: 'content' in params ? params.content : '',
- editorData: 'editorData' in params ? params.editorData : {},
- slug: 'slug' in params ? params.slug : undefined,
- title: 'title' in params ? params.title : 'Untitled',
- }),
- metadata: params.metadata,
- };
-
- // 2. Update store immediately (UI instant feedback)
- const { resourceMap, resourceList } = get();
- const newMap = new Map(resourceMap);
- newMap.set(tempId, optimisticResource);
+ /**
+ * Clear all resources and reset state
+ */
+ clearResources = (): void => {
+ this.#set(
+ {
+ hasMore: false,
+ offset: 0,
+ queryParams: undefined,
+ resourceList: [],
+ resourceMap: new Map(),
+ syncQueue: [],
+ total: 0,
+ },
+ false,
+ 'clearResources',
+ );
+ };
- set(
- {
- resourceList: [optimisticResource, ...resourceList],
- resourceMap: newMap,
- },
- false,
- 'createResourceAndSync/optimistic',
- );
+ /**
+ * Create a new resource with optimistic update
+ * Returns temp ID for immediate UI feedback
+ */
+ createResource = async (params: CreateResourceParams): Promise<string> => {
+ const tempId = `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
+
+ // 1. Create optimistic resource
+ const optimisticResource: ResourceItem = {
+ _optimistic: { isPending: true, retryCount: 0 },
+ createdAt: new Date(),
+ fileType: params.fileType,
+ id: tempId,
+ knowledgeBaseId: params.knowledgeBaseId,
+ name: 'title' in params ? params.title : params.name,
+ parentId: params.parentId,
+ size: 'size' in params ? params.size : 0,
+ sourceType: params.sourceType,
+ updatedAt: new Date(),
+ ...(params.sourceType === 'file'
+ ? {
+ url: 'url' in params ? params.url : '',
+ }
+ : {
+ content: 'content' in params ? params.content : '',
+ editorData: 'editorData' in params ? params.editorData : {},
+ slug: 'slug' in params ? params.slug : undefined,
+ title: 'title' in params ? params.title : 'Untitled',
+ }),
+ metadata: params.metadata,
+ };
+
+ // 2. Update store immediately (UI instant feedback)
+ const { resourceMap, resourceList } = this.#get();
+ const newMap = new Map(resourceMap);
+ newMap.set(tempId, optimisticResource);
+
+ this.#set(
+ {
+ resourceList: [optimisticResource, ...resourceList],
+ resourceMap: newMap,
+ },
+ false,
+ 'createResource/optimistic',
+ );
+
+ // 3. Enqueue sync (background)
+ const syncEngine = this.#getSyncEngine();
+ syncEngine.enqueue({
+ id: `sync-${tempId}`,
+ payload: params,
+ resourceId: tempId,
+ retryCount: 0,
+ timestamp: new Date(),
+ type: 'create',
+ });
+
+ return tempId;
+ };
- // 3. Enqueue sync and wait for completion
- const syncEngine = getSyncEngine();
- const realId = await syncEngine.enqueue({
- id: `sync-${tempId}`,
- payload: params,
- resourceId: tempId,
- retryCount: 0,
- timestamp: new Date(),
- type: 'create',
- });
+ /**
+ * Create a new resource and wait for sync to complete
+ * Returns real ID from server (useful for auto-rename after creation)
+ */
+ createResourceAndSync = async (params: CreateResourceParams): Promise<string> => {
+ const tempId = `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
+
+ // 1. Create optimistic resource
+ const optimisticResource: ResourceItem = {
+ _optimistic: { isPending: true, retryCount: 0 },
+ createdAt: new Date(),
+ fileType: params.fileType,
+ id: tempId,
+ knowledgeBaseId: params.knowledgeBaseId,
+ name: 'title' in params ? params.title : params.name,
+ parentId: params.parentId,
+ size: 'size' in params ? params.size : 0,
+ sourceType: params.sourceType,
+ updatedAt: new Date(),
+ ...(params.sourceType === 'file'
+ ? {
+ url: 'url' in params ? params.url : '',
+ }
+ : {
+ content: 'content' in params ? params.content : '',
+ editorData: 'editorData' in params ? params.editorData : {},
+ slug: 'slug' in params ? params.slug : undefined,
+ title: 'title' in params ? params.title : 'Untitled',
+ }),
+ metadata: params.metadata,
+ };
+
+ // 2. Update store immediately (UI instant feedback)
+ const { resourceMap, resourceList } = this.#get();
+ const newMap = new Map(resourceMap);
+ newMap.set(tempId, optimisticResource);
+
+ this.#set(
+ {
+ resourceList: [optimisticResource, ...resourceList],
+ resourceMap: newMap,
+ },
+ false,
+ 'createResourceAndSync/optimistic',
+ );
+
+ // 3. Enqueue sync and wait for completion
+ const syncEngine = this.#getSyncEngine();
+ const realId = await syncEngine.enqueue({
+ id: `sync-${tempId}`,
+ payload: params,
+ resourceId: tempId,
+ retryCount: 0,
+ timestamp: new Date(),
+ type: 'create',
+ });
+
+ return (realId as string) || tempId;
+ };
- return (realId as string) || tempId;
- },
+ /**
+ * Delete a resource with optimistic update
+ */
+ deleteResource = async (id: string): Promise<void> => {
+ const { resourceList, resourceMap } = this.#get();
+ const newMap = new Map(resourceMap);
+ newMap.delete(id);
+
+ log('deleteResource', id, newMap, resourceList);
+
+ this.#set(
+ {
+ resourceList: resourceList.filter((item) => item.id !== id),
+ resourceMap: newMap,
+ },
+ false,
+ 'deleteResource/optimistic',
+ );
+
+ const syncEngine = this.#getSyncEngine();
+ await syncEngine.enqueue({
+ id: `sync-${id}-${Date.now()}`,
+ payload: {},
+ resourceId: id,
+ retryCount: 0,
+ timestamp: new Date(),
+ type: 'delete',
+ });
+
+ log('enqueue deleteResource', id, syncEngine);
+ };
- deleteResource: async (id) => {
- // 1. Remove immediately (optimistic)
- const { resourceMap, resourceList } = get();
- const newMap = new Map(resourceMap);
- newMap.delete(id);
+ /**
+ * Flush pending sync operations immediately
+ */
+ flushSync = async (): Promise<void> => {
+ const syncEngine = this.#getSyncEngine();
+ await syncEngine.flush();
+ };
- log('deleteResource', id, newMap, resourceList);
+ /**
+ * Load more resources (pagination)
+ */
+ loadMoreResources = async (): Promise<void> => {
+ const { offset, queryParams, hasMore } = this.#get();
+ if (!hasMore || !queryParams) return;
- set(
- {
- resourceList: resourceList.filter((r) => r.id !== id),
- resourceMap: newMap,
- },
- false,
- 'deleteResource/optimistic',
- );
+ this.#set({ isLoadingMore: true }, false, 'loadMoreResources/start');
- // 2. Enqueue sync and await completion.
- // Important: if callers revalidate the list immediately, doing so before the server-side
- // deletion finishes can re-introduce the item from a still-stale query response.
- const syncEngine = getSyncEngine();
- await syncEngine.enqueue({
- id: `sync-${id}-${Date.now()}`,
- payload: {},
- resourceId: id,
- retryCount: 0,
- timestamp: new Date(),
- type: 'delete',
+ try {
+ const { items } = await resourceService.queryResources({
+ ...queryParams,
+ limit: 50,
+ offset,
});
- log('enqueue deleteResource', id, syncEngine);
- },
-
- flushSync: async () => {
- const syncEngine = getSyncEngine();
- await syncEngine.flush();
- },
-
- loadMoreResources: async () => {
- const { offset, queryParams, hasMore } = get();
- if (!hasMore || !queryParams) return;
-
- set({ isLoadingMore: true }, false, 'loadMoreResources/start');
-
- try {
- const { items } = await resourceService.queryResources({
- ...queryParams,
- limit: 50,
- offset,
- });
-
- // Merge into existing map/list
- const { resourceMap, resourceList } = get();
- const newMap = new Map(resourceMap);
- items.forEach((item) => newMap.set(item.id, item));
-
- set(
- {
- hasMore: items.length === 50,
- isLoadingMore: false,
- offset: offset + items.length,
- resourceList: [...resourceList, ...items],
- resourceMap: newMap,
- },
- false,
- 'loadMoreResources/success',
- );
- } catch (error) {
- set({ isLoadingMore: false }, false, 'loadMoreResources/error');
- throw error;
- }
- },
-
- moveResource: async (id, parentId) => {
- // 1. Optimistically remove from current view (it's moving away)
- const { resourceMap, resourceList } = get();
- const existing = resourceMap.get(id);
-
- if (!existing) {
- console.warn(`Resource ${id} not found for move`);
- return;
- }
-
- // Remove from list and map immediately
+ const { resourceMap, resourceList } = this.#get();
const newMap = new Map(resourceMap);
- newMap.delete(id);
+ items.forEach((item) => newMap.set(item.id, item));
- set(
+ this.#set(
{
- resourceList: resourceList.filter((r) => r.id !== id),
+ hasMore: items.length === 50,
+ isLoadingMore: false,
+ offset: offset + items.length,
+ resourceList: [...resourceList, ...items],
resourceMap: newMap,
},
false,
- 'moveResource/optimistic',
+ 'loadMoreResources/success',
);
+ } catch (error) {
+ this.#set({ isLoadingMore: false }, false, 'loadMoreResources/error');
+ throw error;
+ }
+ };
- // 2. Enqueue move operation (background sync) and wait for it to complete
- const syncEngine = getSyncEngine();
- return syncEngine.enqueue({
- id: `sync-move-${id}-${Date.now()}`,
- payload: { parentId },
- resourceId: id,
- retryCount: 0,
- timestamp: new Date(),
- type: 'move',
- });
- },
-
- retrySync: async (resourceId) => {
- // Find the resource and re-enqueue if it has an error
- const { resourceMap } = get();
- const resource = resourceMap.get(resourceId);
-
- if (resource?._optimistic?.error) {
- // Clear error state
- const updated = {
- ...resource,
- _optimistic: {
- isPending: true,
- retryCount: 0,
- },
- };
-
- const newMap = new Map(resourceMap);
- newMap.set(resourceId, updated);
-
- const { resourceList } = get();
- const listIndex = resourceList.findIndex((r) => r.id === resourceId);
- const newList = [...resourceList];
- if (listIndex >= 0) {
- newList[listIndex] = updated;
- }
-
- set(
- {
- resourceList: newList,
- resourceMap: newMap,
- },
- false,
- 'retrySync',
- );
-
- // Re-enqueue the operation
- // Note: We need to reconstruct the original operation
- // For now, we'll just try an update operation
- const syncEngine = getSyncEngine();
- syncEngine.enqueue({
- id: `sync-retry-${resourceId}-${Date.now()}`,
- payload: {}, // Empty update to trigger re-sync
- resourceId,
- retryCount: 0,
- timestamp: new Date(),
- type: 'update',
- });
- }
- },
+ /**
+ * Move a resource to a different parent folder
+ */
+ moveResource = async (id: string, parentId: string | null): Promise<void> => {
+ const { resourceMap, resourceList } = this.#get();
+ const existing = resourceMap.get(id);
- updateResource: async (id, updates) => {
- // 1. Apply updates immediately (optimistic)
- const { resourceMap, resourceList } = get();
- const existing = resourceMap.get(id);
+ if (!existing) {
+ console.warn(`Resource ${id} not found for move`);
+ return;
+ }
- if (!existing) {
- console.warn(`Resource ${id} not found for update`);
- return;
- }
+ const newMap = new Map(resourceMap);
+ newMap.delete(id);
+
+ this.#set(
+ {
+ resourceList: resourceList.filter((item) => item.id !== id),
+ resourceMap: newMap,
+ },
+ false,
+ 'moveResource/optimistic',
+ );
+
+ const syncEngine = this.#getSyncEngine();
+ await syncEngine.enqueue({
+ id: `sync-move-${id}-${Date.now()}`,
+ payload: { parentId },
+ resourceId: id,
+ retryCount: 0,
+ timestamp: new Date(),
+ type: 'move',
+ });
+ };
- log('updateResource', id, existing, updates);
+ /**
+ * Retry a failed sync operation
+ */
+ retrySync = async (resourceId: string): Promise<void> => {
+ const { resourceMap } = this.#get();
+ const resource = resourceMap.get(resourceId);
+ if (resource?._optimistic?.error) {
const updated: ResourceItem = {
- ...existing,
- ...updates,
- _optimistic: { isPending: true, retryCount: 0 },
- name: updates.name || updates.title || existing.name,
- updatedAt: new Date(),
+ ...resource,
+ _optimistic: {
+ isPending: true,
+ retryCount: 0,
+ },
};
const newMap = new Map(resourceMap);
- newMap.set(id, updated);
+ newMap.set(resourceId, updated);
- const listIndex = resourceList.findIndex((r) => r.id === id);
+ const { resourceList } = this.#get();
+ const listIndex = resourceList.findIndex((item) => item.id === resourceId);
const newList = [...resourceList];
if (listIndex >= 0) {
newList[listIndex] = updated;
}
- set(
+ this.#set(
{
resourceList: newList,
resourceMap: newMap,
},
false,
- 'updateResource/optimistic',
+ 'retrySync',
);
- // 2. Enqueue sync (background)
- const syncEngine = getSyncEngine();
+ const syncEngine = this.#getSyncEngine();
syncEngine.enqueue({
- id: `sync-${id}-${Date.now()}`,
- payload: updates,
- resourceId: id,
+ id: `sync-retry-${resourceId}-${Date.now()}`,
+ payload: {},
+ resourceId,
retryCount: 0,
timestamp: new Date(),
type: 'update',
});
+ }
+ };
- log('enqueue updateResource', id, syncEngine);
- },
+ /**
+ * Update a resource with optimistic update
+ */
+ updateResource = async (id: string, updates: UpdateResourceParams): Promise<void> => {
+ const { resourceMap, resourceList } = this.#get();
+ const existing = resourceMap.get(id);
+
+ if (!existing) {
+ console.warn(`Resource ${id} not found for update`);
+ return;
+ }
+
+ log('updateResource', id, existing, updates);
+
+ const updated: ResourceItem = {
+ ...existing,
+ ...updates,
+ _optimistic: { isPending: true, retryCount: 0 },
+ name: updates.name || updates.title || existing.name,
+ updatedAt: new Date(),
+ };
+
+ const newMap = new Map(resourceMap);
+ newMap.set(id, updated);
+
+ const listIndex = resourceList.findIndex((item) => item.id === id);
+ const newList = [...resourceList];
+ if (listIndex >= 0) {
+ newList[listIndex] = updated;
+ }
+
+ this.#set(
+ {
+ resourceList: newList,
+ resourceMap: newMap,
+ },
+ false,
+ 'updateResource/optimistic',
+ );
+
+ const syncEngine = this.#getSyncEngine();
+ syncEngine.enqueue({
+ id: `sync-${id}-${Date.now()}`,
+ payload: updates,
+ resourceId: id,
+ retryCount: 0,
+ timestamp: new Date(),
+ type: 'update',
+ });
+
+ log('enqueue updateResource', id, syncEngine);
};
-};
+}
+
+export type ResourceAction = Pick<ResourceActionImpl, keyof ResourceActionImpl>;
+export type ResourceSlice = ResourceAction & ResourceState;
diff --git a/src/store/file/slices/resource/hooks.ts b/src/store/file/slices/resource/hooks.ts
index 2bedf49225f..08fb3fb3242 100644
--- a/src/store/file/slices/resource/hooks.ts
+++ b/src/store/file/slices/resource/hooks.ts
@@ -23,7 +23,7 @@ export const revalidateResources = async (params?: ResourceQueryParams) => {
/**
* Custom SWR hook for fetching resources with caching and revalidation
*/
-export const useFetchResources = (params: ResourceQueryParams | null, enable = true) => {
+export const useFetchResources = (params: ResourceQueryParams | null, enable: any = true) => {
return useClientDataSWR(
enable && params ? [SWR_KEY_RESOURCES, params] : null,
async ([, queryParams]: [string, ResourceQueryParams]) => {
@@ -40,7 +40,7 @@ export const useFetchResources = (params: ResourceQueryParams | null, enable = t
onSuccess: (data: { hasMore: boolean; items: any[]; total?: number }) => {
const { resourceList, resourceMap } = useFileStore.getState();
- const newResourceMap = new Map(data.items.map((item: any) => [item.id, item]));
+ const newResourceMap = new Map(data.items.map((item) => [item.id, item]));
const newResourceList = data.items;
// Only update store if data actually changed
diff --git a/src/store/file/slices/tts/action.ts b/src/store/file/slices/tts/action.ts
index b032926fd7f..ff811656486 100644
--- a/src/store/file/slices/tts/action.ts
+++ b/src/store/file/slices/tts/action.ts
@@ -1,35 +1,36 @@
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWR } from '@/libs/swr';
import { fileService } from '@/services/file';
+import { type StoreSetter } from '@/store/types';
import { type FileItem } from '@/types/files';
import { type FileStore } from '../../store';
const FETCH_TTS_FILE = 'fetchTTSFile';
-export interface TTSFileAction {
- removeTTSFile: (id: string) => Promise<void>;
+type Setter = StoreSetter<FileStore>;
+export const createTTSFileSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
+ new TTSFileActionImpl(set, get, _api);
- uploadTTSByArrayBuffers: (
- messageId: string,
- arrayBuffers: ArrayBuffer[],
- ) => Promise<string | undefined>;
+export class TTSFileActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
- useFetchTTSFile: (id: string | null) => SWRResponse<FileItem>;
-}
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createTTSFileSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- TTSFileAction
-> = (_, get) => ({
- removeTTSFile: async (id) => {
+ removeTTSFile = async (id: string): Promise<void> => {
await fileService.removeFile(id);
- },
- uploadTTSByArrayBuffers: async (messageId, arrayBuffers) => {
+ };
+
+ uploadTTSByArrayBuffers = async (
+ messageId: string,
+ arrayBuffers: ArrayBuffer[],
+ ): Promise<string | undefined> => {
const fileType = 'audio/mp3';
const blob = new Blob(arrayBuffers, { type: fileType });
const fileName = `${messageId}.mp3`;
@@ -39,10 +40,14 @@ export const createTTSFileSlice: StateCreator<
};
const file = new File([blob], fileName, fileOptions);
- const res = await get().uploadWithProgress({ file, skipCheckFileType: true });
+ const res = await this.#get().uploadWithProgress({ file, skipCheckFileType: true });
return res?.id;
- },
- useFetchTTSFile: (id) =>
- useClientDataSWR(!!id ? [FETCH_TTS_FILE, id] : null, () => fileService.getFile(id!)),
-});
+ };
+
+ useFetchTTSFile = (id: string | null): SWRResponse<FileItem> => {
+ return useClientDataSWR(!!id ? [FETCH_TTS_FILE, id] : null, () => fileService.getFile(id!));
+ };
+}
+
+export type TTSFileAction = Pick<TTSFileActionImpl, keyof TTSFileActionImpl>;
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index 3c283163cca..7e8c2de055e 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -1,11 +1,11 @@
import { LOBE_CHAT_CLOUD } from '@lobechat/business-const';
import { t } from 'i18next';
import { sha256 } from 'js-sha256';
-import { type StateCreator } from 'zustand/vanilla';
import { message, notification } from '@/components/AntdStaticMethods';
import { fileService } from '@/services/file';
import { uploadService } from '@/services/upload';
+import { type StoreSetter } from '@/store/types';
import { type FileMetadata, type UploadFileItem } from '@/types/files';
import { getImageDimensions } from '@/utils/client/imageDimensions';
@@ -52,26 +52,23 @@ interface UploadWithProgressResult {
url: string;
}
-export interface FileUploadAction {
- uploadBase64FileWithProgress: (
- base64: string,
- params?: {
- onStatusUpdate?: OnStatusUpdate;
- },
- ) => Promise<UploadWithProgressResult | undefined>;
-
- uploadWithProgress: (
- params: UploadWithProgressParams,
- ) => Promise<UploadWithProgressResult | undefined>;
-}
+type Setter = StoreSetter<FileStore>;
+export const createFileUploadSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
+ new FileUploadActionImpl(set, get, _api);
+
+export class FileUploadActionImpl {
+ readonly #get: () => FileStore;
+ readonly #set: Setter;
-export const createFileUploadSlice: StateCreator<
- FileStore,
- [['zustand/devtools', never]],
- [],
- FileUploadAction
-> = () => ({
- uploadBase64FileWithProgress: async (base64) => {
+ constructor(set: Setter, get: () => FileStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ uploadBase64FileWithProgress = async (
+ base64: string,
+ ): Promise<UploadWithProgressResult | undefined> => {
// Extract image dimensions from base64 data
const dimensions = await getImageDimensions(base64);
@@ -86,8 +83,9 @@ export const createFileUploadSlice: StateCreator<
url: metadata.path,
});
return { ...res, dimensions, filename: metadata.filename };
- },
- uploadWithProgress: async ({
+ };
+
+ uploadWithProgress = async ({
file,
onStatusUpdate,
knowledgeBaseId,
@@ -95,8 +93,9 @@ export const createFileUploadSlice: StateCreator<
parentId,
source,
abortController,
- }) => {
+ }: UploadWithProgressParams): Promise<UploadWithProgressResult | undefined> => {
try {
+ const fileArrayBuffer = await file.arrayBuffer();
const fileArrayBuffer = await file.arrayBuffer();
// 1. extract image dimensions if applicable
@@ -195,5 +194,7 @@ export const createFileUploadSlice: StateCreator<
}
throw error;
}
- },
-});
+ }
+}
+
+export type FileUploadAction = Pick<FileUploadActionImpl, keyof FileUploadActionImpl>;
diff --git a/src/store/file/store.ts b/src/store/file/store.ts
index bb8555a720d..6ee8a407a3c 100644
--- a/src/store/file/store.ts
+++ b/src/store/file/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type FilesStoreState, initialState } from './initialState';
import { type FileAction, createFileSlice } from './slices/chat';
import { type FileChunkAction, createFileChunkSlice } from './slices/chunk';
@@ -25,15 +26,27 @@ export type FileStore = FilesStoreState &
ResourceAction &
ResourceState;
-const createStore: StateCreator<FileStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type FileStoreAction = FileAction &
+ DocumentAction &
+ TTSFileAction &
+ FileManageAction &
+ FileChunkAction &
+ FileUploadAction &
+ ResourceAction;
+
+const createStore: StateCreator<FileStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<FileStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createFileSlice(...parameters),
- ...createDocumentSlice(...parameters),
- ...createFileManageSlice(...parameters),
- ...createTTSFileSlice(...parameters),
- ...createFileChunkSlice(...parameters),
- ...createFileUploadSlice(...parameters),
- ...createResourceSlice(...parameters),
+ ...flattenActions<FileStoreAction>([
+ createFileSlice(...parameters),
+ createDocumentSlice(...parameters),
+ createFileManageSlice(...parameters),
+ createTTSFileSlice(...parameters),
+ createFileChunkSlice(...parameters),
+ createFileUploadSlice(...parameters),
+ createResourceSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/global/actions/general.ts b/src/store/global/actions/general.ts
index 23cb984530e..a51d065910d 100644
--- a/src/store/global/actions/general.ts
+++ b/src/store/global/actions/general.ts
@@ -1,7 +1,6 @@
import isEqual from 'fast-deep-equal';
import { gt, parse, valid } from 'semver';
import { type SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { CURRENT_VERSION, isDesktop } from '@/const/version';
import { useOnlyFetchOnceSWR } from '@/libs/swr';
@@ -9,6 +8,7 @@ import { globalService } from '@/services/global';
import { getElectronStoreState } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
import type { SystemStatus } from '@/store/global/initialState';
+import { type StoreSetter } from '@/store/types';
import { type LocaleMode } from '@/types/locale';
import { switchLang } from '@/utils/client/switchLang';
import { merge } from '@/utils/merge';
@@ -18,24 +18,21 @@ import type { GlobalStore } from '../store';
const n = setNamespace('g');
-export interface GlobalGeneralAction {
- openAgentInNewWindow: (agentId: string) => Promise<void>;
- openTopicInNewWindow: (agentId: string, topicId: string) => Promise<void>;
- switchLocale: (locale: LocaleMode, params?: { skipBroadcast?: boolean }) => void;
- updateResourceManagerColumnWidth: (column: 'name' | 'date' | 'size', width: number) => void;
- updateSystemStatus: (status: Partial<SystemStatus>, action?: any) => void;
- useCheckLatestVersion: (enabledCheck?: boolean) => SWRResponse<string>;
- useCheckServerVersion: () => SWRResponse<string | null>;
- useInitSystemStatus: () => SWRResponse;
-}
+type Setter = StoreSetter<GlobalStore>;
+export const generalActionSlice = (set: Setter, get: () => GlobalStore, _api?: unknown) =>
+ new GlobalGeneralActionImpl(set, get, _api);
+
+export class GlobalGeneralActionImpl {
+ readonly #get: () => GlobalStore;
+ readonly #set: Setter;
-export const generalActionSlice: StateCreator<
- GlobalStore,
- [['zustand/devtools', never]],
- [],
- GlobalGeneralAction
-> = (set, get) => ({
- openAgentInNewWindow: async (agentId: string) => {
+ constructor(set: Setter, get: () => GlobalStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ openAgentInNewWindow = async (agentId: string): Promise<void> => {
const url = `/agent/${agentId}${isDesktop ? '?mode=single' : ''}`;
if (isDesktop) {
@@ -64,9 +61,9 @@ export const generalActionSlice: StateCreator<
const features = `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes,status=yes`;
window.open(url, `agent_${agentId}`, features);
}
- },
+ };
- openTopicInNewWindow: async (agentId: string, topicId: string) => {
+ openTopicInNewWindow = async (agentId: string, topicId: string): Promise<void> => {
const url = `/agent/${agentId}?topic=${topicId}${isDesktop ? '&mode=single' : ''}`;
if (isDesktop) {
@@ -95,10 +92,13 @@ export const generalActionSlice: StateCreator<
const features = `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes,status=yes`;
window.open(url, `agent_${agentId}_topic_${topicId}`, features);
}
- },
+ };
- switchLocale: (locale, { skipBroadcast } = {}) => {
- get().updateSystemStatus({ language: locale });
+ switchLocale = (
+ locale: LocaleMode,
+ { skipBroadcast }: { skipBroadcast?: boolean } = {},
+ ): void => {
+ this.#get().updateSystemStatus({ language: locale });
switchLang(locale);
@@ -113,34 +113,36 @@ export const generalActionSlice: StateCreator<
}
})();
}
- },
- updateResourceManagerColumnWidth: (column, width) => {
- const currentWidths = get().status.resourceManagerColumnWidths || {
+ };
+
+ updateResourceManagerColumnWidth = (column: 'name' | 'date' | 'size', width: number): void => {
+ const currentWidths = this.#get().status.resourceManagerColumnWidths || {
date: 160,
name: 574,
size: 140,
};
- get().updateSystemStatus({
+ this.#get().updateSystemStatus({
resourceManagerColumnWidths: {
...currentWidths,
[column]: width,
},
});
- },
- updateSystemStatus: (status, action) => {
- if (!get().isStatusInit) return;
+ };
- const nextStatus = merge(get().status, status);
+ updateSystemStatus = (status: Partial<SystemStatus>, action?: any): void => {
+ if (!this.#get().isStatusInit) return;
- if (isEqual(get().status, nextStatus)) return;
+ const nextStatus = merge(this.#get().status, status);
- set({ status: nextStatus }, false, action || n('updateSystemStatus'));
- get().statusStorage.saveToLocalStorage(nextStatus);
- },
+ if (isEqual(this.#get().status, nextStatus)) return;
- useCheckLatestVersion: (enabledCheck = true) =>
- useOnlyFetchOnceSWR(
+ this.#set({ status: nextStatus }, false, action || n('updateSystemStatus'));
+ this.#get().statusStorage.saveToLocalStorage(nextStatus);
+ };
+
+ useCheckLatestVersion = (enabledCheck: boolean = true): SWRResponse<string> => {
+ return useOnlyFetchOnceSWR(
enabledCheck ? 'checkLatestVersion' : null,
async () => globalService.getLatestVersion(),
{
@@ -157,28 +159,29 @@ export const generalActionSlice: StateCreator<
const latestMajorMinor = `${latestVersion.major}.${latestVersion.minor}.0`;
if (gt(latestMajorMinor, currentMajorMinor)) {
- set({ hasNewVersion: true, latestVersion: data }, false, n('checkLatestVersion'));
+ this.#set({ hasNewVersion: true, latestVersion: data }, false, n('checkLatestVersion'));
}
},
},
- ),
+ );
+ };
- useCheckServerVersion: () =>
- useOnlyFetchOnceSWR(
+ useCheckServerVersion = (): SWRResponse<string | null> => {
+ return useOnlyFetchOnceSWR(
isDesktop &&
- // only check server version for self-hosted remote server
- electronSyncSelectors.storageMode(getElectronStoreState()) !== 'cloud'
+ // only check server version for self-hosted remote server
+ electronSyncSelectors.storageMode(getElectronStoreState()) !== 'cloud'
? 'checkServerVersion'
: null,
async () => globalService.getServerVersion(),
{
onSuccess: (data: string | null) => {
if (data === null) {
- set({ isServerVersionOutdated: true }, false);
+ this.#set({ isServerVersionOutdated: true }, false);
return;
}
- set({ serverVersion: data }, false);
+ this.#set({ serverVersion: data }, false);
if (!valid(CURRENT_VERSION) || !valid(data)) return;
@@ -206,19 +209,20 @@ export const generalActionSlice: StateCreator<
(clientVersion.patch - serverVersion.patch);
if (versionDiff >= DIFF_THRESHOLD) {
- set({ isServerVersionOutdated: true }, false);
+ this.#set({ isServerVersionOutdated: true }, false);
}
},
},
- ),
+ );
+ };
- useInitSystemStatus: () =>
- useOnlyFetchOnceSWR<SystemStatus>(
+ useInitSystemStatus = (): SWRResponse => {
+ return useOnlyFetchOnceSWR<SystemStatus>(
'initSystemStatus',
- () => get().statusStorage.getFromLocalStorage(),
+ () => this.#get().statusStorage.getFromLocalStorage(),
{
onSuccess: (status) => {
- set({ isStatusInit: true }, false, 'setStatusInit');
+ this.#set({ isStatusInit: true }, false, 'setStatusInit');
// Reset transient UI states that should not persist across page reloads
const statusWithResetTransientStates = {
@@ -227,8 +231,11 @@ export const generalActionSlice: StateCreator<
showHotkeyHelper: false,
};
- get().updateSystemStatus(statusWithResetTransientStates, 'initSystemStatus');
+ this.#get().updateSystemStatus(statusWithResetTransientStates, 'initSystemStatus');
},
},
- ),
-});
+ );
+ };
+}
+
+export type GlobalGeneralAction = Pick<GlobalGeneralActionImpl, keyof GlobalGeneralActionImpl>;
diff --git a/src/store/global/actions/workspacePane.ts b/src/store/global/actions/workspacePane.ts
index c20bdd90f63..e1b4daf663d 100644
--- a/src/store/global/actions/workspacePane.ts
+++ b/src/store/global/actions/workspacePane.ts
@@ -1,45 +1,38 @@
import { produce } from 'immer';
-import type { StateCreator } from 'zustand/vanilla';
import { INBOX_SESSION_ID } from '@/const/session';
import { SESSION_CHAT_URL } from '@/const/url';
import type { GlobalStore } from '@/store/global';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('w');
-export interface GlobalWorkspacePaneAction {
- switchBackToChat: (sessionId?: string) => void;
- toggleAgentSystemRoleExpand: (agentId: string, expanded?: boolean) => void;
- toggleCommandMenu: (visible?: boolean) => void;
- toggleExpandInputActionbar: (expand?: boolean) => void;
- toggleExpandSessionGroup: (id: string, expand: boolean) => void;
- toggleLeftPanel: (visible?: boolean) => void;
- toggleMobilePortal: (visible?: boolean) => void;
- toggleMobileTopic: (visible?: boolean) => void;
- toggleRightPanel: (visible?: boolean) => void;
- toggleSystemRole: (visible?: boolean) => void;
- toggleWideScreen: (enable?: boolean) => void;
- toggleZenMode: () => void;
-}
+type Setter = StoreSetter<GlobalStore>;
+export const globalWorkspaceSlice = (set: Setter, get: () => GlobalStore, _api?: unknown) =>
+ new GlobalWorkspacePaneActionImpl(set, get, _api);
+
+export class GlobalWorkspacePaneActionImpl {
+ readonly #get: () => GlobalStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => GlobalStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ switchBackToChat = (sessionId?: string): void => {
+ const target = SESSION_CHAT_URL(sessionId || INBOX_SESSION_ID, this.#get().isMobile);
+ this.#get().navigate?.(target);
+ };
-export const globalWorkspaceSlice: StateCreator<
- GlobalStore,
- [['zustand/devtools', never]],
- [],
- GlobalWorkspacePaneAction
-> = (set, get) => ({
- switchBackToChat: (sessionId) => {
- const target = SESSION_CHAT_URL(sessionId || INBOX_SESSION_ID, get().isMobile);
- get().navigate?.(target);
- },
-
- toggleAgentSystemRoleExpand: (agentId, expanded) => {
- const { status } = get();
+ toggleAgentSystemRoleExpand = (agentId: string, expanded?: boolean): void => {
+ const { status } = this.#get();
const systemRoleExpandedMap = status.systemRoleExpandedMap || {};
const nextExpanded = typeof expanded === 'boolean' ? expanded : !systemRoleExpandedMap[agentId];
- get().updateSystemStatus(
+ this.#get().updateSystemStatus(
{
systemRoleExpandedMap: {
...systemRoleExpandedMap,
@@ -48,22 +41,27 @@ export const globalWorkspaceSlice: StateCreator<
},
n('toggleAgentSystemRoleExpand', { agentId, expanded: nextExpanded }),
);
- },
+ };
- toggleCommandMenu: (visible) => {
- const currentVisible = get().status.showCommandMenu;
- get().updateSystemStatus({
+ toggleCommandMenu = (visible?: boolean): void => {
+ const currentVisible = this.#get().status.showCommandMenu;
+ this.#get().updateSystemStatus({
showCommandMenu: typeof visible === 'boolean' ? visible : !currentVisible,
});
- },
- toggleExpandInputActionbar: (newValue) => {
+ };
+
+ toggleExpandInputActionbar = (newValue?: boolean): void => {
const expandInputActionbar =
- typeof newValue === 'boolean' ? newValue : !get().status.expandInputActionbar;
+ typeof newValue === 'boolean' ? newValue : !this.#get().status.expandInputActionbar;
+
+ this.#get().updateSystemStatus(
+ { expandInputActionbar },
+ n('toggleExpandInputActionbar', newValue),
+ );
+ };
- get().updateSystemStatus({ expandInputActionbar }, n('toggleExpandInputActionbar', newValue));
- },
- toggleExpandSessionGroup: (id, expand) => {
- const { status } = get();
+ toggleExpandSessionGroup = (id: string, expand: boolean): void => {
+ const { status } = this.#get();
const nextExpandSessionGroup = produce(status.expandSessionGroupKeys, (draft: string[]) => {
if (expand) {
if (draft.includes(id)) return;
@@ -73,44 +71,59 @@ export const globalWorkspaceSlice: StateCreator<
if (index !== -1) draft.splice(index, 1);
}
});
- get().updateSystemStatus({ expandSessionGroupKeys: nextExpandSessionGroup });
- },
- toggleLeftPanel: (newValue) => {
- const showLeftPanel = typeof newValue === 'boolean' ? newValue : !get().status.showLeftPanel;
- get().updateSystemStatus({ showLeftPanel }, n('toggleLeftPanel', newValue));
- },
- toggleMobilePortal: (newValue) => {
+ this.#get().updateSystemStatus({ expandSessionGroupKeys: nextExpandSessionGroup });
+ };
+
+ toggleLeftPanel = (newValue?: boolean): void => {
+ const showLeftPanel =
+ typeof newValue === 'boolean' ? newValue : !this.#get().status.showLeftPanel;
+ this.#get().updateSystemStatus({ showLeftPanel }, n('toggleLeftPanel', newValue));
+ };
+
+ toggleMobilePortal = (newValue?: boolean): void => {
const mobileShowPortal =
- typeof newValue === 'boolean' ? newValue : !get().status.mobileShowPortal;
+ typeof newValue === 'boolean' ? newValue : !this.#get().status.mobileShowPortal;
+
+ this.#get().updateSystemStatus({ mobileShowPortal }, n('toggleMobilePortal', newValue));
+ };
- get().updateSystemStatus({ mobileShowPortal }, n('toggleMobilePortal', newValue));
- },
- toggleMobileTopic: (newValue) => {
+ toggleMobileTopic = (newValue?: boolean): void => {
const mobileShowTopic =
- typeof newValue === 'boolean' ? newValue : !get().status.mobileShowTopic;
+ typeof newValue === 'boolean' ? newValue : !this.#get().status.mobileShowTopic;
+
+ this.#get().updateSystemStatus({ mobileShowTopic }, n('toggleMobileTopic', newValue));
+ };
+
+ toggleRightPanel = (newValue?: boolean): void => {
+ const showRightPanel =
+ typeof newValue === 'boolean' ? newValue : !this.#get().status.showRightPanel;
- get().updateSystemStatus({ mobileShowTopic }, n('toggleMobileTopic', newValue));
- },
+ this.#get().updateSystemStatus({ showRightPanel }, n('toggleRightPanel', newValue));
+ };
- toggleRightPanel: (newValue) => {
- const showRightPanel = typeof newValue === 'boolean' ? newValue : !get().status.showRightPanel;
+ toggleSystemRole = (newValue?: boolean): void => {
+ const showSystemRole =
+ typeof newValue === 'boolean' ? newValue : !this.#get().status.mobileShowTopic;
- get().updateSystemStatus({ showRightPanel }, n('toggleRightPanel', newValue));
- },
- toggleSystemRole: (newValue) => {
- const showSystemRole = typeof newValue === 'boolean' ? newValue : !get().status.mobileShowTopic;
+ this.#get().updateSystemStatus({ showSystemRole }, n('toggleMobileTopic', newValue));
+ };
- get().updateSystemStatus({ showSystemRole }, n('toggleMobileTopic', newValue));
- },
- toggleWideScreen: (newValue) => {
- const noWideScreen = typeof newValue === 'boolean' ? !newValue : !get().status.noWideScreen;
+ toggleWideScreen = (newValue?: boolean): void => {
+ const noWideScreen =
+ typeof newValue === 'boolean' ? !newValue : !this.#get().status.noWideScreen;
- get().updateSystemStatus({ noWideScreen }, n('toggleWideScreen', newValue));
- },
- toggleZenMode: () => {
- const { status } = get();
+ this.#get().updateSystemStatus({ noWideScreen }, n('toggleWideScreen', newValue));
+ };
+
+ toggleZenMode = (): void => {
+ const { status } = this.#get();
const nextZenMode = !status.zenMode;
- get().updateSystemStatus({ zenMode: nextZenMode }, n('toggleZenMode'));
- },
-});
+ this.#get().updateSystemStatus({ zenMode: nextZenMode }, n('toggleZenMode'));
+ };
+}
+
+export type GlobalWorkspacePaneAction = Pick<
+ GlobalWorkspacePaneActionImpl,
+ keyof GlobalWorkspacePaneActionImpl
+>;
diff --git a/src/store/global/store.ts b/src/store/global/store.ts
index f57cb92ab76..06d9e804aa3 100644
--- a/src/store/global/store.ts
+++ b/src/store/global/store.ts
@@ -4,6 +4,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type GlobalGeneralAction, generalActionSlice } from './actions/general';
import { type GlobalWorkspacePaneAction, globalWorkspaceSlice } from './actions/workspacePane';
import { type GlobalState, initialState } from './initialState';
@@ -14,10 +15,16 @@ export interface GlobalStore extends GlobalState, GlobalWorkspacePaneAction, Glo
/* empty */
}
-const createStore: StateCreator<GlobalStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type GlobalStoreAction = GlobalWorkspacePaneAction & GlobalGeneralAction;
+
+const createStore: StateCreator<GlobalStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<GlobalStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...globalWorkspaceSlice(...parameters),
- ...generalActionSlice(...parameters),
+ ...flattenActions<GlobalStoreAction>([
+ globalWorkspaceSlice(...parameters),
+ generalActionSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/groupProfile/action.ts b/src/store/groupProfile/action.ts
index add4fed40b5..57510a1f6dc 100644
--- a/src/store/groupProfile/action.ts
+++ b/src/store/groupProfile/action.ts
@@ -2,6 +2,7 @@ import { debounce } from 'es-toolkit/compat';
import { type StateCreator } from 'zustand';
import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';
+import { type StoreSetter } from '@/store/types';
import { type SaveState, type SaveStatus, type State, initialState } from './initialState';
@@ -10,21 +11,7 @@ type SaveContentPayload = {
editorData: Record<string, any>;
};
-export interface Action {
- appendStreamingContent: (chunk: string) => void;
- finishStreaming: (saveCallback: (payload: SaveContentPayload) => Promise<void>) => Promise<void>;
- flushSave: () => void;
- handleContentChange: (saveCallback: (payload: SaveContentPayload) => Promise<void>) => void;
- setActiveTabId: (tabId: string) => void;
- /**
- * Set content from agent builder - triggers editor to update
- * @param entityId - groupId for group editor, agentId for member editor
- */
- setAgentBuilderContent: (entityId: string, content: string) => void;
- setChatPanelExpanded: (expanded: boolean | ((prev: boolean) => boolean)) => void;
- updateSaveStatus: (tabId: string, status: SaveStatus) => void;
-}
-
+export type Action = Pick<ActionImpl, keyof ActionImpl>;
export type Store = State & Action;
// Store the latest saveCallback and tabId references to avoid stale closures
@@ -33,11 +20,42 @@ let currentTabIdRef: string | null = null;
const DEFAULT_SAVE_STATE: SaveState = { lastUpdatedTime: null, saveStatus: 'idle' };
-export const store: StateCreator<Store> = (set, get) => {
- const updateSaveStatusInternal = (tabId: string, status: SaveStatus) => {
- const { saveStateMap } = get();
+type Setter = StoreSetter<Store>;
+export class ActionImpl {
+ #debouncedSave: ReturnType<typeof debounce>;
+ #get: () => Store;
+ #set: Setter;
+
+ constructor(set: Setter, get: () => Store, _api?: unknown) {
+ // keep signature aligned with StateCreator params: (set, get, api)
+ void _api;
+ this.#get = get;
+ this.#set = set;
+
+ this.#debouncedSave = debounce(
+ async (payload: SaveContentPayload) => {
+ const tabId = currentTabIdRef;
+ if (!tabId) return;
+
+ try {
+ if (saveCallbackRef) {
+ await saveCallbackRef(payload);
+ this.#updateSaveStatusInternal(tabId, 'saved');
+ }
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save:', error);
+ this.#updateSaveStatusInternal(tabId, 'idle');
+ }
+ },
+ EDITOR_DEBOUNCE_TIME,
+ { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
+ );
+ }
+
+ #updateSaveStatusInternal = (tabId: string, status: SaveStatus) => {
+ const { saveStateMap } = this.#get();
const currentState = saveStateMap[tabId] || DEFAULT_SAVE_STATE;
- set({
+ this.#set({
saveStateMap: {
...saveStateMap,
[tabId]: {
@@ -49,135 +67,118 @@ export const store: StateCreator<Store> = (set, get) => {
});
};
- // Create debounced save that uses the latest callback reference
- const debouncedSave = debounce(
- async (payload: SaveContentPayload) => {
- const tabId = currentTabIdRef;
- if (!tabId) return;
+ appendStreamingContent = (chunk: string): void => {
+ const currentContent = this.#get().streamingContent || '';
+ const newContent = currentContent + chunk;
+ this.#set({ streamingContent: newContent });
+ const { editor } = this.#get();
+ if (editor) {
try {
- if (saveCallbackRef) {
- await saveCallbackRef(payload);
- updateSaveStatusInternal(tabId, 'saved');
- }
- } catch (error) {
- console.error('[ProfileEditor] Failed to save:', error);
- updateSaveStatusInternal(tabId, 'idle');
+ editor.setDocument('markdown', newContent);
+ } catch {
+ // Ignore errors during streaming updates
}
- },
- EDITOR_DEBOUNCE_TIME,
- { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
- );
-
- return {
- ...initialState,
+ }
+ };
- appendStreamingContent: (chunk) => {
- const currentContent = get().streamingContent || '';
- const newContent = currentContent + chunk;
- set({ streamingContent: newContent });
+ finishStreaming = async (
+ saveCallback: (payload: SaveContentPayload) => Promise<void>,
+ ): Promise<void> => {
+ const { activeTabId, editor, streamingContent } = this.#get();
+ if (!streamingContent) {
+ this.#set({ streamingInProgress: false });
+ return;
+ }
- const { editor } = get();
- if (editor) {
- try {
- editor.setDocument('markdown', newContent);
- } catch {
- // Ignore errors during streaming updates
- }
- }
- },
+ let finalContent = streamingContent;
+ let editorData = {};
- finishStreaming: async (saveCallback) => {
- const { activeTabId, editor, streamingContent } = get();
- if (!streamingContent) {
- set({ streamingInProgress: false });
- return;
+ if (editor) {
+ try {
+ finalContent = (editor.getDocument('markdown') as unknown as string) || streamingContent;
+ editorData = editor.getDocument('json') as unknown as Record<string, any>;
+ } catch {
+ // Use streaming content if editor read fails
}
+ }
- let finalContent = streamingContent;
- let editorData = {};
+ this.#updateSaveStatusInternal(activeTabId, 'saving');
- if (editor) {
- try {
- finalContent = (editor.getDocument('markdown') as unknown as string) || streamingContent;
- editorData = editor.getDocument('json') as unknown as Record<string, any>;
- } catch {
- // Use streaming content if editor read fails
- }
- }
+ try {
+ await saveCallback({
+ content: finalContent,
+ editorData: structuredClone(editorData || {}),
+ });
+ this.#updateSaveStatusInternal(activeTabId, 'saved');
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to save streaming content:', error);
+ this.#updateSaveStatusInternal(activeTabId, 'idle');
+ }
+
+ this.#set({
+ streamingContent: undefined,
+ streamingInProgress: false,
+ });
+ };
- updateSaveStatusInternal(activeTabId, 'saving');
+ flushSave = (): void => {
+ this.#debouncedSave.flush();
+ };
- try {
- await saveCallback({
- content: finalContent,
- editorData: structuredClone(editorData || {}),
- });
- updateSaveStatusInternal(activeTabId, 'saved');
- } catch (error) {
- console.error('[ProfileEditor] Failed to save streaming content:', error);
- updateSaveStatusInternal(activeTabId, 'idle');
- }
+ handleContentChange = (saveCallback: (payload: SaveContentPayload) => Promise<void>): void => {
+ const { activeTabId, editor } = this.#get();
+ if (!editor) return;
- set({
- streamingContent: undefined,
- streamingInProgress: false,
- });
- },
+ // Always update refs to use the latest callback and tabId
+ saveCallbackRef = saveCallback;
+ currentTabIdRef = activeTabId;
- flushSave: () => {
- debouncedSave.flush();
- },
+ // Set saving status immediately when user makes changes
+ this.#updateSaveStatusInternal(activeTabId, 'saving');
- handleContentChange: (saveCallback) => {
- const { activeTabId, editor } = get();
- if (!editor) return;
+ try {
+ const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
+ const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;
- // Always update refs to use the latest callback and tabId
- saveCallbackRef = saveCallback;
- currentTabIdRef = activeTabId;
+ this.#debouncedSave({
+ content: markdownContent || '',
+ editorData: structuredClone(jsonContent || {}),
+ });
+ } catch (error) {
+ console.error('[ProfileEditor] Failed to read editor content:', error);
+ this.#updateSaveStatusInternal(activeTabId, 'idle');
+ }
+ };
- // Set saving status immediately when user makes changes
- updateSaveStatusInternal(activeTabId, 'saving');
+ setActiveTabId = (tabId: string): void => {
+ this.#set({ activeTabId: tabId });
+ };
- try {
- const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
- const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;
-
- debouncedSave({
- content: markdownContent || '',
- editorData: structuredClone(jsonContent || {}),
- });
- } catch (error) {
- console.error('[ProfileEditor] Failed to read editor content:', error);
- updateSaveStatusInternal(activeTabId, 'idle');
- }
- },
-
- setActiveTabId: (tabId) => {
- set({ activeTabId: tabId });
- },
-
- setAgentBuilderContent: (entityId, content) => {
- set({
- agentBuilderContentUpdate: {
- content,
- entityId,
- timestamp: Date.now(),
- },
- });
- },
+ setAgentBuilderContent = (entityId: string, content: string): void => {
+ this.#set({
+ agentBuilderContentUpdate: {
+ content,
+ entityId,
+ timestamp: Date.now(),
+ },
+ });
+ };
- setChatPanelExpanded: (expanded) => {
- if (typeof expanded === 'function') {
- set((state) => ({ chatPanelExpanded: expanded(state.chatPanelExpanded) }));
- } else {
- set({ chatPanelExpanded: expanded });
- }
- },
+ setChatPanelExpanded = (expanded: boolean | ((prev: boolean) => boolean)): void => {
+ if (typeof expanded === 'function') {
+ this.#set((state) => ({ chatPanelExpanded: expanded(state.chatPanelExpanded) }));
+ } else {
+ this.#set({ chatPanelExpanded: expanded });
+ }
+ };
- updateSaveStatus: (tabId, status) => {
- updateSaveStatusInternal(tabId, status);
- },
+ updateSaveStatus = (tabId: string, status: SaveStatus): void => {
+ this.#updateSaveStatusInternal(tabId, status);
};
-};
+}
+
+export const store: StateCreator<Store> = (set, get, _api) => ({
+ ...initialState,
+ ...new ActionImpl(set, get, _api),
+});
diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.ts
index 71f69330a61..230a0fb6d80 100644
--- a/src/store/home/slices/agentList/action.ts
+++ b/src/store/home/slices/agentList/action.ts
@@ -1,11 +1,11 @@
import isEqual from 'fast-deep-equal';
import type { SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import type { SidebarAgentItem, SidebarAgentListResponse } from '@/database/repositories/home';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
import { homeService } from '@/services/home';
import type { HomeStore } from '@/store/home/store';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { mapResponseToState } from './initialState';
@@ -15,54 +15,39 @@ const n = setNamespace('agentList');
const FETCH_AGENT_LIST_KEY = 'fetchAgentList';
const SEARCH_AGENTS_KEY = 'searchAgents';
-export interface AgentListAction {
- /**
- * Close all agents drawer
- */
- closeAllAgentsDrawer: () => void;
- /**
- * Open all agents drawer
- */
- openAllAgentsDrawer: () => void;
- /**
- * Refresh the agent list (mutate SWR cache)
- */
- refreshAgentList: () => Promise<void>;
- /**
- * SWR hook to fetch sidebar agent list
- */
- useFetchAgentList: (isLogin: boolean | undefined) => SWRResponse<SidebarAgentListResponse>;
- /**
- * SWR hook to search agents by keyword
- */
- useSearchAgents: (keyword?: string) => SWRResponse<SidebarAgentItem[]>;
-}
+type Setter = StoreSetter<HomeStore>;
+export const createAgentListSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new AgentListActionImpl(set, get, _api);
+
+export class AgentListActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ closeAllAgentsDrawer = (): void => {
+ this.#set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));
+ };
-export const createAgentListSlice: StateCreator<
- HomeStore,
- [['zustand/devtools', never]],
- [],
- AgentListAction
-> = (set, get) => ({
- closeAllAgentsDrawer: () => {
- set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));
- },
-
- openAllAgentsDrawer: () => {
- set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));
- },
-
- refreshAgentList: async () => {
+ openAllAgentsDrawer = (): void => {
+ this.#set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));
+ };
+
+ refreshAgentList = async (): Promise<void> => {
await mutate([FETCH_AGENT_LIST_KEY, true]);
- },
+ };
- useFetchAgentList: (isLogin) =>
- useClientDataSWRWithSync<SidebarAgentListResponse>(
+ useFetchAgentList = (isLogin: boolean | undefined): SWRResponse<SidebarAgentListResponse> => {
+ return useClientDataSWRWithSync<SidebarAgentListResponse>(
isLogin === true ? [FETCH_AGENT_LIST_KEY, isLogin] : null,
() => homeService.getSidebarAgentList(),
{
onData: (data) => {
- const state = get();
+ const state = this.#get();
const newState = mapResponseToState(data);
// Skip update if data is the same
@@ -75,7 +60,7 @@ export const createAgentListSlice: StateCreator<
return;
}
- set(
+ this.#set(
{
...newState,
isAgentListInit: true,
@@ -85,12 +70,16 @@ export const createAgentListSlice: StateCreator<
);
},
},
- ),
+ );
+ };
- useSearchAgents: (keyword) =>
- useClientDataSWR<SidebarAgentItem[]>([SEARCH_AGENTS_KEY, keyword], async () => {
+ useSearchAgents = (keyword?: string): SWRResponse<SidebarAgentItem[]> => {
+ return useClientDataSWR<SidebarAgentItem[]>([SEARCH_AGENTS_KEY, keyword], async () => {
if (!keyword) return [];
return homeService.searchAgents(keyword);
- }),
-});
+ });
+ };
+}
+
+export type AgentListAction = Pick<AgentListActionImpl, keyof AgentListActionImpl>;
diff --git a/src/store/home/slices/group/action.ts b/src/store/home/slices/group/action.ts
index abbe4a60152..87bad0c8672 100644
--- a/src/store/home/slices/group/action.ts
+++ b/src/store/home/slices/group/action.ts
@@ -1,19 +1,24 @@
-import type { StateCreator } from 'zustand/vanilla';
-
import type { HomeStore } from '@/store/home/store';
+import { type StoreSetter } from '@/store/types';
-export interface GroupAction {
- switchToGroup: (groupId: string) => void;
-}
+type Setter = StoreSetter<HomeStore>;
+export const createGroupSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new GroupActionImpl(set, get, _api);
+
+export class GroupActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #set: Setter;
-export const createGroupSlice: StateCreator<
- HomeStore,
- [['zustand/devtools', never]],
- [],
- GroupAction
-> = (_set, get) => ({
- switchToGroup: (groupId) => {
- const { navigate } = get();
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ switchToGroup = (groupId: string): void => {
+ const { navigate } = this.#get();
navigate?.(`/group/${groupId}`);
- },
-});
+ };
+}
+
+export type GroupAction = Pick<GroupActionImpl, keyof GroupActionImpl>;
diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.ts
index c073225dd5e..401231646fc 100644
--- a/src/store/home/slices/homeInput/action.ts
+++ b/src/store/home/slices/homeInput/action.ts
@@ -1,5 +1,4 @@
import type { NavigateFunction } from 'react-router-dom';
-import type { StateCreator } from 'zustand/vanilla';
import { chatGroupService } from '@/services/chatGroup';
import { documentService } from '@/services/document';
@@ -8,34 +7,33 @@ import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { getChatGroupStoreState } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
import type { HomeStore } from '@/store/home/store';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type { StarterMode } from './initialState';
const n = setNamespace('homeInput');
-export interface HomeInputAction {
- clearInputMode: () => void;
- sendAsAgent: (message: string) => Promise<string>;
- sendAsGroup: (message: string) => Promise<string>;
- sendAsResearch: (message: string) => Promise<void>;
- sendAsWrite: (message: string) => Promise<string>;
- setInputActiveMode: (mode: StarterMode) => void;
- setNavigate: (navigate: NavigateFunction) => void;
-}
+type Setter = StoreSetter<HomeStore>;
+export const createHomeInputSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new HomeInputActionImpl(set, get, _api);
+
+export class HomeInputActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createHomeInputSlice: StateCreator<
- HomeStore,
- [['zustand/devtools', never]],
- [],
- HomeInputAction
-> = (set, get) => ({
- clearInputMode: () => {
- set({ inputActiveMode: null }, false, n('clearInputMode'));
- },
+ clearInputMode = (): void => {
+ this.#set({ inputActiveMode: null }, false, n('clearInputMode'));
+ };
- sendAsAgent: async (message) => {
- set({ homeInputLoading: true }, false, n('sendAsAgent/start'));
+ sendAsAgent = async (message: string): Promise<string> => {
+ this.#set({ homeInputLoading: true }, false, n('sendAsAgent/start'));
try {
const agentState = getAgentStoreState();
@@ -59,13 +57,13 @@ export const createHomeInputSlice: StateCreator<
});
// 3. Navigate to Agent profile page
- const { navigate } = get();
+ const { navigate } = this.#get();
if (navigate) {
navigate(`/agent/${result.agentId}/profile`);
}
// 4. Refresh agent list
- get().refreshAgentList();
+ this.#get().refreshAgentList();
// 5. Update agentBuilder's model config and send initial message
if (result.agentId) {
@@ -84,16 +82,16 @@ export const createHomeInputSlice: StateCreator<
}
// 6. Clear mode
- set({ inputActiveMode: null }, false, n('sendAsAgent/clearMode'));
+ this.#set({ inputActiveMode: null }, false, n('sendAsAgent/clearMode'));
return result.agentId!;
} finally {
- set({ homeInputLoading: false }, false, n('sendAsAgent/end'));
+ this.#set({ homeInputLoading: false }, false, n('sendAsAgent/end'));
}
- },
+ };
- sendAsGroup: async (message) => {
- set({ homeInputLoading: true }, false, n('sendAsGroup/start'));
+ sendAsGroup = async (message: string): Promise<string> => {
+ this.#set({ homeInputLoading: true }, false, n('sendAsGroup/start'));
try {
const agentState = getAgentStoreState();
@@ -119,10 +117,10 @@ export const createHomeInputSlice: StateCreator<
await groupStore.loadGroups();
// 4. Refresh sidebar agent list
- get().refreshAgentList();
+ this.#get().refreshAgentList();
// 5. Navigate to Group profile page
- const { navigate } = get();
+ const { navigate } = this.#get();
if (navigate) {
navigate(`/group/${group.id}/profile`);
}
@@ -144,24 +142,24 @@ export const createHomeInputSlice: StateCreator<
}
// 7. Clear mode
- set({ inputActiveMode: null }, false, n('sendAsGroup/clearMode'));
+ this.#set({ inputActiveMode: null }, false, n('sendAsGroup/clearMode'));
return group.id;
} finally {
- set({ homeInputLoading: false }, false, n('sendAsGroup/end'));
+ this.#set({ homeInputLoading: false }, false, n('sendAsGroup/end'));
}
- },
+ };
- sendAsResearch: async (message) => {
+ sendAsResearch = async (message: string): Promise<void> => {
// TODO: Implement DeepResearch mode
console.log('sendAsResearch:', message);
// Clear mode
- set({ inputActiveMode: null }, false, n('sendAsResearch'));
- },
+ this.#set({ inputActiveMode: null }, false, n('sendAsResearch'));
+ };
- sendAsWrite: async (message) => {
- set({ homeInputLoading: true }, false, n('sendAsWrite/start'));
+ sendAsWrite = async (message: string): Promise<string> => {
+ this.#set({ homeInputLoading: true }, false, n('sendAsWrite/start'));
try {
const agentState = getAgentStoreState();
@@ -182,7 +180,7 @@ export const createHomeInputSlice: StateCreator<
});
// 3. Navigate to Page
- const { navigate } = get();
+ const { navigate } = this.#get();
if (navigate) {
navigate(`/page/${newDoc.id}`);
}
@@ -204,19 +202,21 @@ export const createHomeInputSlice: StateCreator<
}
// 5. Clear mode
- set({ inputActiveMode: null }, false, n('sendAsWrite/clearMode'));
+ this.#set({ inputActiveMode: null }, false, n('sendAsWrite/clearMode'));
return newDoc.id;
} finally {
- set({ homeInputLoading: false }, false, n('sendAsWrite/end'));
+ this.#set({ homeInputLoading: false }, false, n('sendAsWrite/end'));
}
- },
+ };
- setInputActiveMode: (mode) => {
- set({ inputActiveMode: mode }, false, n('setInputActiveMode', mode));
- },
+ setInputActiveMode = (mode: StarterMode): void => {
+ this.#set({ inputActiveMode: mode }, false, n('setInputActiveMode', mode));
+ };
+
+ setNavigate = (navigate: NavigateFunction): void => {
+ this.#set({ navigate }, false, n('setNavigate'));
+ };
+}
- setNavigate: (navigate) => {
- set({ navigate }, false, n('setNavigate'));
- },
-});
+export type HomeInputAction = Pick<HomeInputActionImpl, keyof HomeInputActionImpl>;
diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.ts
index 3f20ee978e1..55fa656b305 100644
--- a/src/store/home/slices/recent/action.ts
+++ b/src/store/home/slices/recent/action.ts
@@ -1,11 +1,11 @@
import isEqual from 'fast-deep-equal';
import type { SWRResponse } from 'swr';
-import type { StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { fileService } from '@/services/file';
import { topicService } from '@/services/topic';
import type { HomeStore } from '@/store/home/store';
+import { type StoreSetter } from '@/store/types';
import type { FileListItem } from '@/types/files';
import type { RecentTopic } from '@/types/topic';
import { setNamespace } from '@/utils/storeDebug';
@@ -16,69 +16,77 @@ const FETCH_RECENT_TOPICS_KEY = 'fetchRecentTopics';
const FETCH_RECENT_RESOURCES_KEY = 'fetchRecentResources';
const FETCH_RECENT_PAGES_KEY = 'fetchRecentPages';
-export interface RecentAction {
- useFetchRecentPages: (isLogin: boolean | undefined) => SWRResponse<any[]>;
- useFetchRecentResources: (isLogin: boolean | undefined) => SWRResponse<FileListItem[]>;
- useFetchRecentTopics: (isLogin: boolean | undefined) => SWRResponse<RecentTopic[]>;
-}
+type Setter = StoreSetter<HomeStore>;
+export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new RecentActionImpl(set, get, _api);
+
+export class RecentActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createRecentSlice: StateCreator<
- HomeStore,
- [['zustand/devtools', never]],
- [],
- RecentAction
-> = (set, get) => ({
- useFetchRecentPages: (isLogin) =>
- useClientDataSWRWithSync<any[]>(
+ useFetchRecentPages = (isLogin: boolean | undefined): SWRResponse<any[]> => {
+ return useClientDataSWRWithSync<any[]>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true ? [FETCH_RECENT_PAGES_KEY, isLogin] : null,
async () => fileService.getRecentPages(12),
{
onData: (data) => {
- if (get().isRecentPagesInit && isEqual(get().recentPages, data)) return;
+ if (this.#get().isRecentPagesInit && isEqual(this.#get().recentPages, data)) return;
- set(
+ this.#set(
{ isRecentPagesInit: true, recentPages: data },
false,
n('useFetchRecentPages/onData'),
);
},
},
- ),
+ );
+ };
- useFetchRecentResources: (isLogin) =>
- useClientDataSWRWithSync<FileListItem[]>(
+ useFetchRecentResources = (isLogin: boolean | undefined): SWRResponse<FileListItem[]> => {
+ return useClientDataSWRWithSync<FileListItem[]>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true ? [FETCH_RECENT_RESOURCES_KEY, isLogin] : null,
async () => fileService.getRecentFiles(12),
{
onData: (data) => {
- if (get().isRecentResourcesInit && isEqual(get().recentResources, data)) return;
+ if (this.#get().isRecentResourcesInit && isEqual(this.#get().recentResources, data))
+ return;
- set(
+ this.#set(
{ isRecentResourcesInit: true, recentResources: data },
false,
n('useFetchRecentResources/onData'),
);
},
},
- ),
+ );
+ };
- useFetchRecentTopics: (isLogin) =>
- useClientDataSWRWithSync<RecentTopic[]>(
+ useFetchRecentTopics = (isLogin: boolean | undefined): SWRResponse<RecentTopic[]> => {
+ return useClientDataSWRWithSync<RecentTopic[]>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true ? [FETCH_RECENT_TOPICS_KEY, isLogin] : null,
async () => topicService.getRecentTopics(12),
{
onData: (data) => {
- if (get().isRecentTopicsInit && isEqual(get().recentTopics, data)) return;
+ if (this.#get().isRecentTopicsInit && isEqual(this.#get().recentTopics, data)) return;
- set(
+ this.#set(
{ isRecentTopicsInit: true, recentTopics: data },
false,
n('useFetchRecentTopics/onData'),
);
},
},
- ),
-});
+ );
+ };
+}
+
+export type RecentAction = Pick<RecentActionImpl, keyof RecentActionImpl>;
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index d300bed0e46..bf617669681 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -1,6 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix,typescript-sort-keys/interface */
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { message } from '@/components/AntdStaticMethods';
import { agentService } from '@/services/agent';
@@ -9,91 +8,27 @@ import { homeService } from '@/services/home';
import { sessionService } from '@/services/session';
import { getAgentStoreState } from '@/store/agent';
import type { HomeStore } from '@/store/home/store';
-import type { SessionGroupItemBase } from '@/types/session';
+import { type StoreSetter } from '@/store/types';
+import { type SessionGroupItem } from '@/types/session';
import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('sidebarUI');
-export interface SidebarUIAction {
- // ========== Agent Operations ==========
- /**
- * Duplicate an agent using agentService
- */
- duplicateAgent: (agentId: string, newTitle?: string) => Promise<void>;
- /**
- * Duplicate a chat group (multi-agent group)
- */
- duplicateAgentGroup: (groupId: string, newTitle?: string) => Promise<void>;
- /**
- * Pin or unpin an agent
- */
- pinAgent: (agentId: string, pinned: boolean) => Promise<void>;
- /**
- * Pin or unpin an agent group
- */
- pinAgentGroup: (groupId: string, pinned: boolean) => Promise<void>;
- /**
- * Remove an agent
- */
- removeAgent: (agentId: string) => Promise<void>;
- /**
- * Remove an agent group (group chat)
- */
- removeAgentGroup: (groupId: string) => Promise<void>;
- /**
- * Rename an agent group (group chat)
- */
- renameAgentGroup: (groupId: string, title: string) => Promise<void>;
- /**
- * Update agent's group
- */
- updateAgentGroup: (agentId: string, groupId: string | null) => Promise<void>;
-
- // ========== Group Operations ==========
- /**
- * Add a new group
- */
- addGroup: (name: string) => Promise<string>;
- /**
- * Remove a group
- */
- removeGroup: (groupId: string) => Promise<void>;
- /**
- * Update group name
- */
- updateGroupName: (groupId: string, name: string) => Promise<void>;
- /**
- * Update group sort order
- */
- updateGroupSort: (items: SessionGroupItemBase[]) => Promise<void>;
-
- // ========== UI State Actions ==========
- /**
- * Set agent renaming id
- */
- setAgentRenamingId: (id: string | null) => void;
- /**
- * Set agent updating id
- */
- setAgentUpdatingId: (id: string | null) => void;
- /**
- * Set group renaming id
- */
- setGroupRenamingId: (id: string | null) => void;
- /**
- * Set group updating id
- */
- setGroupUpdatingId: (id: string | null) => void;
-}
+type Setter = StoreSetter<HomeStore>;
+export const createSidebarUISlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new SidebarUIActionImpl(set, get, _api);
+
+export class SidebarUIActionImpl {
+ readonly #get: () => HomeStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createSidebarUISlice: StateCreator<
- HomeStore,
- [['zustand/devtools', never]],
- [],
- SidebarUIAction
-> = (set, get) => ({
- // ========== Agent Operations ==========
- duplicateAgent: async (agentId, newTitle?: string) => {
+ duplicateAgent = async (agentId: string, newTitle?: string): Promise<void> => {
const messageLoadingKey = 'duplicateAgent.loading';
message.loading({
@@ -110,16 +45,16 @@ export const createSidebarUISlice: StateCreator<
return;
}
- await get().refreshAgentList();
+ await this.#get().refreshAgentList();
message.destroy(messageLoadingKey);
message.success(t('duplicateSession.success', { ns: 'chat' }));
// Switch to the new agent
const agentStore = getAgentStoreState();
agentStore.setActiveAgentId(result.agentId);
- },
+ };
- duplicateAgentGroup: async (groupId, newTitle?: string) => {
+ duplicateAgentGroup = async (groupId: string, newTitle?: string): Promise<void> => {
const messageLoadingKey = 'duplicateAgentGroup.loading';
message.loading({
@@ -136,64 +71,63 @@ export const createSidebarUISlice: StateCreator<
return;
}
- await get().refreshAgentList();
+ await this.#get().refreshAgentList();
message.destroy(messageLoadingKey);
message.success(t('duplicateSession.success', { ns: 'chat' }));
// Switch to the new group (using supervisor agent id)
const agentStore = getAgentStoreState();
agentStore.setActiveAgentId(result.supervisorAgentId);
- },
+ };
- pinAgent: async (agentId, pinned) => {
+ pinAgent = async (agentId: string, pinned: boolean): Promise<void> => {
await agentService.updateAgentPinned(agentId, pinned);
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- pinAgentGroup: async (groupId, pinned) => {
+ pinAgentGroup = async (groupId: string, pinned: boolean): Promise<void> => {
await chatGroupService.updateGroup(groupId, { pinned });
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- removeAgent: async (agentId) => {
+ removeAgent = async (agentId: string): Promise<void> => {
await agentService.removeAgent(agentId);
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- removeAgentGroup: async (groupId) => {
+ removeAgentGroup = async (groupId: string): Promise<void> => {
// Delete the group
await chatGroupService.deleteGroup(groupId);
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- renameAgentGroup: async (groupId, title) => {
+ renameAgentGroup = async (groupId: string, title: string): Promise<void> => {
await chatGroupService.updateGroup(groupId, { title });
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- updateAgentGroup: async (agentId, groupId) => {
+ updateAgentGroup = async (agentId: string, groupId: string | null): Promise<void> => {
await homeService.updateAgentSessionGroupId(agentId, groupId === 'default' ? null : groupId);
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- // ========== Group Operations ==========
- addGroup: async (name) => {
+ addGroup = async (name: string): Promise<string> => {
const id = await sessionService.createSessionGroup(name);
- await get().refreshAgentList();
+ await this.#get().refreshAgentList();
return id;
- },
+ };
- removeGroup: async (groupId) => {
+ removeGroup = async (groupId: string): Promise<void> => {
await sessionService.removeSessionGroup(groupId);
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- updateGroupName: async (groupId, name) => {
+ updateGroupName = async (groupId: string, name: string): Promise<void> => {
await sessionService.updateSessionGroup(groupId, { name });
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- updateGroupSort: async (items) => {
+ updateGroupSort = async (items: SessionGroupItem[]): Promise<void> => {
const sortMap = items.map((item, index) => ({ id: item.id, sort: index }));
message.loading({
@@ -206,23 +140,24 @@ export const createSidebarUISlice: StateCreator<
message.destroy('updateGroupSort');
message.success(t('sessionGroup.sortSuccess', { ns: 'chat' }));
- await get().refreshAgentList();
- },
+ await this.#get().refreshAgentList();
+ };
- // ========== UI State Actions ==========
- setAgentRenamingId: (id) => {
- set({ agentRenamingId: id }, false, n('setAgentRenamingId'));
- },
+ setAgentRenamingId = (id: string | null): void => {
+ this.#set({ agentRenamingId: id }, false, n('setAgentRenamingId'));
+ };
- setAgentUpdatingId: (id) => {
- set({ agentUpdatingId: id }, false, n('setAgentUpdatingId'));
- },
+ setAgentUpdatingId = (id: string | null): void => {
+ this.#set({ agentUpdatingId: id }, false, n('setAgentUpdatingId'));
+ };
- setGroupRenamingId: (id) => {
- set({ groupRenamingId: id }, false, n('setGroupRenamingId'));
- },
+ setGroupRenamingId = (id: string | null): void => {
+ this.#set({ groupRenamingId: id }, false, n('setGroupRenamingId'));
+ };
+
+ setGroupUpdatingId = (id: string | null): void => {
+ this.#set({ groupUpdatingId: id }, false, n('setGroupUpdatingId'));
+ };
+}
- setGroupUpdatingId: (id) => {
- set({ groupUpdatingId: id }, false, n('setGroupUpdatingId'));
- },
-});
+export type SidebarUIAction = Pick<SidebarUIActionImpl, keyof SidebarUIActionImpl>;
diff --git a/src/store/home/store.ts b/src/store/home/store.ts
index 5744eb46cd5..f2d2ac8a18d 100644
--- a/src/store/home/store.ts
+++ b/src/store/home/store.ts
@@ -6,6 +6,7 @@ import type { StateCreator } from 'zustand/vanilla';
import { isDev } from '@/utils/env';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type HomeStoreState, initialState } from './initialState';
import { type AgentListAction, createAgentListSlice } from './slices/agentList/action';
import { type GroupAction, createGroupSlice } from './slices/group/action';
@@ -24,13 +25,23 @@ export interface HomeStore
SidebarUIAction,
HomeStoreState {}
-const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type HomeStoreAction = AgentListAction &
+ GroupAction &
+ RecentAction &
+ HomeInputAction &
+ SidebarUIAction;
+
+const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<HomeStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createAgentListSlice(...parameters),
- ...createGroupSlice(...parameters),
- ...createRecentSlice(...parameters),
- ...createHomeInputSlice(...parameters),
- ...createSidebarUISlice(...parameters),
+ ...flattenActions<HomeStoreAction>([
+ createAgentListSlice(...parameters),
+ createGroupSlice(...parameters),
+ createRecentSlice(...parameters),
+ createHomeInputSlice(...parameters),
+ createSidebarUISlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/image/slices/createImage/action.ts b/src/store/image/slices/createImage/action.ts
index f794723d299..482491f9cbc 100644
--- a/src/store/image/slices/createImage/action.ts
+++ b/src/store/image/slices/createImage/action.ts
@@ -1,8 +1,8 @@
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
-import { type StateCreator } from 'zustand';
import { markUserValidAction } from '@/business/client/markUserValidAction';
import { imageService } from '@/services/image';
+import { type StoreSetter } from '@/store/types';
import { type ImageStore } from '../../store';
import { generationBatchSelectors } from '../generationBatch/selectors';
@@ -11,28 +11,29 @@ import { generationTopicSelectors } from '../generationTopic';
// ====== action interface ====== //
-export interface CreateImageAction {
- createImage: () => Promise<void>;
- /**
- * eg: invalid api key, recreate image
- */
- recreateImage: (generationBatchId: string) => Promise<void>;
-}
-
// ====== helper functions ====== //
// ====== action implementation ====== //
-export const createCreateImageSlice: StateCreator<
- ImageStore,
- [['zustand/devtools', never]],
- [],
- CreateImageAction
-> = (set, get) => ({
+type Setter = StoreSetter<ImageStore>;
+export const createCreateImageSlice = (set: Setter, get: () => ImageStore, _api?: unknown) =>
+ new CreateImageActionImpl(set, get, _api);
+
+export class CreateImageActionImpl {
+ readonly #get: () => ImageStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ImageStore, _api?: unknown) {
+ // keep signature aligned with StateCreator params: (set, get, api)
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
async createImage() {
- set({ isCreating: true }, false, 'createImage/startCreateImage');
+ this.#set({ isCreating: true }, false, 'createImage/startCreateImage');
- const store = get();
+ const store = this.#get();
const imageNum = imageGenerationConfigSelectors.imageNum(store);
const parameters = imageGenerationConfigSelectors.parameters(store);
const provider = imageGenerationConfigSelectors.provider(store);
@@ -71,7 +72,11 @@ export const createCreateImageSlice: StateCreator<
try {
// 4. If it's a new topic, set the creating state after topic creation
if (isNewTopic) {
- set({ isCreatingWithNewTopic: true }, false, 'createImage/startCreateImageWithNewTopic');
+ this.#set(
+ { isCreatingWithNewTopic: true },
+ false,
+ 'createImage/startCreateImageWithNewTopic',
+ );
}
if (ENABLE_BUSINESS_FEATURES) {
@@ -89,11 +94,11 @@ export const createCreateImageSlice: StateCreator<
// 6. Only refresh generation batches if it's not a new topic
if (!isNewTopic) {
- await get().refreshGenerationBatches();
+ await this.#get().refreshGenerationBatches();
}
// 7. Clear the prompt input after successful image creation
- set(
+ this.#set(
(state) => ({
parameters: { ...state.parameters, prompt: '' },
}),
@@ -103,21 +108,21 @@ export const createCreateImageSlice: StateCreator<
} finally {
// 8. Reset all creating states
if (isNewTopic) {
- set(
+ this.#set(
{ isCreating: false, isCreatingWithNewTopic: false },
false,
'createImage/endCreateImageWithNewTopic',
);
} else {
- set({ isCreating: false }, false, 'createImage/endCreateImage');
+ this.#set({ isCreating: false }, false, 'createImage/endCreateImage');
}
}
- },
+ }
async recreateImage(generationBatchId: string) {
- set({ isCreating: true }, false, 'recreateImage/startCreateImage');
+ this.#set({ isCreating: true }, false, 'recreateImage/startCreateImage');
- const store = get();
+ const store = this.#get();
const activeGenerationTopicId = generationTopicSelectors.activeGenerationTopicId(store);
if (!activeGenerationTopicId) {
throw new Error('No active generation topic');
@@ -145,7 +150,9 @@ export const createCreateImageSlice: StateCreator<
// 3. Refresh generation batches to show the real data
await store.refreshGenerationBatches();
} finally {
- set({ isCreating: false }, false, 'recreateImage/endCreateImage');
+ this.#set({ isCreating: false }, false, 'recreateImage/endCreateImage');
}
- },
-});
+ }
+}
+
+export type CreateImageAction = Pick<CreateImageActionImpl, keyof CreateImageActionImpl>;
diff --git a/src/store/image/slices/generationBatch/action.ts b/src/store/image/slices/generationBatch/action.ts
index 5d4622c64aa..9314b6aae96 100644
--- a/src/store/image/slices/generationBatch/action.ts
+++ b/src/store/image/slices/generationBatch/action.ts
@@ -1,12 +1,12 @@
import { isEqual } from 'es-toolkit/compat';
import { useRef } from 'react';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';
import { generationService } from '@/services/generation';
import { generationBatchService } from '@/services/generationBatch';
+import { type StoreSetter } from '@/store/types';
import { AsyncTaskStatus } from '@/types/asyncTask';
import { type GenerationBatch } from '@/types/generation';
import { setNamespace } from '@/utils/storeDebug';
@@ -23,66 +23,54 @@ const SWR_USE_CHECK_GENERATION_STATUS = 'SWR_USE_CHECK_GENERATION_STATUS';
// ====== action interface ====== //
-export interface GenerationBatchAction {
- setTopicBatchLoaded: (topicId: string) => void;
- internal_dispatchGenerationBatch: (
- topicId: string,
- payload: GenerationBatchDispatch,
- action?: string,
- ) => void;
- removeGeneration: (generationId: string) => Promise<void>;
- internal_deleteGeneration: (generationId: string) => Promise<void>;
- removeGenerationBatch: (batchId: string, topicId: string) => Promise<void>;
- internal_deleteGenerationBatch: (batchId: string, topicId: string) => Promise<void>;
- refreshGenerationBatches: () => Promise<void>;
- useCheckGenerationStatus: (
- generationId: string,
- asyncTaskId: string,
- topicId: string,
- enable?: boolean,
- ) => SWRResponse<GetGenerationStatusResult>;
- useFetchGenerationBatches: (topicId?: string | null) => SWRResponse<GenerationBatch[]>;
-}
-
// ====== action implementation ====== //
-export const createGenerationBatchSlice: StateCreator<
- ImageStore,
- [['zustand/devtools', never]],
- [],
- GenerationBatchAction
-> = (set, get) => ({
- setTopicBatchLoaded: (topicId: string) => {
+type Setter = StoreSetter<ImageStore>;
+export const createGenerationBatchSlice = (set: Setter, get: () => ImageStore, _api?: unknown) =>
+ new GenerationBatchActionImpl(set, get, _api);
+
+export class GenerationBatchActionImpl {
+ readonly #get: () => ImageStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ImageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ setTopicBatchLoaded = (topicId: string): void => {
const nextMap = {
- ...get().generationBatchesMap,
+ ...this.#get().generationBatchesMap,
[topicId]: [],
};
// no need to update map if the map is the same
- if (isEqual(nextMap, get().generationBatchesMap)) return;
+ if (isEqual(nextMap, this.#get().generationBatchesMap)) return;
- set(
+ this.#set(
{
generationBatchesMap: nextMap,
},
false,
n('setTopicBatchLoaded'),
);
- },
+ };
- removeGeneration: async (generationId: string) => {
- const { internal_deleteGeneration, activeGenerationTopicId, refreshGenerationBatches } = get();
+ removeGeneration = async (generationId: string): Promise<void> => {
+ const { internal_deleteGeneration, activeGenerationTopicId, refreshGenerationBatches } =
+ this.#get();
await internal_deleteGeneration(generationId);
// Check if any batch becomes empty after deletion, and if so, delete the empty batch
if (activeGenerationTopicId) {
- const updatedBatches = get().generationBatchesMap[activeGenerationTopicId] || [];
+ const updatedBatches = this.#get().generationBatchesMap[activeGenerationTopicId] || [];
const emptyBatches = updatedBatches.filter((batch) => batch.generations.length === 0);
// Delete all empty batches
for (const emptyBatch of emptyBatches) {
- await get().internal_deleteGenerationBatch(emptyBatch.id, activeGenerationTopicId);
+ await this.#get().internal_deleteGenerationBatch(emptyBatch.id, activeGenerationTopicId);
}
// If empty batches were deleted, refresh data again to ensure consistency
@@ -90,16 +78,16 @@ export const createGenerationBatchSlice: StateCreator<
await refreshGenerationBatches();
}
}
- },
+ };
- internal_deleteGeneration: async (generationId: string) => {
+ internal_deleteGeneration = async (generationId: string): Promise<void> => {
const { activeGenerationTopicId, refreshGenerationBatches, internal_dispatchGenerationBatch } =
- get();
+ this.#get();
if (!activeGenerationTopicId) return;
// Find the batch containing this generation
- const currentBatches = get().generationBatchesMap[activeGenerationTopicId] || [];
+ const currentBatches = this.#get().generationBatchesMap[activeGenerationTopicId] || [];
const targetBatch = currentBatches.find((batch) =>
batch.generations.some((gen) => gen.id === generationId),
);
@@ -118,15 +106,15 @@ export const createGenerationBatchSlice: StateCreator<
// 3. Refresh data to ensure consistency
await refreshGenerationBatches();
- },
+ };
- removeGenerationBatch: async (batchId: string, topicId: string) => {
- const { internal_deleteGenerationBatch } = get();
+ removeGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {
+ const { internal_deleteGenerationBatch } = this.#get();
await internal_deleteGenerationBatch(batchId, topicId);
- },
+ };
- internal_deleteGenerationBatch: async (batchId: string, topicId: string) => {
- const { internal_dispatchGenerationBatch, refreshGenerationBatches } = get();
+ internal_deleteGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {
+ const { internal_dispatchGenerationBatch, refreshGenerationBatches } = this.#get();
// 1. Immediately update frontend state (optimistic update)
internal_dispatchGenerationBatch(
@@ -140,38 +128,42 @@ export const createGenerationBatchSlice: StateCreator<
// 3. Refresh data to ensure consistency
await refreshGenerationBatches();
- },
+ };
- internal_dispatchGenerationBatch: (topicId, payload, action) => {
- const currentBatches = get().generationBatchesMap[topicId] || [];
+ internal_dispatchGenerationBatch = (
+ topicId: string,
+ payload: GenerationBatchDispatch,
+ action?: string,
+ ): void => {
+ const currentBatches = this.#get().generationBatchesMap[topicId] || [];
const nextBatches = generationBatchReducer(currentBatches, payload);
const nextMap = {
- ...get().generationBatchesMap,
+ ...this.#get().generationBatchesMap,
[topicId]: nextBatches,
};
// no need to update map if the map is the same
- if (isEqual(nextMap, get().generationBatchesMap)) return;
+ if (isEqual(nextMap, this.#get().generationBatchesMap)) return;
- set(
+ this.#set(
{
generationBatchesMap: nextMap,
},
false,
action ?? n(`dispatchGenerationBatch/${payload.type}`),
);
- },
+ };
- refreshGenerationBatches: async () => {
- const { activeGenerationTopicId } = get();
+ refreshGenerationBatches = async (): Promise<void> => {
+ const { activeGenerationTopicId } = this.#get();
if (activeGenerationTopicId) {
await mutate([SWR_USE_FETCH_GENERATION_BATCHES, activeGenerationTopicId]);
}
- },
+ };
- useFetchGenerationBatches: (topicId) =>
- useClientDataSWR<GenerationBatch[]>(
+ useFetchGenerationBatches = (topicId?: string | null): SWRResponse<GenerationBatch[]> => {
+ return useClientDataSWR<GenerationBatch[]>(
topicId ? [SWR_USE_FETCH_GENERATION_BATCHES, topicId] : null,
async ([, topicId]: [string, string]) => {
return generationBatchService.getGenerationBatches(topicId);
@@ -179,14 +171,14 @@ export const createGenerationBatchSlice: StateCreator<
{
onSuccess: (data) => {
const nextMap = {
- ...get().generationBatchesMap,
+ ...this.#get().generationBatchesMap,
[topicId!]: data,
};
// no need to update map if the map is the same
- if (isEqual(nextMap, get().generationBatchesMap)) return;
+ if (isEqual(nextMap, this.#get().generationBatchesMap)) return;
- set(
+ this.#set(
{
generationBatchesMap: nextMap,
},
@@ -195,9 +187,15 @@ export const createGenerationBatchSlice: StateCreator<
);
},
},
- ),
+ );
+ };
- useCheckGenerationStatus: (generationId, asyncTaskId, topicId, enable = true) => {
+ useCheckGenerationStatus = (
+ generationId: string,
+ asyncTaskId: string,
+ topicId: string,
+ enable: boolean = true,
+ ): SWRResponse<GetGenerationStatusResult> => {
const requestCountRef = useRef(0);
const isErrorRef = useRef(false);
@@ -249,8 +247,8 @@ export const createGenerationBatchSlice: StateCreator<
// Reset error state on success
isErrorRef.current = false;
- // Find the corresponding batch, generation database record contains generationBatchId
- const currentBatches = get().generationBatchesMap[topicId] || [];
+ // 找到对应的 batch,generation 数据库记录包含 generationBatchId
+ const currentBatches = this.#get().generationBatchesMap[topicId] || [];
const targetBatch = currentBatches.find((batch) =>
batch.generations.some((gen) => gen.id === generationId),
);
@@ -264,8 +262,8 @@ export const createGenerationBatchSlice: StateCreator<
requestCountRef.current = 0;
if (data.generation) {
- // Update generation data
- get().internal_dispatchGenerationBatch(
+ // 更新 generation 数据
+ this.#get().internal_dispatchGenerationBatch(
topicId,
{
type: 'updateGenerationInBatch',
@@ -280,12 +278,13 @@ export const createGenerationBatchSlice: StateCreator<
// If generation succeeds and has a thumbnail, check if the current topic has an imageUrl
if (data.status === AsyncTaskStatus.Success && data.generation.asset?.thumbnailUrl) {
- const currentTopic =
- generationTopicSelectors.getGenerationTopicById(topicId)(get());
+ const currentTopic = generationTopicSelectors.getGenerationTopicById(topicId)(
+ this.#get(),
+ );
// If the current topic doesn't have an imageUrl, update it with this generation's thumbnailUrl
if (currentTopic && !currentTopic.coverUrl) {
- await get().updateGenerationTopicCover(
+ await this.#get().updateGenerationTopicCover(
topicId,
data.generation.asset.thumbnailUrl,
);
@@ -294,10 +293,15 @@ export const createGenerationBatchSlice: StateCreator<
}
// Refresh generation batches after success or failure
- await get().refreshGenerationBatches();
+ await this.#get().refreshGenerationBatches();
}
},
},
);
- },
-});
+ };
+}
+
+export type GenerationBatchAction = Pick<
+ GenerationBatchActionImpl,
+ keyof GenerationBatchActionImpl
+>;
diff --git a/src/store/image/slices/generationBatch/reducer.ts b/src/store/image/slices/generationBatch/reducer.ts
index 2cb10d38ef7..79b15831111 100644
--- a/src/store/image/slices/generationBatch/reducer.ts
+++ b/src/store/image/slices/generationBatch/reducer.ts
@@ -2,34 +2,34 @@ import { produce } from 'immer';
import { type Generation, type GenerationBatch } from '@/types/generation';
-interface UpdateGenerationInBatchAction {
+type UpdateGenerationInBatchAction = {
batchId: string;
generationId: string;
type: 'updateGenerationInBatch';
value: Partial<Generation>;
-}
+};
-interface UpdateGenerationBatchAction {
+type UpdateGenerationBatchAction = {
id: string;
type: 'updateBatch';
value: Partial<GenerationBatch>;
-}
+};
-interface DeleteGenerationBatchAction {
+type DeleteGenerationBatchAction = {
id: string;
type: 'deleteBatch';
-}
+};
-interface DeleteGenerationInBatchAction {
+type DeleteGenerationInBatchAction = {
batchId: string;
generationId: string;
type: 'deleteGenerationInBatch';
-}
+};
-interface AddGenerationBatchAction {
+type AddGenerationBatchAction = {
type: 'addBatch';
value: GenerationBatch;
-}
+};
export type GenerationBatchDispatch =
| UpdateGenerationInBatchAction
diff --git a/src/store/image/slices/generationConfig/action.ts b/src/store/image/slices/generationConfig/action.ts
index a4c63b1cef6..350d556005b 100644
--- a/src/store/image/slices/generationConfig/action.ts
+++ b/src/store/image/slices/generationConfig/action.ts
@@ -6,10 +6,10 @@ import {
type RuntimeImageGenParamsValue,
extractDefaultValues,
} from 'model-bank';
-import { type StateCreator } from 'zustand/vanilla';
import { aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
import { useGlobalStore } from '@/store/global';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
import { settingsSelectors } from '@/store/user/slices/settings/selectors';
@@ -18,37 +18,6 @@ import type { ImageStore } from '../../store';
import { calculateInitialAspectRatio } from '../../utils/aspectRatio';
import { adaptSizeToRatio, parseRatio } from '../../utils/size';
-export interface GenerationConfigAction {
- setParamOnInput<K extends RuntimeImageGenParamsKeys>(
- paramName: K,
- value: RuntimeImageGenParamsValue,
- ): void;
-
- setModelAndProviderOnSelect(model: string, provider: string): void;
-
- setImageNum: (imageNum: number) => void;
-
- reuseSettings: (
- model: string,
- provider: string,
- settings: Partial<RuntimeImageGenParams>,
- ) => void;
- reuseSeed: (seed: number) => void;
-
- setWidth(width: number): void;
- setHeight(height: number): void;
- toggleAspectRatioLock(): void;
- setAspectRatio(aspectRatio: string): void;
-
- // Initialization related methods
- _initializeDefaultImageConfig(): void;
- initializeImageConfig(
- isLogin?: boolean,
- lastSelectedImageModel?: string,
- lastSelectedImageProvider?: string,
- ): void;
-}
-
/**
* @internal
* This function is exported only for testing purposes.
@@ -95,14 +64,25 @@ function prepareModelConfigState(model: string, provider: string) {
};
}
-export const createGenerationConfigSlice: StateCreator<
- ImageStore,
- [['zustand/devtools', never]],
- [],
- GenerationConfigAction
-> = (set, get) => ({
- setParamOnInput: (paramName, value) => {
- set(
+type Setter = StoreSetter<ImageStore>;
+export const createGenerationConfigSlice = (set: Setter, get: () => ImageStore, _api?: unknown) =>
+ new GenerationConfigActionImpl(set, get, _api);
+
+export class GenerationConfigActionImpl {
+ readonly #get: () => ImageStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ImageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ setParamOnInput = <T extends RuntimeImageGenParamsKeys>(
+ paramName: T,
+ value: RuntimeImageGenParamsValue,
+ ): void => {
+ this.#set(
(state) => {
const { parameters } = state;
return { parameters: { ...parameters, [paramName]: value } };
@@ -110,10 +90,10 @@ export const createGenerationConfigSlice: StateCreator<
false,
`setParamOnInput/${paramName}`,
);
- },
+ };
- setWidth: (width) => {
- set(
+ setWidth = (width: number): void => {
+ this.#set(
(state) => {
const {
parameters,
@@ -141,10 +121,10 @@ export const createGenerationConfigSlice: StateCreator<
false,
`setWidth`,
);
- },
+ };
- setHeight: (height) => {
- set(
+ setHeight = (height: number): void => {
+ this.#set(
(state) => {
const {
parameters,
@@ -172,10 +152,10 @@ export const createGenerationConfigSlice: StateCreator<
false,
`setHeight`,
);
- },
+ };
- toggleAspectRatioLock: () => {
- set(
+ toggleAspectRatioLock = (): void => {
+ this.#set(
(state) => {
const {
isAspectRatioLocked,
@@ -244,10 +224,10 @@ export const createGenerationConfigSlice: StateCreator<
false,
'toggleAspectRatioLock',
);
- },
+ };
- setAspectRatio: (aspectRatio) => {
- const { parameters, parametersSchema: parametersSchema } = get();
+ setAspectRatio = (aspectRatio: string): void => {
+ const { parameters, parametersSchema: parametersSchema } = this.#get();
if (!parameters || !parametersSchema) return;
const defaultValues = extractDefaultValues(parametersSchema);
@@ -271,20 +251,20 @@ export const createGenerationConfigSlice: StateCreator<
newParams.aspectRatio = aspectRatio;
}
- set(
+ this.#set(
{ activeAspectRatio: aspectRatio, parameters: newParams },
false,
`setAspectRatio/${aspectRatio}`,
);
- },
+ };
- setModelAndProviderOnSelect: (model, provider) => {
+ setModelAndProviderOnSelect = (model: string, provider: string): void => {
const { defaultValues, parametersSchema, initialActiveRatio } = prepareModelConfigState(
model,
provider,
);
- set(
+ this.#set(
{
model,
provider,
@@ -305,15 +285,19 @@ export const createGenerationConfigSlice: StateCreator<
lastSelectedImageProvider: provider,
});
}
- },
+ };
- setImageNum: (imageNum) => {
- set(() => ({ imageNum }), false, `setImageNum/${imageNum}`);
- },
+ setImageNum = (imageNum: number): void => {
+ this.#set(() => ({ imageNum }), false, `setImageNum/${imageNum}`);
+ };
- reuseSettings: (model: string, provider: string, settings: Partial<RuntimeImageGenParams>) => {
+ reuseSettings = (
+ model: string,
+ provider: string,
+ settings: Partial<RuntimeImageGenParams>,
+ ): void => {
const { defaultValues, parametersSchema } = getModelAndDefaults(model, provider);
- set(
+ this.#set(
() => ({
model,
provider,
@@ -323,19 +307,27 @@ export const createGenerationConfigSlice: StateCreator<
false,
`reuseSettings/${model}/${provider}`,
);
- },
+ };
- reuseSeed: (seed: number) => {
- set((state) => ({ parameters: { ...state.parameters, seed } }), false, `reuseSeed/${seed}`);
- },
+ reuseSeed = (seed: number): void => {
+ this.#set(
+ (state) => ({ parameters: { ...state.parameters, seed } }),
+ false,
+ `reuseSeed/${seed}`,
+ );
+ };
- _initializeDefaultImageConfig: () => {
+ _initializeDefaultImageConfig = (): void => {
const { defaultImageNum } = settingsSelectors.currentImageSettings(useUserStore.getState());
- set({ imageNum: defaultImageNum, isInit: true }, false, 'initializeImageConfig/default');
- },
+ this.#set({ imageNum: defaultImageNum, isInit: true }, false, 'initializeImageConfig/default');
+ };
- initializeImageConfig: (isLogin, lastSelectedImageModel, lastSelectedImageProvider) => {
- const { _initializeDefaultImageConfig } = get();
+ initializeImageConfig = (
+ isLogin?: boolean,
+ lastSelectedImageModel?: string,
+ lastSelectedImageProvider?: string,
+ ): void => {
+ const { _initializeDefaultImageConfig } = this.#get();
const { defaultImageNum } = settingsSelectors.currentImageSettings(useUserStore.getState());
if (isLogin && lastSelectedImageModel && lastSelectedImageProvider) {
@@ -345,7 +337,7 @@ export const createGenerationConfigSlice: StateCreator<
lastSelectedImageProvider,
);
- set(
+ this.#set(
{
model: lastSelectedImageModel,
provider: lastSelectedImageProvider,
@@ -365,5 +357,10 @@ export const createGenerationConfigSlice: StateCreator<
} else {
_initializeDefaultImageConfig();
}
- },
-});
+ };
+}
+
+export type GenerationConfigAction = Pick<
+ GenerationConfigActionImpl,
+ keyof GenerationConfigActionImpl
+>;
diff --git a/src/store/image/slices/generationTopic/action.ts b/src/store/image/slices/generationTopic/action.ts
index fb2a669684b..0f8ccec6266 100644
--- a/src/store/image/slices/generationTopic/action.ts
+++ b/src/store/image/slices/generationTopic/action.ts
@@ -1,7 +1,6 @@
import { chainSummaryGenerationTitle } from '@lobechat/prompts';
import isEqual from 'fast-deep-equal';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { LOADING_FLAT } from '@/const/message';
import { mutate, useClientDataSWR } from '@/libs/swr';
@@ -9,6 +8,7 @@ import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
import { chatService } from '@/services/chat';
import { generationTopicService } from '@/services/generationTopic';
import { globalHelpers } from '@/store/global/helpers';
+import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors } from '@/store/user/selectors';
import { type ImageGenerationTopic } from '@/types/generation';
@@ -23,38 +23,27 @@ const FETCH_GENERATION_TOPICS_KEY = 'fetchGenerationTopics';
const n = setNamespace('generationTopic');
-export interface GenerationTopicAction {
- createGenerationTopic: (prompts: string[]) => Promise<string>;
- removeGenerationTopic: (id: string) => Promise<void>;
- useFetchGenerationTopics: (enabled: boolean) => SWRResponse<ImageGenerationTopic[]>;
- summaryGenerationTopicTitle: (topicId: string, prompts: string[]) => Promise<string>;
- refreshGenerationTopics: () => Promise<void>;
- switchGenerationTopic: (topicId: string) => void;
- openNewGenerationTopic: () => void;
- updateGenerationTopicCover: (topicId: string, imageUrl: string) => Promise<void>;
-
- internal_updateGenerationTopicLoading: (id: string, loading: boolean) => void;
- internal_dispatchGenerationTopic: (payload: GenerationTopicDispatch, action?: any) => void;
- internal_createGenerationTopic: () => Promise<string>;
- internal_updateGenerationTopic: (id: string, data: UpdateTopicValue) => Promise<void>;
- internal_updateGenerationTopicTitleInSummary: (id: string, title: string) => void;
- internal_removeGenerationTopic: (id: string) => Promise<void>;
- internal_updateGenerationTopicCover: (topicId: string, coverUrl: string) => Promise<void>;
-}
+type Setter = StoreSetter<ImageStore>;
+export const createGenerationTopicSlice = (set: Setter, get: () => ImageStore, _api?: unknown) =>
+ new GenerationTopicActionImpl(set, get, _api);
+
+export class GenerationTopicActionImpl {
+ readonly #get: () => ImageStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ImageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createGenerationTopicSlice: StateCreator<
- ImageStore,
- [['zustand/devtools', never]],
- [],
- GenerationTopicAction
-> = (set, get) => ({
- createGenerationTopic: async (prompts: string[]) => {
+ createGenerationTopic = async (prompts: string[]): Promise<string> => {
// Validate prompts - cannot be empty
if (!prompts || prompts.length === 0) {
throw new Error('Prompts cannot be empty when creating a generation topic');
}
- const { internal_createGenerationTopic, summaryGenerationTopicTitle } = get();
+ const { internal_createGenerationTopic, summaryGenerationTopicTitle } = this.#get();
// Create topic with default title
const topicId = await internal_createGenerationTopic();
@@ -63,11 +52,11 @@ export const createGenerationTopicSlice: StateCreator<
summaryGenerationTopicTitle(topicId, prompts);
return topicId;
- },
+ };
- switchGenerationTopic: (topicId: string) => {
+ switchGenerationTopic = (topicId: string): void => {
// Check if topic exists
- const currentTopics = get().generationTopics;
+ const currentTopics = this.#get().generationTopics;
const targetTopic = currentTopics.find((topic) => topic.id === topicId);
if (!targetTopic) {
@@ -76,21 +65,21 @@ export const createGenerationTopicSlice: StateCreator<
}
// Don't update if already active
- if (get().activeGenerationTopicId === topicId) return;
+ if (this.#get().activeGenerationTopicId === topicId) return;
- set({ activeGenerationTopicId: topicId }, false, n('switchGenerationTopic'));
- },
+ this.#set({ activeGenerationTopicId: topicId }, false, n('switchGenerationTopic'));
+ };
- openNewGenerationTopic: () => {
- set({ activeGenerationTopicId: null }, false, n('openNewGenerationTopic'));
- },
+ openNewGenerationTopic = (): void => {
+ this.#set({ activeGenerationTopicId: null }, false, n('openNewGenerationTopic'));
+ };
- summaryGenerationTopicTitle: async (topicId: string, prompts: string[]) => {
- const topic = generationTopicSelectors.getGenerationTopicById(topicId)(get());
+ summaryGenerationTopicTitle = async (topicId: string, prompts: string[]): Promise<string> => {
+ const topic = generationTopicSelectors.getGenerationTopicById(topicId)(this.#get());
if (!topic) throw new Error(`Topic ${topicId} not found`);
const { internal_updateGenerationTopicTitleInSummary, internal_updateGenerationTopicLoading } =
- get();
+ this.#get();
internal_updateGenerationTopicLoading(topicId, true);
internal_updateGenerationTopicTitleInSummary(topicId, LOADING_FLAT);
@@ -124,10 +113,10 @@ export const createGenerationTopicSlice: StateCreator<
const fallbackTitle = generateFallbackTitle();
internal_updateGenerationTopicTitleInSummary(topicId, fallbackTitle);
// Update the topic with fallback title
- await get().internal_updateGenerationTopic(topicId, { title: fallbackTitle });
+ await this.#get().internal_updateGenerationTopic(topicId, { title: fallbackTitle });
},
onFinish: async (text) => {
- await get().internal_updateGenerationTopic(topicId, { title: text });
+ await this.#get().internal_updateGenerationTopic(topicId, { title: text });
},
onLoadingChange: (loading) => {
internal_updateGenerationTopicLoading(topicId, loading);
@@ -143,55 +132,55 @@ export const createGenerationTopicSlice: StateCreator<
});
return output;
- },
+ };
- internal_createGenerationTopic: async () => {
+ internal_createGenerationTopic = async (): Promise<string> => {
const tmpId = Date.now().toString();
// 1. Optimistic update - add temporary topic
- get().internal_dispatchGenerationTopic(
+ this.#get().internal_dispatchGenerationTopic(
{ type: 'addTopic', value: { id: tmpId, title: '' } },
'internal_createGenerationTopic',
);
- get().internal_updateGenerationTopicLoading(tmpId, true);
+ this.#get().internal_updateGenerationTopicLoading(tmpId, true);
// 2. Call backend service
const topicId = await generationTopicService.createTopic();
- get().internal_updateGenerationTopicLoading(tmpId, false);
+ this.#get().internal_updateGenerationTopicLoading(tmpId, false);
// 3. Refresh data to ensure consistency
- get().internal_updateGenerationTopicLoading(topicId, true);
- await get().refreshGenerationTopics();
- get().internal_updateGenerationTopicLoading(topicId, false);
+ this.#get().internal_updateGenerationTopicLoading(topicId, true);
+ await this.#get().refreshGenerationTopics();
+ this.#get().internal_updateGenerationTopicLoading(topicId, false);
return topicId;
- },
+ };
- internal_updateGenerationTopic: async (id, data) => {
+ internal_updateGenerationTopic = async (id: string, data: UpdateTopicValue): Promise<void> => {
// 1. Optimistic update
- get().internal_dispatchGenerationTopic({ type: 'updateTopic', id, value: data });
+ this.#get().internal_dispatchGenerationTopic({ type: 'updateTopic', id, value: data });
// 2. Update loading state
- get().internal_updateGenerationTopicLoading(id, true);
+ this.#get().internal_updateGenerationTopicLoading(id, true);
// 3. Call backend service
await generationTopicService.updateTopic(id, data);
// 4. Refresh data and clear loading
- await get().refreshGenerationTopics();
- get().internal_updateGenerationTopicLoading(id, false);
- },
+ await this.#get().refreshGenerationTopics();
+ this.#get().internal_updateGenerationTopicLoading(id, false);
+ };
- internal_updateGenerationTopicTitleInSummary: (id, title) => {
- get().internal_dispatchGenerationTopic(
+ internal_updateGenerationTopicTitleInSummary = (id: string, title: string): void => {
+ this.#get().internal_dispatchGenerationTopic(
{ type: 'updateTopic', id, value: { title } },
'updateGenerationTopicTitleInSummary',
);
- },
+ };
- internal_updateGenerationTopicLoading: (id, loading) => {
- set(
+ internal_updateGenerationTopicLoading = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading) return { loadingGenerationTopicIds: [...state.loadingGenerationTopicIds, id] };
@@ -202,47 +191,48 @@ export const createGenerationTopicSlice: StateCreator<
false,
n('updateGenerationTopicLoading'),
);
- },
+ };
- internal_dispatchGenerationTopic: (payload, action) => {
- const nextTopics = generationTopicReducer(get().generationTopics, payload);
+ internal_dispatchGenerationTopic = (payload: GenerationTopicDispatch, action?: any): void => {
+ const nextTopics = generationTopicReducer(this.#get().generationTopics, payload);
// No need to update if the topics are the same
- if (isEqual(nextTopics, get().generationTopics)) return;
+ if (isEqual(nextTopics, this.#get().generationTopics)) return;
- set(
+ this.#set(
{ generationTopics: nextTopics },
false,
action ?? n(`dispatchGenerationTopic/${payload.type}`),
);
- },
+ };
- useFetchGenerationTopics: (enabled) =>
- useClientDataSWR<ImageGenerationTopic[]>(
+ useFetchGenerationTopics = (enabled: boolean): SWRResponse<ImageGenerationTopic[]> => {
+ return useClientDataSWR<ImageGenerationTopic[]>(
enabled ? [FETCH_GENERATION_TOPICS_KEY] : null,
() => generationTopicService.getAllGenerationTopics(),
{
suspense: true,
onSuccess: (data) => {
// No need to update if data is the same
- if (isEqual(data, get().generationTopics)) return;
- set({ generationTopics: data }, false, n('useFetchGenerationTopics'));
+ if (isEqual(data, this.#get().generationTopics)) return;
+ this.#set({ generationTopics: data }, false, n('useFetchGenerationTopics'));
},
},
- ),
+ );
+ };
- refreshGenerationTopics: async () => {
+ refreshGenerationTopics = async (): Promise<void> => {
await mutate([FETCH_GENERATION_TOPICS_KEY]);
- },
+ };
- removeGenerationTopic: async (id: string) => {
+ removeGenerationTopic = async (id: string): Promise<void> => {
const {
internal_removeGenerationTopic,
generationTopics,
activeGenerationTopicId,
switchGenerationTopic,
openNewGenerationTopic,
- } = get();
+ } = this.#get();
const isRemovingActiveTopic = activeGenerationTopicId === id;
let topicIndexToRemove = -1;
@@ -255,7 +245,7 @@ export const createGenerationTopicSlice: StateCreator<
// if the active topic is the one being deleted, switch to the next topic
if (isRemovingActiveTopic) {
- const newTopics = get().generationTopics;
+ const newTopics = this.#get().generationTopics;
if (newTopics.length > 0) {
// try to select the topic at the same index, if not, select the last one
@@ -273,29 +263,32 @@ export const createGenerationTopicSlice: StateCreator<
openNewGenerationTopic();
}
}
- },
+ };
- internal_removeGenerationTopic: async (id: string) => {
- get().internal_updateGenerationTopicLoading(id, true);
+ internal_removeGenerationTopic = async (id: string): Promise<void> => {
+ this.#get().internal_updateGenerationTopicLoading(id, true);
try {
await generationTopicService.deleteTopic(id);
- await get().refreshGenerationTopics();
+ await this.#get().refreshGenerationTopics();
} finally {
- get().internal_updateGenerationTopicLoading(id, false);
+ this.#get().internal_updateGenerationTopicLoading(id, false);
}
- },
+ };
- updateGenerationTopicCover: async (topicId: string, coverUrl: string) => {
- const { internal_updateGenerationTopicCover } = get();
+ updateGenerationTopicCover = async (topicId: string, coverUrl: string): Promise<void> => {
+ const { internal_updateGenerationTopicCover } = this.#get();
await internal_updateGenerationTopicCover(topicId, coverUrl);
- },
+ };
- internal_updateGenerationTopicCover: async (topicId: string, coverUrl: string) => {
+ internal_updateGenerationTopicCover = async (
+ topicId: string,
+ coverUrl: string,
+ ): Promise<void> => {
const {
internal_dispatchGenerationTopic,
internal_updateGenerationTopicLoading,
refreshGenerationTopics,
- } = get();
+ } = this.#get();
// 1. Optimistic update - immediately show the new cover URL in UI
internal_dispatchGenerationTopic(
@@ -316,5 +309,10 @@ export const createGenerationTopicSlice: StateCreator<
// 5. Clear loading state
internal_updateGenerationTopicLoading(topicId, false);
}
- },
-});
+ };
+}
+
+export type GenerationTopicAction = Pick<
+ GenerationTopicActionImpl,
+ keyof GenerationTopicActionImpl
+>;
diff --git a/src/store/image/slices/generationTopic/reducer.ts b/src/store/image/slices/generationTopic/reducer.ts
index 537c29103a4..1b1ed62ce5e 100644
--- a/src/store/image/slices/generationTopic/reducer.ts
+++ b/src/store/image/slices/generationTopic/reducer.ts
@@ -3,21 +3,21 @@ import { produce } from 'immer';
import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';
import { type ImageGenerationTopic } from '@/types/generation';
-interface AddGenerationTopicAction {
+type AddGenerationTopicAction = {
type: 'addTopic';
value: Partial<ImageGenerationTopic> & { id: string };
-}
+};
-interface UpdateGenerationTopicAction {
+type UpdateGenerationTopicAction = {
id: string;
type: 'updateTopic';
value: UpdateTopicValue;
-}
+};
-interface DeleteGenerationTopicAction {
+type DeleteGenerationTopicAction = {
id: string;
type: 'deleteTopic';
-}
+};
export type GenerationTopicDispatch =
| AddGenerationTopicAction
diff --git a/src/store/image/store.ts b/src/store/image/store.ts
index f37b81b1497..e9c181ff3bf 100644
--- a/src/store/image/store.ts
+++ b/src/store/image/store.ts
@@ -4,30 +4,47 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type ImageStoreState, initialState } from './initialState';
import { type CreateImageAction, createCreateImageSlice } from './slices/createImage/action';
-import { type GenerationBatchAction, createGenerationBatchSlice } from './slices/generationBatch/action';
+import {
+ type GenerationBatchAction,
+ createGenerationBatchSlice,
+} from './slices/generationBatch/action';
import {
type GenerationConfigAction,
createGenerationConfigSlice,
} from './slices/generationConfig/action';
-import { type GenerationTopicAction, createGenerationTopicSlice } from './slices/generationTopic/action';
+import {
+ type GenerationTopicAction,
+ createGenerationTopicSlice,
+} from './slices/generationTopic/action';
// =============== aggregate createStoreFn ============ //
export interface ImageStore
- extends GenerationConfigAction,
+ extends
+ GenerationConfigAction,
GenerationTopicAction,
GenerationBatchAction,
CreateImageAction,
ImageStoreState {}
-const createStore: StateCreator<ImageStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type ImageStoreAction = GenerationConfigAction &
+ GenerationTopicAction &
+ GenerationBatchAction &
+ CreateImageAction;
+
+const createStore: StateCreator<ImageStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<ImageStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createGenerationConfigSlice(...parameters),
- ...createGenerationTopicSlice(...parameters),
- ...createGenerationBatchSlice(...parameters),
- ...createCreateImageSlice(...parameters),
+ ...flattenActions<ImageStoreAction>([
+ createGenerationConfigSlice(...parameters),
+ createGenerationTopicSlice(...parameters),
+ createGenerationBatchSlice(...parameters),
+ createCreateImageSlice(...parameters),
+ ]),
});
// =============== implement useStore ============ //
diff --git a/src/store/library/slices/content/action.ts b/src/store/library/slices/content/action.ts
index 38ca36f505c..af71b6d5d44 100644
--- a/src/store/library/slices/content/action.ts
+++ b/src/store/library/slices/content/action.ts
@@ -1,31 +1,38 @@
-import { type StateCreator } from 'zustand/vanilla';
-
import { knowledgeBaseService } from '@/services/knowledgeBase';
import { revalidateResources } from '@/store/file/slices/resource/hooks';
import { type KnowledgeBaseStore } from '@/store/library/store';
+import { type StoreSetter } from '@/store/types';
-export interface KnowledgeBaseContentAction {
- addFilesToKnowledgeBase: (knowledgeBaseId: string, ids: string[]) => Promise<void>;
- removeFilesFromKnowledgeBase: (knowledgeBaseId: string, ids: string[]) => Promise<void>;
-}
+type Setter = StoreSetter<KnowledgeBaseStore>;
+export const createContentSlice = (set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) =>
+ new KnowledgeBaseContentActionImpl(set, get, _api);
+
+export class KnowledgeBaseContentActionImpl {
+ readonly #get: () => KnowledgeBaseStore;
+ readonly #set: Setter;
-export const createContentSlice: StateCreator<
- KnowledgeBaseStore,
- [['zustand/devtools', never]],
- [],
- KnowledgeBaseContentAction
-> = () => ({
- addFilesToKnowledgeBase: async (knowledgeBaseId, ids) => {
+ constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ addFilesToKnowledgeBase = async (knowledgeBaseId: string, ids: string[]): Promise<void> => {
await knowledgeBaseService.addFilesToKnowledgeBase(knowledgeBaseId, ids);
// Revalidate resource list to show updated KB associations
await revalidateResources();
- },
+ };
- removeFilesFromKnowledgeBase: async (knowledgeBaseId, ids) => {
+ removeFilesFromKnowledgeBase = async (knowledgeBaseId: string, ids: string[]): Promise<void> => {
await knowledgeBaseService.removeFilesFromKnowledgeBase(knowledgeBaseId, ids);
// Revalidate resource list to show updated KB associations
await revalidateResources();
- },
-});
+ };
+}
+
+export type KnowledgeBaseContentAction = Pick<
+ KnowledgeBaseContentActionImpl,
+ keyof KnowledgeBaseContentActionImpl
+>;
diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.ts
index 3407ffe1995..02c29d670c8 100644
--- a/src/store/library/slices/crud/action.test.ts
+++ b/src/store/library/slices/crud/action.test.ts
@@ -226,9 +226,12 @@ describe('KnowledgeBaseCrudAction', () => {
vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(mockItem);
- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-1'), {
- wrapper: withSWR,
- });
+ const { result } = renderHook(
+ () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-1'),
+ {
+ wrapper: withSWR,
+ },
+ );
await waitFor(() => {
expect(result.current.data).toEqual(mockItem);
@@ -253,9 +256,12 @@ describe('KnowledgeBaseCrudAction', () => {
vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(mockItem);
- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-2'), {
- wrapper: withSWR,
- });
+ const { result } = renderHook(
+ () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-2'),
+ {
+ wrapper: withSWR,
+ },
+ );
await waitFor(() => {
expect(result.current.data).toEqual(mockItem);
@@ -276,9 +282,12 @@ describe('KnowledgeBaseCrudAction', () => {
});
});
- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-3'), {
- wrapper: withSWR,
- });
+ const { result } = renderHook(
+ () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-3'),
+ {
+ wrapper: withSWR,
+ },
+ );
await waitFor(() => {
expect(result.current.data).toBeUndefined();
@@ -326,9 +335,12 @@ describe('KnowledgeBaseCrudAction', () => {
vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(newItem);
- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-new'), {
- wrapper: withSWR,
- });
+ const { result } = renderHook(
+ () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-new'),
+ {
+ wrapper: withSWR,
+ },
+ );
await waitFor(() => {
expect(result.current.data).toEqual(newItem);
diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.ts
index f86dea75616..ac61e66004c 100644
--- a/src/store/library/slices/crud/action.ts
+++ b/src/store/library/slices/crud/action.ts
@@ -1,41 +1,38 @@
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { knowledgeBaseService } from '@/services/knowledgeBase';
import { type KnowledgeBaseStore } from '@/store/library/store';
+import { type StoreSetter } from '@/store/types';
import { type CreateKnowledgeBaseParams, type KnowledgeBaseItem } from '@/types/knowledgeBase';
const FETCH_KNOWLEDGE_BASE_LIST_KEY = 'FETCH_KNOWLEDGE_BASE';
const FETCH_KNOWLEDGE_BASE_ITEM_KEY = 'FETCH_KNOWLEDGE_BASE_ITEM';
-export interface KnowledgeBaseCrudAction {
- createNewKnowledgeBase: (params: CreateKnowledgeBaseParams) => Promise<string>;
- internal_toggleKnowledgeBaseLoading: (id: string, loading: boolean) => void;
- refreshKnowledgeBaseList: () => Promise<void>;
+type Setter = StoreSetter<KnowledgeBaseStore>;
+export const createCrudSlice = (set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) =>
+ new KnowledgeBaseCrudActionImpl(set, get, _api);
- removeKnowledgeBase: (id: string) => Promise<void>;
- updateKnowledgeBase: (id: string, value: CreateKnowledgeBaseParams) => Promise<void>;
+export class KnowledgeBaseCrudActionImpl {
+ readonly #get: () => KnowledgeBaseStore;
+ readonly #set: Setter;
- useFetchKnowledgeBaseItem: (id: string) => SWRResponse<KnowledgeBaseItem | undefined>;
- useFetchKnowledgeBaseList: (params?: { suspense?: boolean }) => SWRResponse<KnowledgeBaseItem[]>;
-}
+ constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createCrudSlice: StateCreator<
- KnowledgeBaseStore,
- [['zustand/devtools', never]],
- [],
- KnowledgeBaseCrudAction
-> = (set, get) => ({
- createNewKnowledgeBase: async (params) => {
+ createNewKnowledgeBase = async (params: CreateKnowledgeBaseParams): Promise<string> => {
const id = await knowledgeBaseService.createKnowledgeBase(params);
- await get().refreshKnowledgeBaseList();
+ await this.#get().refreshKnowledgeBaseList();
return id;
- },
- internal_toggleKnowledgeBaseLoading: (id, loading) => {
- set(
+ };
+
+ internal_toggleKnowledgeBaseLoading = (id: string, loading: boolean): void => {
+ this.#set(
(state) => {
if (loading) return { knowledgeBaseLoadingIds: [...state.knowledgeBaseLoadingIds, id] };
@@ -44,52 +41,64 @@ export const createCrudSlice: StateCreator<
false,
'toggleKnowledgeBaseLoading',
);
- },
- refreshKnowledgeBaseList: async () => {
+ };
+
+ refreshKnowledgeBaseList = async (): Promise<void> => {
await mutate(FETCH_KNOWLEDGE_BASE_LIST_KEY);
- },
- removeKnowledgeBase: async (id) => {
+ };
+
+ removeKnowledgeBase = async (id: string): Promise<void> => {
await knowledgeBaseService.deleteKnowledgeBase(id);
- await get().refreshKnowledgeBaseList();
- },
- updateKnowledgeBase: async (id, value) => {
- get().internal_toggleKnowledgeBaseLoading(id, true);
+ await this.#get().refreshKnowledgeBaseList();
+ };
+
+ updateKnowledgeBase = async (id: string, value: CreateKnowledgeBaseParams): Promise<void> => {
+ this.#get().internal_toggleKnowledgeBaseLoading(id, true);
await knowledgeBaseService.updateKnowledgeBaseList(id, value);
- await get().refreshKnowledgeBaseList();
+ await this.#get().refreshKnowledgeBaseList();
- get().internal_toggleKnowledgeBaseLoading(id, false);
- },
+ this.#get().internal_toggleKnowledgeBaseLoading(id, false);
+ };
- useFetchKnowledgeBaseItem: (id) =>
- useClientDataSWR<KnowledgeBaseItem | undefined>(
+ useFetchKnowledgeBaseItem = (id: string): SWRResponse<KnowledgeBaseItem | undefined> => {
+ return useClientDataSWR<KnowledgeBaseItem | undefined>(
[FETCH_KNOWLEDGE_BASE_ITEM_KEY, id],
() => knowledgeBaseService.getKnowledgeBaseById(id),
{
onSuccess: (item) => {
if (!item) return;
- set({
+ this.#set({
activeKnowledgeBaseId: id,
activeKnowledgeBaseItems: {
- ...get().activeKnowledgeBaseItems,
+ ...this.#get().activeKnowledgeBaseItems,
[id]: item,
},
});
},
},
- ),
+ );
+ };
- useFetchKnowledgeBaseList: (params = {}) =>
- useClientDataSWR<KnowledgeBaseItem[]>(
+ useFetchKnowledgeBaseList = (
+ params: { suspense?: boolean } = {},
+ ): SWRResponse<KnowledgeBaseItem[]> => {
+ return useClientDataSWR<KnowledgeBaseItem[]>(
FETCH_KNOWLEDGE_BASE_LIST_KEY,
() => knowledgeBaseService.getKnowledgeBaseList(),
{
fallbackData: [],
onSuccess: () => {
- if (!get().initKnowledgeBaseList)
- set({ initKnowledgeBaseList: true }, false, 'useFetchKnowledgeBaseList/init');
+ if (!this.#get().initKnowledgeBaseList)
+ this.#set({ initKnowledgeBaseList: true }, false, 'useFetchKnowledgeBaseList/init');
},
suspense: params.suspense,
},
- ),
-});
+ );
+ };
+}
+
+export type KnowledgeBaseCrudAction = Pick<
+ KnowledgeBaseCrudActionImpl,
+ keyof KnowledgeBaseCrudActionImpl
+>;
diff --git a/src/store/library/slices/ragEval/actions/dataset.ts b/src/store/library/slices/ragEval/actions/dataset.ts
index 331baa81f4b..0653c9673a5 100644
--- a/src/store/library/slices/ragEval/actions/dataset.ts
+++ b/src/store/library/slices/ragEval/actions/dataset.ts
@@ -6,38 +6,39 @@ import {
} from '@lobechat/types';
import i18n from 'i18next';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { notification } from '@/components/AntdStaticMethods';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { ragEvalService } from '@/services/ragEval';
import { type KnowledgeBaseStore } from '@/store/library/store';
+import { type StoreSetter } from '@/store/types';
const FETCH_DATASET_LIST_KEY = 'FETCH_DATASET_LIST';
const FETCH_DATASET_RECORD_KEY = 'FETCH_DATASET_RECORD_KEY';
-export interface RAGEvalDatasetAction {
- createNewDataset: (params: CreateNewEvalDatasets) => Promise<void>;
+type Setter = StoreSetter<KnowledgeBaseStore>;
+export const createRagEvalDatasetSlice = (
+ set: Setter,
+ get: () => KnowledgeBaseStore,
+ _api?: unknown,
+) => new RAGEvalDatasetActionImpl(set, get, _api);
- importDataset: (file: File, datasetId: string) => Promise<void>;
- refreshDatasetList: () => Promise<void>;
- removeDataset: (id: string) => Promise<void>;
- useFetchDatasetRecords: (datasetId: string | null) => SWRResponse<EvalDatasetRecord[]>;
- useFetchDatasets: (knowledgeBaseId: string) => SWRResponse<RAGEvalDataSetItem[]>;
-}
+export class RAGEvalDatasetActionImpl {
+ readonly #get: () => KnowledgeBaseStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createRagEvalDatasetSlice: StateCreator<
- KnowledgeBaseStore,
- [['zustand/devtools', never]],
- [],
- RAGEvalDatasetAction
-> = (set, get) => ({
- createNewDataset: async (params) => {
+ createNewDataset = async (params: CreateNewEvalDatasets): Promise<void> => {
await ragEvalService.createDataset(params);
- await get().refreshDatasetList();
- },
+ await this.#get().refreshDatasetList();
+ };
- importDataset: async (file, datasetId) => {
+ importDataset = async (file: File, datasetId: string): Promise<void> => {
if (!datasetId) return;
const fileType = file.name.split('.').pop();
@@ -62,31 +63,38 @@ export const createRagEvalDatasetSlice: StateCreator<
}
}
- await get().refreshDatasetList();
- },
- refreshDatasetList: async () => {
+ await this.#get().refreshDatasetList();
+ };
+
+ refreshDatasetList = async (): Promise<void> => {
await mutate(FETCH_DATASET_LIST_KEY);
- },
+ };
- removeDataset: async (id) => {
+ removeDataset = async (id: string): Promise<void> => {
await ragEvalService.removeDataset(id);
- await get().refreshDatasetList();
- },
- useFetchDatasetRecords: (datasetId) =>
- useClientDataSWR<EvalDatasetRecord[]>(
+ await this.#get().refreshDatasetList();
+ };
+
+ useFetchDatasetRecords = (datasetId: string | null): SWRResponse<EvalDatasetRecord[]> => {
+ return useClientDataSWR<EvalDatasetRecord[]>(
!!datasetId ? [FETCH_DATASET_RECORD_KEY, datasetId] : null,
() => ragEvalService.getDatasetRecords(datasetId!),
- ),
- useFetchDatasets: (knowledgeBaseId) =>
- useClientDataSWR<RAGEvalDataSetItem[]>(
+ );
+ };
+
+ useFetchDatasets = (knowledgeBaseId: string): SWRResponse<RAGEvalDataSetItem[]> => {
+ return useClientDataSWR<RAGEvalDataSetItem[]>(
[FETCH_DATASET_LIST_KEY, knowledgeBaseId],
() => ragEvalService.getDatasets(knowledgeBaseId),
{
fallbackData: [],
onSuccess: () => {
- if (!get().initDatasetList)
- set({ initDatasetList: true }, false, 'useFetchDatasets/init');
+ if (!this.#get().initDatasetList)
+ this.#set({ initDatasetList: true }, false, 'useFetchDatasets/init');
},
},
- ),
-});
+ );
+ };
+}
+
+export type RAGEvalDatasetAction = Pick<RAGEvalDatasetActionImpl, keyof RAGEvalDatasetActionImpl>;
diff --git a/src/store/library/slices/ragEval/actions/evaluation.ts b/src/store/library/slices/ragEval/actions/evaluation.ts
index 686d3a88990..ea1f9835023 100644
--- a/src/store/library/slices/ragEval/actions/evaluation.ts
+++ b/src/store/library/slices/ragEval/actions/evaluation.ts
@@ -1,62 +1,68 @@
import { type CreateNewEvalEvaluation, type RAGEvalDataSetItem } from '@lobechat/types';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { ragEvalService } from '@/services/ragEval';
import { type KnowledgeBaseStore } from '@/store/library/store';
+import { type StoreSetter } from '@/store/types';
const FETCH_EVALUATION_LIST_KEY = 'FETCH_EVALUATION_LIST_KEY';
-export interface RAGEvalEvaluationAction {
- checkEvaluationStatus: (id: string) => Promise<void>;
+type Setter = StoreSetter<KnowledgeBaseStore>;
+export const createRagEvalEvaluationSlice = (
+ set: Setter,
+ get: () => KnowledgeBaseStore,
+ _api?: unknown,
+) => new RAGEvalEvaluationActionImpl(set, get, _api);
- createNewEvaluation: (params: CreateNewEvalEvaluation) => Promise<void>;
- refreshEvaluationList: () => Promise<void>;
+export class RAGEvalEvaluationActionImpl {
+ readonly #get: () => KnowledgeBaseStore;
+ readonly #set: Setter;
- removeEvaluation: (id: string) => Promise<void>;
- runEvaluation: (id: string) => Promise<void>;
+ constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- useFetchEvaluationList: (knowledgeBaseId: string) => SWRResponse<RAGEvalDataSetItem[]>;
-}
-
-export const createRagEvalEvaluationSlice: StateCreator<
- KnowledgeBaseStore,
- [['zustand/devtools', never]],
- [],
- RAGEvalEvaluationAction
-> = (set, get) => ({
- checkEvaluationStatus: async (id) => {
+ checkEvaluationStatus = async (id: string): Promise<void> => {
await ragEvalService.checkEvaluationStatus(id);
- },
+ };
- createNewEvaluation: async (params) => {
+ createNewEvaluation = async (params: CreateNewEvalEvaluation): Promise<void> => {
await ragEvalService.createEvaluation(params);
- await get().refreshEvaluationList();
- },
- refreshEvaluationList: async () => {
+ await this.#get().refreshEvaluationList();
+ };
+
+ refreshEvaluationList = async (): Promise<void> => {
await mutate(FETCH_EVALUATION_LIST_KEY);
- },
+ };
- removeEvaluation: async (id) => {
+ removeEvaluation = async (id: string): Promise<void> => {
await ragEvalService.removeEvaluation(id);
- // await get().refreshEvaluationList();
- },
+ // await this.#get().refreshEvaluationList();
+ };
- runEvaluation: async (id) => {
+ runEvaluation = async (id: string): Promise<void> => {
await ragEvalService.startEvaluationTask(id);
- },
+ };
- useFetchEvaluationList: (knowledgeBaseId) =>
- useClientDataSWR<RAGEvalDataSetItem[]>(
+ useFetchEvaluationList = (knowledgeBaseId: string): SWRResponse<RAGEvalDataSetItem[]> => {
+ return useClientDataSWR<RAGEvalDataSetItem[]>(
[FETCH_EVALUATION_LIST_KEY, knowledgeBaseId],
() => ragEvalService.getEvaluationList(knowledgeBaseId),
{
fallbackData: [],
onSuccess: () => {
- if (!get().initDatasetList)
- set({ initDatasetList: true }, false, 'useFetchDatasets/init');
+ if (!this.#get().initDatasetList)
+ this.#set({ initDatasetList: true }, false, 'useFetchDatasets/init');
},
},
- ),
-});
+ );
+ };
+}
+
+export type RAGEvalEvaluationAction = Pick<
+ RAGEvalEvaluationActionImpl,
+ keyof RAGEvalEvaluationActionImpl
+>;
diff --git a/src/store/library/slices/ragEval/actions/index.ts b/src/store/library/slices/ragEval/actions/index.ts
index 18b315863c4..5e0ab0561e6 100644
--- a/src/store/library/slices/ragEval/actions/index.ts
+++ b/src/store/library/slices/ragEval/actions/index.ts
@@ -1,20 +1,24 @@
import { type StateCreator } from 'zustand/vanilla';
import { type KnowledgeBaseStore } from '@/store/library/store';
+import { flattenActions } from '@/store/utils/flattenActions';
import { type RAGEvalDatasetAction, createRagEvalDatasetSlice } from './dataset';
import { type RAGEvalEvaluationAction, createRagEvalEvaluationSlice } from './evaluation';
-export interface RAGEvalAction extends RAGEvalDatasetAction, RAGEvalEvaluationAction {
- // empty
-}
+export type RAGEvalAction = RAGEvalDatasetAction & RAGEvalEvaluationAction;
export const createRagEvalSlice: StateCreator<
KnowledgeBaseStore,
[['zustand/devtools', never]],
[],
RAGEvalAction
-> = (...params) => ({
- ...createRagEvalDatasetSlice(...params),
- ...createRagEvalEvaluationSlice(...params),
-});
+> = (
+ ...params: Parameters<
+ StateCreator<KnowledgeBaseStore, [['zustand/devtools', never]], [], RAGEvalAction>
+ >
+) =>
+ flattenActions<RAGEvalAction>([
+ createRagEvalDatasetSlice(...params),
+ createRagEvalEvaluationSlice(...params),
+ ]);
diff --git a/src/store/library/store.ts b/src/store/library/store.ts
index c8208709ed7..3665b7ce3d9 100644
--- a/src/store/library/store.ts
+++ b/src/store/library/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type KnowledgeBaseStoreState, initialState } from './initialState';
import { type KnowledgeBaseContentAction, createContentSlice } from './slices/content';
import { type KnowledgeBaseCrudAction, createCrudSlice } from './slices/crud';
@@ -11,20 +12,27 @@ import { type RAGEvalAction, createRagEvalSlice } from './slices/ragEval';
// =============== Aggregate createStoreFn ============ //
export interface KnowledgeBaseStore
- extends KnowledgeBaseStoreState,
+ extends
+ KnowledgeBaseStoreState,
KnowledgeBaseCrudAction,
KnowledgeBaseContentAction,
RAGEvalAction {
// empty
}
+type KnowledgeBaseStoreAction = KnowledgeBaseCrudAction &
+ KnowledgeBaseContentAction &
+ RAGEvalAction;
+
const createStore: StateCreator<KnowledgeBaseStore, [['zustand/devtools', never]]> = (
- ...parameters
+ ...parameters: Parameters<StateCreator<KnowledgeBaseStore, [['zustand/devtools', never]]>>
) => ({
...initialState,
- ...createCrudSlice(...parameters),
- ...createContentSlice(...parameters),
- ...createRagEvalSlice(...parameters),
+ ...flattenActions<KnowledgeBaseStoreAction>([
+ createCrudSlice(...parameters),
+ createContentSlice(...parameters),
+ createRagEvalSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/mention/action.ts b/src/store/mention/action.ts
index 1e8f28dcd8b..093fb123c2a 100644
--- a/src/store/mention/action.ts
+++ b/src/store/mention/action.ts
@@ -1,24 +1,23 @@
-import { type StateCreator } from 'zustand/vanilla';
+import { type StoreSetter } from '@/store/types';
-import { type MentionState, initialMentionState } from './initialState';
+import { type MentionStore } from './store';
-export interface MentionAction {
- addMentionedUser: (userId: string) => void;
- clearMentionedUsers: () => void;
- removeMentionedUser: (userId: string) => void;
- setMentionedUsers: (users: string[]) => void;
-}
+type Setter = StoreSetter<MentionStore>;
+export const createMentionSlice = (set: Setter, get: () => MentionStore, _api?: unknown) =>
+ new MentionActionImpl(set, get, _api);
+
+export class MentionActionImpl {
+ readonly #get: () => MentionStore;
+ readonly #set: Setter;
-export const createMentionSlice: StateCreator<
- MentionState,
- [['zustand/devtools', never]],
- [],
- MentionAction
-> = (set) => ({
- ...initialMentionState,
+ constructor(set: Setter, get: () => MentionStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- addMentionedUser: (userId: string) => {
- set(
+ addMentionedUser = (userId: string): void => {
+ this.#set(
(state) => ({
mentionedUsers: state.mentionedUsers.includes(userId)
? state.mentionedUsers
@@ -27,23 +26,25 @@ export const createMentionSlice: StateCreator<
false,
'addMentionedUser',
);
- },
+ };
- clearMentionedUsers: () => {
- set({ mentionedUsers: [] }, false, 'clearMentionedUsers');
- },
+ clearMentionedUsers = (): void => {
+ this.#set({ mentionedUsers: [] }, false, 'clearMentionedUsers');
+ };
- removeMentionedUser: (userId: string) => {
- set(
+ removeMentionedUser = (userId: string): void => {
+ this.#set(
(state) => ({
mentionedUsers: state.mentionedUsers.filter((id) => id !== userId),
}),
false,
'removeMentionedUser',
);
- },
+ };
+
+ setMentionedUsers = (users: string[]): void => {
+ this.#set({ mentionedUsers: users }, false, 'setMentionedUsers');
+ };
+}
- setMentionedUsers: (users: string[]) => {
- set({ mentionedUsers: users }, false, 'setMentionedUsers');
- },
-});
+export type MentionAction = Pick<MentionActionImpl, keyof MentionActionImpl>;
diff --git a/src/store/mention/store.ts b/src/store/mention/store.ts
index 7e02c997093..2589ee6067f 100644
--- a/src/store/mention/store.ts
+++ b/src/store/mention/store.ts
@@ -3,14 +3,17 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type MentionAction, createMentionSlice } from './action';
import { type MentionState, initialMentionState } from './initialState';
export type MentionStore = MentionState & MentionAction;
-const createStore: StateCreator<MentionStore, [['zustand/devtools', never]]> = (...parameters) => ({
+const createStore: StateCreator<MentionStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<MentionStore, [['zustand/devtools', never]]>>
+) => ({
...initialMentionState,
- ...createMentionSlice(...parameters),
+ ...flattenActions<MentionAction>([createMentionSlice(...parameters)]),
});
const devtools = createDevtools('mention');
diff --git a/src/store/notebook/action.ts b/src/store/notebook/action.ts
index 7adb88153eb..140fb3bdeab 100644
--- a/src/store/notebook/action.ts
+++ b/src/store/notebook/action.ts
@@ -3,11 +3,11 @@ import { type DocumentItem } from '@lobechat/database/schemas';
import { type NotebookDocument } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import { type SWRResponse, mutate } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWR } from '@/libs/swr';
import { notebookService } from '@/services/notebook';
import { useChatStore } from '@/store/chat';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type { NotebookStore } from './store';
@@ -35,33 +35,30 @@ interface UpdateDocumentParams {
title?: string;
}
-export interface NotebookAction {
- createDocument: (params: CreateDocumentParams) => Promise<DocumentItem>;
- deleteDocument: (id: string, topicId: string) => Promise<void>;
- refreshDocuments: (topicId: string) => Promise<void>;
- updateDocument: (
- params: UpdateDocumentParams,
- topicId: string,
- ) => Promise<DocumentItem | undefined>;
- useFetchDocuments: (topicId: string | undefined) => SWRResponse<NotebookDocument[]>;
-}
+type Setter = StoreSetter<NotebookStore>;
+export const createNotebookAction = (set: Setter, get: () => NotebookStore, _api?: unknown) =>
+ new NotebookActionImpl(set, get, _api);
+
+export class NotebookActionImpl {
+ readonly #get: () => NotebookStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => NotebookStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createNotebookAction: StateCreator<
- NotebookStore,
- [['zustand/devtools', never]],
- [],
- NotebookAction
-> = (set, get) => ({
- createDocument: async (params) => {
+ createDocument = async (params: CreateDocumentParams): Promise<DocumentItem> => {
const document = await notebookService.createDocument(params);
// Refresh the documents list
await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, params.topicId]);
return document;
- },
+ };
- deleteDocument: async (id, topicId) => {
+ deleteDocument = async (id: string, topicId: string): Promise<void> => {
// If the deleted document is currently open, close it
const portalDocumentId = useChatStore.getState().portalDocumentId;
if (portalDocumentId === id) {
@@ -73,22 +70,25 @@ export const createNotebookAction: StateCreator<
// Refresh the documents list
await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId]);
- },
+ };
- refreshDocuments: async (topicId) => {
+ refreshDocuments = async (topicId: string): Promise<void> => {
await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId]);
- },
+ };
- updateDocument: async (params, topicId) => {
+ updateDocument = async (
+ params: UpdateDocumentParams,
+ topicId: string,
+ ): Promise<DocumentItem | undefined> => {
const document = await notebookService.updateDocument(params);
// Refresh the documents list
await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId]);
return document;
- },
+ };
- useFetchDocuments: (topicId) => {
+ useFetchDocuments = (topicId: string | undefined): SWRResponse<NotebookDocument[]> => {
return useClientDataSWR<NotebookDocument[]>(
topicId ? [SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId] : null,
async () => {
@@ -102,14 +102,14 @@ export const createNotebookAction: StateCreator<
onSuccess: (documents) => {
if (!topicId) return;
- const currentDocuments = get().notebookMap[topicId];
+ const currentDocuments = this.#get().notebookMap[topicId];
// Skip update if data is the same
if (currentDocuments && isEqual(documents, currentDocuments)) return;
- set(
+ this.#set(
{
- notebookMap: { ...get().notebookMap, [topicId]: documents },
+ notebookMap: { ...this.#get().notebookMap, [topicId]: documents },
},
false,
n('useFetchDocuments(onSuccess)', { topicId }),
@@ -117,5 +117,7 @@ export const createNotebookAction: StateCreator<
},
},
);
- },
-});
+ };
+}
+
+export type NotebookAction = Pick<NotebookActionImpl, keyof NotebookActionImpl>;
diff --git a/src/store/notebook/store.ts b/src/store/notebook/store.ts
index 35edec2f4c7..310d2109175 100644
--- a/src/store/notebook/store.ts
+++ b/src/store/notebook/store.ts
@@ -3,16 +3,17 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type NotebookAction, createNotebookAction } from './action';
import { type NotebookState, initialNotebookState } from './initialState';
export type NotebookStore = NotebookState & NotebookAction;
const createStore: StateCreator<NotebookStore, [['zustand/devtools', never]]> = (
- ...parameters
+ ...parameters: Parameters<StateCreator<NotebookStore, [['zustand/devtools', never]]>>
) => ({
...initialNotebookState,
- ...createNotebookAction(...parameters),
+ ...flattenActions<NotebookAction>([createNotebookAction(...parameters)]),
});
const devtools = createDevtools('notebook');
diff --git a/src/store/page/slices/crud/action.ts b/src/store/page/slices/crud/action.ts
index 054c7226bd2..c4b31bd2ff6 100644
--- a/src/store/page/slices/crud/action.ts
+++ b/src/store/page/slices/crud/action.ts
@@ -1,8 +1,8 @@
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
+import { type StoreSetter } from '@/store/types';
import { DocumentSourceType, type LobeDocument } from '@/types/document';
import { standardizeIdentifier } from '@/utils/identifier';
import { setNamespace } from '@/utils/storeDebug';
@@ -21,75 +21,26 @@ export interface PageUpdateParams {
title?: string;
}
-export interface CrudAction {
- /**
- * Create a new page with optimistic update (for page explorer)
- */
- createNewPage: (title: string) => Promise<string>;
- /**
- * Create a new optimistic page immediately in documents array
- */
- createOptimisticPage: (title?: string) => string;
- /**
- * Create a new page with markdown content (not optimistic, waits for server response)
- */
- createPage: (params: {
- content?: string;
- knowledgeBaseId?: string;
- parentId?: string;
- title: string;
- }) => Promise<{ [key: string]: any; id: string }>;
- /**
- * Delete a page and update selection if needed
- */
- deletePage: (pageId: string) => Promise<void>;
- /**
- * Duplicate an existing page
- */
- duplicatePage: (pageId: string) => Promise<{ [key: string]: any; id: string }>;
- navigateToPage: (pageId: string | null) => void;
- /**
- * Remove a page (deletes from documents table)
- */
- removePage: (pageId: string) => Promise<void>;
- /**
- * Remove a temp page from documents array
- */
- removeTempPage: (tempId: string) => void;
- /**
- * Rename a page
- */
- renamePage: (pageId: string, title: string, emoji?: string) => Promise<void>;
- /**
- * Replace a temp page with real page data
- */
- replaceTempPageWithReal: (tempId: string, realPage: LobeDocument) => void;
- /**
- * Update page directly (no optimistic update)
- */
- updatePage: (pageId: string, updates: Partial<LobeDocument>) => Promise<void>;
- /**
- * Optimistically update page in documents array and queue for DB sync
- */
- updatePageOptimistically: (pageId: string, updates: PageUpdateParams) => Promise<void>;
- /**
- * SWR hook to fetch page detail with caching and auto-sync to store
- */
- useFetchPageDetail: (pageId: string | undefined) => SWRResponse<LobeDocument | null>;
-}
+type Setter = StoreSetter<PageStore>;
+export const createCrudSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>
+ new CrudActionImpl(set, get, _api);
+
+export class CrudActionImpl {
+ readonly #get: () => PageStore;
+ readonly #set: Setter;
-export const createCrudSlice: StateCreator<
- PageStore,
- [['zustand/devtools', never]],
- [],
- CrudAction
-> = (set, get) => ({
- createNewPage: async (title: string) => {
- const { createOptimisticPage, createPage, replaceTempPageWithReal } = get();
+ constructor(set: Setter, get: () => PageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ createNewPage = async (title: string): Promise<string> => {
+ const { createOptimisticPage, createPage, replaceTempPageWithReal } = this.#get();
// Create optimistic page immediately
const tempPageId = createOptimisticPage(title);
- set({ isCreatingNew: true, selectedPageId: tempPageId }, false, n('createNewPage/start'));
+ this.#set({ isCreatingNew: true, selectedPageId: tempPageId }, false, n('createNewPage/start'));
try {
// Create real page
@@ -117,22 +68,27 @@ export const createCrudSlice: StateCreator<
// Replace optimistic with real
replaceTempPageWithReal(tempPageId, realPage);
- set({ isCreatingNew: false, selectedPageId: newPage.id }, false, n('createNewPage/success'));
+ this.#set(
+ { isCreatingNew: false, selectedPageId: newPage.id },
+ false,
+ n('createNewPage/success'),
+ );
// Navigate to the new page
- get().navigateToPage(newPage.id);
+ this.#get().navigateToPage(newPage.id);
return newPage.id;
} catch (error) {
console.error('Failed to create page:', error);
- get().removeTempPage(tempPageId);
- set({ isCreatingNew: false, selectedPageId: null }, false, n('createNewPage/error'));
- get().navigate?.('/page');
+ this.#get().removeTempPage(tempPageId);
+ this.#set({ isCreatingNew: false, selectedPageId: null }, false, n('createNewPage/error'));
+ this.#get().navigate?.('/page');
throw error;
}
- },
- createOptimisticPage: (title = 'Untitled') => {
+ };
+
+ createOptimisticPage = (title: string = 'Untitled'): string => {
// Generate temporary ID with prefix to identify optimistic pages
const tempId = `temp-page-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
const now = new Date();
@@ -154,12 +110,22 @@ export const createCrudSlice: StateCreator<
};
// Add to documents array via internal dispatch
- get().internal_dispatchDocuments({ document: newPage, type: 'addDocument' });
+ this.#get().internal_dispatchDocuments({ document: newPage, type: 'addDocument' });
return tempId;
- },
-
- createPage: async ({ title, content = '', knowledgeBaseId, parentId }) => {
+ };
+
+ createPage = async ({
+ title,
+ content = '',
+ knowledgeBaseId,
+ parentId,
+ }: {
+ content?: string;
+ knowledgeBaseId?: string;
+ parentId?: string;
+ title: string;
+ }): Promise<{ [key: string]: any; id: string }> => {
const now = Date.now();
const newPage = await documentService.createDocument({
@@ -175,18 +141,18 @@ export const createCrudSlice: StateCreator<
});
return newPage;
- },
+ };
- deletePage: async (pageId: string) => {
- const { selectedPageId } = get();
+ deletePage = async (pageId: string): Promise<void> => {
+ const { selectedPageId } = this.#get();
if (selectedPageId === pageId) {
- set({ isCreatingNew: false, selectedPageId: null }, false, n('deletePage'));
- get().navigateToPage(null);
+ this.#set({ isCreatingNew: false, selectedPageId: null }, false, n('deletePage'));
+ this.#get().navigateToPage(null);
}
- },
+ };
- duplicatePage: async (pageId) => {
+ duplicatePage = async (pageId: string): Promise<{ [key: string]: any; id: string }> => {
// Fetch the source page
const sourcePage = await documentService.getDocumentById(pageId);
@@ -231,32 +197,32 @@ export const createCrudSlice: StateCreator<
updatedAt: newPage.updatedAt ? new Date(newPage.updatedAt) : new Date(),
};
- get().internal_dispatchDocuments({ document: editorPage, type: 'addDocument' });
+ this.#get().internal_dispatchDocuments({ document: editorPage, type: 'addDocument' });
return newPage;
- },
+ };
- navigateToPage: (pageId) => {
+ navigateToPage = (pageId: string | null): void => {
if (!pageId) {
- get().navigate?.('/page');
+ this.#get().navigate?.('/page');
} else {
- get().navigate?.(`/page/${standardizeIdentifier(pageId)}`);
+ this.#get().navigate?.(`/page/${standardizeIdentifier(pageId)}`);
}
- },
+ };
- removePage: async (pageId) => {
- const { documents, selectedPageId } = get();
+ removePage = async (pageId: string): Promise<void> => {
+ const { documents, selectedPageId } = this.#get();
// Store original documents for rollback
const originalDocuments = documents;
// Remove from documents array via internal dispatch (optimistic update)
- get().internal_dispatchDocuments({ id: pageId, type: 'removeDocument' });
+ this.#get().internal_dispatchDocuments({ id: pageId, type: 'removeDocument' });
// Clear selected page ID if the deleted page is currently selected
if (selectedPageId === pageId) {
- set({ selectedPageId: null }, false, n('removePage/clearSelection'));
- get().navigateToPage(null);
+ this.#set({ selectedPageId: null }, false, n('removePage/clearSelection'));
+ this.#get().navigateToPage(null);
}
try {
@@ -266,41 +232,44 @@ export const createCrudSlice: StateCreator<
console.error('Failed to delete page:', error);
// Restore documents on error
if (originalDocuments) {
- get().internal_dispatchDocuments({ documents: originalDocuments, type: 'setDocuments' });
+ this.#get().internal_dispatchDocuments({
+ documents: originalDocuments,
+ type: 'setDocuments',
+ });
}
if (selectedPageId === pageId) {
- set({ selectedPageId: pageId }, false, n('removePage/restoreSelection'));
- get().navigateToPage(pageId);
+ this.#set({ selectedPageId: pageId }, false, n('removePage/restoreSelection'));
+ this.#get().navigateToPage(pageId);
}
throw error;
}
- },
+ };
- removeTempPage: (tempId) => {
- get().internal_dispatchDocuments({ id: tempId, type: 'removeDocument' });
- },
+ removeTempPage = (tempId: string): void => {
+ this.#get().internal_dispatchDocuments({ id: tempId, type: 'removeDocument' });
+ };
- renamePage: async (pageId: string, title: string, emoji?: string) => {
- const { updatePageOptimistically } = get();
+ renamePage = async (pageId: string, title: string, emoji?: string): Promise<void> => {
+ const { updatePageOptimistically } = this.#get();
try {
await updatePageOptimistically(pageId, { emoji, title });
} catch (error) {
console.error('Failed to rename page:', error);
} finally {
- set({ renamingPageId: null }, false, n('renamePage'));
+ this.#set({ renamingPageId: null }, false, n('renamePage'));
}
- },
+ };
- replaceTempPageWithReal: (tempId, realPage) => {
- get().internal_dispatchDocuments({
+ replaceTempPageWithReal = (tempId: string, realPage: LobeDocument): void => {
+ this.#get().internal_dispatchDocuments({
document: realPage,
oldId: tempId,
type: 'replaceDocument',
});
- },
+ };
- updatePage: async (id, updates) => {
+ updatePage = async (id: string, updates: Partial<LobeDocument>): Promise<void> => {
await documentService.updateDocument({
content: updates.content ?? undefined,
editorData: updates.editorData
@@ -313,11 +282,11 @@ export const createCrudSlice: StateCreator<
parentId: updates.parentId !== undefined ? updates.parentId : undefined,
title: updates.title,
});
- await get().refreshDocuments();
- },
+ await this.#get().refreshDocuments();
+ };
- updatePageOptimistically: async (pageId, updates) => {
- const { documents } = get();
+ updatePageOptimistically = async (pageId: string, updates: PageUpdateParams): Promise<void> => {
+ const { documents } = this.#get();
// Find the page in documents array
const existingPage = documents?.find((doc) => doc.id === pageId);
@@ -346,7 +315,11 @@ export const createCrudSlice: StateCreator<
};
// Update documents array via internal dispatch (optimistic)
- get().internal_dispatchDocuments({ document: updatedPage, id: pageId, type: 'updateDocument' });
+ this.#get().internal_dispatchDocuments({
+ document: updatedPage,
+ id: pageId,
+ type: 'updateDocument',
+ });
// Queue background sync to DB
try {
@@ -363,19 +336,19 @@ export const createCrudSlice: StateCreator<
});
// After successful sync, refresh document list to get server state
- await get().refreshDocuments();
+ await this.#get().refreshDocuments();
} catch (error) {
console.error('[updatePageOptimistically] Failed to sync to DB:', error);
// On error, revert by restoring original page
- get().internal_dispatchDocuments({
+ this.#get().internal_dispatchDocuments({
document: existingPage,
id: pageId,
type: 'updateDocument',
});
}
- },
+ };
- useFetchPageDetail: (pageId) => {
+ useFetchPageDetail = (pageId: string | undefined): SWRResponse<LobeDocument | null> => {
const swrKey = pageId ? ['pageDetail', pageId] : null;
return useClientDataSWRWithSync<LobeDocument | null>(
@@ -417,13 +390,19 @@ export const createCrudSlice: StateCreator<
if (!document || !pageId) return;
// Auto-sync to documents array via internal dispatch
- const { documents } = get();
+ const { documents } = this.#get();
if (documents?.some((doc) => doc.id === pageId)) {
- get().internal_dispatchDocuments({ document, id: pageId, type: 'updateDocument' });
+ this.#get().internal_dispatchDocuments({
+ document,
+ id: pageId,
+ type: 'updateDocument',
+ });
}
},
revalidateOnFocus: true,
},
);
- },
-});
+ };
+}
+
+export type CrudAction = Pick<CrudActionImpl, keyof CrudActionImpl>;
diff --git a/src/store/page/slices/internal/action.ts b/src/store/page/slices/internal/action.ts
index 1cde12b6013..86d2fd47f0d 100644
--- a/src/store/page/slices/internal/action.ts
+++ b/src/store/page/slices/internal/action.ts
@@ -1,6 +1,6 @@
import isEqual from 'fast-deep-equal';
-import { type StateCreator } from 'zustand/vanilla';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type PageStore } from '../../store';
@@ -8,25 +8,32 @@ import { type DocumentsDispatch, documentsReducer } from './reducer';
const n = setNamespace('page/internal');
-export interface InternalAction {
- /**
- * Dispatch action to update documents array
- */
- internal_dispatchDocuments: (payload: DocumentsDispatch, action?: string) => void;
-}
+type Setter = StoreSetter<PageStore>;
+export const createInternalSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>
+ new InternalActionImpl(set, get, _api);
+
+export class InternalActionImpl {
+ readonly #get: () => PageStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => PageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createInternalSlice: StateCreator<
- PageStore,
- [['zustand/devtools', never]],
- [],
- InternalAction
-> = (set, get) => ({
- internal_dispatchDocuments: (payload, action) => {
- const { documents } = get();
+ internal_dispatchDocuments = (payload: DocumentsDispatch, action?: string): void => {
+ const { documents } = this.#get();
const nextDocuments = documentsReducer(documents, payload);
if (isEqual(documents, nextDocuments)) return;
- set({ documents: nextDocuments }, false, action ?? n(`dispatchDocuments/${payload.type}`));
- },
-});
+ this.#set(
+ { documents: nextDocuments },
+ false,
+ action ?? n(`dispatchDocuments/${payload.type}`),
+ );
+ };
+}
+
+export type InternalAction = Pick<InternalActionImpl, keyof InternalActionImpl>;
diff --git a/src/store/page/slices/internal/reducer.ts b/src/store/page/slices/internal/reducer.ts
index edba24f5dad..88bc35e5730 100644
--- a/src/store/page/slices/internal/reducer.ts
+++ b/src/store/page/slices/internal/reducer.ts
@@ -4,37 +4,37 @@ import { type LobeDocument } from '@/types/document';
// ============ Action Types ============
-interface AddDocumentAction {
+type AddDocumentAction = {
document: LobeDocument;
type: 'addDocument';
-}
+};
-interface RemoveDocumentAction {
+type RemoveDocumentAction = {
id: string;
type: 'removeDocument';
-}
+};
-interface UpdateDocumentAction {
+type UpdateDocumentAction = {
document: LobeDocument;
id: string;
type: 'updateDocument';
-}
+};
-interface ReplaceDocumentAction {
+type ReplaceDocumentAction = {
document: LobeDocument;
oldId: string;
type: 'replaceDocument';
-}
+};
-interface SetDocumentsAction {
+type SetDocumentsAction = {
documents: LobeDocument[];
type: 'setDocuments';
-}
+};
-interface AppendDocumentsAction {
+type AppendDocumentsAction = {
documents: LobeDocument[];
type: 'appendDocuments';
-}
+};
export type DocumentsDispatch =
| AddDocumentAction
diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.ts
index 867be0bd711..f3d89f0bad3 100644
--- a/src/store/page/slices/list/action.ts
+++ b/src/store/page/slices/list/action.ts
@@ -1,9 +1,9 @@
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
import { useGlobalStore } from '@/store/global';
+import { type StoreSetter } from '@/store/types';
import { type LobeDocument } from '@/types/document';
import { setNamespace } from '@/utils/storeDebug';
@@ -24,40 +24,21 @@ const isAllowedPage = (page: { fileType: string; sourceType: string }) => {
);
};
-export interface ListAction {
- /**
- * Fetch documents from the server with pagination
- */
- fetchDocuments: () => Promise<void>;
- /**
- * Load more documents (next page)
- */
- loadMoreDocuments: () => Promise<void>;
- /**
- * Refresh document list (re-fetch from server)
- */
- refreshDocuments: () => Promise<void>;
- /**
- * Set search keywords
- */
- setSearchKeywords: (keywords: string) => void;
- /**
- * Toggle filter to show only pages not in any library
- */
- setShowOnlyPagesNotInLibrary: (show: boolean) => void;
- /**
- * SWR hook to fetch documents list with caching and auto-sync to store
- */
- useFetchDocuments: () => SWRResponse<LobeDocument[]>;
-}
+type Setter = StoreSetter<PageStore>;
+export const createListSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>
+ new ListActionImpl(set, get, _api);
+
+export class ListActionImpl {
+ readonly #get: () => PageStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => PageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createListSlice: StateCreator<
- PageStore,
- [['zustand/devtools', never]],
- [],
- ListAction
-> = (set, get) => ({
- fetchDocuments: async () => {
+ fetchDocuments = async (): Promise<void> => {
try {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
const queryFilters: PageQueryFilter = {
@@ -79,9 +60,9 @@ export const createListSlice: StateCreator<
const hasMore = result.items.length >= pageSize;
// Use internal dispatch to set documents
- get().internal_dispatchDocuments({ documents, type: 'setDocuments' });
+ this.#get().internal_dispatchDocuments({ documents, type: 'setDocuments' });
- set(
+ this.#set(
{
currentPage: 0,
documentsTotal: result.total,
@@ -95,16 +76,17 @@ export const createListSlice: StateCreator<
console.error('Failed to fetch documents:', error);
throw error;
}
- },
+ };
- loadMoreDocuments: async () => {
- const { currentPage, isLoadingMoreDocuments, hasMoreDocuments, queryFilter, documents } = get();
+ loadMoreDocuments = async (): Promise<void> => {
+ const { currentPage, isLoadingMoreDocuments, hasMoreDocuments, queryFilter, documents } =
+ this.#get();
if (isLoadingMoreDocuments || !hasMoreDocuments || !documents) return;
const nextPage = currentPage + 1;
- set({ isLoadingMoreDocuments: true }, false, n('loadMoreDocuments/start'));
+ this.#set({ isLoadingMoreDocuments: true }, false, n('loadMoreDocuments/start'));
try {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
@@ -122,9 +104,9 @@ export const createListSlice: StateCreator<
const hasMore = result.items.length >= pageSize;
// Use internal dispatch to append documents
- get().internal_dispatchDocuments({ documents: newDocuments, type: 'appendDocuments' });
+ this.#get().internal_dispatchDocuments({ documents: newDocuments, type: 'appendDocuments' });
- set(
+ this.#set(
{
currentPage: nextPage,
documentsTotal: result.total,
@@ -136,23 +118,23 @@ export const createListSlice: StateCreator<
);
} catch (error) {
console.error('Failed to load more documents:', error);
- set({ isLoadingMoreDocuments: false }, false, n('loadMoreDocuments/error'));
+ this.#set({ isLoadingMoreDocuments: false }, false, n('loadMoreDocuments/error'));
}
- },
+ };
- refreshDocuments: async () => {
- await get().fetchDocuments();
- },
+ refreshDocuments = async (): Promise<void> => {
+ await this.#get().fetchDocuments();
+ };
- setSearchKeywords: (keywords: string) => {
- set({ searchKeywords: keywords }, false, n('setSearchKeywords'));
- },
+ setSearchKeywords = (keywords: string): void => {
+ this.#set({ searchKeywords: keywords }, false, n('setSearchKeywords'));
+ };
- setShowOnlyPagesNotInLibrary: (show: boolean) => {
- set({ showOnlyPagesNotInLibrary: show }, false, n('setShowOnlyPagesNotInLibrary'));
- },
+ setShowOnlyPagesNotInLibrary = (show: boolean): void => {
+ this.#set({ showOnlyPagesNotInLibrary: show }, false, n('setShowOnlyPagesNotInLibrary'));
+ };
- useFetchDocuments: () => {
+ useFetchDocuments = (): SWRResponse<LobeDocument[]> => {
return useClientDataSWRWithSync<LobeDocument[]>(
['pageDocuments'],
async () => {
@@ -183,9 +165,9 @@ export const createListSlice: StateCreator<
const hasMore = documents.length >= pageSize;
// Use internal dispatch to set documents
- get().internal_dispatchDocuments({ documents, type: 'setDocuments' });
+ this.#get().internal_dispatchDocuments({ documents, type: 'setDocuments' });
- set(
+ this.#set(
{
currentPage: 0,
documentsTotal: documents.length,
@@ -202,5 +184,7 @@ export const createListSlice: StateCreator<
revalidateOnFocus: true,
},
);
- },
-});
+ };
+}
+
+export type ListAction = Pick<ListActionImpl, keyof ListActionImpl>;
diff --git a/src/store/page/slices/selection/action.ts b/src/store/page/slices/selection/action.ts
index 59a04d798c1..be3ac130479 100644
--- a/src/store/page/slices/selection/action.ts
+++ b/src/store/page/slices/selection/action.ts
@@ -1,67 +1,53 @@
-import { type StateCreator } from 'zustand/vanilla';
-
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type PageStore } from '../../store';
const n = setNamespace('page/selection');
-export interface SelectionAction {
- /**
- * Close all pages drawer
- */
- closeAllPagesDrawer: () => void;
- /**
- * Open all pages drawer
- */
- openAllPagesDrawer: () => void;
- /**
- * Select a page (updates URL and state)
- */
- selectPage: (pageId: string) => void;
- /**
- * Set the ID of the page being renamed
- */
- setRenamingPageId: (pageId: string | null) => void;
- /**
- * Set selected page ID
- */
- setSelectedPageId: (pageId: string | null, shouldNavigate?: boolean) => void;
-}
+type Setter = StoreSetter<PageStore>;
+export const createSelectionSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>
+ new SelectionActionImpl(set, get, _api);
+
+export class SelectionActionImpl {
+ readonly #get: () => PageStore;
+ readonly #set: Setter;
-export const createSelectionSlice: StateCreator<
- PageStore,
- [['zustand/devtools', never]],
- [],
- SelectionAction
-> = (set, get) => ({
- closeAllPagesDrawer: () => {
- set({ allPagesDrawerOpen: false }, false, n('closeAllPagesDrawer'));
- },
+ constructor(set: Setter, get: () => PageStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- openAllPagesDrawer: () => {
- set({ allPagesDrawerOpen: true }, false, n('openAllPagesDrawer'));
- },
+ closeAllPagesDrawer = (): void => {
+ this.#set({ allPagesDrawerOpen: false }, false, n('closeAllPagesDrawer'));
+ };
- selectPage: (pageId: string) => {
- const { selectedPageId } = get();
+ openAllPagesDrawer = (): void => {
+ this.#set({ allPagesDrawerOpen: true }, false, n('openAllPagesDrawer'));
+ };
+
+ selectPage = (pageId: string): void => {
+ const { selectedPageId } = this.#get();
// Don't allow deselecting the current page
if (selectedPageId === pageId) return;
// Select and navigate
- set({ isCreatingNew: false, selectedPageId: pageId }, false, n('selectPage'));
- get().navigateToPage(pageId);
- },
+ this.#set({ isCreatingNew: false, selectedPageId: pageId }, false, n('selectPage'));
+ this.#get().navigateToPage(pageId);
+ };
- setRenamingPageId: (pageId: string | null) => {
- set({ renamingPageId: pageId }, false, n('setRenamingPageId'));
- },
+ setRenamingPageId = (pageId: string | null): void => {
+ this.#set({ renamingPageId: pageId }, false, n('setRenamingPageId'));
+ };
- setSelectedPageId: (pageId: string | null, shouldNavigate = true) => {
- set({ selectedPageId: pageId }, false, n('setSelectedPageId'));
+ setSelectedPageId = (pageId: string | null, shouldNavigate: boolean = true): void => {
+ this.#set({ selectedPageId: pageId }, false, n('setSelectedPageId'));
if (shouldNavigate) {
- get().navigateToPage(pageId);
+ this.#get().navigateToPage(pageId);
}
- },
-});
+ };
+}
+
+export type SelectionAction = Pick<SelectionActionImpl, keyof SelectionActionImpl>;
diff --git a/src/store/page/store.ts b/src/store/page/store.ts
index 943f92258ab..6440ca1b119 100644
--- a/src/store/page/store.ts
+++ b/src/store/page/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type PageState, initialState } from './initialState';
import { type CrudAction, createCrudSlice } from './slices/crud';
import { type InternalAction, createInternalSlice } from './slices/internal';
@@ -13,12 +14,18 @@ import { type SelectionAction, createSelectionSlice } from './slices/selection';
export type PageStore = PageState & InternalAction & ListAction & SelectionAction & CrudAction;
-const createStore: StateCreator<PageStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type PageStoreAction = InternalAction & ListAction & SelectionAction & CrudAction;
+
+const createStore: StateCreator<PageStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<PageStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createInternalSlice(...parameters),
- ...createListSlice(...parameters),
- ...createSelectionSlice(...parameters),
- ...createCrudSlice(...parameters),
+ ...flattenActions<PageStoreAction>([
+ createInternalSlice(...parameters),
+ createListSlice(...parameters),
+ createSelectionSlice(...parameters),
+ createCrudSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/serverConfig/action.ts b/src/store/serverConfig/action.ts
index 792010f6530..76ee99888c6 100644
--- a/src/store/serverConfig/action.ts
+++ b/src/store/serverConfig/action.ts
@@ -1,30 +1,38 @@
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useOnlyFetchOnceSWR } from '@/libs/swr';
import { globalService } from '@/services/global';
+import { type StoreSetter } from '@/store/types';
import { type GlobalRuntimeConfig } from '@/types/serverConfig';
import type { ServerConfigStore } from './store';
const FETCH_SERVER_CONFIG_KEY = 'FETCH_SERVER_CONFIG';
-export interface ServerConfigAction {
- useInitServerConfig: () => SWRResponse<GlobalRuntimeConfig>;
-}
-export const createServerConfigSlice: StateCreator<
- ServerConfigStore,
- [['zustand/devtools', never]],
- [],
- ServerConfigAction
-> = (set) => ({
- useInitServerConfig: () => {
+type Setter = StoreSetter<ServerConfigStore>;
+export const createServerConfigSlice = (
+ set: Setter,
+ get: () => ServerConfigStore,
+ _api?: unknown,
+) => new ServerConfigActionImpl(set, get, _api);
+
+export class ServerConfigActionImpl {
+ readonly #get: () => ServerConfigStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ServerConfigStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ useInitServerConfig = (): SWRResponse<GlobalRuntimeConfig> => {
return useOnlyFetchOnceSWR<GlobalRuntimeConfig>(
FETCH_SERVER_CONFIG_KEY,
() => globalService.getGlobalConfig(),
{
onSuccess: (data) => {
- set(
+ this.#set(
{
featureFlags: data.serverFeatureFlags,
serverConfig: data.serverConfig,
@@ -36,5 +44,7 @@ export const createServerConfigSlice: StateCreator<
},
},
);
- },
-});
+ };
+}
+
+export type ServerConfigAction = Pick<ServerConfigActionImpl, keyof ServerConfigActionImpl>;
diff --git a/src/store/serverConfig/store.ts b/src/store/serverConfig/store.ts
index fe0e247c4ce..dd7113b0584 100644
--- a/src/store/serverConfig/store.ts
+++ b/src/store/serverConfig/store.ts
@@ -14,6 +14,7 @@ import { createDevtools } from '@/store/middleware/createDevtools';
import { type GlobalServerConfig } from '@/types/serverConfig';
import { merge } from '@/utils/merge';
+import { flattenActions } from '../utils/flattenActions';
import { type ServerConfigAction, createServerConfigSlice } from './action';
interface ServerConfigState {
@@ -35,15 +36,17 @@ const initialState: ServerConfigState = {
export interface ServerConfigStore extends ServerConfigState, ServerConfigAction {}
+type ServerConfigStoreAction = ServerConfigAction;
+
type CreateStore = (
initState: Partial<ServerConfigStore>,
) => StateCreator<ServerConfigStore, [['zustand/devtools', never]]>;
const createStore: CreateStore =
- (runtimeState) =>
+ (runtimeState: any) =>
(...params) => ({
...merge(initialState, runtimeState),
- ...createServerConfigSlice(...params),
+ ...flattenActions<ServerConfigStoreAction>([createServerConfigSlice(...params)]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/session/slices/homeInput/action.ts b/src/store/session/slices/homeInput/action.ts
index 903d907f92d..231855f8c26 100644
--- a/src/store/session/slices/homeInput/action.ts
+++ b/src/store/session/slices/homeInput/action.ts
@@ -1,40 +1,38 @@
-import type { StateCreator } from 'zustand/vanilla';
-
import { documentService } from '@/services/document';
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import type { SessionStore } from '@/store/session/store';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import type { StarterMode } from './initialState';
const n = setNamespace('homeInput');
-export interface HomeInputAction {
- clearInputMode: () => void;
- sendAsAgent: (message: string) => Promise<string>;
- sendAsImage: () => void;
- sendAsResearch: (message: string) => Promise<void>;
- sendAsWrite: (message: string) => Promise<string>;
- setInputActiveMode: (mode: StarterMode) => void;
-}
+type Setter = StoreSetter<SessionStore>;
+export const createHomeInputSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>
+ new HomeInputActionImpl(set, get, _api);
+
+export class HomeInputActionImpl {
+ readonly #get: () => SessionStore;
+ readonly #set: Setter;
-export const createHomeInputSlice: StateCreator<
- SessionStore,
- [['zustand/devtools', never]],
- [],
- HomeInputAction
-> = (set, get) => ({
- clearInputMode: () => {
- set({ inputActiveMode: null }, false, n('clearInputMode'));
- },
+ constructor(set: Setter, get: () => SessionStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
- sendAsAgent: async (message) => {
- set({ homeInputLoading: true }, false, n('sendAsAgent/start'));
+ clearInputMode = (): void => {
+ this.#set({ inputActiveMode: null }, false, n('clearInputMode'));
+ };
+
+ sendAsAgent = async (message: string): Promise<string> => {
+ this.#set({ homeInputLoading: true }, false, n('sendAsAgent/start'));
try {
// 1. Create new Agent using existing createSession action
- const newAgentId = await get().createSession(
+ const newAgentId = await this.#get().createSession(
{
config: { systemRole: message },
meta: { title: message?.slice(0, 50) || 'New Agent' },
@@ -56,15 +54,15 @@ export const createHomeInputSlice: StateCreator<
});
// 4. Clear mode
- set({ inputActiveMode: null }, false, n('sendAsAgent/clearMode'));
+ this.#set({ inputActiveMode: null }, false, n('sendAsAgent/clearMode'));
return newAgentId;
} finally {
- set({ homeInputLoading: false }, false, n('sendAsAgent/end'));
+ this.#set({ homeInputLoading: false }, false, n('sendAsAgent/end'));
}
- },
+ };
- sendAsImage: () => {
+ sendAsImage = (): void => {
// Navigate to /image page
const navigate = useGlobalStore.getState().navigate;
if (navigate) {
@@ -72,19 +70,19 @@ export const createHomeInputSlice: StateCreator<
}
// Clear mode
- set({ inputActiveMode: null }, false, n('sendAsImage'));
- },
+ this.#set({ inputActiveMode: null }, false, n('sendAsImage'));
+ };
- sendAsResearch: async (message) => {
+ sendAsResearch = async (message: string): Promise<void> => {
// TODO: Implement DeepResearch mode
console.log('sendAsResearch:', message);
// Clear mode
- set({ inputActiveMode: null }, false, n('sendAsResearch'));
- },
+ this.#set({ inputActiveMode: null }, false, n('sendAsResearch'));
+ };
- sendAsWrite: async (message) => {
- set({ homeInputLoading: true }, false, n('sendAsWrite/start'));
+ sendAsWrite = async (message: string): Promise<string> => {
+ this.#set({ homeInputLoading: true }, false, n('sendAsWrite/start'));
try {
// 1. Create new Document
@@ -110,15 +108,17 @@ export const createHomeInputSlice: StateCreator<
});
// 4. Clear mode
- set({ inputActiveMode: null }, false, n('sendAsWrite/clearMode'));
+ this.#set({ inputActiveMode: null }, false, n('sendAsWrite/clearMode'));
return newDoc.id;
} finally {
- set({ homeInputLoading: false }, false, n('sendAsWrite/end'));
+ this.#set({ homeInputLoading: false }, false, n('sendAsWrite/end'));
}
- },
+ };
+
+ setInputActiveMode = (mode: StarterMode): void => {
+ this.#set({ inputActiveMode: mode }, false, n('setInputActiveMode', mode));
+ };
+}
- setInputActiveMode: (mode) => {
- set({ inputActiveMode: mode }, false, n('setInputActiveMode', mode));
- },
-});
+export type HomeInputAction = Pick<HomeInputActionImpl, keyof HomeInputActionImpl>;
diff --git a/src/store/session/slices/recent/action.ts b/src/store/session/slices/recent/action.ts
index cfce538b054..30309fb8dbf 100644
--- a/src/store/session/slices/recent/action.ts
+++ b/src/store/session/slices/recent/action.ts
@@ -1,10 +1,10 @@
import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWR } from '@/libs/swr';
import { fileService } from '@/services/file';
import { topicService } from '@/services/topic';
+import { type StoreSetter } from '@/store/types';
import { type FileListItem } from '@/types/files';
import { type RecentTopic } from '@/types/topic';
import { setNamespace } from '@/utils/storeDebug';
@@ -17,69 +17,77 @@ const FETCH_RECENT_TOPICS_KEY = 'fetchRecentTopics';
const FETCH_RECENT_RESOURCES_KEY = 'fetchRecentResources';
const FETCH_RECENT_PAGES_KEY = 'fetchRecentPages';
-export interface RecentAction {
- useFetchRecentPages: (isLogin: boolean | undefined) => SWRResponse<any[]>;
- useFetchRecentResources: (isLogin: boolean | undefined) => SWRResponse<FileListItem[]>;
- useFetchRecentTopics: (isLogin: boolean | undefined) => SWRResponse<RecentTopic[]>;
-}
+type Setter = StoreSetter<SessionStore>;
+export const createRecentSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>
+ new RecentActionImpl(set, get, _api);
+
+export class RecentActionImpl {
+ readonly #get: () => SessionStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => SessionStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createRecentSlice: StateCreator<
- SessionStore,
- [['zustand/devtools', never]],
- [],
- RecentAction
-> = (set, get) => ({
- useFetchRecentPages: (isLogin) =>
- useClientDataSWR<any[]>(
+ useFetchRecentPages = (isLogin: boolean | undefined): SWRResponse<any[]> => {
+ return useClientDataSWR<any[]>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true ? [FETCH_RECENT_PAGES_KEY, isLogin] : null,
async () => fileService.getRecentPages(12),
{
onSuccess: (data) => {
- if (get().isRecentPagesInit && isEqual(get().recentPages, data)) return;
+ if (this.#get().isRecentPagesInit && isEqual(this.#get().recentPages, data)) return;
- set(
+ this.#set(
{ isRecentPagesInit: true, recentPages: data },
false,
n('useFetchRecentPages/onSuccess'),
);
},
},
- ),
+ );
+ };
- useFetchRecentResources: (isLogin) =>
- useClientDataSWR<FileListItem[]>(
+ useFetchRecentResources = (isLogin: boolean | undefined): SWRResponse<FileListItem[]> => {
+ return useClientDataSWR<FileListItem[]>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true ? [FETCH_RECENT_RESOURCES_KEY, isLogin] : null,
async () => fileService.getRecentFiles(12),
{
onSuccess: (data) => {
- if (get().isRecentResourcesInit && isEqual(get().recentResources, data)) return;
+ if (this.#get().isRecentResourcesInit && isEqual(this.#get().recentResources, data))
+ return;
- set(
+ this.#set(
{ isRecentResourcesInit: true, recentResources: data },
false,
n('useFetchRecentResources/onSuccess'),
);
},
},
- ),
+ );
+ };
- useFetchRecentTopics: (isLogin) =>
- useClientDataSWR<RecentTopic[]>(
+ useFetchRecentTopics = (isLogin: boolean | undefined): SWRResponse<RecentTopic[]> => {
+ return useClientDataSWR<RecentTopic[]>(
// Only fetch when login status is explicitly true (not null/undefined)
isLogin === true ? [FETCH_RECENT_TOPICS_KEY, isLogin] : null,
async () => topicService.getRecentTopics(12),
{
onSuccess: (data) => {
- if (get().isRecentTopicsInit && isEqual(get().recentTopics, data)) return;
+ if (this.#get().isRecentTopicsInit && isEqual(this.#get().recentTopics, data)) return;
- set(
+ this.#set(
{ isRecentTopicsInit: true, recentTopics: data },
false,
n('useFetchRecentTopics/onSuccess'),
);
},
},
- ),
-});
+ );
+ };
+}
+
+export type RecentAction = Pick<RecentActionImpl, keyof RecentActionImpl>;
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index c84a2ced746..22f2f2bc15b 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -3,7 +3,6 @@ import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
import useSWR, { type SWRResponse } from 'swr';
import type { PartialDeep } from 'type-fest';
-import { type StateCreator } from 'zustand/vanilla';
import { message } from '@/components/AntdStaticMethods';
import { DEFAULT_AGENT_LOBE_SESSION, INBOX_SESSION_ID } from '@/const/session';
@@ -12,6 +11,7 @@ import { chatGroupService } from '@/services/chatGroup';
import { sessionService } from '@/services/session';
import { getChatGroupStoreState } from '@/store/agentGroup';
import { type SessionStore } from '@/store/session';
+import { type StoreSetter } from '@/store/types';
import { getUserStoreState, useUserStore } from '@/store/user';
import { settingsSelectors, userProfileSelectors } from '@/store/user/selectors';
import {
@@ -35,89 +35,35 @@ const FETCH_SESSIONS_KEY = 'fetchSessions';
const SEARCH_SESSIONS_KEY = 'searchSessions';
/* eslint-disable typescript-sort-keys/interface */
-export interface SessionAction {
- /**
- * switch the session
- */
- switchSession: (sessionId: string) => void;
- /**
- * reset sessions to default
- */
- clearSessions: () => Promise<void>;
- closeAllAgentsDrawer: () => void;
- /**
- * create a new session
- * @param agent
- * @returns sessionId
- */
- createSession: (
- session?: PartialDeep<LobeAgentSession>,
- isSwitchSession?: boolean,
- ) => Promise<string>;
-
- duplicateSession: (id: string) => Promise<void>;
- openAllAgentsDrawer: () => void;
- triggerSessionUpdate: (id: string) => Promise<void>;
- updateSessionGroupId: (sessionId: string, groupId: string) => Promise<void>;
-
- /**
- * Pins or unpins a session.
- */
- pinSession: (id: string, pinned: boolean) => Promise<void>;
- /**
- * re-fetch the data
- */
- refreshSessions: () => Promise<void>;
- /**
- * remove session
- * @param id - sessionId
- */
- removeSession: (id: string) => Promise<void>;
-
- /**
- * Set the agent panel pinned state
- */
- setAgentPinned: (pinned: boolean | ((prev: boolean) => boolean)) => void;
- /**
- * Toggle the agent panel pinned state
- */
- toggleAgentPinned: () => void;
-
- updateSearchKeywords: (keywords: string) => void;
-
- useFetchSessions: (
- enabled: boolean,
- isLogin: boolean | undefined,
- ) => SWRResponse<ChatSessionList>;
- useSearchSessions: (keyword?: string) => SWRResponse<any>;
-
- internal_dispatchSessions: (payload: SessionDispatch) => void;
- internal_updateSession: (id: string, data: Partial<UpdateSessionParams>) => Promise<void>;
- internal_processSessions: (
- sessions: LobeSessions,
- customGroups: LobeSessionGroups,
- actions?: string,
- ) => void;
- /* eslint-enable */
-}
-export const createSessionSlice: StateCreator<
- SessionStore,
- [['zustand/devtools', never]],
- [],
- SessionAction
-> = (set, get) => ({
- clearSessions: async () => {
+type Setter = StoreSetter<SessionStore>;
+export const createSessionSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>
+ new SessionActionImpl(set, get, _api);
+
+export class SessionActionImpl {
+ readonly #get: () => SessionStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => SessionStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ clearSessions = async (): Promise<void> => {
await sessionService.removeAllSessions();
- await get().refreshSessions();
- },
+ await this.#get().refreshSessions();
+ };
- closeAllAgentsDrawer: () => {
- set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));
- },
+ closeAllAgentsDrawer = (): void => {
+ this.#set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));
+ };
- createSession: async (agent, isSwitchSession = true) => {
- const { switchSession, refreshSessions } = get();
+ createSession = async (
+ agent?: PartialDeep<LobeAgentSession>,
+ isSwitchSession: boolean = true,
+ ): Promise<string> => {
+ const { switchSession, refreshSessions } = this.#get();
// merge the defaultAgent in settings
const defaultAgent = merge(
@@ -151,11 +97,11 @@ export const createSessionSlice: StateCreator<
if (isSwitchSession) switchSession(id);
return id;
- },
+ };
- duplicateSession: async (id) => {
- const { switchSession, refreshSessions } = get();
- const session = sessionSelectors.getSessionById(id)(get());
+ duplicateSession = async (id: string): Promise<void> => {
+ const { switchSession, refreshSessions } = this.#get();
+ const session = sessionSelectors.getSessionById(id)(this.#get());
if (!session) return;
const title = sessionMetaSelectors.getTitle(session.meta);
@@ -184,73 +130,78 @@ export const createSessionSlice: StateCreator<
message.success(t('duplicateSession.success', { ns: 'chat' }));
switchSession(newId);
- },
-
- openAllAgentsDrawer: () => {
- set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));
- },
- pinSession: async (id, pinned) => {
- await get().internal_updateSession(id, { pinned });
- },
- removeSession: async (sessionId) => {
+ };
+
+ openAllAgentsDrawer = (): void => {
+ this.#set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));
+ };
+
+ pinSession = async (id: string, pinned: boolean): Promise<void> => {
+ await this.#get().internal_updateSession(id, { pinned });
+ };
+
+ removeSession = async (sessionId: string): Promise<void> => {
await sessionService.removeSession(sessionId);
- await get().refreshSessions();
+ await this.#get().refreshSessions();
// If the active session deleted, switch to the inbox session
- if (sessionId === get().activeId) {
- get().switchSession(INBOX_SESSION_ID);
+ if (sessionId === this.#get().activeId) {
+ this.#get().switchSession(INBOX_SESSION_ID);
}
- },
+ };
- setAgentPinned: (value) => {
- set(
+ setAgentPinned = (value: boolean | ((prev: boolean) => boolean)): void => {
+ this.#set(
(state) => ({
isAgentPinned: typeof value === 'function' ? value(state.isAgentPinned) : value,
}),
false,
n('setAgentPinned'),
);
- },
+ };
- switchSession: (sessionId) => {
- if (get().activeAgentId === sessionId) return;
+ switchSession = (sessionId: string): void => {
+ if (this.#get().activeAgentId === sessionId) return;
- set({ activeAgentId: sessionId }, false, n(`activeSession/${sessionId}`));
- },
+ this.#set({ activeAgentId: sessionId }, false, n(`activeSession/${sessionId}`));
+ };
- toggleAgentPinned: () => {
- set((state) => ({ isAgentPinned: !state.isAgentPinned }), false, n('toggleAgentPinned'));
- },
+ toggleAgentPinned = (): void => {
+ this.#set((state) => ({ isAgentPinned: !state.isAgentPinned }), false, n('toggleAgentPinned'));
+ };
- triggerSessionUpdate: async (id) => {
- await get().internal_updateSession(id, { updatedAt: new Date() });
- },
+ triggerSessionUpdate = async (id: string): Promise<void> => {
+ await this.#get().internal_updateSession(id, { updatedAt: new Date() });
+ };
- updateSearchKeywords: (keywords) => {
- set(
+ updateSearchKeywords = (keywords: string): void => {
+ this.#set(
{ isSearching: !!keywords, sessionSearchKeywords: keywords },
false,
n('updateSearchKeywords'),
);
- },
+ };
- updateSessionGroupId: async (sessionId, group) => {
- const session = sessionSelectors.getSessionById(sessionId)(get());
+ updateSessionGroupId = async (sessionId: string, group: string): Promise<void> => {
+ const session = sessionSelectors.getSessionById(sessionId)(this.#get());
if (session?.type === 'group') {
// For group sessions (chat groups), use the chat group service
await chatGroupService.updateGroup(sessionId, {
groupId: group === 'default' ? null : group,
});
- await get().refreshSessions();
+ await this.#get().refreshSessions();
} else {
// For regular agent sessions, use the existing session service
- await get().internal_updateSession(sessionId, { group });
+ await this.#get().internal_updateSession(sessionId, { group });
}
- },
+ };
- useFetchSessions: (enabled, isLogin) =>
- useClientDataSWR<ChatSessionList>(
+ useFetchSessions = (
+ enabled: boolean,
+ isLogin: boolean | undefined,
+ ): SWRResponse<ChatSessionList> => {
+ return useClientDataSWR<ChatSessionList>(
enabled ? [FETCH_SESSIONS_KEY, isLogin] : null,
() => sessionService.getGroupedSessions(),
{
@@ -260,17 +211,13 @@ export const createSessionSlice: StateCreator<
},
onSuccess: (data) => {
if (
- get().isSessionsFirstFetchFinished &&
- isEqual(get().sessions, data.sessions) &&
- isEqual(get().sessionGroups, data.sessionGroups)
+ this.#get().isSessionsFirstFetchFinished &&
+ isEqual(this.#get().sessions, data.sessions) &&
+ isEqual(this.#get().sessionGroups, data.sessionGroups)
)
return;
- get().internal_processSessions(
- data.sessions,
- data.sessionGroups,
- n('useFetchSessions/updateData') as any,
- );
+ this.#get().internal_processSessions(data.sessions, data.sessionGroups);
// Sync chat groups from group sessions to chat store
const groupSessions = data.sessions.filter((session) => session.type === 'group');
@@ -308,13 +255,19 @@ export const createSessionSlice: StateCreator<
chatGroupStore.internal_updateGroupMaps(chatGroups);
}
- set({ isSessionsFirstFetchFinished: true }, false, n('useFetchSessions/onSuccess', data));
+ this.#set(
+ { isSessionsFirstFetchFinished: true },
+ false,
+ n('useFetchSessions/onSuccess', data),
+ );
},
suspense: true,
},
- ),
- useSearchSessions: (keyword) =>
- useSWR<LobeSessions>(
+ );
+ };
+
+ useSearchSessions = (keyword?: string): SWRResponse<any> => {
+ return useSWR<LobeSessions>(
[SEARCH_SESSIONS_KEY, keyword],
async () => {
if (!keyword) return [];
@@ -322,20 +275,25 @@ export const createSessionSlice: StateCreator<
return sessionService.searchSessions(keyword);
},
{ revalidateOnFocus: false, revalidateOnMount: false },
- ),
+ );
+ };
- /* eslint-disable sort-keys-fix/sort-keys-fix */
- internal_dispatchSessions: (payload) => {
- const nextSessions = sessionsReducer(get().sessions, payload);
- get().internal_processSessions(nextSessions, get().sessionGroups);
- },
- internal_updateSession: async (id, data) => {
- get().internal_dispatchSessions({ type: 'updateSession', id, value: data });
+ internal_dispatchSessions = (payload: SessionDispatch): void => {
+ const nextSessions = sessionsReducer(this.#get().sessions, payload);
+ this.#get().internal_processSessions(nextSessions, this.#get().sessionGroups);
+ };
+
+ internal_updateSession = async (
+ id: string,
+ data: Partial<UpdateSessionParams>,
+ ): Promise<void> => {
+ this.#get().internal_dispatchSessions({ id, type: 'updateSession', value: data });
await sessionService.updateSession(id, data);
- await get().refreshSessions();
- },
- internal_processSessions: (sessions, sessionGroups) => {
+ await this.#get().refreshSessions();
+ };
+
+ internal_processSessions = (sessions: LobeSessions, sessionGroups: LobeSessionGroups): void => {
const customGroups = sessionGroups.map((item) => ({
...item,
children: sessions.filter((i) => i.group === item.id && !i.pinned),
@@ -346,7 +304,7 @@ export const createSessionSlice: StateCreator<
);
const pinnedGroup = sessions.filter((item) => item.pinned);
- set(
+ this.#set(
{
customSessionGroups: customGroups,
defaultSessions: defaultGroup,
@@ -357,8 +315,11 @@ export const createSessionSlice: StateCreator<
false,
n('processSessions'),
);
- },
- refreshSessions: async () => {
+ };
+
+ refreshSessions = async (): Promise<void> => {
await mutate([FETCH_SESSIONS_KEY, true]);
- },
-});
+ };
+}
+
+export type SessionAction = Pick<SessionActionImpl, keyof SessionActionImpl>;
diff --git a/src/store/session/slices/session/helpers.ts b/src/store/session/slices/session/helpers.ts
index 9fe9b46dd5c..8252275ba36 100644
--- a/src/store/session/slices/session/helpers.ts
+++ b/src/store/session/slices/session/helpers.ts
@@ -3,7 +3,12 @@ import { t } from 'i18next';
import { DEFAULT_AVATAR } from '@/const/meta';
import { DEFAULT_AGENT_LOBE_SESSION } from '@/const/session';
import { type MetaData } from '@/types/meta';
-import { type LobeAgentSession, type LobeGroupSession, type LobeSession, type LobeSessions } from '@/types/session';
+import {
+ type LobeAgentSession,
+ type LobeGroupSession,
+ type LobeSession,
+ type LobeSessions,
+} from '@/types/session';
export const getSessionPinned = (session: LobeSession) => session.pinned;
diff --git a/src/store/session/slices/sessionGroup/action.ts b/src/store/session/slices/sessionGroup/action.ts
index 413785bba23..ffba4c11deb 100644
--- a/src/store/session/slices/sessionGroup/action.ts
+++ b/src/store/session/slices/sessionGroup/action.ts
@@ -1,56 +1,58 @@
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { message } from '@/components/AntdStaticMethods';
import { sessionService } from '@/services/session';
import { type SessionStore } from '@/store/session';
+import { type StoreSetter } from '@/store/types';
import { type SessionGroupItem } from '@/types/session';
import { type SessionGroupsDispatch, sessionGroupsReducer } from './reducer';
/* eslint-disable typescript-sort-keys/interface */
-export interface SessionGroupAction {
- addSessionGroup: (name: string) => Promise<string>;
- clearSessionGroups: () => Promise<void>;
- removeSessionGroup: (id: string) => Promise<void>;
- updateSessionGroupName: (id: string, name: string) => Promise<void>;
- updateSessionGroupSort: (items: SessionGroupItem[]) => Promise<void>;
- internal_dispatchSessionGroups: (payload: SessionGroupsDispatch) => void;
-}
+
/* eslint-enable */
-export const createSessionGroupSlice: StateCreator<
- SessionStore,
- [['zustand/devtools', never]],
- [],
- SessionGroupAction
-> = (set, get) => ({
- addSessionGroup: async (name) => {
+type Setter = StoreSetter<SessionStore>;
+export const createSessionGroupSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>
+ new SessionGroupActionImpl(set, get, _api);
+
+export class SessionGroupActionImpl {
+ readonly #get: () => SessionStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => SessionStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ addSessionGroup = async (name: string): Promise<string> => {
const id = await sessionService.createSessionGroup(name);
- await get().refreshSessions();
+ await this.#get().refreshSessions();
return id;
- },
+ };
- clearSessionGroups: async () => {
+ clearSessionGroups = async (): Promise<void> => {
await sessionService.removeSessionGroups();
- await get().refreshSessions();
- },
+ await this.#get().refreshSessions();
+ };
- removeSessionGroup: async (id) => {
+ removeSessionGroup = async (id: string): Promise<void> => {
await sessionService.removeSessionGroup(id);
- await get().refreshSessions();
- },
+ await this.#get().refreshSessions();
+ };
- updateSessionGroupName: async (id, name) => {
+ updateSessionGroupName = async (id: string, name: string): Promise<void> => {
await sessionService.updateSessionGroup(id, { name });
- await get().refreshSessions();
- },
- updateSessionGroupSort: async (items) => {
+ await this.#get().refreshSessions();
+ };
+
+ updateSessionGroupSort = async (items: SessionGroupItem[]): Promise<void> => {
const sortMap = items.map((item, index) => ({ id: item.id, sort: index }));
- get().internal_dispatchSessionGroups({ sortMap, type: 'updateSessionGroupOrder' });
+ this.#get().internal_dispatchSessionGroups({ sortMap, type: 'updateSessionGroupOrder' });
message.loading({
content: t('sessionGroup.sorting', { ns: 'chat' }),
@@ -62,12 +64,13 @@ export const createSessionGroupSlice: StateCreator<
message.destroy('updateSessionGroupSort');
message.success(t('sessionGroup.sortSuccess', { ns: 'chat' }));
- await get().refreshSessions();
- },
+ await this.#get().refreshSessions();
+ };
+
+ internal_dispatchSessionGroups = (payload: SessionGroupsDispatch): void => {
+ const nextSessionGroups = sessionGroupsReducer(this.#get().sessionGroups, payload);
+ this.#get().internal_processSessions(this.#get().sessions, nextSessionGroups);
+ };
+}
- /* eslint-disable sort-keys-fix/sort-keys-fix */
- internal_dispatchSessionGroups: (payload) => {
- const nextSessionGroups = sessionGroupsReducer(get().sessionGroups, payload);
- get().internal_processSessions(get().sessions, nextSessionGroups, 'updateSessionGroups');
- },
-});
+export type SessionGroupAction = Pick<SessionGroupActionImpl, keyof SessionGroupActionImpl>;
diff --git a/src/store/session/store.ts b/src/store/session/store.ts
index 42eb8db1210..bd9a0438f81 100644
--- a/src/store/session/store.ts
+++ b/src/store/session/store.ts
@@ -6,6 +6,7 @@ import { type StateCreator } from 'zustand/vanilla';
import { isDev } from '@/utils/env';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type SessionStoreState, initialState } from './initialState';
import { type HomeInputAction, createHomeInputSlice } from './slices/homeInput/action';
import { type RecentAction, createRecentSlice } from './slices/recent/action';
@@ -17,12 +18,18 @@ import { type SessionGroupAction, createSessionGroupSlice } from './slices/sessi
export interface SessionStore
extends SessionAction, SessionGroupAction, RecentAction, HomeInputAction, SessionStoreState {}
-const createStore: StateCreator<SessionStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type SessionStoreAction = SessionAction & SessionGroupAction & RecentAction & HomeInputAction;
+
+const createStore: StateCreator<SessionStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<SessionStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createSessionSlice(...parameters),
- ...createSessionGroupSlice(...parameters),
- ...createRecentSlice(...parameters),
- ...createHomeInputSlice(...parameters),
+ ...flattenActions<SessionStoreAction>([
+ createSessionSlice(...parameters),
+ createSessionGroupSlice(...parameters),
+ createRecentSlice(...parameters),
+ createHomeInputSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/tool/slices/builtin/action.ts b/src/store/tool/slices/builtin/action.ts
index d028d3064ca..b23174f02af 100644
--- a/src/store/tool/slices/builtin/action.ts
+++ b/src/store/tool/slices/builtin/action.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import { type StateCreator } from 'zustand/vanilla';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
@@ -13,38 +13,31 @@ const log = debug('lobe-store:builtin-tool');
/**
* Builtin Tool Action Interface
*/
-export interface BuiltinToolAction {
- /**
- * Invoke a builtin tool executor
- *
- * @param identifier - Tool identifier (e.g., 'lobe-knowledge-base')
- * @param apiName - API name (e.g., 'searchKnowledgeBase')
- * @param params - Parameters parsed from tool call arguments
- * @param ctx - Execution context with messageId, operationId, signal, etc.
- * @returns BuiltinToolResult with content, state, error, success, stop
- */
- invokeBuiltinTool: (
+
+type Setter = StoreSetter<ToolStore>;
+export const createBuiltinToolSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new BuiltinToolActionImpl(set, get, _api);
+
+export class BuiltinToolActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ invokeBuiltinTool = async (
identifier: string,
apiName: string,
params: any,
ctx: BuiltinToolContext,
- ) => Promise<BuiltinToolResult>;
-
- toggleBuiltinToolLoading: (key: string, value: boolean) => void;
- transformApiArgumentsToAiState: (key: string, params: any) => Promise<string | undefined>;
-}
-
-export const createBuiltinToolSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- BuiltinToolAction
-> = (set, get) => ({
- invokeBuiltinTool: async (identifier, apiName, params, ctx) => {
+ ): Promise<BuiltinToolResult> => {
const executorKey = `${identifier}/${apiName}`;
log('invokeBuiltinTool: %s', executorKey);
- const { toggleBuiltinToolLoading } = get();
+ const { toggleBuiltinToolLoading } = this.#get();
toggleBuiltinToolLoading(executorKey, true);
try {
@@ -66,17 +59,20 @@ export const createBuiltinToolSlice: StateCreator<
success: false,
};
}
- },
+ };
- toggleBuiltinToolLoading: (key, value) => {
- set({ builtinToolLoading: { [key]: value } }, false, n('toggleBuiltinToolLoading'));
- },
+ toggleBuiltinToolLoading = (key: string, value: boolean): void => {
+ this.#set({ builtinToolLoading: { [key]: value } }, false, n('toggleBuiltinToolLoading'));
+ };
- transformApiArgumentsToAiState: async (key, params) => {
- const { builtinToolLoading, toggleBuiltinToolLoading } = get();
+ transformApiArgumentsToAiState = async (
+ key: string,
+ params: any,
+ ): Promise<string | undefined> => {
+ const { builtinToolLoading, toggleBuiltinToolLoading } = this.#get();
if (builtinToolLoading[key]) return;
- const { [key as keyof BuiltinToolAction]: action } = get();
+ const { [key as keyof BuiltinToolAction]: action } = this.#get();
if (!action) return JSON.stringify(params);
@@ -93,5 +89,7 @@ export const createBuiltinToolSlice: StateCreator<
toggleBuiltinToolLoading(key, false);
throw e;
}
- },
-});
+ };
+}
+
+export type BuiltinToolAction = Pick<BuiltinToolActionImpl, keyof BuiltinToolActionImpl>;
diff --git a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts b/src/store/tool/slices/builtin/executors/lobe-page-agent.ts
index c1f08b49907..23a51f92245 100644
--- a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-page-agent.ts
@@ -4,8 +4,8 @@
* Creates and exports the PageAgentExecutor instance for registration.
* Also exports the runtime for editor instance injection.
*/
-import { EditorRuntime } from '@lobechat/editor-runtime';
import { PageAgentExecutor } from '@lobechat/builtin-tool-page-agent/executor';
+import { EditorRuntime } from '@lobechat/editor-runtime';
// Create singleton instance of the runtime
export const pageAgentRuntime = new EditorRuntime();
diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.ts
index 33310481557..c9147890067 100644
--- a/src/store/tool/slices/customPlugin/action.ts
+++ b/src/store/tool/slices/customPlugin/action.ts
@@ -1,13 +1,13 @@
import { type LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
import { merge } from 'es-toolkit/compat';
import { t } from 'i18next';
-import { type StateCreator } from 'zustand/vanilla';
import { notification } from '@/components/AntdStaticMethods';
import { mcpService } from '@/services/mcp';
import { pluginService } from '@/services/plugin';
import { toolService } from '@/services/tool';
import { pluginHelpers } from '@/store/tool/helpers';
+import { type StoreSetter } from '@/store/types';
import { type LobeToolCustomPlugin, type PluginInstallError } from '@/types/tool/plugin';
import { setNamespace } from '@/utils/storeDebug';
@@ -17,31 +17,32 @@ import { defaultCustomPlugin } from './initialState';
const n = setNamespace('customPlugin');
-export interface CustomPluginAction {
- installCustomPlugin: (value: LobeToolCustomPlugin) => Promise<void>;
- reinstallCustomPlugin: (id: string) => Promise<void>;
- uninstallCustomPlugin: (id: string) => Promise<void>;
- updateCustomPlugin: (id: string, value: LobeToolCustomPlugin) => Promise<void>;
- updateNewCustomPlugin: (value: Partial<LobeToolCustomPlugin>) => void;
-}
+type Setter = StoreSetter<ToolStore>;
+export const createCustomPluginSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new CustomPluginActionImpl(set, get, _api);
+
+export class CustomPluginActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
-export const createCustomPluginSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- CustomPluginAction
-> = (set, get) => ({
- installCustomPlugin: async (value) => {
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ installCustomPlugin = async (value: LobeToolCustomPlugin): Promise<void> => {
await pluginService.createCustomPlugin(value);
- await get().refreshPlugins();
- set({ newCustomPlugin: defaultCustomPlugin }, false, n('saveToCustomPluginList'));
- },
- reinstallCustomPlugin: async (id) => {
- const plugin = pluginSelectors.getCustomPluginById(id)(get());
+ await this.#get().refreshPlugins();
+ this.#set({ newCustomPlugin: defaultCustomPlugin }, false, n('saveToCustomPluginList'));
+ };
+
+ reinstallCustomPlugin = async (id: string): Promise<void> => {
+ const plugin = pluginSelectors.getCustomPluginById(id)(this.#get());
if (!plugin) return;
- const { refreshPlugins, updateInstallLoadingState } = get();
+ const { refreshPlugins, updateInstallLoadingState } = this.#get();
try {
updateInstallLoadingState(id, true);
@@ -77,7 +78,7 @@ export const createCustomPluginSlice: StateCreator<
console.error(error);
const err = error as PluginInstallError;
- const meta = pluginSelectors.getPluginMetaById(id)(get());
+ const meta = pluginSelectors.getPluginMetaById(id)(this.#get());
const name = pluginHelpers.getPluginTitle(meta);
notification.error({
@@ -85,25 +86,29 @@ export const createCustomPluginSlice: StateCreator<
message: t('error.reinstallError', { name, ns: 'plugin' }),
});
}
- },
- uninstallCustomPlugin: async (id) => {
+ };
+
+ uninstallCustomPlugin = async (id: string): Promise<void> => {
await pluginService.uninstallPlugin(id);
- await get().refreshPlugins();
- },
+ await this.#get().refreshPlugins();
+ };
- updateCustomPlugin: async (id, value) => {
- const { reinstallCustomPlugin } = get();
+ updateCustomPlugin = async (id: string, value: LobeToolCustomPlugin): Promise<void> => {
+ const { reinstallCustomPlugin } = this.#get();
// 1. Update list item information
await pluginService.updatePlugin(id, value);
// 2. Reinstall plugin
await reinstallCustomPlugin(id);
- },
- updateNewCustomPlugin: (newCustomPlugin) => {
- set(
- { newCustomPlugin: merge({}, get().newCustomPlugin, newCustomPlugin) },
+ };
+
+ updateNewCustomPlugin = (newCustomPlugin: Partial<LobeToolCustomPlugin>): void => {
+ this.#set(
+ { newCustomPlugin: merge({}, this.#get().newCustomPlugin, newCustomPlugin) },
false,
n('updateNewDevPlugin'),
);
- },
-});
+ };
+}
+
+export type CustomPluginAction = Pick<CustomPluginActionImpl, keyof CustomPluginActionImpl>;
diff --git a/src/store/tool/slices/klavisStore/action.ts b/src/store/tool/slices/klavisStore/action.ts
index dbed519e067..814481c6ca3 100644
--- a/src/store/tool/slices/klavisStore/action.ts
+++ b/src/store/tool/slices/klavisStore/action.ts
@@ -1,8 +1,8 @@
import { enableMapSet, produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { lambdaClient, toolsClient } from '@/libs/trpc/client';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
@@ -23,61 +23,27 @@ const n = setNamespace('klavisStore');
/**
* Klavis Store Actions
*/
-export interface KlavisStoreAction {
- /**
- * Call Klavis tool
- */
- callKlavisTool: (params: CallKlavisToolParams) => Promise<CallKlavisToolResult>;
-
- /**
- * Complete OAuth authentication and update server status
- * @param identifier - Server identifier (e.g., 'google-calendar')
- */
- completeKlavisServerAuth: (identifier: string) => Promise<void>;
-
- /**
- * Create a single Klavis MCP Server instance
- * @returns Created server instance, or object with oauthUrl if OAuth is required
- */
- createKlavisServer: (params: CreateKlavisServerParams) => Promise<KlavisServer | undefined>;
-
- /**
- * Refresh Klavis Server tool list
- * @param identifier - Server identifier (e.g., 'google-calendar')
- */
- refreshKlavisServerTools: (identifier: string) => Promise<void>;
-
- /**
- * Remove Klavis Server
- * @param identifier - Server identifier (e.g., 'google-calendar')
- */
- removeKlavisServer: (identifier: string) => Promise<void>;
-
- /**
- * Use SWR to fetch tools for a Klavis server by serverName
- * @param serverName - Klavis server name (e.g., 'Google Calendar')
- */
- useFetchServerTools: (serverName: string | undefined) => SWRResponse<KlavisTool[]>;
-
- /**
- * Use SWR to fetch user's Klavis server list
- * @param enabled - Whether to enable fetching
- */
- useFetchUserKlavisServers: (enabled: boolean) => SWRResponse<KlavisServer[]>;
-}
-export const createKlavisStoreSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- KlavisStoreAction
-> = (set, get) => ({
- callKlavisTool: async (params) => {
+type Setter = StoreSetter<ToolStore>;
+export const createKlavisStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new KlavisStoreActionImpl(set, get, _api);
+
+export class KlavisStoreActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ callKlavisTool = async (params: CallKlavisToolParams): Promise<CallKlavisToolResult> => {
const { serverUrl, toolName, toolArgs } = params;
const toolId = `${serverUrl}:${toolName}`;
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.executingToolIds.add(toolId);
}),
@@ -95,7 +61,7 @@ export const createKlavisStoreSlice: StateCreator<
console.log('toolsClient.klavis.callTool-response', response);
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.executingToolIds.delete(toolId);
}),
@@ -107,7 +73,7 @@ export const createKlavisStoreSlice: StateCreator<
} catch (error) {
console.error('[Klavis] Failed to call tool:', error);
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.executingToolIds.delete(toolId);
}),
@@ -120,17 +86,19 @@ export const createKlavisStoreSlice: StateCreator<
success: false,
};
}
- },
+ };
- completeKlavisServerAuth: async (identifier) => {
+ completeKlavisServerAuth = async (identifier: string): Promise<void> => {
// After OAuth completes, refresh tool list
- await get().refreshKlavisServerTools(identifier);
- },
+ await this.#get().refreshKlavisServerTools(identifier);
+ };
- createKlavisServer: async (params) => {
+ createKlavisServer = async (
+ params: CreateKlavisServerParams,
+ ): Promise<KlavisServer | undefined> => {
const { userId, serverName, identifier } = params;
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.loadingServerIds.add(identifier);
}),
@@ -161,7 +129,7 @@ export const createKlavisStoreSlice: StateCreator<
};
// Add to servers list
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
// Check if already exists (using identifier), update if exists
const existingIndex = draft.servers.findIndex((s) => s.identifier === identifier);
@@ -180,7 +148,7 @@ export const createKlavisStoreSlice: StateCreator<
} catch (error) {
console.error('[Klavis] Failed to create server:', error);
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.loadingServerIds.delete(identifier);
}),
@@ -190,10 +158,10 @@ export const createKlavisStoreSlice: StateCreator<
return undefined;
}
- },
+ };
- refreshKlavisServerTools: async (identifier) => {
- const { servers } = get();
+ refreshKlavisServerTools = async (identifier: string): Promise<void> => {
+ const { servers } = this.#get();
// Find server using identifier
const server = servers.find((s) => s.identifier === identifier);
@@ -202,7 +170,7 @@ export const createKlavisStoreSlice: StateCreator<
return;
}
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.loadingServerIds.add(identifier);
}),
@@ -219,7 +187,7 @@ export const createKlavisStoreSlice: StateCreator<
// If server returned an auth error (during polling), silently return
// This happens when user is still in the process of authorizing
if (instanceStatus.error === 'AUTH_ERROR') {
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.loadingServerIds.delete(identifier);
}),
@@ -233,7 +201,7 @@ export const createKlavisStoreSlice: StateCreator<
if (!instanceStatus.isAuthenticated) {
if (!instanceStatus.authNeeded) {
// If no authentication needed, all is well
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.loadingServerIds.delete(identifier);
}),
@@ -244,7 +212,7 @@ export const createKlavisStoreSlice: StateCreator<
}
// Remove from local state (using identifier)
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
draft.servers = draft.servers.filter((s) => s.identifier !== identifier);
draft.loadingServerIds.delete(identifier);
@@ -269,7 +237,7 @@ export const createKlavisStoreSlice: StateCreator<
const tools = response.tools as KlavisTool[];
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
// Find server using identifier
const serverIndex = draft.servers.findIndex((s) => s.identifier === identifier);
@@ -301,7 +269,7 @@ export const createKlavisStoreSlice: StateCreator<
} catch (error) {
console.error('[Klavis] Failed to refresh tools:', error);
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
// Find server using identifier
const serverIndex = draft.servers.findIndex((s) => s.identifier === identifier);
@@ -316,14 +284,14 @@ export const createKlavisStoreSlice: StateCreator<
n('refreshKlavisServerTools/error'),
);
}
- },
+ };
- removeKlavisServer: async (identifier) => {
- const { servers } = get();
+ removeKlavisServer = async (identifier: string): Promise<void> => {
+ const { servers } = this.#get();
// Find server using identifier
const server = servers.find((s) => s.identifier === identifier);
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
// Filter using identifier
draft.servers = draft.servers.filter((s) => s.identifier !== identifier);
@@ -343,10 +311,10 @@ export const createKlavisStoreSlice: StateCreator<
console.error('[Klavis] Failed to delete server instance:', error);
}
}
- },
+ };
- useFetchServerTools: (serverName) =>
- useSWR<KlavisTool[]>(
+ useFetchServerTools = (serverName: string | undefined): SWRResponse<KlavisTool[]> => {
+ return useSWR<KlavisTool[]>(
serverName ? `klavis-server-tools-${serverName}` : null,
async () => {
const response = await toolsClient.klavis.getTools.query({ serverName: serverName! });
@@ -360,10 +328,11 @@ export const createKlavisStoreSlice: StateCreator<
fallbackData: [],
revalidateOnFocus: false,
},
- ),
+ );
+ };
- useFetchUserKlavisServers: (enabled) =>
- useSWR<KlavisServer[]>(
+ useFetchUserKlavisServers = (enabled: boolean): SWRResponse<KlavisServer[]> => {
+ return useSWR<KlavisServer[]>(
enabled ? 'fetchUserKlavisServers' : null,
async () => {
const klavisPlugins = await lambdaClient.klavis.getKlavisPlugins.query();
@@ -399,7 +368,7 @@ export const createKlavisStoreSlice: StateCreator<
{
fallbackData: [],
onSuccess: (data) => {
- set(
+ this.#set(
produce((draft: KlavisStoreState) => {
if (data.length > 0) {
// Check if already exists using identifier
@@ -415,5 +384,8 @@ export const createKlavisStoreSlice: StateCreator<
},
revalidateOnFocus: false,
},
- ),
-});
+ );
+ };
+}
+
+export type KlavisStoreAction = Pick<KlavisStoreActionImpl, keyof KlavisStoreActionImpl>;
diff --git a/src/store/tool/slices/lobehubSkillStore/action.ts b/src/store/tool/slices/lobehubSkillStore/action.ts
index 5437820bb43..e2b48e9517d 100644
--- a/src/store/tool/slices/lobehubSkillStore/action.ts
+++ b/src/store/tool/slices/lobehubSkillStore/action.ts
@@ -1,9 +1,9 @@
import { getLobehubSkillProviderById } from '@lobechat/const';
import { enableMapSet, produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { toolsClient } from '@/libs/trpc/client';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
@@ -23,79 +23,28 @@ const n = setNamespace('lobehubSkillStore');
/**
* LobeHub Skill Store Actions
*/
-export interface LobehubSkillStoreAction {
- /**
- * Call LobeHub Skill tool
- */
- callLobehubSkillTool: (params: CallLobehubSkillToolParams) => Promise<CallLobehubSkillToolResult>;
-
- /**
- * Get single Provider connection status
- * @param provider - Provider ID (e.g., 'linear')
- */
- checkLobehubSkillStatus: (provider: string) => Promise<LobehubSkillServer | undefined>;
-
- /**
- * Get Provider authorization info (URL, code, expiration time)
- * @param provider - Provider ID (e.g., 'linear')
- * @param options - Optional scopes and redirectUri
- * @returns Authorization URL and related info
- */
- getLobehubSkillAuthorizeUrl: (
- provider: string,
- options?: { redirectUri?: string; scopes?: string[] },
- ) => Promise<{ authorizeUrl: string; code: string; expiresIn: number }>;
- /**
- * Internal method: Update Server status
- */
- internal_updateLobehubSkillServer: (
- provider: string,
- update: Partial<LobehubSkillServer>,
- ) => void;
-
- /**
- * Refresh Provider Token (if supported)
- * @param provider - Provider ID
- */
- refreshLobehubSkillToken: (provider: string) => Promise<boolean>;
-
- /**
- * Refresh Provider tool list
- * @param provider - Provider ID
- */
- refreshLobehubSkillTools: (provider: string) => Promise<void>;
-
- /**
- * Disconnect Provider connection
- * @param provider - Provider ID
- */
- revokeLobehubSkill: (provider: string) => Promise<void>;
-
- /**
- * Use SWR to fetch user's all connection statuses
- * @param enabled - Whether to enable fetching
- */
- useFetchLobehubSkillConnections: (enabled: boolean) => SWRResponse<LobehubSkillServer[]>;
-
- /**
- * Use SWR to fetch tools for a LobeHub Skill provider
- * @param provider - Provider ID (e.g., 'linear')
- */
- useFetchProviderTools: (provider: string | undefined) => SWRResponse<LobehubSkillTool[]>;
-}
+type Setter = StoreSetter<ToolStore>;
+export const createLobehubSkillStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new LobehubSkillStoreActionImpl(set, get, _api);
+
+export class LobehubSkillStoreActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
-export const createLobehubSkillStoreSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- LobehubSkillStoreAction
-> = (set, get) => ({
- callLobehubSkillTool: async (params) => {
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ callLobehubSkillTool = async (
+ params: CallLobehubSkillToolParams,
+ ): Promise<CallLobehubSkillToolResult> => {
const { provider, toolName, args } = params;
const toolId = `${provider}:${toolName}`;
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillExecutingToolIds.add(toolId);
}),
@@ -110,7 +59,7 @@ export const createLobehubSkillStoreSlice: StateCreator<
toolName,
});
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillExecutingToolIds.delete(toolId);
}),
@@ -122,7 +71,7 @@ export const createLobehubSkillStoreSlice: StateCreator<
} catch (error) {
console.error('[LobehubSkill] Failed to call tool:', error);
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillExecutingToolIds.delete(toolId);
}),
@@ -145,10 +94,10 @@ export const createLobehubSkillStoreSlice: StateCreator<
success: false,
};
}
- },
+ };
- checkLobehubSkillStatus: async (provider) => {
- set(
+ checkLobehubSkillStatus = async (provider: string): Promise<LobehubSkillServer | undefined> => {
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillLoadingIds.add(provider);
}),
@@ -176,7 +125,7 @@ export const createLobehubSkillStoreSlice: StateCreator<
tokenExpiresAt: response.connection?.tokenExpiresAt,
};
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
const existingIndex = draft.lobehubSkillServers.findIndex(
(s) => s.identifier === provider,
@@ -193,14 +142,14 @@ export const createLobehubSkillStoreSlice: StateCreator<
);
if (server.isConnected) {
- get().refreshLobehubSkillTools(provider);
+ this.#get().refreshLobehubSkillTools(provider);
}
return server;
} catch (error) {
console.error('[LobehubSkill] Failed to check status:', error);
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillLoadingIds.delete(provider);
}),
@@ -210,9 +159,12 @@ export const createLobehubSkillStoreSlice: StateCreator<
return undefined;
}
- },
+ };
- getLobehubSkillAuthorizeUrl: async (provider, options) => {
+ getLobehubSkillAuthorizeUrl = async (
+ provider: string,
+ options?: { redirectUri?: string; scopes?: string[] },
+ ): Promise<{ authorizeUrl: string; code: string; expiresIn: number }> => {
const response = await toolsClient.market.connectGetAuthorizeUrl.query({
provider,
redirectUri: options?.redirectUri,
@@ -224,10 +176,13 @@ export const createLobehubSkillStoreSlice: StateCreator<
code: response.code,
expiresIn: response.expiresIn,
};
- },
+ };
- internal_updateLobehubSkillServer: (provider, update) => {
- set(
+ internal_updateLobehubSkillServer = (
+ provider: string,
+ update: Partial<LobehubSkillServer>,
+ ): void => {
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
const serverIndex = draft.lobehubSkillServers.findIndex((s) => s.identifier === provider);
if (serverIndex >= 0) {
@@ -240,14 +195,14 @@ export const createLobehubSkillStoreSlice: StateCreator<
false,
n('internal_updateLobehubSkillServer'),
);
- },
+ };
- refreshLobehubSkillToken: async (provider) => {
+ refreshLobehubSkillToken = async (provider: string): Promise<boolean> => {
try {
const response = await toolsClient.market.connectRefresh.mutate({ provider });
if (response.refreshed) {
- get().internal_updateLobehubSkillServer(provider, {
+ this.#get().internal_updateLobehubSkillServer(provider, {
status: LobehubSkillStatus.CONNECTED,
tokenExpiresAt: response.connection?.tokenExpiresAt,
});
@@ -258,13 +213,13 @@ export const createLobehubSkillStoreSlice: StateCreator<
console.error('[LobehubSkill] Failed to refresh token:', error);
return false;
}
- },
+ };
- refreshLobehubSkillTools: async (provider) => {
+ refreshLobehubSkillTools = async (provider: string): Promise<void> => {
try {
const response = await toolsClient.market.connectListTools.query({ provider });
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
const serverIndex = draft.lobehubSkillServers.findIndex((s) => s.identifier === provider);
if (serverIndex >= 0) {
@@ -277,10 +232,10 @@ export const createLobehubSkillStoreSlice: StateCreator<
} catch (error) {
console.error('[LobehubSkill] Failed to refresh tools:', error);
}
- },
+ };
- revokeLobehubSkill: async (provider) => {
- set(
+ revokeLobehubSkill = async (provider: string): Promise<void> => {
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillLoadingIds.add(provider);
}),
@@ -291,7 +246,7 @@ export const createLobehubSkillStoreSlice: StateCreator<
try {
await toolsClient.market.connectRevoke.mutate({ provider });
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillServers = draft.lobehubSkillServers.filter(
(s) => s.identifier !== provider,
@@ -304,7 +259,7 @@ export const createLobehubSkillStoreSlice: StateCreator<
} catch (error) {
console.error('[LobehubSkill] Failed to revoke:', error);
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
draft.lobehubSkillLoadingIds.delete(provider);
}),
@@ -312,10 +267,10 @@ export const createLobehubSkillStoreSlice: StateCreator<
n('revokeLobehubSkill/error'),
);
}
- },
+ };
- useFetchLobehubSkillConnections: (enabled) =>
- useSWR<LobehubSkillServer[]>(
+ useFetchLobehubSkillConnections = (enabled: boolean): SWRResponse<LobehubSkillServer[]> => {
+ return useSWR<LobehubSkillServer[]>(
enabled ? 'fetchLobehubSkillConnections' : null,
async () => {
const response = await toolsClient.market.connectListConnections.query();
@@ -345,7 +300,7 @@ export const createLobehubSkillStoreSlice: StateCreator<
fallbackData: [],
onSuccess: (data) => {
if (data.length > 0) {
- set(
+ this.#set(
produce((draft: LobehubSkillStoreState) => {
const existingIds = new Set(draft.lobehubSkillServers.map((s) => s.identifier));
const newServers = data.filter((s) => !existingIds.has(s.identifier));
@@ -356,16 +311,17 @@ export const createLobehubSkillStoreSlice: StateCreator<
);
for (const server of data) {
- get().refreshLobehubSkillTools(server.identifier);
+ this.#get().refreshLobehubSkillTools(server.identifier);
}
}
},
revalidateOnFocus: false,
},
- ),
+ );
+ };
- useFetchProviderTools: (provider) =>
- useSWR<LobehubSkillTool[]>(
+ useFetchProviderTools = (provider: string | undefined): SWRResponse<LobehubSkillTool[]> => {
+ return useSWR<LobehubSkillTool[]>(
provider ? `lobehub-skill-tools-${provider}` : null,
async () => {
const response = await toolsClient.market.connectListTools.query({ provider: provider! });
@@ -379,5 +335,11 @@ export const createLobehubSkillStoreSlice: StateCreator<
fallbackData: [],
revalidateOnFocus: false,
},
- ),
-});
+ );
+ };
+}
+
+export type LobehubSkillStoreAction = Pick<
+ LobehubSkillStoreActionImpl,
+ keyof LobehubSkillStoreActionImpl
+>;
diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.ts
index 3aea527749d..6466d9b7995 100644
--- a/src/store/tool/slices/mcpStore/action.ts
+++ b/src/store/tool/slices/mcpStore/action.ts
@@ -7,7 +7,6 @@ import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import { gt, valid } from 'semver';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { type MCPErrorData, parseStdioErrorMessage } from '@/libs/mcp/types';
import { discoverService } from '@/services/discover';
@@ -15,6 +14,7 @@ import { mcpService } from '@/services/mcp';
import { pluginService } from '@/services/plugin';
import { globalHelpers } from '@/store/global/helpers';
import { mcpStoreSelectors } from '@/store/tool/selectors';
+import { type StoreSetter } from '@/store/types';
import { McpConnectionType } from '@/types/discover';
import {
type CheckMcpInstallResult,
@@ -138,36 +138,28 @@ export interface TestMcpConnectionResult {
success: boolean;
}
-export interface PluginMCPStoreAction {
- cancelInstallMCPPlugin: (identifier: string) => Promise<void>;
- cancelMcpConnectionTest: (identifier: string) => void;
- installMCPPlugin: (
- identifier: string,
- options?: { config?: Record<string, any>; resume?: boolean; skipDepsCheck?: boolean },
- ) => Promise<boolean | undefined>;
- loadMoreMCPPlugins: () => void;
- resetMCPPluginList: (keywords?: string) => void;
- // Test connection related methods
- testMcpConnection: (params: McpConnectionParams) => Promise<TestMcpConnectionResult>;
- uninstallMCPPlugin: (identifier: string) => Promise<void>;
- updateMCPInstallProgress: (identifier: string, progress: MCPInstallProgress | undefined) => void;
- useFetchMCPPluginList: (params: MCPPluginListParams) => SWRResponse<PluginListResponse>;
-}
+type Setter = StoreSetter<ToolStore>;
+export const createMCPPluginStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new PluginMCPStoreActionImpl(set, get, _api);
+
+export class PluginMCPStoreActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createMCPPluginStoreSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- PluginMCPStoreAction
-> = (set, get) => ({
- cancelInstallMCPPlugin: async (identifier) => {
+ cancelInstallMCPPlugin = async (identifier: string): Promise<void> => {
// Get and cancel AbortController
- const abortController = get().mcpInstallAbortControllers[identifier];
+ const abortController = this.#get().mcpInstallAbortControllers[identifier];
if (abortController) {
abortController.abort();
// Clean up AbortController storage
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
delete draft.mcpInstallAbortControllers[identifier];
}),
@@ -177,18 +169,17 @@ export const createMCPPluginStoreSlice: StateCreator<
}
// Clean up installation progress and loading state
- get().updateMCPInstallProgress(identifier, undefined);
- get().updateInstallLoadingState(identifier, undefined);
- },
+ this.#get().updateMCPInstallProgress(identifier, undefined);
+ this.#get().updateInstallLoadingState(identifier, undefined);
+ };
- // Cancel MCP connection test
- cancelMcpConnectionTest: (identifier) => {
- const abortController = get().mcpTestAbortControllers[identifier];
+ cancelMcpConnectionTest = (identifier: string): void => {
+ const abortController = this.#get().mcpTestAbortControllers[identifier];
if (abortController) {
abortController.abort();
// Clean up state
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpTestLoading[identifier] = false;
delete draft.mcpTestAbortControllers[identifier];
@@ -198,12 +189,15 @@ export const createMCPPluginStoreSlice: StateCreator<
n('cancelMcpConnectionTest'),
);
}
- },
+ };
- installMCPPlugin: async (identifier, options = {}) => {
+ installMCPPlugin = async (
+ identifier: string,
+ options: { config?: Record<string, any>; resume?: boolean; skipDepsCheck?: boolean } = {},
+ ): Promise<boolean | undefined> => {
const { resume = false, config, skipDepsCheck } = options;
const normalizedConfig = toNonEmptyStringRecord(config);
- let plugin = mcpStoreSelectors.getPluginById(identifier)(get());
+ let plugin = mcpStoreSelectors.getPluginById(identifier)(this.#get());
if (!plugin || !plugin.manifestUrl) {
const data = await discoverService.getMcpDetail({ identifier });
@@ -218,13 +212,13 @@ export const createMCPPluginStoreSlice: StateCreator<
// @ts-expect-error
const { haveCloudEndpoint } = plugin || {};
- const { updateInstallLoadingState, refreshPlugins, updateMCPInstallProgress } = get();
+ const { updateInstallLoadingState, refreshPlugins, updateMCPInstallProgress } = this.#get();
// Create AbortController for canceling installation
const abortController = new AbortController();
// Store AbortController
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpInstallAbortControllers[identifier] = abortController;
}),
@@ -248,7 +242,7 @@ export const createMCPPluginStoreSlice: StateCreator<
if (resume) {
// Resume mode: get previous info from storage
- const configInfo = get().mcpInstallProgress[identifier];
+ const configInfo = this.#get().mcpInstallProgress[identifier];
if (!configInfo) {
console.error('No config info found for resume');
return;
@@ -614,7 +608,7 @@ export const createMCPPluginStoreSlice: StateCreator<
updateInstallLoadingState(identifier, undefined);
// Clean up AbortController
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
delete draft.mcpInstallAbortControllers[identifier];
}),
@@ -698,7 +692,7 @@ export const createMCPPluginStoreSlice: StateCreator<
updateInstallLoadingState(identifier, undefined);
// Clean up AbortController
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
delete draft.mcpInstallAbortControllers[identifier];
}),
@@ -706,14 +700,14 @@ export const createMCPPluginStoreSlice: StateCreator<
n('installMCPPlugin/clearController'),
);
}
- },
+ };
- loadMoreMCPPlugins: () => {
- const { mcpPluginItems, totalCount, currentPage } = get();
+ loadMoreMCPPlugins = (): void => {
+ const { mcpPluginItems, totalCount, currentPage } = this.#get();
// Check if there's more data to load
if (mcpPluginItems.length < (totalCount || 0)) {
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
draft.currentPage = currentPage + 1;
}),
@@ -721,10 +715,10 @@ export const createMCPPluginStoreSlice: StateCreator<
n('loadMoreMCPPlugins'),
);
}
- },
+ };
- resetMCPPluginList: (keywords) => {
- set(
+ resetMCPPluginList = (keywords?: string): void => {
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpPluginItems = [];
draft.currentPage = 1;
@@ -734,17 +728,16 @@ export const createMCPPluginStoreSlice: StateCreator<
false,
n('resetMCPPluginList'),
);
- },
+ };
- // Test MCP connection
- testMcpConnection: async (params) => {
+ testMcpConnection = async (params: McpConnectionParams): Promise<TestMcpConnectionResult> => {
const { identifier, connection, metadata } = params;
// Create AbortController for canceling test
const abortController = new AbortController();
// Store AbortController and set loading state
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpTestAbortControllers[identifier] = abortController;
draft.mcpTestLoading[identifier] = true;
@@ -797,7 +790,7 @@ export const createMCPPluginStoreSlice: StateCreator<
}
// Clean up state
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpTestLoading[identifier] = false;
delete draft.mcpTestAbortControllers[identifier];
@@ -826,7 +819,7 @@ export const createMCPPluginStoreSlice: StateCreator<
const { originalMessage, errorLog } = parseStdioErrorMessage(rawErrorMessage);
// Set error state
- set(
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpTestLoading[identifier] = false;
draft.mcpTestErrors[identifier] = originalMessage;
@@ -838,30 +831,33 @@ export const createMCPPluginStoreSlice: StateCreator<
return { error: originalMessage, errorLog, success: false };
}
- },
+ };
- uninstallMCPPlugin: async (identifier) => {
+ uninstallMCPPlugin = async (identifier: string): Promise<void> => {
await pluginService.uninstallPlugin(identifier);
- await get().refreshPlugins();
+ await this.#get().refreshPlugins();
discoverService.reportMcpEvent({
event: 'uninstall',
identifier: identifier,
source: 'self',
});
- },
+ };
- updateMCPInstallProgress: (identifier, progress) => {
- set(
+ updateMCPInstallProgress = (
+ identifier: string,
+ progress: MCPInstallProgress | undefined,
+ ): void => {
+ this.#set(
produce((draft: MCPStoreState) => {
draft.mcpInstallProgress[identifier] = progress;
}),
false,
n(`updateMCPInstallProgress/${progress?.step || 'clear'}`),
);
- },
+ };
- useFetchMCPPluginList: (params) => {
+ useFetchMCPPluginList = (params: MCPPluginListParams): SWRResponse<PluginListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
const requestParams = isDesktop
? params
@@ -883,8 +879,8 @@ export const createMCPPluginStoreSlice: StateCreator<
swrKey,
() => discoverService.getMCPPluginList(requestParams),
{
- onSuccess(data) {
- set(
+ onSuccess: (data) => {
+ this.#set(
produce((draft: MCPStoreState) => {
draft.searchLoading = false;
@@ -917,5 +913,7 @@ export const createMCPPluginStoreSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type PluginMCPStoreAction = Pick<PluginMCPStoreActionImpl, keyof PluginMCPStoreActionImpl>;
diff --git a/src/store/tool/slices/oldStore/action.ts b/src/store/tool/slices/oldStore/action.ts
index 0408e03e92a..081c8fa7a3a 100644
--- a/src/store/tool/slices/oldStore/action.ts
+++ b/src/store/tool/slices/oldStore/action.ts
@@ -3,7 +3,6 @@ import { uniqBy } from 'es-toolkit/compat';
import { t } from 'i18next';
import { produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { notification } from '@/components/AntdStaticMethods';
import { mutate } from '@/libs/swr';
@@ -11,50 +10,49 @@ import { pluginService } from '@/services/plugin';
import { toolService } from '@/services/tool';
import { globalHelpers } from '@/store/global/helpers';
import { pluginStoreSelectors } from '@/store/tool/selectors';
-import { type DiscoverPluginItem, type PluginListResponse, type PluginQueryParams } from '@/types/discover';
+import { type StoreSetter } from '@/store/types';
+import {
+ type DiscoverPluginItem,
+ type PluginListResponse,
+ type PluginQueryParams,
+} from '@/types/discover';
import { type PluginInstallError } from '@/types/tool/plugin';
import { sleep } from '@/utils/sleep';
import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
-import { type PluginInstallProgress, PluginInstallStep, type PluginStoreState } from './initialState';
+import {
+ type PluginInstallProgress,
+ PluginInstallStep,
+ type PluginStoreState,
+} from './initialState';
const n = setNamespace('pluginStore');
const INSTALLED_PLUGINS = 'loadInstalledPlugins';
-export interface PluginStoreAction {
- installOldPlugin: (identifier: string, source?: 'plugin' | 'customPlugin') => Promise<void>;
- installPlugin: (identifier: string, source?: 'plugin' | 'customPlugin') => Promise<void>;
- installPlugins: (plugins: string[]) => Promise<void>;
- loadMorePlugins: () => void;
- loadPluginStore: () => Promise<DiscoverPluginItem[]>;
- refreshPlugins: () => Promise<void>;
-
- resetPluginList: (keywords?: string) => void;
- uninstallPlugin: (identifier: string) => Promise<void>;
- updateInstallLoadingState: (key: string, value: boolean | undefined) => void;
- updatePluginInstallProgress: (
- identifier: string,
- progress: PluginInstallProgress | undefined,
- ) => void;
-
- useFetchInstalledPlugins: (enabled: boolean) => SWRResponse<LobeTool[]>;
- useFetchPluginList: (params: PluginQueryParams) => SWRResponse<PluginListResponse>;
- useFetchPluginStore: () => SWRResponse<DiscoverPluginItem[]>;
-}
-
-export const createPluginStoreSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- PluginStoreAction
-> = (set, get) => ({
- installOldPlugin: async (name, type = 'plugin') => {
- const plugin = pluginStoreSelectors.getPluginById(name)(get());
+type Setter = StoreSetter<ToolStore>;
+export const createPluginStoreSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new PluginStoreActionImpl(set, get, _api);
+
+export class PluginStoreActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ installOldPlugin = async (
+ name: string,
+ type: 'plugin' | 'customPlugin' = 'plugin',
+ ): Promise<void> => {
+ const plugin = pluginStoreSelectors.getPluginById(name)(this.#get());
if (!plugin) return;
- const { updateInstallLoadingState, refreshPlugins, updatePluginInstallProgress } = get();
+ const { updateInstallLoadingState, refreshPlugins, updatePluginInstallProgress } = this.#get();
try {
// Start installation process
@@ -113,12 +111,16 @@ export const createPluginStoreSlice: StateCreator<
message: t('error.installError', { name: plugin.title, ns: 'plugin' }),
});
}
- },
- installPlugin: async (name, type = 'plugin') => {
- const plugin = pluginStoreSelectors.getPluginById(name)(get());
+ };
+
+ installPlugin = async (
+ name: string,
+ type: 'plugin' | 'customPlugin' = 'plugin',
+ ): Promise<void> => {
+ const plugin = pluginStoreSelectors.getPluginById(name)(this.#get());
if (!plugin) return;
- const { updateInstallLoadingState, refreshPlugins } = get();
+ const { updateInstallLoadingState, refreshPlugins } = this.#get();
try {
updateInstallLoadingState(name, true);
const data = await toolService.getToolManifest(plugin.manifest);
@@ -139,18 +141,20 @@ export const createPluginStoreSlice: StateCreator<
message: t('error.installError', { name: plugin.title, ns: 'plugin' }),
});
}
- },
- installPlugins: async (plugins) => {
- const { installPlugin } = get();
+ };
+
+ installPlugins = async (plugins: string[]): Promise<void> => {
+ const { installPlugin } = this.#get();
await Promise.all(plugins.map((identifier) => installPlugin(identifier)));
- },
- loadMorePlugins: () => {
- const { oldPluginItems, pluginTotalCount, currentPluginPage } = get();
+ };
+
+ loadMorePlugins = (): void => {
+ const { oldPluginItems, pluginTotalCount, currentPluginPage } = this.#get();
// Check if there is more data to load
if (oldPluginItems.length < (pluginTotalCount || 0)) {
- set(
+ this.#set(
produce((draft: PluginStoreState) => {
draft.currentPluginPage = currentPluginPage + 1;
}),
@@ -158,8 +162,9 @@ export const createPluginStoreSlice: StateCreator<
n('loadMorePlugins'),
);
}
- },
- loadPluginStore: async () => {
+ };
+
+ loadPluginStore = async (): Promise<DiscoverPluginItem[]> => {
const locale = globalHelpers.getCurrentLanguage();
const data = await toolService.getOldPluginList({
@@ -168,15 +173,17 @@ export const createPluginStoreSlice: StateCreator<
pageSize: 50,
});
- set({ oldPluginItems: data.items }, false, n('loadPluginList'));
+ this.#set({ oldPluginItems: data.items }, false, n('loadPluginList'));
return data.items;
- },
- refreshPlugins: async () => {
+ };
+
+ refreshPlugins = async (): Promise<void> => {
await mutate(INSTALLED_PLUGINS);
- },
- resetPluginList: (keywords) => {
- set(
+ };
+
+ resetPluginList = (keywords?: string): void => {
+ this.#set(
produce((draft: PluginStoreState) => {
draft.oldPluginItems = [];
draft.currentPluginPage = 1;
@@ -185,52 +192,64 @@ export const createPluginStoreSlice: StateCreator<
false,
n('resetPluginList'),
);
- },
- uninstallPlugin: async (identifier) => {
+ };
+
+ uninstallPlugin = async (identifier: string): Promise<void> => {
await pluginService.uninstallPlugin(identifier);
- await get().refreshPlugins();
- },
- updateInstallLoadingState: (key, value) => {
- set(
+ await this.#get().refreshPlugins();
+ };
+
+ updateInstallLoadingState = (key: string, value: boolean | undefined): void => {
+ this.#set(
produce((draft: PluginStoreState) => {
draft.pluginInstallLoading[key] = value;
}),
false,
n('updateInstallLoadingState'),
);
- },
- updatePluginInstallProgress: (identifier, progress) => {
- set(
+ };
+
+ updatePluginInstallProgress = (
+ identifier: string,
+ progress: PluginInstallProgress | undefined,
+ ): void => {
+ this.#set(
produce((draft: PluginStoreState) => {
draft.pluginInstallProgress[identifier] = progress;
}),
false,
n(`updatePluginInstallProgress/${progress?.step || 'clear'}`),
);
- },
-
- useFetchInstalledPlugins: (enabled: boolean) =>
- useSWR<LobeTool[]>(enabled ? INSTALLED_PLUGINS : null, pluginService.getInstalledPlugins, {
- fallbackData: [],
- onSuccess: (data) => {
- set(
- { installedPlugins: data, loadingInstallPlugins: false },
- false,
- n('useFetchInstalledPlugins'),
- );
+ };
+
+ useFetchInstalledPlugins = (enabled: boolean): SWRResponse<LobeTool[]> => {
+ return useSWR<LobeTool[]>(
+ enabled ? INSTALLED_PLUGINS : null,
+ pluginService.getInstalledPlugins,
+ {
+ fallbackData: [],
+ onSuccess: (data) => {
+ this.#set(
+ { installedPlugins: data, loadingInstallPlugins: false },
+ false,
+ n('useFetchInstalledPlugins'),
+ );
+ },
+ revalidateOnFocus: false,
+ suspense: true,
},
- revalidateOnFocus: false,
- suspense: true,
- }),
- useFetchPluginList: (params) => {
+ );
+ };
+
+ useFetchPluginList = (params: PluginQueryParams): SWRResponse<PluginListResponse> => {
const locale = globalHelpers.getCurrentLanguage();
return useSWR<PluginListResponse>(
['useFetchPluginList', locale, ...Object.values(params)].filter(Boolean).join('-'),
async () => toolService.getOldPluginList(params),
{
- onSuccess(data) {
- set(
+ onSuccess: (data) => {
+ this.#set(
produce((draft: PluginStoreState) => {
draft.pluginSearchLoading = false;
@@ -260,9 +279,13 @@ export const createPluginStoreSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
- useFetchPluginStore: () =>
- useSWR<DiscoverPluginItem[]>('loadPluginStore', get().loadPluginStore, {
+ };
+
+ useFetchPluginStore = (): SWRResponse<DiscoverPluginItem[]> => {
+ return useSWR<DiscoverPluginItem[]>('loadPluginStore', this.#get().loadPluginStore, {
revalidateOnFocus: false,
- }),
-});
+ });
+ };
+}
+
+export type PluginStoreAction = Pick<PluginStoreActionImpl, keyof PluginStoreActionImpl>;
diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.ts
index c2a495b4550..a531485560b 100644
--- a/src/store/tool/slices/plugin/action.ts
+++ b/src/store/tool/slices/plugin/action.ts
@@ -1,10 +1,10 @@
import { type Schema, type ValidationResult } from '@cfworker/json-schema';
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { MESSAGE_CANCEL_FLAT } from '@/const/message';
import { useClientDataSWR } from '@/libs/swr';
import { pluginService } from '@/services/plugin';
+import { type StoreSetter } from '@/store/types';
import { merge } from '@/utils/merge';
import { type ToolStore } from '../../store';
@@ -14,46 +14,43 @@ import { pluginSelectors } from './selectors';
/**
* Plugin interface
*/
-export interface PluginAction {
- checkPluginsIsInstalled: (plugins: string[]) => Promise<void>;
- removeAllPlugins: () => Promise<void>;
- updateInstallMcpPlugin: (id: string, value: any) => Promise<void>;
- updatePluginSettings: <T>(
- id: string,
- settings: Partial<T>,
- options?: { override?: boolean },
- ) => Promise<void>;
- useCheckPluginsIsInstalled: (enable: boolean, plugins: string[]) => SWRResponse;
- validatePluginSettings: (identifier: string) => Promise<ValidationResult | undefined>;
-}
-export const createPluginSlice: StateCreator<
- ToolStore,
- [['zustand/devtools', never]],
- [],
- PluginAction
-> = (set, get) => ({
- checkPluginsIsInstalled: async (plugins) => {
+type Setter = StoreSetter<ToolStore>;
+export const createPluginSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
+ new PluginActionImpl(set, get, _api);
+
+export class PluginActionImpl {
+ readonly #get: () => ToolStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ checkPluginsIsInstalled = async (plugins: string[]): Promise<void> => {
// if there is no plugins, just skip.
if (plugins.length === 0) return;
- const { loadPluginStore, installPlugins } = get();
+ const { loadPluginStore, installPlugins } = this.#get();
// check if the store is empty
// if it is, we need to load the plugin store
- if (pluginStoreSelectors.onlinePluginStore(get()).length === 0) {
+ if (pluginStoreSelectors.onlinePluginStore(this.#get()).length === 0) {
await loadPluginStore();
}
await installPlugins(plugins);
- },
- removeAllPlugins: async () => {
+ };
+
+ removeAllPlugins = async (): Promise<void> => {
await pluginService.removeAllPlugins();
- await get().refreshPlugins();
- },
+ await this.#get().refreshPlugins();
+ };
- updateInstallMcpPlugin: async (id, value) => {
- const installedPlugin = pluginSelectors.getInstalledPluginById(id)(get());
+ updateInstallMcpPlugin = async (id: string, value: any): Promise<void> => {
+ const installedPlugin = pluginSelectors.getInstalledPluginById(id)(this.#get());
if (!installedPlugin) return;
@@ -61,29 +58,37 @@ export const createPluginSlice: StateCreator<
customParams: { mcp: merge(installedPlugin.customParams?.mcp, value) },
});
- await get().refreshPlugins();
- },
+ await this.#get().refreshPlugins();
+ };
- updatePluginSettings: async (id, settings, { override } = {}) => {
- const signal = get().updatePluginSettingsSignal;
+ updatePluginSettings = async <T>(
+ id: string,
+ settings: Partial<T>,
+ options: { override?: boolean } = {},
+ ): Promise<void> => {
+ const { override } = options;
+ const signal = this.#get().updatePluginSettingsSignal;
if (signal) signal.abort(MESSAGE_CANCEL_FLAT);
const newSignal = new AbortController();
- const previousSettings = pluginSelectors.getPluginSettingsById(id)(get());
+ const previousSettings = pluginSelectors.getPluginSettingsById(id)(this.#get());
const nextSettings = override ? settings : merge(previousSettings, settings);
- set({ updatePluginSettingsSignal: newSignal }, false, 'create new Signal');
+ this.#set({ updatePluginSettingsSignal: newSignal }, false, 'create new Signal');
await pluginService.updatePluginSettings(id, nextSettings, newSignal.signal);
- await get().refreshPlugins();
- },
- useCheckPluginsIsInstalled: (enable, plugins) =>
- useClientDataSWR(enable ? plugins : null, get().checkPluginsIsInstalled),
- validatePluginSettings: async (identifier) => {
- const manifest = pluginSelectors.getToolManifestById(identifier)(get());
+ await this.#get().refreshPlugins();
+ };
+
+ useCheckPluginsIsInstalled = (enable: boolean, plugins: string[]): SWRResponse => {
+ return useClientDataSWR(enable ? plugins : null, this.#get().checkPluginsIsInstalled);
+ };
+
+ validatePluginSettings = async (identifier: string): Promise<ValidationResult | undefined> => {
+ const manifest = pluginSelectors.getToolManifestById(identifier)(this.#get());
if (!manifest || !manifest.settings) return;
- const settings = pluginSelectors.getPluginSettingsById(identifier)(get());
+ const settings = pluginSelectors.getPluginSettingsById(identifier)(this.#get());
// validate the settings
const { Validator } = await import('@cfworker/json-schema');
@@ -93,5 +98,7 @@ export const createPluginSlice: StateCreator<
if (!result.valid) return { errors: result.errors, valid: false };
return { errors: [], valid: true };
- },
-});
+ };
+}
+
+export type PluginAction = Pick<PluginActionImpl, keyof PluginActionImpl>;
diff --git a/src/store/tool/store.ts b/src/store/tool/store.ts
index 654492d454b..1bde4b8249d 100644
--- a/src/store/tool/store.ts
+++ b/src/store/tool/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type ToolStoreState, initialState } from './initialState';
import { type BuiltinToolAction, createBuiltinToolSlice } from './slices/builtin';
import { type CustomPluginAction, createCustomPluginSlice } from './slices/customPlugin';
@@ -26,15 +27,27 @@ export type ToolStore = ToolStoreState &
KlavisStoreAction &
LobehubSkillStoreAction;
-const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type ToolStoreAction = CustomPluginAction &
+ PluginAction &
+ PluginStoreAction &
+ BuiltinToolAction &
+ PluginMCPStoreAction &
+ KlavisStoreAction &
+ LobehubSkillStoreAction;
+
+const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<ToolStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createPluginSlice(...parameters),
- ...createCustomPluginSlice(...parameters),
- ...createPluginStoreSlice(...parameters),
- ...createBuiltinToolSlice(...parameters),
- ...createMCPPluginStoreSlice(...parameters),
- ...createKlavisStoreSlice(...parameters),
- ...createLobehubSkillStoreSlice(...parameters),
+ ...flattenActions<ToolStoreAction>([
+ createPluginSlice(...parameters),
+ createCustomPluginSlice(...parameters),
+ createPluginStoreSlice(...parameters),
+ createBuiltinToolSlice(...parameters),
+ createMCPPluginStoreSlice(...parameters),
+ createKlavisStoreSlice(...parameters),
+ createLobehubSkillStoreSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/types.ts b/src/store/types.ts
new file mode 100644
index 00000000000..34b594a71c7
--- /dev/null
+++ b/src/store/types.ts
@@ -0,0 +1,8 @@
+export interface StoreSetter<TStore> {
+ (
+ partial: TStore | Partial<TStore> | ((state: TStore) => TStore | Partial<TStore>),
+ replace?: false | undefined,
+ action?: any,
+ ): void;
+ (state: TStore | ((state: TStore) => TStore), replace: true, action?: any): void;
+}
diff --git a/src/store/user/slices/auth/action.ts b/src/store/user/slices/auth/action.ts
index 60c14c22129..c27919917fe 100644
--- a/src/store/user/slices/auth/action.ts
+++ b/src/store/user/slices/auth/action.ts
@@ -1,5 +1,6 @@
import { type SSOProvider } from '@lobechat/types';
-import { type StateCreator } from 'zustand/vanilla';
+
+import { type StoreSetter } from '@/store/types';
import type { UserStore } from '../../store';
@@ -8,25 +9,6 @@ interface AuthProvidersData {
providers: SSOProvider[];
}
-export interface UserAuthAction {
- /**
- * Fetch auth providers (SSO accounts) for the current user
- */
- fetchAuthProviders: () => Promise<void>;
- /**
- * universal logout method
- */
- logout: () => Promise<void>;
- /**
- * universal login method
- */
- openLogin: () => Promise<void>;
- /**
- * Refresh auth providers after link/unlink
- */
- refreshAuthProviders: () => Promise<void>;
-}
-
const fetchAuthProvidersData = async (): Promise<AuthProvidersData> => {
const { accountInfo, listAccounts } = await import('@/libs/better-auth/auth-client');
const result = await listAccounts();
@@ -50,25 +32,34 @@ const fetchAuthProvidersData = async (): Promise<AuthProvidersData> => {
return { hasPasswordAccount, providers };
};
-export const createAuthSlice: StateCreator<
- UserStore,
- [['zustand/devtools', never]],
- [],
- UserAuthAction
-> = (set, get) => ({
- fetchAuthProviders: async () => {
+type Setter = StoreSetter<UserStore>;
+export const createAuthSlice = (set: Setter, get: () => UserStore, _api?: unknown) =>
+ new UserAuthActionImpl(set, get, _api);
+
+export class UserAuthActionImpl {
+ readonly #get: () => UserStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ fetchAuthProviders = async (): Promise<void> => {
// Skip if already loaded
- if (get().isLoadedAuthProviders) return;
+ if (this.#get().isLoadedAuthProviders) return;
try {
const { hasPasswordAccount, providers } = await fetchAuthProvidersData();
- set({ authProviders: providers, hasPasswordAccount, isLoadedAuthProviders: true });
+ this.#set({ authProviders: providers, hasPasswordAccount, isLoadedAuthProviders: true });
} catch (error) {
console.error('Failed to fetch auth providers:', error);
- set({ isLoadedAuthProviders: true });
+ this.#set({ isLoadedAuthProviders: true });
}
- },
- logout: async () => {
+ };
+
+ logout = async (): Promise<void> => {
const { signOut } = await import('@/libs/better-auth/auth-client');
await signOut({
fetchOptions: {
@@ -79,8 +70,9 @@ export const createAuthSlice: StateCreator<
},
},
});
- },
- openLogin: async () => {
+ };
+
+ openLogin = async (): Promise<void> => {
// Skip if already on a login page (/signin, /signup)
const pathname = location.pathname;
if (pathname.startsWith('/signin') || pathname.startsWith('/signup')) {
@@ -89,13 +81,16 @@ export const createAuthSlice: StateCreator<
const currentUrl = location.toString();
window.location.href = `/signin?callbackUrl=${encodeURIComponent(currentUrl)}`;
- },
- refreshAuthProviders: async () => {
+ };
+
+ refreshAuthProviders = async (): Promise<void> => {
try {
const { hasPasswordAccount, providers } = await fetchAuthProvidersData();
- set({ authProviders: providers, hasPasswordAccount });
+ this.#set({ authProviders: providers, hasPasswordAccount });
} catch (error) {
console.error('Failed to refresh auth providers:', error);
}
- },
-});
+ };
+}
+
+export type UserAuthAction = Pick<UserAuthActionImpl, keyof UserAuthActionImpl>;
diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.ts
index 5e6afdd873c..cdfc78a99a1 100644
--- a/src/store/user/slices/common/action.test.ts
+++ b/src/store/user/slices/common/action.test.ts
@@ -167,7 +167,7 @@ describe('createCommonSlice', () => {
);
await waitFor(() => {
- expect(preference.current.data.preference).toEqual(savedPreference);
+ expect(preference.current.data?.preference).toEqual(savedPreference);
expect(result.current.isUserStateInit).toBeTruthy();
expect(result.current.preference).toEqual(savedPreference);
});
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index 4ea02bd570d..81eefccdf41 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -2,11 +2,11 @@ import { isDesktop } from '@lobechat/const';
import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
import useSWR, { type SWRResponse } from 'swr';
import type { PartialDeep } from 'type-fest';
-import type { StateCreator } from 'zustand/vanilla';
import { DEFAULT_PREFERENCE } from '@/const/user';
import { mutate, useOnlyFetchOnceSWR } from '@/libs/swr';
import { userService } from '@/services/user';
+import { type StoreSetter } from '@/store/types';
import type { UserStore } from '@/store/user';
import type { GlobalServerConfig } from '@/types/serverConfig';
import { type LobeUser, type UserInitializationState } from '@/types/user';
@@ -22,74 +22,75 @@ const GET_USER_STATE_KEY = 'initUserState';
/**
* Common actions
*/
-export interface CommonAction {
- refreshUserState: () => Promise<void>;
- updateAvatar: (avatar: string) => Promise<void>;
- updateFullName: (fullName: string) => Promise<void>;
- updateInterests: (interests: string[]) => Promise<void>;
- updateKeyVaultConfig: (provider: string, config: any) => Promise<void>;
- updateUsername: (username: string) => Promise<void>;
- useCheckTrace: (shouldFetch: boolean) => SWRResponse;
- useInitUserState: (
- isLogin: boolean | undefined,
- serverConfig: GlobalServerConfig,
- options?: {
- onError?: (error: any) => void;
- onSuccess: (data: UserInitializationState) => void;
- },
- ) => SWRResponse;
-}
-export const createCommonSlice: StateCreator<
- UserStore,
- [['zustand/devtools', never]],
- [],
- CommonAction
-> = (set, get) => ({
- refreshUserState: async () => {
+type Setter = StoreSetter<UserStore>;
+export const createCommonSlice = (set: Setter, get: () => UserStore, _api?: unknown) =>
+ new CommonActionImpl(set, get, _api);
+
+export class CommonActionImpl {
+ readonly #get: () => UserStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ refreshUserState = async (): Promise<void> => {
await mutate(GET_USER_STATE_KEY);
- },
- updateAvatar: async (avatar) => {
+ };
+
+ updateAvatar = async (avatar: string): Promise<void> => {
await userService.updateAvatar(avatar);
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- updateFullName: async (fullName) => {
+ updateFullName = async (fullName: string): Promise<void> => {
await userService.updateFullName(fullName);
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- updateInterests: async (interests) => {
+ updateInterests = async (interests: string[]): Promise<void> => {
await userService.updateInterests(interests);
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- updateKeyVaultConfig: async (provider, config) => {
- await get().setSettings({ keyVaults: { [provider]: config } });
- },
+ updateKeyVaultConfig = async (provider: string, config: any): Promise<void> => {
+ await this.#get().setSettings({ keyVaults: { [provider]: config } });
+ };
- updateUsername: async (username) => {
+ updateUsername = async (username: string): Promise<void> => {
await userService.updateUsername(username);
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- useCheckTrace: (shouldFetch) =>
- useSWR<boolean>(
+ useCheckTrace = (shouldFetch: boolean): SWRResponse<any> => {
+ return useSWR<boolean>(
shouldFetch ? 'checkTrace' : null,
() => {
- const telemetry = userGeneralSettingsSelectors.telemetry(get());
+ const telemetry = userGeneralSettingsSelectors.telemetry(this.#get());
// if user have set the telemetry, return false
if (typeof telemetry === 'boolean') return Promise.resolve(false);
- return Promise.resolve(get().isUserCanEnableTrace);
+ return Promise.resolve(this.#get().isUserCanEnableTrace);
},
{
revalidateOnFocus: false,
},
- ),
- useInitUserState: (isLogin, serverConfig, options) =>
- useOnlyFetchOnceSWR<UserInitializationState>(
+ );
+ };
+
+ useInitUserState = (
+ isLogin: boolean | undefined,
+ serverConfig: GlobalServerConfig,
+ options?: {
+ onError?: (error: any) => void;
+ onSuccess?: (data: UserInitializationState) => void;
+ },
+ ): SWRResponse => {
+ return useOnlyFetchOnceSWR<UserInitializationState>(
!!isLogin || isDesktop ? GET_USER_STATE_KEY : null,
() => userService.getUserState(),
{
@@ -107,7 +108,7 @@ export const createCommonSlice: StateCreator<
systemAgent: serverConfig.systemAgent,
};
- const defaultSettings = merge(get().defaultSettings, serverSettings);
+ const defaultSettings = merge(this.#get().defaultSettings, serverSettings);
// merge preference
const isEmpty = Object.keys(data.preference || {}).length === 0;
@@ -116,7 +117,7 @@ export const createCommonSlice: StateCreator<
// if there is avatar or userId (from client DB), update it into user
const user =
data.avatar || data.userId
- ? merge(get().user, {
+ ? merge(this.#get().user, {
avatar: data.avatar,
email: data.email,
firstName: data.firstName,
@@ -126,9 +127,9 @@ export const createCommonSlice: StateCreator<
latestName: data.lastName,
username: data.username,
} as LobeUser)
- : get().user;
+ : this.#get().user;
- set(
+ this.#set(
{
defaultSettings,
isFreePlan: data.isFreePlan,
@@ -158,5 +159,8 @@ export const createCommonSlice: StateCreator<
}
},
},
- ),
-});
+ );
+ };
+}
+
+export type CommonAction = Pick<CommonActionImpl, keyof CommonActionImpl>;
diff --git a/src/store/user/slices/onboarding/action.ts b/src/store/user/slices/onboarding/action.ts
index 21f9e2a1bb5..226e80a5a53 100644
--- a/src/store/user/slices/onboarding/action.ts
+++ b/src/store/user/slices/onboarding/action.ts
@@ -1,45 +1,30 @@
import { CURRENT_ONBOARDING_VERSION, INBOX_SESSION_ID } from '@lobechat/const';
import { MAX_ONBOARDING_STEPS } from '@lobechat/types';
-import type { StateCreator } from 'zustand/vanilla';
import { userService } from '@/services/user';
import { getAgentStoreState } from '@/store/agent';
+import { type StoreSetter } from '@/store/types';
import type { UserStore } from '@/store/user';
import { settingsSelectors } from '../settings/selectors';
import { onboardingSelectors } from './selectors';
-export interface OnboardingAction {
- finishOnboarding: () => Promise<void>;
- goToNextStep: () => void;
- goToPreviousStep: () => void;
- /**
- * Internal method to process the step update queue
- */
- internal_processStepUpdateQueue: () => Promise<void>;
- /**
- * Internal method to queue a step update
- */
- internal_queueStepUpdate: (step: number) => void;
- setOnboardingStep: (step: number) => Promise<void>;
- /**
- * Toggle plugin in default agent config for onboarding
- */
- toggleInboxAgentDefaultPlugin: (id: string, open?: boolean) => Promise<void>;
- /**
- * Update default model for both user settings and inbox agent
- */
- updateDefaultModel: (model: string, provider: string) => Promise<void>;
-}
+type Setter = StoreSetter<UserStore>;
+export const createOnboardingSlice = (set: Setter, get: () => UserStore, _api?: unknown) =>
+ new OnboardingActionImpl(set, get, _api);
+
+export class OnboardingActionImpl {
+ readonly #get: () => UserStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createOnboardingSlice: StateCreator<
- UserStore,
- [['zustand/devtools', never]],
- [],
- OnboardingAction
-> = (set, get) => ({
- finishOnboarding: async () => {
- const currentStep = onboardingSelectors.currentStep(get());
+ finishOnboarding = async (): Promise<void> => {
+ const currentStep = onboardingSelectors.currentStep(this.#get());
await userService.updateOnboarding({
currentStep,
@@ -47,36 +32,36 @@ export const createOnboardingSlice: StateCreator<
version: CURRENT_ONBOARDING_VERSION,
});
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- goToNextStep: () => {
- const currentStep = onboardingSelectors.currentStep(get());
+ goToNextStep = (): void => {
+ const currentStep = onboardingSelectors.currentStep(this.#get());
if (currentStep === MAX_ONBOARDING_STEPS) return;
const nextStep = currentStep + 1;
- set({ localOnboardingStep: nextStep }, false, 'goToNextStep/optimistic');
- get().internal_queueStepUpdate(nextStep);
- },
+ this.#set({ localOnboardingStep: nextStep }, false, 'goToNextStep/optimistic');
+ this.#get().internal_queueStepUpdate(nextStep);
+ };
- goToPreviousStep: () => {
- const currentStep = onboardingSelectors.currentStep(get());
+ goToPreviousStep = (): void => {
+ const currentStep = onboardingSelectors.currentStep(this.#get());
if (currentStep === 1) return;
const prevStep = currentStep - 1;
- set({ localOnboardingStep: prevStep }, false, 'goToPreviousStep/optimistic');
- get().internal_queueStepUpdate(prevStep);
- },
+ this.#set({ localOnboardingStep: prevStep }, false, 'goToPreviousStep/optimistic');
+ this.#get().internal_queueStepUpdate(prevStep);
+ };
- internal_processStepUpdateQueue: async () => {
- const { isProcessingStepQueue, stepUpdateQueue } = get();
+ internal_processStepUpdateQueue = async (): Promise<void> => {
+ const { isProcessingStepQueue, stepUpdateQueue } = this.#get();
if (isProcessingStepQueue || stepUpdateQueue.length === 0) return;
- set({ isProcessingStepQueue: true }, false, 'processStepUpdateQueue/start');
+ this.#set({ isProcessingStepQueue: true }, false, 'processStepUpdateQueue/start');
- while (get().stepUpdateQueue.length > 0) {
- const step = get().stepUpdateQueue[0];
- const finishedAt = onboardingSelectors.finishedAt(get());
+ while (this.#get().stepUpdateQueue.length > 0) {
+ const step = this.#get().stepUpdateQueue[0];
+ const finishedAt = onboardingSelectors.finishedAt(this.#get());
try {
await userService.updateOnboarding({
@@ -89,51 +74,51 @@ export const createOnboardingSlice: StateCreator<
}
// Remove the completed task
- set(
- { stepUpdateQueue: get().stepUpdateQueue.slice(1) },
+ this.#set(
+ { stepUpdateQueue: this.#get().stepUpdateQueue.slice(1) },
false,
'processStepUpdateQueue/shift',
);
}
- set({ isProcessingStepQueue: false }, false, 'processStepUpdateQueue/end');
+ this.#set({ isProcessingStepQueue: false }, false, 'processStepUpdateQueue/end');
// Sync with server state after all updates complete
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- internal_queueStepUpdate: (step) => {
- const { stepUpdateQueue } = get();
+ internal_queueStepUpdate = (step: number): void => {
+ const { stepUpdateQueue } = this.#get();
if (stepUpdateQueue.length === 0) {
// Queue is empty, add task and start processing
- set({ stepUpdateQueue: [step] }, false, 'queueStepUpdate/push');
- get().internal_processStepUpdateQueue();
+ this.#set({ stepUpdateQueue: [step] }, false, 'queueStepUpdate/push');
+ this.#get().internal_processStepUpdateQueue();
} else if (stepUpdateQueue.length === 1) {
// One task is executing, add as pending
- set({ stepUpdateQueue: [...stepUpdateQueue, step] }, false, 'queueStepUpdate/push');
+ this.#set({ stepUpdateQueue: [...stepUpdateQueue, step] }, false, 'queueStepUpdate/push');
} else {
// Queue is full (length >= 2), replace the pending task
- set({ stepUpdateQueue: [stepUpdateQueue[0], step] }, false, 'queueStepUpdate/replace');
+ this.#set({ stepUpdateQueue: [stepUpdateQueue[0], step] }, false, 'queueStepUpdate/replace');
}
- },
+ };
- setOnboardingStep: async (step) => {
+ setOnboardingStep = async (step: number): Promise<void> => {
// Optimistic update
- set({ localOnboardingStep: step }, false, 'setOnboardingStep/optimistic');
+ this.#set({ localOnboardingStep: step }, false, 'setOnboardingStep/optimistic');
- const finishedAt = onboardingSelectors.finishedAt(get());
+ const finishedAt = onboardingSelectors.finishedAt(this.#get());
await userService.updateOnboarding({
currentStep: step,
finishedAt,
version: CURRENT_ONBOARDING_VERSION,
});
- await get().refreshUserState();
- },
+ await this.#get().refreshUserState();
+ };
- toggleInboxAgentDefaultPlugin: async (id, open) => {
- const currentSettings = settingsSelectors.currentSettings(get());
+ toggleInboxAgentDefaultPlugin = async (id: string, open?: boolean): Promise<void> => {
+ const currentSettings = settingsSelectors.currentSettings(this.#get());
const currentPlugins = currentSettings.defaultAgent?.config?.plugins || [];
const index = currentPlugins.indexOf(id);
@@ -155,17 +140,19 @@ export const createOnboardingSlice: StateCreator<
if (inboxAgentId) {
await agentStore.updateAgentConfigById(inboxAgentId, { plugins: newInboxPlugins });
}
- },
+ };
- updateDefaultModel: async (model, provider) => {
+ updateDefaultModel = async (model: string, provider: string): Promise<void> => {
const agentStore = getAgentStoreState();
const inboxAgentId = agentStore.builtinAgentIdMap[INBOX_SESSION_ID];
await Promise.all([
// 1. Update user settings' defaultAgentConfig
- get().updateDefaultAgent({ config: { model, provider } }),
+ this.#get().updateDefaultAgent({ config: { model, provider } }),
// 2. Update inbox agent's model
inboxAgentId && agentStore.updateAgentConfigById(inboxAgentId, { model, provider }),
]);
- },
-});
+ };
+}
+
+export type OnboardingAction = Pick<OnboardingActionImpl, keyof OnboardingActionImpl>;
diff --git a/src/store/user/slices/preference/action.ts b/src/store/user/slices/preference/action.ts
index 0800dd8911d..e98bda28dfc 100644
--- a/src/store/user/slices/preference/action.ts
+++ b/src/store/user/slices/preference/action.ts
@@ -1,6 +1,5 @@
-import type { StateCreator } from 'zustand/vanilla';
-
import { userService } from '@/services/user';
+import { type StoreSetter } from '@/store/types';
import type { UserStore } from '@/store/user';
import { type UserGuide, type UserLab, type UserPreference } from '@/types/user';
import { merge } from '@/utils/merge';
@@ -8,35 +7,39 @@ import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('preference');
-export interface PreferenceAction {
- updateGuideState: (guide: Partial<UserGuide>) => Promise<void>;
- updateLab: (lab: Partial<UserLab>) => Promise<void>;
- updatePreference: (preference: Partial<UserPreference>, action?: any) => Promise<void>;
-}
+type Setter = StoreSetter<UserStore>;
+export const createPreferenceSlice = (set: Setter, get: () => UserStore, _api?: unknown) =>
+ new PreferenceActionImpl(set, get, _api);
+
+export class PreferenceActionImpl {
+ readonly #get: () => UserStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ updateGuideState = async (guide: Partial<UserGuide>, action?: any): Promise<void> => {
+ const { updatePreference } = this.#get();
+ const nextGuide = merge(this.#get().preference.guide, guide);
+ await updatePreference({ guide: nextGuide }, action);
+ };
-export const createPreferenceSlice: StateCreator<
- UserStore,
- [['zustand/devtools', never]],
- [],
- PreferenceAction
-> = (set, get) => ({
- updateGuideState: async (guide) => {
- const { updatePreference } = get();
- const nextGuide = merge(get().preference.guide, guide);
- await updatePreference({ guide: nextGuide });
- },
-
- updateLab: async (lab) => {
- const { updatePreference } = get();
- const nextLab = merge(get().preference.lab, lab);
- await updatePreference({ lab: nextLab }, n('updateLab'));
- },
-
- updatePreference: async (preference, action) => {
- const nextPreference = merge(get().preference, preference);
-
- set({ preference: nextPreference }, false, action || n('updatePreference'));
+ updateLab = async (lab: Partial<UserLab>, action?: any): Promise<void> => {
+ const { updatePreference } = this.#get();
+ const nextLab = merge(this.#get().preference.lab, lab);
+ await updatePreference({ lab: nextLab }, action || n('updateLab'));
+ };
+
+ updatePreference = async (preference: Partial<UserPreference>, action?: any): Promise<void> => {
+ const nextPreference = merge(this.#get().preference, preference);
+
+ this.#set({ preference: nextPreference }, false, action || n('updatePreference'));
await userService.updatePreference(nextPreference);
- },
-});
+ };
+}
+
+export type PreferenceAction = Pick<PreferenceActionImpl, keyof PreferenceActionImpl>;
diff --git a/src/store/user/slices/settings/action.ts b/src/store/user/slices/settings/action.ts
index d7f9bc1aefe..4e549632de4 100644
--- a/src/store/user/slices/settings/action.ts
+++ b/src/store/user/slices/settings/action.ts
@@ -1,10 +1,10 @@
import isEqual from 'fast-deep-equal';
import type { PartialDeep } from 'type-fest';
-import type { StateCreator } from 'zustand/vanilla';
import { MESSAGE_CANCEL_FLAT } from '@/const/message';
import { shareService } from '@/services/share';
import { userService } from '@/services/user';
+import { type StoreSetter } from '@/store/types';
import type { UserStore } from '@/store/user';
import { type LobeAgentSettings } from '@/types/session';
import {
@@ -17,57 +17,41 @@ import {
import { difference } from '@/utils/difference';
import { merge } from '@/utils/merge';
-export interface UserSettingsAction {
- addToolToAllowList: (toolKey: string) => Promise<void>;
- importAppSettings: (settings: UserSettings) => Promise<void>;
- importUrlShareSettings: (settingsParams: string | null) => Promise<void>;
- internal_createSignal: () => AbortController;
- resetSettings: () => Promise<void>;
- setSettings: (settings: PartialDeep<UserSettings>) => Promise<void>;
- updateDefaultAgent: (agent: PartialDeep<LobeAgentSettings>) => Promise<void>;
- updateGeneralConfig: (settings: Partial<UserGeneralConfig>) => Promise<void>;
- updateHumanIntervention: (config: {
- allowList?: string[];
- approvalMode?: 'auto-run' | 'allow-list' | 'manual';
- }) => Promise<void>;
- updateKeyVaults: (settings: Partial<UserKeyVaults>) => Promise<void>;
+type Setter = StoreSetter<UserStore>;
+export const createSettingsSlice = (set: Setter, get: () => UserStore, _api?: unknown) =>
+ new UserSettingsActionImpl(set, get, _api);
- updateSystemAgent: (
- key: UserSystemAgentConfigKey,
- value: Partial<SystemAgentItem>,
- ) => Promise<void>;
-}
+export class UserSettingsActionImpl {
+ readonly #get: () => UserStore;
+ readonly #set: Setter;
-export const createSettingsSlice: StateCreator<
- UserStore,
- [['zustand/devtools', never]],
- [],
- UserSettingsAction
-> = (set, get) => ({
- addToolToAllowList: async (toolKey) => {
- const currentAllowList = get().settings.tool?.humanIntervention?.allowList || [];
+ constructor(set: Setter, get: () => UserStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ addToolToAllowList = async (toolKey: string): Promise<void> => {
+ const currentAllowList = this.#get().settings.tool?.humanIntervention?.allowList || [];
if (currentAllowList.includes(toolKey)) return;
- await get().setSettings({
+ await this.#get().setSettings({
tool: {
humanIntervention: {
allowList: [...currentAllowList, toolKey],
},
},
});
- },
+ };
- importAppSettings: async (importAppSettings) => {
- const { setSettings } = get();
+ importAppSettings = async (importAppSettings: UserSettings): Promise<void> => {
+ const { setSettings } = this.#get();
await setSettings(importAppSettings);
- },
+ };
- /**
- * Import settings from a string in json format
- */
- importUrlShareSettings: async (settingsParams: string | null) => {
+ importUrlShareSettings = async (settingsParams: string | null): Promise<void> => {
if (settingsParams) {
const importSettings = shareService.decodeShareSettings(settingsParams);
if (importSettings?.message || !importSettings?.data) {
@@ -75,28 +59,29 @@ export const createSettingsSlice: StateCreator<
return;
}
- await get().setSettings(importSettings.data);
+ await this.#get().setSettings(importSettings.data);
}
- },
+ };
- internal_createSignal: () => {
- const abortController = get().updateSettingsSignal;
+ internal_createSignal = (): AbortController => {
+ const abortController = this.#get().updateSettingsSignal;
if (abortController && !abortController.signal.aborted)
abortController.abort(MESSAGE_CANCEL_FLAT);
const newSignal = new AbortController();
- set({ updateSettingsSignal: newSignal }, false, 'signalForUpdateSettings');
+ this.#set({ updateSettingsSignal: newSignal }, false, 'signalForUpdateSettings');
return newSignal;
- },
+ };
- resetSettings: async () => {
+ resetSettings = async (): Promise<void> => {
await userService.resetUserSettings();
- await get().refreshUserState();
- },
- setSettings: async (settings) => {
- const { settings: prevSetting, defaultSettings } = get();
+ await this.#get().refreshUserState();
+ };
+
+ setSettings = async (settings: PartialDeep<UserSettings>): Promise<void> => {
+ const { settings: prevSetting, defaultSettings } = this.#get();
const nextSettings = merge(prevSetting, settings);
@@ -114,32 +99,45 @@ export const createSettingsSlice: StateCreator<
}
}
- set({ settings: diffs }, false, 'optimistic_updateSettings');
+ this.#set({ settings: diffs }, false, 'optimistic_updateSettings');
- const abortController = get().internal_createSignal();
+ const abortController = this.#get().internal_createSignal();
await userService.updateUserSettings(diffs, abortController.signal);
- await get().refreshUserState();
- },
- updateDefaultAgent: async (defaultAgent) => {
- await get().setSettings({ defaultAgent });
- },
- updateGeneralConfig: async (general) => {
- await get().setSettings({ general });
- },
- updateHumanIntervention: async (config) => {
- const current = get().settings.tool?.humanIntervention || {};
- await get().setSettings({
+ await this.#get().refreshUserState();
+ };
+
+ updateDefaultAgent = async (defaultAgent: PartialDeep<LobeAgentSettings>): Promise<void> => {
+ await this.#get().setSettings({ defaultAgent });
+ };
+
+ updateGeneralConfig = async (general: Partial<UserGeneralConfig>): Promise<void> => {
+ await this.#get().setSettings({ general });
+ };
+
+ updateHumanIntervention = async (config: {
+ allowList?: string[];
+ approvalMode?: 'auto-run' | 'allow-list' | 'manual';
+ }): Promise<void> => {
+ const current = this.#get().settings.tool?.humanIntervention || {};
+ await this.#get().setSettings({
tool: {
humanIntervention: { ...current, ...config },
},
});
- },
- updateKeyVaults: async (keyVaults) => {
- await get().setSettings({ keyVaults });
- },
- updateSystemAgent: async (key, value) => {
- await get().setSettings({
+ };
+
+ updateKeyVaults = async (keyVaults: Partial<UserKeyVaults>): Promise<void> => {
+ await this.#get().setSettings({ keyVaults });
+ };
+
+ updateSystemAgent = async (
+ key: UserSystemAgentConfigKey,
+ value: Partial<SystemAgentItem>,
+ ): Promise<void> => {
+ await this.#get().setSettings({
systemAgent: { [key]: { ...value } },
});
- },
-});
+ };
+}
+
+export type UserSettingsAction = Pick<UserSettingsActionImpl, keyof UserSettingsActionImpl>;
diff --git a/src/store/user/store.ts b/src/store/user/store.ts
index 71c2778bf59..0ef7c4700b6 100644
--- a/src/store/user/store.ts
+++ b/src/store/user/store.ts
@@ -4,6 +4,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type UserState, initialState } from './initialState';
import { type UserAuthAction, createAuthSlice } from './slices/auth/action';
import { type CommonAction, createCommonSlice } from './slices/common/action';
@@ -20,13 +21,23 @@ export type UserStore = UserState &
CommonAction &
OnboardingAction;
-const createStore: StateCreator<UserStore, [['zustand/devtools', never]]> = (...parameters) => ({
+type UserStoreAction = UserSettingsAction &
+ PreferenceAction &
+ UserAuthAction &
+ CommonAction &
+ OnboardingAction;
+
+const createStore: StateCreator<UserStore, [['zustand/devtools', never]]> = (
+ ...parameters: Parameters<StateCreator<UserStore, [['zustand/devtools', never]]>>
+) => ({
...initialState,
- ...createSettingsSlice(...parameters),
- ...createPreferenceSlice(...parameters),
- ...createAuthSlice(...parameters),
- ...createCommonSlice(...parameters),
- ...createOnboardingSlice(...parameters),
+ ...flattenActions<UserStoreAction>([
+ createSettingsSlice(...parameters),
+ createPreferenceSlice(...parameters),
+ createAuthSlice(...parameters),
+ createCommonSlice(...parameters),
+ createOnboardingSlice(...parameters),
+ ]),
});
// =============== Implement useStore ============ //
diff --git a/src/store/userMemory/slices/activity/action.ts b/src/store/userMemory/slices/activity/action.ts
index d876d9e2c9f..7de361e407b 100644
--- a/src/store/userMemory/slices/activity/action.ts
+++ b/src/store/userMemory/slices/activity/action.ts
@@ -2,10 +2,10 @@ import type { ActivityListResult } from '@lobechat/types';
import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { userMemoryService } from '@/services/userMemory';
import { memoryCRUDService } from '@/services/userMemory/index';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type UserMemoryStore } from '../../store';
@@ -18,31 +18,35 @@ export interface ActivityQueryParams {
q?: string;
sort?: 'capturedAt' | 'startsAt';
status?: string[];
- types?: string[];
+ types?: string[];
}
-export interface ActivityAction {
- deleteActivity: (id: string) => Promise<void>;
- loadMoreActivities: () => void;
- resetActivitiesList: (params?: Omit<ActivityQueryParams, 'page' | 'pageSize'>) => void;
- useFetchActivities: (params: ActivityQueryParams) => SWRResponse<ActivityListResult>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createActivitySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new ActivityActionImpl(set, get, _api);
+
+export class ActivityActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createActivitySlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- ActivityAction
-> = (set, get) => ({
- deleteActivity: async (id) => {
+ deleteActivity = async (id: string): Promise<void> => {
await memoryCRUDService.deleteActivity(id);
- get().resetActivitiesList({ q: get().activitiesQuery, sort: get().activitiesSort });
- },
+ this.#get().resetActivitiesList({
+ q: this.#get().activitiesQuery,
+ sort: this.#get().activitiesSort,
+ });
+ };
- loadMoreActivities: () => {
- const { activitiesPage, activitiesTotal, activities } = get();
+ loadMoreActivities = (): void => {
+ const { activitiesPage, activitiesTotal, activities } = this.#get();
if (activities.length < (activitiesTotal || 0)) {
- set(
+ this.#set(
produce((draft) => {
draft.activitiesPage = activitiesPage + 1;
}),
@@ -50,10 +54,10 @@ export const createActivitySlice: StateCreator<
n('loadMoreActivities'),
);
}
- },
+ };
- resetActivitiesList: (params) => {
- set(
+ resetActivitiesList = (params?: Omit<ActivityQueryParams, 'page' | 'pageSize'>): void => {
+ this.#set(
produce((draft) => {
draft.activities = [];
draft.activitiesPage = 1;
@@ -64,9 +68,9 @@ export const createActivitySlice: StateCreator<
false,
n('resetActivitiesList'),
);
- },
+ };
- useFetchActivities: (params) => {
+ useFetchActivities = (params: ActivityQueryParams): SWRResponse<ActivityListResult> => {
const swrKeyParts = [
'useFetchActivities',
params.page,
@@ -94,8 +98,8 @@ export const createActivitySlice: StateCreator<
});
},
{
- onSuccess(data: ActivityListResult) {
- set(
+ onSuccess: (data: ActivityListResult) => {
+ this.#set(
produce((draft) => {
draft.activitiesSearchLoading = false;
draft.activitiesTotal = data.total;
@@ -119,5 +123,7 @@ export const createActivitySlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type ActivityAction = Pick<ActivityActionImpl, keyof ActivityActionImpl>;
diff --git a/src/store/userMemory/slices/activity/index.ts b/src/store/userMemory/slices/activity/index.ts
index fdf48a10cb6..787b5379044 100644
--- a/src/store/userMemory/slices/activity/index.ts
+++ b/src/store/userMemory/slices/activity/index.ts
@@ -1,2 +1,2 @@
-export { type ActivityAction,createActivitySlice } from './action';
+export { type ActivityAction, createActivitySlice } from './action';
export { activityInitialState, type ActivitySliceState } from './initialState';
diff --git a/src/store/userMemory/slices/agent/action.ts b/src/store/userMemory/slices/agent/action.ts
index 728a5b50237..c215b152bf2 100644
--- a/src/store/userMemory/slices/agent/action.ts
+++ b/src/store/userMemory/slices/agent/action.ts
@@ -1,9 +1,9 @@
import { omit } from 'es-toolkit';
import type { SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { userMemoryService } from '@/services/userMemory';
+import { type StoreSetter } from '@/store/types';
import type { RetrieveMemoryResult } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
@@ -11,35 +11,30 @@ import { type UserMemoryStore } from '../../store';
const n = setNamespace('userMemory/agent');
-export interface AgentMemoryAction {
- /**
- * Clear memories for a specific topic (e.g., when topic is deleted)
- */
- clearTopicMemories: (topicId: string) => void;
+type Setter = StoreSetter<UserMemoryStore>;
+export const createAgentMemorySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new AgentMemoryActionImpl(set, get, _api);
- /**
- * Fetch and cache memories for a specific topic
- * Uses SWR for caching and revalidation
- */
- useFetchMemoriesForTopic: (topicId?: string | null) => SWRResponse<RetrieveMemoryResult>;
-}
+export class AgentMemoryActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createAgentMemorySlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- AgentMemoryAction
-> = (set, get) => ({
- clearTopicMemories: (topicId) => {
- set(
- { topicMemoriesMap: omit(get().topicMemoriesMap, [topicId]) },
+ clearTopicMemories = (topicId: string): void => {
+ this.#set(
+ { topicMemoriesMap: omit(this.#get().topicMemoriesMap, [topicId]) },
false,
n('clearTopicMemories', { topicId }),
);
- },
+ };
- useFetchMemoriesForTopic: (topicId) =>
- useClientDataSWRWithSync<RetrieveMemoryResult>(
+ useFetchMemoriesForTopic = (topicId?: string | null): SWRResponse<RetrieveMemoryResult> => {
+ return useClientDataSWRWithSync<RetrieveMemoryResult>(
topicId ? ['useFetchMemoriesForTopic', topicId] : null,
async () => {
// Retrieve memories using topic's context
@@ -50,7 +45,7 @@ export const createAgentMemorySlice: StateCreator<
onData: (data) => {
if (!topicId || !data) return;
- set(
+ this.#set(
(state) => ({
topicMemoriesMap: { ...state.topicMemoriesMap, [topicId]: data },
}),
@@ -66,5 +61,8 @@ export const createAgentMemorySlice: StateCreator<
},
revalidateOnFocus: false,
},
- ),
-});
+ );
+ };
+}
+
+export type AgentMemoryAction = Pick<AgentMemoryActionImpl, keyof AgentMemoryActionImpl>;
diff --git a/src/store/userMemory/slices/agent/selectors.ts b/src/store/userMemory/slices/agent/selectors.ts
index 0ab0e2a15b0..71b8cce4220 100644
--- a/src/store/userMemory/slices/agent/selectors.ts
+++ b/src/store/userMemory/slices/agent/selectors.ts
@@ -3,22 +3,20 @@ import type { RetrieveMemoryResult } from '@/types/userMemory';
import type { UserMemoryStoreState } from '../../initialState';
export const agentMemorySelectors = {
-
/**
* Check if memories exist for a specific topic
*/
-hasTopicMemories:
+ hasTopicMemories:
(topicId: string | undefined) =>
(state: UserMemoryStoreState): boolean => {
if (!topicId) return false;
return !!state.topicMemoriesMap[topicId];
},
-
/**
* Get memories for a specific topic
*/
-topicMemories:
+ topicMemories:
(topicId: string | undefined) =>
(state: UserMemoryStoreState): RetrieveMemoryResult | undefined => {
if (!topicId) return undefined;
diff --git a/src/store/userMemory/slices/base/action.ts b/src/store/userMemory/slices/base/action.ts
index 88f8a6426f2..3b22d00d4c3 100644
--- a/src/store/userMemory/slices/base/action.ts
+++ b/src/store/userMemory/slices/base/action.ts
@@ -1,10 +1,10 @@
import isEqual from 'fast-deep-equal';
import type { SWRResponse } from 'swr';
import useSWR from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
import { userMemoryService } from '@/services/userMemory';
+import { type StoreSetter } from '@/store/types';
import { LayersEnum } from '@/types/userMemory';
import type { RetrieveMemoryParams, RetrieveMemoryResult } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
@@ -19,36 +19,22 @@ const n = setNamespace('userMemory');
type MemoryContext = Parameters<typeof createMemorySearchParams>[0];
-export interface BaseAction {
- clearEditingMemory: () => void;
- refreshUserMemory: (params: RetrieveMemoryParams) => Promise<void>;
- setActiveMemoryContext: (context?: MemoryContext) => void;
- setEditingMemory: (
- id: string,
- content: string,
- layer: 'activity' | 'context' | 'experience' | 'identity' | 'preference',
- ) => void;
- updateMemory: (id: string, content: string, layer: LayersEnum) => Promise<void>;
- useFetchMemoryDetail: (id: string | null, layer: LayersEnum) => SWRResponse<any>;
- useFetchUserMemory: (
- enable: boolean,
- params?: RetrieveMemoryParams,
- ) => SWRResponse<RetrieveMemoryResult>;
- /**
- * Initialize global identities at app startup
- * Fetches up to 50 most recent identities for chat context injection
- */
- useInitIdentities: (isLogin: boolean) => SWRResponse<any>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createBaseSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new BaseActionImpl(set, get, _api);
+
+export class BaseActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createBaseSlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- BaseAction
-> = (set, get) => ({
- clearEditingMemory: () => {
- set(
+ clearEditingMemory = (): void => {
+ this.#set(
{
editingMemoryContent: undefined,
editingMemoryId: undefined,
@@ -57,27 +43,31 @@ export const createBaseSlice: StateCreator<
false,
n('clearEditingMemory'),
);
- },
+ };
- refreshUserMemory: async (params) => {
+ refreshUserMemory = async (params: RetrieveMemoryParams): Promise<void> => {
const key = userMemoryCacheKey(params);
await mutate([SWR_FETCH_USER_MEMORY, key]);
- },
+ };
- setActiveMemoryContext: (context) => {
+ setActiveMemoryContext = (context?: MemoryContext): void => {
const params = context ? createMemorySearchParams(context) : undefined;
const key = params ? userMemoryCacheKey(params) : undefined;
- set(
+ this.#set(
{ activeParams: params, activeParamsKey: key },
false,
n('setActiveMemoryContext', { key }),
);
- },
+ };
- setEditingMemory: (id, content, layer) => {
- set(
+ setEditingMemory = (
+ id: string,
+ content: string,
+ layer: 'activity' | 'context' | 'experience' | 'identity' | 'preference',
+ ): void => {
+ this.#set(
{
editingMemoryContent: content,
editingMemoryId: id,
@@ -86,9 +76,9 @@ export const createBaseSlice: StateCreator<
false,
n('setEditingMemory', { id, layer }),
);
- },
+ };
- updateMemory: async (id, content, layer) => {
+ updateMemory = async (id: string, content: string, layer: LayersEnum): Promise<void> => {
const { memoryCRUDService } = await import('@/services/userMemory');
const {
resetActivitiesList,
@@ -96,42 +86,48 @@ export const createBaseSlice: StateCreator<
resetExperiencesList,
resetIdentitiesList,
resetPreferencesList,
- } = get();
+ } = this.#get();
// Update the memory content based on layer
switch (layer) {
case LayersEnum.Activity: {
await memoryCRUDService.updateActivity(id, { narrative: content });
- resetActivitiesList({ q: get().activitiesQuery, sort: get().activitiesSort });
+ resetActivitiesList({ q: this.#get().activitiesQuery, sort: this.#get().activitiesSort });
break;
}
case LayersEnum.Context: {
await memoryCRUDService.updateContext(id, { description: content });
- resetContextsList({ q: get().contextsQuery, sort: get().contextsSort });
+ resetContextsList({ q: this.#get().contextsQuery, sort: this.#get().contextsSort });
break;
}
case LayersEnum.Experience: {
await memoryCRUDService.updateExperience(id, { keyLearning: content });
- resetExperiencesList({ q: get().experiencesQuery, sort: get().experiencesSort });
+ resetExperiencesList({
+ q: this.#get().experiencesQuery,
+ sort: this.#get().experiencesSort,
+ });
break;
}
case LayersEnum.Identity: {
await memoryCRUDService.updateIdentity(id, { description: content });
- resetIdentitiesList({ q: get().identitiesQuery, types: get().identitiesTypes });
+ resetIdentitiesList({ q: this.#get().identitiesQuery, types: this.#get().identitiesTypes });
break;
}
case LayersEnum.Preference: {
await memoryCRUDService.updatePreference(id, { conclusionDirectives: content });
- resetPreferencesList({ q: get().preferencesQuery, sort: get().preferencesSort });
+ resetPreferencesList({
+ q: this.#get().preferencesQuery,
+ sort: this.#get().preferencesSort,
+ });
break;
}
}
// Clear editing state
- get().clearEditingMemory();
- },
+ this.#get().clearEditingMemory();
+ };
- useFetchMemoryDetail: (id, layer) => {
+ useFetchMemoryDetail = (id: string | null, layer: LayersEnum): SWRResponse<any> => {
const swrKey = id ? `memoryDetail-${layer}-${id}` : null;
return useSWR(
@@ -208,10 +204,13 @@ export const createBaseSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
+ };
- useFetchUserMemory: (enable, params) => {
- const resolvedParams = params ?? get().activeParams;
+ useFetchUserMemory = (
+ enable: boolean,
+ params?: RetrieveMemoryParams,
+ ): SWRResponse<RetrieveMemoryResult> => {
+ const resolvedParams = params ?? this.#get().activeParams;
const key = resolvedParams ? userMemoryCacheKey(resolvedParams) : undefined;
return useClientDataSWR<RetrieveMemoryResult>(
@@ -221,13 +220,13 @@ export const createBaseSlice: StateCreator<
onSuccess: (result) => {
if (!resolvedParams || !key) return;
- const state = get();
+ const state = this.#get();
const previous = state.memoryMap[key];
const next = result ?? { activities: [], contexts: [], experiences: [], preferences: [] };
const fetchedAt = Date.now();
if (previous && isEqual(previous, next)) {
- set(
+ this.#set(
{
memoryFetchedAtMap: {
...state.memoryFetchedAtMap,
@@ -249,7 +248,7 @@ export const createBaseSlice: StateCreator<
return;
}
- set(
+ this.#set(
{
memoryFetchedAtMap: {
...state.memoryFetchedAtMap,
@@ -274,9 +273,9 @@ export const createBaseSlice: StateCreator<
},
},
);
- },
+ };
- useInitIdentities: (isLogin) => {
+ useInitIdentities = (isLogin: boolean): SWRResponse<any> => {
return useClientDataSWRWithSync<IdentityForInjection[]>(
isLogin ? 'useInitIdentities' : null,
// Use dedicated API that filters for self identities only
@@ -287,7 +286,7 @@ export const createBaseSlice: StateCreator<
const fetchedAt = Date.now();
- set(
+ this.#set(
{
globalIdentities: data,
globalIdentitiesFetchedAt: fetchedAt,
@@ -299,5 +298,7 @@ export const createBaseSlice: StateCreator<
},
},
);
- },
-});
+ };
+}
+
+export type BaseAction = Pick<BaseActionImpl, keyof BaseActionImpl>;
diff --git a/src/store/userMemory/slices/base/index.ts b/src/store/userMemory/slices/base/index.ts
index 23c8874230c..ceb887490ed 100644
--- a/src/store/userMemory/slices/base/index.ts
+++ b/src/store/userMemory/slices/base/index.ts
@@ -1 +1 @@
-export { type BaseAction,createBaseSlice } from './action';
+export { type BaseAction, createBaseSlice } from './action';
diff --git a/src/store/userMemory/slices/context/action.ts b/src/store/userMemory/slices/context/action.ts
index a3a7e653a69..1459411d265 100644
--- a/src/store/userMemory/slices/context/action.ts
+++ b/src/store/userMemory/slices/context/action.ts
@@ -1,10 +1,11 @@
import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
+import { type DisplayContextMemory } from '@/database/repositories/userMemory';
import { userMemoryService } from '@/services/userMemory';
import { memoryCRUDService } from '@/services/userMemory/index';
+import { type StoreSetter } from '@/store/types';
import { LayersEnum } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
@@ -19,29 +20,30 @@ export interface ContextQueryParams {
sort?: 'capturedAt' | 'scoreImpact' | 'scoreUrgency';
}
-export interface ContextAction {
- deleteContext: (id: string) => Promise<void>;
- loadMoreContexts: () => void;
- resetContextsList: (params?: Omit<ContextQueryParams, 'page' | 'pageSize'>) => void;
- useFetchContexts: (params: ContextQueryParams) => SWRResponse<any>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createContextSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new ContextActionImpl(set, get, _api);
+
+export class ContextActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createContextSlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- ContextAction
-> = (set, get) => ({
- deleteContext: async (id) => {
+ deleteContext = async (id: string): Promise<void> => {
await memoryCRUDService.deleteContext(id);
// Reset list to refresh
- get().resetContextsList({ q: get().contextsQuery, sort: get().contextsSort });
- },
+ this.#get().resetContextsList({ q: this.#get().contextsQuery, sort: this.#get().contextsSort });
+ };
- loadMoreContexts: () => {
- const { contextsPage, contextsTotal, contexts } = get();
+ loadMoreContexts = (): void => {
+ const { contextsPage, contextsTotal, contexts } = this.#get();
if (contexts.length < (contextsTotal || 0)) {
- set(
+ this.#set(
produce((draft) => {
draft.contextsPage = contextsPage + 1;
}),
@@ -49,10 +51,10 @@ export const createContextSlice: StateCreator<
n('loadMoreContexts'),
);
}
- },
+ };
- resetContextsList: (params) => {
- set(
+ resetContextsList = (params?: Omit<ContextQueryParams, 'page' | 'pageSize'>): void => {
+ this.#set(
produce((draft) => {
draft.contexts = [];
draft.contextsPage = 1;
@@ -63,9 +65,9 @@ export const createContextSlice: StateCreator<
false,
n('resetContextsList'),
);
- },
+ };
- useFetchContexts: (params) => {
+ useFetchContexts = (params: ContextQueryParams): SWRResponse<any> => {
const swrKeyParts = ['useFetchContexts', params.page, params.pageSize, params.q, params.sort];
const swrKey = swrKeyParts
.filter((part) => part !== undefined && part !== null && part !== '')
@@ -86,8 +88,8 @@ export const createContextSlice: StateCreator<
return result;
},
{
- onSuccess(data: any) {
- set(
+ onSuccess: (data: any) => {
+ this.#set(
produce((draft) => {
draft.contextsSearchLoading = false;
@@ -98,7 +100,7 @@ export const createContextSlice: StateCreator<
}
// Transform data structure
- const transformedItems = data.items.map((item: any) => ({
+ const transformedItems: DisplayContextMemory[] = data.items.map((item: any) => ({
...item.memory,
...item.context,
source: null,
@@ -123,5 +125,7 @@ export const createContextSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type ContextAction = Pick<ContextActionImpl, keyof ContextActionImpl>;
diff --git a/src/store/userMemory/slices/context/index.ts b/src/store/userMemory/slices/context/index.ts
index f6e181b7305..ba0739d5f2d 100644
--- a/src/store/userMemory/slices/context/index.ts
+++ b/src/store/userMemory/slices/context/index.ts
@@ -1,2 +1,2 @@
-export { type ContextAction,createContextSlice } from './action';
+export { type ContextAction, createContextSlice } from './action';
export { contextInitialState, type ContextSliceState } from './initialState';
diff --git a/src/store/userMemory/slices/experience/action.ts b/src/store/userMemory/slices/experience/action.ts
index a71c9099321..00aa1100f02 100644
--- a/src/store/userMemory/slices/experience/action.ts
+++ b/src/store/userMemory/slices/experience/action.ts
@@ -2,10 +2,10 @@ import type { ExperienceListResult } from '@lobechat/types';
import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { userMemoryService } from '@/services/userMemory';
import { memoryCRUDService } from '@/services/userMemory/index';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type UserMemoryStore } from '../../store';
@@ -19,29 +19,33 @@ export interface ExperienceQueryParams {
sort?: 'capturedAt' | 'scoreConfidence';
}
-export interface ExperienceAction {
- deleteExperience: (id: string) => Promise<void>;
- loadMoreExperiences: () => void;
- resetExperiencesList: (params?: Omit<ExperienceQueryParams, 'page' | 'pageSize'>) => void;
- useFetchExperiences: (params: ExperienceQueryParams) => SWRResponse<ExperienceListResult>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createExperienceSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new ExperienceActionImpl(set, get, _api);
+
+export class ExperienceActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createExperienceSlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- ExperienceAction
-> = (set, get) => ({
- deleteExperience: async (id) => {
+ deleteExperience = async (id: string): Promise<void> => {
await memoryCRUDService.deleteExperience(id);
// Reset list to refresh
- get().resetExperiencesList({ q: get().experiencesQuery, sort: get().experiencesSort });
- },
+ this.#get().resetExperiencesList({
+ q: this.#get().experiencesQuery,
+ sort: this.#get().experiencesSort,
+ });
+ };
- loadMoreExperiences: () => {
- const { experiencesPage, experiencesTotal, experiences } = get();
+ loadMoreExperiences = (): void => {
+ const { experiencesPage, experiencesTotal, experiences } = this.#get();
if (experiences.length < (experiencesTotal || 0)) {
- set(
+ this.#set(
produce((draft) => {
draft.experiencesPage = experiencesPage + 1;
}),
@@ -49,10 +53,10 @@ export const createExperienceSlice: StateCreator<
n('loadMoreExperiences'),
);
}
- },
+ };
- resetExperiencesList: (params) => {
- set(
+ resetExperiencesList = (params?: Omit<ExperienceQueryParams, 'page' | 'pageSize'>): void => {
+ this.#set(
produce((draft) => {
draft.experiences = [];
draft.experiencesPage = 1;
@@ -63,9 +67,9 @@ export const createExperienceSlice: StateCreator<
false,
n('resetExperiencesList'),
);
- },
+ };
- useFetchExperiences: (params) => {
+ useFetchExperiences = (params: ExperienceQueryParams): SWRResponse<ExperienceListResult> => {
const swrKeyParts = [
'useFetchExperiences',
params.page,
@@ -90,8 +94,8 @@ export const createExperienceSlice: StateCreator<
});
},
{
- onSuccess(data: ExperienceListResult) {
- set(
+ onSuccess: (data: ExperienceListResult) => {
+ this.#set(
produce((draft) => {
draft.experiencesSearchLoading = false;
draft.experiencesTotal = data.total;
@@ -116,5 +120,7 @@ export const createExperienceSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type ExperienceAction = Pick<ExperienceActionImpl, keyof ExperienceActionImpl>;
diff --git a/src/store/userMemory/slices/home/action.ts b/src/store/userMemory/slices/home/action.ts
index f1bd8e34e86..03dc7388cc7 100644
--- a/src/store/userMemory/slices/home/action.ts
+++ b/src/store/userMemory/slices/home/action.ts
@@ -1,9 +1,9 @@
import { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { type QueryIdentityRolesResult } from '@/database/models/userMemory';
import { useClientDataSWR } from '@/libs/swr';
import { userMemoryService } from '@/services/userMemory';
+import { type StoreSetter } from '@/store/types';
import { type PersonaData } from '../../initialState';
import type { UserMemoryStore } from '../../store';
@@ -12,33 +12,37 @@ const FETCH_TAGS_KEY = 'useFetchTags';
const FETCH_PERSONA_KEY = 'useFetchPersona';
const n = (namespace: string) => namespace;
-export interface HomeAction {
- useFetchPersona: () => SWRResponse<PersonaData | null>;
- useFetchTags: () => SWRResponse<QueryIdentityRolesResult>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createHomeSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new HomeActionImpl(set, get, _api);
+
+export class HomeActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createHomeSlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- HomeAction
-> = (set) => ({
- useFetchPersona: () =>
- useClientDataSWR(FETCH_PERSONA_KEY, () => userMemoryService.getPersona(), {
- onSuccess: (data: PersonaData | null | undefined) => {
- set(
+ useFetchPersona = (): SWRResponse<PersonaData> => {
+ return useClientDataSWR(FETCH_PERSONA_KEY, () => userMemoryService.getPersona(), {
+ onSuccess: (data: PersonaData | undefined) => {
+ this.#set(
{
- persona: data ?? undefined,
+ persona: data,
personaInit: true,
},
false,
n('useFetchPersona/onSuccess'),
);
},
- }),
+ });
+ };
- useFetchTags: () =>
- useClientDataSWR(
+ useFetchTags = (): SWRResponse<QueryIdentityRolesResult> => {
+ return useClientDataSWR(
FETCH_TAGS_KEY,
() =>
userMemoryService.queryIdentityRoles({
@@ -47,7 +51,7 @@ export const createHomeSlice: StateCreator<
}),
{
onSuccess: (data: QueryIdentityRolesResult | undefined) => {
- set(
+ this.#set(
{
roles: data?.roles.map((item) => ({ count: item.count, tag: item.role })) || [],
tags: data?.tags || [],
@@ -58,5 +62,8 @@ export const createHomeSlice: StateCreator<
);
},
},
- ),
-});
+ );
+ };
+}
+
+export type HomeAction = Pick<HomeActionImpl, keyof HomeActionImpl>;
diff --git a/src/store/userMemory/slices/identity/action.ts b/src/store/userMemory/slices/identity/action.ts
index a0cf3a341ba..1a7841ab3a4 100644
--- a/src/store/userMemory/slices/identity/action.ts
+++ b/src/store/userMemory/slices/identity/action.ts
@@ -6,10 +6,10 @@ import {
import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
import { type AddIdentityEntryResult } from '@/database/models/userMemory';
import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
+import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type UserMemoryStore } from '../../store';
@@ -25,48 +25,47 @@ export interface IdentityQueryParams {
types?: string[];
}
-export interface IdentityAction {
- createIdentity: (data: NewUserMemoryIdentity) => Promise<AddIdentityEntryResult>;
- deleteIdentity: (id: string) => Promise<void>;
- loadMoreIdentities: () => void;
- resetIdentitiesList: (params?: Omit<IdentityQueryParams, 'page' | 'pageSize'>) => void;
- updateIdentity: (id: string, data: UpdateUserMemoryIdentity) => Promise<boolean>;
- useFetchIdentities: (params: IdentityQueryParams) => SWRResponse<IdentityListResult>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createIdentitySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new IdentityActionImpl(set, get, _api);
+
+export class IdentityActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createIdentitySlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- IdentityAction
-> = (set, get) => ({
- createIdentity: async (data) => {
+ createIdentity = async (data: NewUserMemoryIdentity): Promise<AddIdentityEntryResult> => {
const result = await memoryCRUDService.createIdentity(data);
// Reset list to refresh
- get().resetIdentitiesList({
- q: get().identitiesQuery,
- relationships: get().identitiesRelationships,
- sort: get().identitiesSort,
- types: get().identitiesTypes,
+ this.#get().resetIdentitiesList({
+ q: this.#get().identitiesQuery,
+ relationships: this.#get().identitiesRelationships,
+ sort: this.#get().identitiesSort,
+ types: this.#get().identitiesTypes,
});
return result;
- },
+ };
- deleteIdentity: async (id) => {
+ deleteIdentity = async (id: string): Promise<void> => {
await memoryCRUDService.deleteIdentity(id);
// Reset list to refresh
- get().resetIdentitiesList({
- q: get().identitiesQuery,
- relationships: get().identitiesRelationships,
- sort: get().identitiesSort,
- types: get().identitiesTypes,
+ this.#get().resetIdentitiesList({
+ q: this.#get().identitiesQuery,
+ relationships: this.#get().identitiesRelationships,
+ sort: this.#get().identitiesSort,
+ types: this.#get().identitiesTypes,
});
- },
+ };
- loadMoreIdentities: () => {
- const { identitiesPage, identitiesTotal, identities } = get();
+ loadMoreIdentities = (): void => {
+ const { identitiesPage, identitiesTotal, identities } = this.#get();
if (identities.length < (identitiesTotal || 0)) {
- set(
+ this.#set(
produce((draft) => {
draft.identitiesPage = identitiesPage + 1;
}),
@@ -74,10 +73,10 @@ export const createIdentitySlice: StateCreator<
n('loadMoreIdentities'),
);
}
- },
+ };
- resetIdentitiesList: (params) => {
- set(
+ resetIdentitiesList = (params?: Omit<IdentityQueryParams, 'page' | 'pageSize'>): void => {
+ this.#set(
produce((draft) => {
draft.identities = [];
draft.identitiesPage = 1;
@@ -90,21 +89,21 @@ export const createIdentitySlice: StateCreator<
false,
n('resetIdentitiesList'),
);
- },
+ };
- updateIdentity: async (id, data) => {
+ updateIdentity = async (id: string, data: UpdateUserMemoryIdentity): Promise<boolean> => {
const result = await memoryCRUDService.updateIdentity(id, data);
// Reset list to refresh
- get().resetIdentitiesList({
- q: get().identitiesQuery,
- relationships: get().identitiesRelationships,
- sort: get().identitiesSort,
- types: get().identitiesTypes,
+ this.#get().resetIdentitiesList({
+ q: this.#get().identitiesQuery,
+ relationships: this.#get().identitiesRelationships,
+ sort: this.#get().identitiesSort,
+ types: this.#get().identitiesTypes,
});
return result;
- },
+ };
- useFetchIdentities: (params) => {
+ useFetchIdentities = (params: IdentityQueryParams): SWRResponse<IdentityListResult> => {
const swrKeyParts = [
'useFetchIdentities',
params.page,
@@ -133,8 +132,8 @@ export const createIdentitySlice: StateCreator<
});
},
{
- onSuccess(data: IdentityListResult) {
- set(
+ onSuccess: (data: IdentityListResult) => {
+ this.#set(
produce((draft) => {
draft.identitiesSearchLoading = false;
draft.identitiesTotal = data.total;
@@ -159,5 +158,7 @@ export const createIdentitySlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type IdentityAction = Pick<IdentityActionImpl, keyof IdentityActionImpl>;
diff --git a/src/store/userMemory/slices/preference/action.ts b/src/store/userMemory/slices/preference/action.ts
index 18cd4d9187c..50a1fd0cae3 100644
--- a/src/store/userMemory/slices/preference/action.ts
+++ b/src/store/userMemory/slices/preference/action.ts
@@ -1,10 +1,11 @@
import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import useSWR, { type SWRResponse } from 'swr';
-import { type StateCreator } from 'zustand/vanilla';
+import { type DisplayPreferenceMemory } from '@/database/repositories/userMemory';
import { userMemoryService } from '@/services/userMemory';
import { memoryCRUDService } from '@/services/userMemory/index';
+import { type StoreSetter } from '@/store/types';
import { LayersEnum } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
@@ -19,29 +20,33 @@ export interface PreferenceQueryParams {
sort?: 'capturedAt' | 'scorePriority';
}
-export interface PreferenceAction {
- deletePreference: (id: string) => Promise<void>;
- loadMorePreferences: () => void;
- resetPreferencesList: (params?: Omit<PreferenceQueryParams, 'page' | 'pageSize'>) => void;
- useFetchPreferences: (params: PreferenceQueryParams) => SWRResponse<any>;
-}
+type Setter = StoreSetter<UserMemoryStore>;
+export const createPreferenceSlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new PreferenceActionImpl(set, get, _api);
+
+export class PreferenceActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
-export const createPreferenceSlice: StateCreator<
- UserMemoryStore,
- [['zustand/devtools', never]],
- [],
- PreferenceAction
-> = (set, get) => ({
- deletePreference: async (id) => {
+ deletePreference = async (id: string): Promise<void> => {
await memoryCRUDService.deletePreference(id);
// Reset list to refresh
- get().resetPreferencesList({ q: get().preferencesQuery, sort: get().preferencesSort });
- },
+ this.#get().resetPreferencesList({
+ q: this.#get().preferencesQuery,
+ sort: this.#get().preferencesSort,
+ });
+ };
- loadMorePreferences: () => {
- const { preferencesPage, preferencesTotal, preferences } = get();
+ loadMorePreferences = (): void => {
+ const { preferencesPage, preferencesTotal, preferences } = this.#get();
if (preferences.length < (preferencesTotal || 0)) {
- set(
+ this.#set(
produce((draft) => {
draft.preferencesPage = preferencesPage + 1;
}),
@@ -49,10 +54,10 @@ export const createPreferenceSlice: StateCreator<
n('loadMorePreferences'),
);
}
- },
+ };
- resetPreferencesList: (params) => {
- set(
+ resetPreferencesList = (params?: Omit<PreferenceQueryParams, 'page' | 'pageSize'>): void => {
+ this.#set(
produce((draft) => {
draft.preferences = [];
draft.preferencesPage = 1;
@@ -63,9 +68,9 @@ export const createPreferenceSlice: StateCreator<
false,
n('resetPreferencesList'),
);
- },
+ };
- useFetchPreferences: (params) => {
+ useFetchPreferences = (params: PreferenceQueryParams): SWRResponse<any> => {
const swrKeyParts = [
'useFetchPreferences',
params.page,
@@ -92,8 +97,8 @@ export const createPreferenceSlice: StateCreator<
return result;
},
{
- onSuccess(data: any) {
- set(
+ onSuccess: (data: any) => {
+ this.#set(
produce((draft) => {
draft.preferencesSearchLoading = false;
@@ -104,7 +109,7 @@ export const createPreferenceSlice: StateCreator<
}
// Transform data structure
- const transformedItems = data.items.map((item: any) => ({
+ const transformedItems: DisplayPreferenceMemory[] = data.items.map((item: any) => ({
...item.memory,
...item.preference,
}));
@@ -128,5 +133,7 @@ export const createPreferenceSlice: StateCreator<
revalidateOnFocus: false,
},
);
- },
-});
+ };
+}
+
+export type PreferenceAction = Pick<PreferenceActionImpl, keyof PreferenceActionImpl>;
diff --git a/src/store/userMemory/store.ts b/src/store/userMemory/store.ts
index 9cce6dc8ca3..8356d33181b 100644
--- a/src/store/userMemory/store.ts
+++ b/src/store/userMemory/store.ts
@@ -3,6 +3,7 @@ import { createWithEqualityFn } from 'zustand/traditional';
import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
+import { flattenActions } from '../utils/flattenActions';
import { type UserMemoryStoreState, initialState } from './initialState';
import { type ActivityAction, createActivitySlice } from './slices/activity';
import { type AgentMemoryAction, createAgentMemorySlice } from './slices/agent';
@@ -23,20 +24,31 @@ export type UserMemoryStore = UserMemoryStoreState &
IdentityAction &
PreferenceAction;
+type UserMemoryStoreAction = ActivityAction &
+ AgentMemoryAction &
+ BaseAction &
+ ContextAction &
+ ExperienceAction &
+ HomeAction &
+ IdentityAction &
+ PreferenceAction;
+
const createStore: StateCreator<UserMemoryStore, [['zustand/devtools', never]]> = (
- set,
- get,
- store,
+ set: any,
+ get: any,
+ store: any,
) => ({
...initialState,
- ...createActivitySlice(set, get, store),
- ...createAgentMemorySlice(set, get, store),
- ...createBaseSlice(set, get, store),
- ...createContextSlice(set, get, store),
- ...createExperienceSlice(set, get, store),
- ...createHomeSlice(set, get, store),
- ...createIdentitySlice(set, get, store),
- ...createPreferenceSlice(set, get, store),
+ ...flattenActions<UserMemoryStoreAction>([
+ createActivitySlice(set, get, store),
+ createAgentMemorySlice(set, get, store),
+ createBaseSlice(set, get, store),
+ createContextSlice(set, get, store),
+ createExperienceSlice(set, get, store),
+ createHomeSlice(set, get, store),
+ createIdentitySlice(set, get, store),
+ createPreferenceSlice(set, get, store),
+ ]),
});
const devtools = createDevtools('userMemory');
diff --git a/src/store/utils/flattenActions.ts b/src/store/utils/flattenActions.ts
new file mode 100644
index 00000000000..e66a11805aa
--- /dev/null
+++ b/src/store/utils/flattenActions.ts
@@ -0,0 +1,52 @@
+/**
+ * 将多个 action 对象(通常是 class 实例)扁平化为一个普通对象
+ *
+ * 解决 class 实例无法通过 spread 操作符正确复制 prototype 方法的问题
+ * 通过反射遍历 prototype chain,提取所有 public methods 并绑定 this 上下文
+ *
+ * @param actions - action 对象数组(通常是 class 实例)
+ * @returns 包含所有 action 方法的普通对象
+ *
+ * @example
+ * ```ts
+ * const store = {
+ * ...initialState,
+ * ...flattenActions([slice1(...params), slice2(...params)]),
+ * };
+ * ```
+ */
+export const flattenActions = <T extends object>(actions: object[]): T => {
+ const result = {} as T;
+
+ for (const action of actions) {
+ // 遍历 prototype chain 获取所有方法
+ let current: object | null = action;
+ while (current && current !== Object.prototype) {
+ const keys = Object.getOwnPropertyNames(current);
+
+ for (const key of keys) {
+ if (key === 'constructor') continue;
+ if (key in result) continue; // 跳过已存在的属性(优先使用第一个 action 的方法)
+
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
+ if (!descriptor) continue;
+
+ if (typeof descriptor.value === 'function') {
+ // 方法: 绑定 this 上下文到原始 action 实例
+ (result as any)[key] = descriptor.value.bind(action);
+ } else {
+ // 非函数属性: 直接复制描述符
+ Object.defineProperty(result, key, {
+ ...descriptor,
+ configurable: true,
+ enumerable: true,
+ });
+ }
+ }
+
+ current = Object.getPrototypeOf(current);
+ }
+ }
+
+ return result;
+};