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(plugin): move the installed plugins onto @lobechat/replica (#20764)

Arvin Xua10dd94fe883
diff --git a/src/features/Settings/skill/features/Actions.tsx b/src/features/Settings/skill/features/Actions.tsx
index 165d67fe7c2..43950fac66d 100644
--- a/src/features/Settings/skill/features/Actions.tsx
+++ b/src/features/Settings/skill/features/Actions.tsx
@@ -41,6 +41,9 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {
agentSelectors.currentAgentPlugins(s).includes(identifier),
]);
const hasSettings = pluginHelpers.isSettingSchemaNonEmpty(plugin?.settings);
+ // Painted from the local cache: settings and connection parameters only
+ // arrive with the server's records, so configuring waits for them.
+ const isConfirming = useToolStore(pluginSelectors.isInstalledPluginsCacheOnly);
const [showModal, setModal] = useState(false);
@@ -49,9 +52,10 @@ const Actions = memo<ActionsProps>(({ identifier, type, isMCP }) => {
const configureButton = (
<Button
- disabled={!canEdit}
+ disabled={!canEdit || isConfirming}
+ loading={isConfirming}
onClick={() => {
- if (!canEdit) return;
+ if (!canEdit || isConfirming) return;
if (isCustomPlugin) {
setModal(true);
} else if (isCommunityMCP) {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 7d55a1f15fc..6b6c8fe04f3 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -784,7 +784,6 @@ export const toolKeys = {
appSlug,
]),
composioConnections: def('tool:composioConnections', () => ['tool:composioConnections']),
- installedPlugins: def('tool:installedPlugins', () => ['tool:installedPlugins']),
};
// ---- global -------------------------------------------------------------
diff --git a/src/services/chat/mecha/toolPreload.ts b/src/services/chat/mecha/toolPreload.ts
index a8e31844e98..a0c0876d719 100644
--- a/src/services/chat/mecha/toolPreload.ts
+++ b/src/services/chat/mecha/toolPreload.ts
@@ -1,6 +1,7 @@
import type { RuntimeSelectedTool } from '@lobechat/types';
import { getToolStoreState } from '@/store/tool';
+import { pluginSelectors } from '@/store/tool/selectors';
// Match <tool name="..." label="..." /> and legacy <action type="..." category="tool" ... />
const TOOL_TAG_REGEX = /<tool\b([^>]*)\/>/g;
@@ -79,7 +80,9 @@ const loadToolContent = (identifier: string): string | undefined => {
return content || undefined;
}
- const installedPlugin = (toolState.installedPlugins || []).find(
+ // Full records only: a plugin painted from the cached display projection is
+ // not in the tool set yet, so it has nothing to preload.
+ const installedPlugin = (pluginSelectors.confirmedInstalledPlugins(toolState) || []).find(
(p) => p.identifier === identifier,
);
diff --git a/src/store/chat/slices/plugin/actions/internals.ts b/src/store/chat/slices/plugin/actions/internals.ts
index a37dc2a762c..23c9633d544 100644
--- a/src/store/chat/slices/plugin/actions/internals.ts
+++ b/src/store/chat/slices/plugin/actions/internals.ts
@@ -41,7 +41,7 @@ export class PluginInternalsActionImpl {
const sourceMap: Record<string, 'builtin' | 'mcp' | 'composio' | 'lobehubSkill'> = {};
// Get all installed plugins (all treated as MCP now)
- const installedPlugins = pluginSelectors.installedPlugins(toolStoreState);
+ const installedPlugins = pluginSelectors.confirmedInstalledPlugins(toolStoreState);
for (const plugin of installedPlugins) {
if (plugin.manifest) {
manifests[plugin.identifier] = plugin.manifest as ToolManifest;
diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.ts
index a1e7d77656c..776141483a5 100644
--- a/src/store/tool/selectors/tool.ts
+++ b/src/store/tool/selectors/tool.ts
@@ -150,9 +150,11 @@ const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscover
name: tool.title || tool.identifier,
}));
- // 2. User-installed plugins — directly from s.installedPlugins
+ // 2. User-installed plugins — only full records: a plugin painted from the
+ // cached display projection has no connection yet, so it cannot be activated.
// Exclude Composio, LobeHub Skill, and agent skill entries (they are handled in dedicated sources)
- const pluginItems = s.installedPlugins
+ const pluginItems = pluginSelectors
+ .confirmedInstalledPlugins(s)
.filter((p) => !composioIds.has(p.identifier))
.filter((p) => !lobehubSkillIds.has(p.identifier))
.filter((p) => !agentSkillIds.has(p.identifier))
diff --git a/src/store/tool/slices/builtin/executors/lobe-activator.ts b/src/store/tool/slices/builtin/executors/lobe-activator.ts
index 8f9dbb04d65..0627339d0d2 100644
--- a/src/store/tool/slices/builtin/executors/lobe-activator.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-activator.ts
@@ -21,6 +21,7 @@ import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionR
import { filterBuiltinSkills } from '@/helpers/skillFilters';
import { agentSkillService } from '@/services/skill';
import { getToolStoreState } from '@/store/tool';
+import { pluginSelectors } from '@/store/tool/selectors';
import { toolSelectors } from '@/store/tool/selectors/tool';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore';
@@ -67,7 +68,7 @@ const service: ActivatorRuntimeService = {
}
// Search installed plugins
- const plugin = s.installedPlugins.find((p) => p.identifier === id);
+ const plugin = pluginSelectors.getInstalledPluginById(id)(s);
if (plugin?.manifest) {
results.push({
apiDescriptions: (plugin.manifest.api || []).map((a) => ({
diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.ts
index 69fb7510f9e..0810982afa5 100644
--- a/src/store/tool/slices/customPlugin/action.ts
+++ b/src/store/tool/slices/customPlugin/action.ts
@@ -67,8 +67,7 @@ export class CustomPluginActionImpl {
};
uninstallCustomPlugin = async (id: string): Promise<void> => {
- await pluginService.uninstallPlugin(id);
- await this.#get().refreshPlugins();
+ await this.#get().uninstallPlugin(id);
};
updateCustomPlugin = async (id: string, value: LobeToolCustomPlugin): Promise<void> => {
diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.ts
index b2fdf2455c0..e1645958930 100644
--- a/src/store/tool/slices/mcpStore/action.ts
+++ b/src/store/tool/slices/mcpStore/action.ts
@@ -878,8 +878,7 @@ export class PluginMCPStoreActionImpl {
};
uninstallMCPPlugin = async (identifier: string): Promise<void> => {
- await pluginService.uninstallPlugin(identifier);
- await this.#get().refreshPlugins();
+ await this.#get().uninstallPlugin(identifier);
discoverService.reportMcpEvent({
event: 'uninstall',
diff --git a/src/store/tool/slices/plugin/action.test.ts b/src/store/tool/slices/plugin/action.test.ts
index 17fc1186bd6..3fb3f5548a0 100644
--- a/src/store/tool/slices/plugin/action.test.ts
+++ b/src/store/tool/slices/plugin/action.test.ts
@@ -37,6 +37,9 @@ describe('useToolStore:plugin', () => {
it('should update settings for a given plugin', async () => {
const pluginId = 'test-plugin';
const newSettings = { setting1: 'new-value' };
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([
+ { identifier: pluginId, type: 'plugin' } as LobeTool,
+ ]);
const { result } = renderHook(() => useToolStore());
@@ -56,9 +59,10 @@ describe('useToolStore:plugin', () => {
const existingSettings = { setting1: 'old-value', setting2: 'old-value' };
const newSettings = { setting1: 'new-value' };
const mergedSettings = merge(existingSettings, newSettings);
- useToolStore.setState({
- installedPlugins: [{ identifier: pluginId, settings: existingSettings }] as LobeTool[],
- });
+ // The merge base is the server's record, loaded before the write.
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([
+ { identifier: pluginId, settings: existingSettings, type: 'plugin' } as LobeTool,
+ ]);
const { result } = renderHook(() => useToolStore());
diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.ts
index 6a880cb8012..fd4249a68a9 100644
--- a/src/store/tool/slices/plugin/action.ts
+++ b/src/store/tool/slices/plugin/action.ts
@@ -3,19 +3,49 @@ import { type LobeTool } from '@lobechat/types';
import { type SWRResponse } from 'swr';
import { MESSAGE_CANCEL_FLAT } from '@/const/message';
+import {
+ cacheScope,
+ createReplicaSlice,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
import { useClientDataSWR } from '@/libs/swr';
-import { toolKeys } from '@/libs/swr/keys';
import { pluginService } from '@/services/plugin';
import { type StoreSetter } from '@/store/types';
import { type PluginInstallError } from '@/types/tool/plugin';
import { merge } from '@/utils/merge';
+import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
+import {
+ INSTALLED_PLUGINS_KEY,
+ INSTALLED_PLUGINS_PARAMS,
+ installedPluginsEntity,
+ installedPluginsResource,
+ type InstalledPluginsResponse,
+ toInstalledPluginsProjection,
+} from './projection';
import { pluginSelectors } from './selectors';
+const n = setNamespace('plugin');
+
/**
- * Plugin interface
+ * The installed plugins keep their long-standing flat `installedPlugins` field
+ * as the replica view, so every selector and direct reader keeps reading what it
+ * did. The init flag gates `get`: before the first hydrate / replace the view
+ * must read `undefined`, otherwise the empty default would block hydration from
+ * storage.
*/
+const installedPluginsLens: ReplicaLens<ToolStore, LobeTool[]> = {
+ clear: () => ({ installedPlugins: [], isInstalledPluginsInit: false }),
+ get: (state) => (state.isInstalledPluginsInit ? state.installedPlugins : undefined),
+ keys: (state) => (state.isInstalledPluginsInit ? [INSTALLED_PLUGINS_KEY] : []),
+ set: (_state, _key, data) =>
+ data
+ ? { installedPlugins: data, isInstalledPluginsInit: true }
+ : { installedPlugins: [], isInstalledPluginsInit: false },
+};
type Setter = StoreSetter<ToolStore>;
export const createPluginSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>
@@ -23,24 +53,117 @@ export const createPluginSlice = (set: Setter, get: () => ToolStore, _api?: unkn
export class PluginActionImpl {
readonly #get: () => ToolStore;
+ /** Responses of requests started at or before this sequence are dropped. */
+ #droppedThroughSeq = 0;
+ /** Start sequence of the last fetch, shared by `useSync` and `refreshPlugins`. */
+ #fetchSeq = 0;
+ readonly #installedPlugins;
readonly #set: Setter;
constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#installedPlugins = createReplicaSlice(installedPluginsResource, {
+ actionPrefix: n('installedPlugins'),
+ entity: installedPluginsEntity,
+ fetcher: () => this.#fetchInstalledPlugins(),
+ get,
+ merge: (incoming) => incoming.plugins,
+ prepareHead: (incoming) => this.#admitResponse(incoming),
+ set,
+ stateKey: 'installedPluginsReplica',
+ // Settings and connection parameters never reach IndexedDB.
+ toPersisted: toInstalledPluginsProjection,
+ view: installedPluginsLens,
+ });
+
+ // Tool assembly and execution read the installed plugins outside any
+ // component, and `refreshPlugins` runs on routes that do not mount
+ // `useFetchInstalledPlugins`. Without a mounted sync nothing would reset the
+ // view on a workspace / account switch until the next dispatch, so the
+ // previous identity's plugins (connection parameters included) would stay
+ // runnable. Drop them the moment the scope changes. The store is an
+ // app-lifetime singleton, so the subscription is never torn down.
+ subscribeCacheScope((scope) => this.#installedPlugins.ensureScope(scope));
}
+ /**
+ * Whether the list holds the server's full records. A list hydrated from the
+ * persisted display projection has no settings and no connection parameters,
+ * and an un-loaded list has nothing at all: a write merged over either would
+ * replace the plugin's real settings / connection with a partial object.
+ */
+ #hasServerRecords = (): boolean =>
+ this.#get().installedPluginsReplica.entries[INSTALLED_PLUGINS_KEY]?.source === 'server';
+
+ /**
+ * Load the server's full records before a write merges onto them. Rejects
+ * when they cannot be loaded, so a write never falls back to the projection.
+ */
+ #loadServerRecords = async (): Promise<void> => {
+ await this.#get().refreshPlugins();
+ if (!this.#hasServerRecords())
+ throw new Error('The installed plugins have not been loaded from the server');
+ };
+
+ /** Every fetch path goes through here, so all responses share one order. */
+ #fetchInstalledPlugins = async (): Promise<InstalledPluginsResponse> => {
+ const seq = ++this.#fetchSeq;
+ const plugins = await pluginService.getInstalledPlugins();
+ return { plugins, seq };
+ };
+
+ /**
+ * Admit a response only when its request started after every response
+ * already applied and after the latest mutation refresh. A mounted sync that
+ * started before an uninstall must not re-add the plugin (and persist it)
+ * when it settles late; an older refresh must not overwrite a newer one.
+ */
+ #admitResponse = (incoming: InstalledPluginsResponse): InstalledPluginsResponse | undefined => {
+ if (incoming.seq <= this.#droppedThroughSeq) return undefined;
+ this.#droppedThroughSeq = incoming.seq;
+ return incoming;
+ };
+
checkPluginsIsInstalled = async (_plugins: string[]): Promise<void> => {
// Old plugin system has been deprecated, skip auto-installation
};
/**
- * Refresh installed plugins from the server and update store state.
+ * Fetch the installed plugins and confirm the replica with them. The painted
+ * list stays on screen while the network answers.
+ *
+ * Imperative on purpose: install / uninstall / settings flows call it on
+ * routes (e.g. the protocol-install popup) where no `useFetchInstalledPlugins`
+ * is mounted, so revalidating the mounted sync queries would resolve without
+ * fetching anything. The scope is captured before the request so a response
+ * that lands after a workspace switch is dropped instead of written into the
+ * next scope. Every mutation ends with this refresh, so it also retires the
+ * requests already in flight (sync or refresh): they started before the
+ * mutation and would paint the pre-mutation list. Rejects when the fetch
+ * fails.
*/
refreshPlugins = async (): Promise<void> => {
- const data = await pluginService.getInstalledPlugins();
- this.#set({ installedPlugins: data }, false, 'refreshPlugins');
+ const scope = cacheScope.get();
+ this.#droppedThroughSeq = this.#fetchSeq;
+ const response = await this.#fetchInstalledPlugins();
+
+ this.#installedPlugins.replace(INSTALLED_PLUGINS_PARAMS, response, scope);
+ };
+
+ /**
+ * Uninstall a plugin. The row stays until the server confirms (a detail pane
+ * bound to it would otherwise blank and blink back on a rejected delete),
+ * then leaves the loaded list *and* the persisted rows: `removeEntity` also
+ * guards hydrates already in flight, so a reload never paints the uninstalled
+ * plugin again.
+ */
+ uninstallPlugin = async (identifier: string): Promise<void> => {
+ await pluginService.uninstallPlugin(identifier);
+ this.#installedPlugins.removeEntity(identifier);
+
+ await this.#get().refreshPlugins();
};
updateInstallLoadingState = (id: string, loading: boolean | undefined): void => {
@@ -60,13 +183,24 @@ export class PluginActionImpl {
};
updateInstallMcpPlugin = async (id: string, value: any): Promise<void> => {
+ // The server replaces `customParams` as a whole: merge onto the full record,
+ // never the display projection (which has no connection parameters).
+ if (!this.#hasServerRecords()) await this.#loadServerRecords();
+
const installedPlugin = pluginSelectors.getInstalledPluginById(id)(this.#get());
if (!installedPlugin) return;
- await pluginService.updatePlugin(id, {
- customParams: { mcp: merge(installedPlugin.customParams?.mcp, value) },
- });
+ const customParams = {
+ ...installedPlugin.customParams,
+ mcp: merge(installedPlugin.customParams?.mcp, value),
+ };
+
+ await this.#installedPlugins.optimistic(
+ INSTALLED_PLUGINS_KEY,
+ (plugins) => plugins.map((p) => (p.identifier === id ? { ...p, customParams } : p)),
+ () => pluginService.updatePlugin(id, { customParams: { mcp: customParams.mcp } }),
+ );
await this.#get().refreshPlugins();
};
@@ -77,42 +211,55 @@ export class PluginActionImpl {
options: { override?: boolean } = {},
): Promise<void> => {
const { override } = options;
- const signal = this.#get().updatePluginSettingsSignal;
- if (signal) signal.abort(MESSAGE_CANCEL_FLAT);
- const newSignal = new AbortController();
+ // Publish this write's controller before anything is awaited, so a newer
+ // call always sees — and aborts — the one still in flight.
+ this.#get().updatePluginSettingsSignal?.abort(MESSAGE_CANCEL_FLAT);
+ const controller = new AbortController();
+ this.#set({ updatePluginSettingsSignal: controller }, false, n('updatePluginSettings/signal'));
+
+ // The server replaces the whole settings object: merge onto the server's
+ // settings, never the display projection (which has none), or saving one
+ // field would erase the others. Synchronous once confirmed, so the row
+ // updates in the same tick as the edit.
+ if (!this.#hasServerRecords()) {
+ await this.#loadServerRecords();
+ // A newer write took over while the records were loading.
+ if (controller.signal.aborted) return;
+ }
const previousSettings = pluginSelectors.getPluginSettingsById(id)(this.#get());
const nextSettings = override ? settings : merge(previousSettings, settings);
- this.#set({ updatePluginSettingsSignal: newSignal }, false, 'create new Signal');
- await pluginService.updatePluginSettings(id, nextSettings, newSignal.signal);
+ // The row shows the new settings immediately; a failed or aborted write
+ // rolls it back to the confirmed value plus any newer write in flight.
+ await this.#installedPlugins.optimistic(
+ INSTALLED_PLUGINS_KEY,
+ (plugins) => plugins.map((p) => (p.identifier === id ? { ...p, settings: nextSettings } : p)),
+ () => pluginService.updatePluginSettings(id, nextSettings, controller.signal),
+ );
await this.#get().refreshPlugins();
};
- useFetchInstalledPlugins = (enable: boolean): SWRResponse => {
- return useClientDataSWR(
- enable ? toolKeys.installedPlugins() : null,
- () => pluginService.getInstalledPlugins(),
- {
- onSuccess: (data: LobeTool[]) => {
- this.#set(
- { installedPlugins: data, loadingInstallPlugins: false },
- false,
- 'useFetchInstalledPlugins/onSuccess',
- );
- },
- },
- );
- };
+ /**
+ * Fetch orchestration for the installed plugins: hydrate the persisted display
+ * projection, then confirm the full records from the server on the same SWR
+ * schedule as before. Read the list through `pluginSelectors`; this only
+ * reports fetch flags.
+ */
+ useFetchInstalledPlugins = (enable: boolean): ReplicaSyncResult =>
+ this.#installedPlugins.useSync(INSTALLED_PLUGINS_PARAMS, { enabled: enable });
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());
+ // Validate the full record: the display projection has no settings, so it
+ // would report every required field as missing.
+ const plugin = pluginSelectors.getInstalledPluginById(identifier)(this.#get());
+ const manifest = plugin?.manifest;
if (!manifest || !manifest.settings) return;
const settings = pluginSelectors.getPluginSettingsById(identifier)(this.#get());
diff --git a/src/store/tool/slices/plugin/initialState.ts b/src/store/tool/slices/plugin/initialState.ts
index 131f2dedbfd..f3c24157daf 100644
--- a/src/store/tool/slices/plugin/initialState.ts
+++ b/src/store/tool/slices/plugin/initialState.ts
@@ -1,22 +1,36 @@
import { type LobeTool } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { type PluginInstallError } from '@/types/tool/plugin';
export type PluginsSettings = Record<string, any>;
export interface PluginState {
+ /**
+ * Installed plugins of the active scope — the view of the `installedPlugins`
+ * replica. Until the server answers it can hold the persisted display
+ * projection (no `settings`, no connection parameters): read full records
+ * through `pluginSelectors.confirmedInstalledPlugins` and the by-id lookups.
+ */
installedPlugins: LobeTool[];
- loadingInstallPlugins: boolean;
+ /** Replica bookkeeping for `installedPlugins`. */
+ installedPluginsReplica: ReplicaState<LobeTool[]>;
+ /**
+ * Whether the installed-plugins view has been filled (from storage or the
+ * server). Gates the replica lens: an un-loaded list must read `undefined`,
+ * otherwise hydration would treat the empty default as a real value.
+ */
+ isInstalledPluginsInit: boolean;
pluginInstallErrors: Record<string, PluginInstallError | undefined>;
pluginInstallLoading: Record<string, boolean | undefined>;
- pluginsSettings: PluginsSettings;
+ /** Lets a newer settings write abort the one still in flight. */
updatePluginSettingsSignal?: AbortController;
}
export const initialPluginState: PluginState = {
installedPlugins: [],
- loadingInstallPlugins: true,
+ installedPluginsReplica: createReplicaState(),
+ isInstalledPluginsInit: false,
pluginInstallErrors: {},
pluginInstallLoading: {},
- pluginsSettings: {},
};
diff --git a/src/store/tool/slices/plugin/projection.ts b/src/store/tool/slices/plugin/projection.ts
new file mode 100644
index 00000000000..0974cb5853b
--- /dev/null
+++ b/src/store/tool/slices/plugin/projection.ts
@@ -0,0 +1,98 @@
+import { type CustomPluginParams, type LobeTool } from '@lobechat/types';
+
+import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';
+
+/**
+ * The installed-plugins list is not paged and not filtered: it is one entry per
+ * cache scope (`${userId}:${workspace}`), so every sync shares these params and
+ * personal / each workspace keep independent rows automatically.
+ */
+export const INSTALLED_PLUGINS_KEY = 'installed';
+
+export type InstalledPluginsParams = Record<string, never>;
+
+export const INSTALLED_PLUGINS_PARAMS: InstalledPluginsParams = {};
+
+/**
+ * One installed-plugins response, tagged with the order its request started
+ * in. The sync hook and the imperative refresh fetch independently, so a
+ * response may settle after a newer one (or after a mutation): the tag lets
+ * the slice drop it instead of painting — and persisting — an older list.
+ */
+export interface InstalledPluginsResponse {
+ plugins: LobeTool[];
+ /** Start order of the request, shared by every fetch path. */
+ seq: number;
+}
+
+/**
+ * Installed plugins (`user_installed_plugins`): read by the skill settings page,
+ * the chat input tool picker, the agent profile and the MCP detail pages, and
+ * written by install / uninstall / settings updates. A local-first replica
+ * paints the persisted display projection on the first frame and lets the
+ * network confirm the full records in the background.
+ */
+export const installedPluginsResource = defineReplica<
+ InstalledPluginsParams,
+ LobeTool[],
+ InstalledPluginsResponse
+>({
+ key: () => INSTALLED_PLUGINS_KEY,
+ name: 'installedPlugins',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Plugins are addressed by `identifier` across the tool store. */
+export const installedPluginsEntity: ReplicaEntityAdapter<LobeTool[], LobeTool> =
+ arrayEntity<LobeTool>((plugin) => plugin.identifier);
+
+/**
+ * Reduce a plugin record to what the first frame paints: identity, manifest
+ * (name, icon, API list) and the two non-secret discriminators display
+ * selectors filter on.
+ *
+ * `settings` and the rest of `customParams` stay in memory only. Plugin
+ * settings are usually API keys, and `customParams.mcp` carries the connection:
+ * URL, command / args, `env`, `headers` and the bearer / OAuth `token` /
+ * `accessToken` / `clientSecret`. Persisted projection rows outlive the session
+ * (sign-out only moves the active scope), so writing them to IndexedDB would
+ * turn an authenticated response into durable plaintext credentials.
+ *
+ * Kept on purpose:
+ * - `customParams.mcp.type` — `isInstalledPluginAvailableInCurrentEnv` reads it
+ * to keep a `stdio` plugin off the web; dropping it would surface the cached
+ * plugin there until the network answers.
+ * - `customParams.composio` as `{ appSlug, status }` — `installedPluginMetaList`
+ * only checks its presence to leave Composio rows to their own surface.
+ *
+ * A row hydrated from this projection is display-only: the full-record
+ * selectors (`pluginSelectors.confirmedInstalledPlugins` and the by-id record
+ * lookups) and every write wait for the server-confirmed list.
+ */
+export const toInstalledPluginProjection = (plugin: LobeTool): LobeTool => {
+ const { customParams, identifier, manifest, runtimeType, source, type } = plugin;
+ const row: LobeTool = { identifier, type };
+ if (manifest !== undefined) row.manifest = manifest;
+ if (runtimeType !== undefined) row.runtimeType = runtimeType;
+ if (source !== undefined) row.source = source;
+
+ const mcpType = customParams?.mcp?.type;
+ const composio = customParams?.composio;
+ if (mcpType || composio) {
+ const params: CustomPluginParams = {};
+ if (mcpType) params.mcp = { type: mcpType };
+ if (composio)
+ params.composio = {
+ appSlug: composio.appSlug,
+ status: composio.status,
+ } as CustomPluginParams['composio'];
+ row.customParams = params;
+ }
+
+ return row;
+};
+
+/** `toPersisted` of the installed-plugins replica: rows only, never the index. */
+export const toInstalledPluginsProjection = (plugins: LobeTool[]): LobeTool[] =>
+ plugins.map(toInstalledPluginProjection);
diff --git a/src/store/tool/slices/plugin/replica.test.ts b/src/store/tool/slices/plugin/replica.test.ts
new file mode 100644
index 00000000000..e948984493b
--- /dev/null
+++ b/src/store/tool/slices/plugin/replica.test.ts
@@ -0,0 +1,645 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The installed-plugins list is a replica: the persisted display projection
+ * paints on the first frame and the network confirms the full records. The
+ * projection never carries settings or connection parameters, so everything
+ * that runs or writes a plugin waits for the server-confirmed records.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { type LobeTool } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { isInstalledPluginAvailableInCurrentEnv } from '@/helpers/toolAvailability';
+import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';
+import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { pluginService } from '@/services/plugin';
+
+import { toolSelectors } from '../../selectors';
+import { useToolStore } from '../../store';
+import { initialPluginState } from './initialState';
+import { installedPluginsResource, toInstalledPluginsProjection } from './projection';
+import { pluginSelectors } from './selectors';
+
+vi.mock('@/services/plugin', () => ({
+ pluginService: {
+ createCustomPlugin: vi.fn(),
+ getInstalledPlugins: vi.fn(),
+ uninstallPlugin: vi.fn(),
+ updatePlugin: vi.fn(),
+ updatePluginSettings: vi.fn(),
+ },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const SECRET = 'sk-live-secret-value';
+
+const plugin = (
+ identifier: string,
+ settings: Record<string, unknown> = {},
+ customParams?: unknown,
+): LobeTool =>
+ ({
+ customParams,
+ identifier,
+ manifest: { api: [], identifier, meta: { title: identifier } },
+ settings,
+ type: 'plugin',
+ }) as unknown as LobeTool;
+
+/** An MCP plugin whose record carries every kind of credential. */
+const mcpPlugin = (identifier: string, type: 'http' | 'stdio' = 'http'): LobeTool =>
+ plugin(
+ identifier,
+ { apiKey: SECRET },
+ {
+ mcp: {
+ args: ['--token', SECRET],
+ auth: { accessToken: SECRET, clientSecret: SECRET, token: SECRET, type: 'oauth2' },
+ command: 'node',
+ env: { TOKEN: SECRET },
+ headers: { Authorization: `Bearer ${SECRET}` },
+ type,
+ url: 'https://mcp.example.com',
+ },
+ },
+ );
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+};
+
+const STORAGE_KEY = installedPluginsResource.storageKey({});
+
+const ids = () => useToolStore.getState().installedPlugins.map((p) => p.identifier);
+
+describe('installed plugins replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+ const readPersisted = async (at = scope) =>
+ (await installedPluginsResource.storage!.get({ queryKey: STORAGE_KEY, scope: at }))?.data;
+ const seedPersisted = (data: LobeTool[]) =>
+ installedPluginsResource.storage!.set({ queryKey: STORAGE_KEY, scope }, { data, updatedAt: 1 });
+ const mountSync = (enabled = true) =>
+ renderHook(() => useToolStore((s) => s.useFetchInstalledPlugins)(enabled), { wrapper });
+
+ /**
+ * Mount the sync over a persisted copy while the network never answers. The
+ * copy is what an earlier session persisted: the display projection.
+ */
+ const paintFromCache = async (data: LobeTool[]) => {
+ await seedPersisted(toInstalledPluginsProjection(data));
+ vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);
+ const sync = mountSync();
+ await waitFor(() => expect(ids()).toEqual(data.map((p) => p.identifier)));
+ return sync;
+ };
+
+ /** Mount the sync and wait for the server's records. */
+ const loadFromServer = async (data: LobeTool[]) => {
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue(data);
+ const sync = mountSync();
+ await waitFor(() =>
+ expect(useToolStore.getState().installedPluginsReplica.entries.installed?.source).toBe(
+ 'server',
+ ),
+ );
+ return sync;
+ };
+
+ beforeEach(() => {
+ resetCacheScopeBroadcast();
+ useScope(`plugin-user-${randomUUID()}:personal`);
+ act(() => useToolStore.setState(initialPluginState));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ [STORAGE_KEY, REPLICA_INDEX_KEY].map((queryKey) =>
+ installedPluginsResource.storage!.remove({ queryKey, scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ describe('hydrate and sync', () => {
+ it('paints the persisted list before the network answers', async () => {
+ const sync = await paintFromCache([plugin('p1')]);
+
+ expect(useToolStore.getState().isInstalledPluginsInit).toBe(true);
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ // Display selectors paint the cached row.
+ const state = useToolStore.getState();
+ expect(pluginSelectors.isPluginInstalled('p1')(state)).toBe(true);
+ expect(pluginSelectors.installedPluginMetaList(state).map((p) => p.identifier)).toEqual([
+ 'p1',
+ ]);
+ expect(pluginSelectors.getPluginMetaById('p1')(state)).toEqual({ title: 'p1' });
+ });
+
+ it('keeps cached rows out of every path that runs or edits a plugin', async () => {
+ await paintFromCache([mcpPlugin('mcp-1')]);
+ const state = useToolStore.getState();
+
+ expect(pluginSelectors.isInstalledPluginsCacheOnly(state)).toBe(true);
+ expect(pluginSelectors.confirmedInstalledPlugins(state)).toEqual([]);
+ expect(pluginSelectors.getInstalledPluginById('mcp-1')(state)).toBeUndefined();
+ expect(pluginSelectors.getCustomPluginById('mcp-1')(state)).toBeUndefined();
+ expect(pluginSelectors.getPluginSettingsById('mcp-1')(state)).toEqual({});
+ // Not offered to the model: the cached row has no connection to call.
+ expect(pluginSelectors.installedPluginManifestList(state)).toEqual([]);
+ expect(toolSelectors.getManifestById('mcp-1')(state)).toBeUndefined();
+ expect(
+ toolSelectors.availableToolsForDiscovery(state).some((t) => t.identifier === 'mcp-1'),
+ ).toBe(false);
+ // Nor validated against settings it does not have.
+ expect(await useToolStore.getState().validatePluginSettings('mcp-1')).toBeUndefined();
+ });
+
+ it('confirms the full records from the server and persists the display projection', async () => {
+ await loadFromServer([plugin('p1', { setting1: 'server' })]);
+ const state = useToolStore.getState();
+
+ expect(ids()).toEqual(['p1']);
+ expect(pluginSelectors.isInstalledPluginsCacheOnly(state)).toBe(false);
+ expect(pluginSelectors.getPluginSettingsById('p1')(state)).toEqual({ setting1: 'server' });
+ expect(pluginSelectors.installedPluginManifestList(state).map((m) => m.identifier)).toEqual([
+ 'p1',
+ ]);
+ await waitFor(async () =>
+ expect(await readPersisted()).toEqual([
+ { identifier: 'p1', manifest: plugin('p1').manifest, type: 'plugin' },
+ ]),
+ );
+ });
+
+ it('never persists plugin settings or credentials', async () => {
+ await loadFromServer([mcpPlugin('mcp-1')]);
+
+ // The in-memory record keeps the full connection…
+ expect(useToolStore.getState().installedPlugins[0].customParams?.mcp?.env).toEqual({
+ TOKEN: SECRET,
+ });
+
+ // …but only the non-secret runtime discriminator reaches storage.
+ await waitFor(async () => expect(await readPersisted()).toHaveLength(1));
+ const persisted = await readPersisted();
+ expect(persisted![0].customParams).toEqual({ mcp: { type: 'http' } });
+ expect(persisted![0].settings).toBeUndefined();
+ expect(JSON.stringify(persisted)).not.toContain(SECRET);
+ });
+
+ it('keeps the discriminators display filters need', async () => {
+ await loadFromServer([
+ mcpPlugin('mcp-stdio', 'stdio'),
+ plugin(
+ 'composio-1',
+ {},
+ {
+ composio: {
+ appSlug: 'gmail',
+ authConfigId: 'auth-secret-ref',
+ connectedAccountId: 'account-ref',
+ status: 'ACTIVE',
+ },
+ },
+ ),
+ ]);
+ await waitFor(async () => expect(await readPersisted()).toHaveLength(2));
+ const [stdio, composio] = (await readPersisted())!;
+
+ // A cached stdio plugin stays off the web before the network answers.
+ expect(isInstalledPluginAvailableInCurrentEnv(stdio, { isDesktop: false })).toBe(false);
+ expect(isInstalledPluginAvailableInCurrentEnv(stdio, { isDesktop: true })).toBe(true);
+ // A cached Composio row stays out of the plugin list.
+ expect(composio.customParams).toEqual({ composio: { appSlug: 'gmail', status: 'ACTIVE' } });
+
+ // Reload: the cached list paints with the same filtering as the server one.
+ cleanup();
+ act(() => useToolStore.setState(initialPluginState));
+ await paintFromCache((await readPersisted())!);
+ expect(pluginSelectors.installedPluginMetaList(useToolStore.getState())).toEqual([]);
+ });
+
+ it('keeps the replica row index as storage keys, never projected', async () => {
+ await loadFromServer([plugin('p1')]);
+
+ await waitFor(async () =>
+ expect(
+ (await installedPluginsResource.storage!.get({ queryKey: REPLICA_INDEX_KEY, scope }))
+ ?.data,
+ ).toEqual([STORAGE_KEY]),
+ );
+ });
+
+ it('does not fetch while the sync is disabled', async () => {
+ mountSync(false);
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(pluginService.getInstalledPlugins).not.toHaveBeenCalled();
+ expect(useToolStore.getState().isInstalledPluginsInit).toBe(false);
+ });
+ });
+
+ describe('scope switch', () => {
+ it('drops the previous identity’s plugins before the next one paints', async () => {
+ const sync = await loadFromServer([plugin('p1')]);
+
+ vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);
+ useScope(`plugin-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(useToolStore.getState().isInstalledPluginsInit).toBe(false));
+ expect(useToolStore.getState().installedPlugins).toEqual([]);
+ });
+
+ it('paints the next scope’s own cached list', async () => {
+ const sync = await loadFromServer([plugin('personal-plugin')]);
+
+ useScope(`plugin-user-${randomUUID()}:ws-1`);
+ await seedPersisted([plugin('workspace-plugin')]);
+ vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);
+ sync.rerender();
+
+ await waitFor(() => expect(ids()).toEqual(['workspace-plugin']));
+ // The workspace's cached row is display-only too.
+ expect(pluginSelectors.confirmedInstalledPlugins(useToolStore.getState())).toEqual([]);
+ });
+
+ it('drops runnable records on a switch even with no sync mounted', async () => {
+ await act(async () => {
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([mcpPlugin('mcp-1')]);
+ await useToolStore.getState().refreshPlugins();
+ });
+ expect(pluginSelectors.getInstalledPluginById('mcp-1')(useToolStore.getState())).toBeTruthy();
+
+ useScope(`plugin-user-${randomUUID()}:ws-1`);
+ act(() => broadcastCacheScope(scope));
+
+ expect(useToolStore.getState().installedPlugins).toEqual([]);
+ expect(pluginSelectors.getInstalledPluginById('mcp-1')(useToolStore.getState())).toBe(
+ undefined,
+ );
+ });
+
+ it('drops a refresh that lands after the scope moved on', async () => {
+ const response = deferred<LobeTool[]>();
+ vi.mocked(pluginService.getInstalledPlugins).mockReturnValue(response.promise);
+ const refresh = useToolStore.getState().refreshPlugins();
+
+ useScope(`plugin-user-${randomUUID()}:ws-1`);
+ act(() => broadcastCacheScope(scope));
+ await act(async () => {
+ response.resolve([plugin('personal-plugin')]);
+ await refresh;
+ });
+
+ expect(useToolStore.getState().installedPlugins).toEqual([]);
+ expect(await readPersisted()).toBeUndefined();
+ });
+ });
+
+ describe('refreshPlugins', () => {
+ it('fetches and confirms imperatively when no sync hook is mounted', async () => {
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([plugin('p1')]);
+
+ await act(async () => {
+ await useToolStore.getState().refreshPlugins();
+ });
+
+ expect(pluginService.getInstalledPlugins).toHaveBeenCalledTimes(1);
+ expect(ids()).toEqual(['p1']);
+ await waitFor(async () => expect(await readPersisted()).toHaveLength(1));
+ });
+
+ it('keeps the painted list on screen while the network answers', async () => {
+ await loadFromServer([plugin('p1')]);
+ vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);
+
+ void useToolStore.getState().refreshPlugins();
+
+ expect(ids()).toEqual(['p1']);
+ });
+
+ it('never lets an older response overwrite a newer one', async () => {
+ const older = deferred<LobeTool[]>();
+ const newer = deferred<LobeTool[]>();
+ vi.mocked(pluginService.getInstalledPlugins)
+ .mockReturnValueOnce(older.promise)
+ .mockReturnValueOnce(newer.promise);
+
+ const first = useToolStore.getState().refreshPlugins();
+ const second = useToolStore.getState().refreshPlugins();
+ await act(async () => {
+ newer.resolve([plugin('p1'), plugin('p2')]);
+ await second;
+ older.resolve([plugin('p1')]);
+ await first;
+ });
+
+ expect(ids()).toEqual(['p1', 'p2']);
+ });
+ });
+
+ describe('install / uninstall propagation', () => {
+ it('shows a newly installed plugin and persists it', async () => {
+ await loadFromServer([plugin('p1')]);
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([
+ plugin('p1'),
+ plugin('custom-1'),
+ ]);
+
+ await act(async () => {
+ await useToolStore
+ .getState()
+ .installCustomPlugin({ identifier: 'custom-1', type: 'customPlugin' } as any);
+ });
+
+ expect(pluginService.createCustomPlugin).toHaveBeenCalled();
+ expect(ids()).toEqual(['p1', 'custom-1']);
+ await waitFor(async () =>
+ expect((await readPersisted())?.map((p) => p.identifier)).toEqual(['p1', 'custom-1']),
+ );
+ });
+
+ it('keeps the row until the server confirms the uninstall, then drops it everywhere', async () => {
+ await loadFromServer([plugin('p1'), plugin('p2')]);
+ await waitFor(async () => expect(await readPersisted()).toHaveLength(2));
+
+ const uninstall = deferred<void>();
+ vi.mocked(pluginService.uninstallPlugin).mockReturnValue(uninstall.promise);
+ // The follow-up refresh has not caught up yet: the removal must still hold.
+ vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);
+
+ void useToolStore.getState().uninstallMCPPlugin('p1');
+ expect(ids()).toEqual(['p1', 'p2']);
+
+ await act(async () => {
+ uninstall.resolve();
+ await uninstall.promise;
+ });
+
+ await waitFor(() => expect(ids()).toEqual(['p2']));
+ await waitFor(async () =>
+ expect((await readPersisted())?.map((p) => p.identifier)).toEqual(['p2']),
+ );
+
+ // Reload: the uninstalled plugin never paints again.
+ cleanup();
+ act(() => useToolStore.setState(initialPluginState));
+ await paintFromCache((await readPersisted())!);
+ expect(ids()).toEqual(['p2']);
+ });
+
+ it('never lets a sync that started before an uninstall re-add the plugin', async () => {
+ const sync = await loadFromServer([plugin('p1'), plugin('p2')]);
+ await waitFor(async () => expect(await readPersisted()).toHaveLength(2));
+
+ // A focus / interval revalidation starts before the uninstall…
+ const stale = deferred<LobeTool[]>();
+ vi.mocked(pluginService.getInstalledPlugins).mockReturnValue(stale.promise);
+ void sync.result.current.revalidate();
+ await waitFor(() => expect(pluginService.getInstalledPlugins).toHaveBeenCalledTimes(2));
+
+ // …the uninstall lands, and its follow-up refresh is still in flight…
+ vi.mocked(pluginService.uninstallPlugin).mockResolvedValue(undefined);
+ vi.mocked(pluginService.getInstalledPlugins).mockImplementation(pending);
+ await act(async () => {
+ void useToolStore.getState().uninstallPlugin('p1');
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(ids()).toEqual(['p2']));
+
+ // …then the pre-uninstall response settles with the old list.
+ await act(async () => {
+ stale.resolve([plugin('p1'), plugin('p2')]);
+ await stale.promise;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(ids()).toEqual(['p2']);
+ await waitFor(async () =>
+ expect((await readPersisted())?.map((p) => p.identifier)).toEqual(['p2']),
+ );
+ });
+
+ it('never lets a sync response overwrite a newer refresh', async () => {
+ const sync = await loadFromServer([plugin('p1')]);
+
+ const stale = deferred<LobeTool[]>();
+ vi.mocked(pluginService.getInstalledPlugins).mockReturnValueOnce(stale.promise);
+ void sync.result.current.revalidate();
+ await waitFor(() => expect(pluginService.getInstalledPlugins).toHaveBeenCalledTimes(2));
+
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValueOnce([
+ plugin('p1'),
+ plugin('p2'),
+ ]);
+ await act(async () => {
+ await useToolStore.getState().refreshPlugins();
+ });
+ expect(ids()).toEqual(['p1', 'p2']);
+
+ await act(async () => {
+ stale.resolve([plugin('p1')]);
+ await stale.promise;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(ids()).toEqual(['p1', 'p2']);
+ });
+
+ it('routes a custom-plugin uninstall through the same removal', async () => {
+ await loadFromServer([plugin('custom-1')]);
+ vi.mocked(pluginService.uninstallPlugin).mockResolvedValue(undefined);
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([]);
+
+ await act(async () => {
+ await useToolStore.getState().uninstallCustomPlugin('custom-1');
+ });
+
+ expect(pluginService.uninstallPlugin).toHaveBeenCalledWith('custom-1');
+ expect(ids()).toEqual([]);
+ await waitFor(async () => expect(await readPersisted()).toEqual([]));
+ });
+
+ it('keeps the plugin when the server rejects the uninstall', async () => {
+ await loadFromServer([plugin('p1')]);
+ vi.mocked(pluginService.uninstallPlugin).mockRejectedValue(new Error('boom'));
+
+ await expect(useToolStore.getState().uninstallPlugin('p1')).rejects.toThrow('boom');
+
+ expect(ids()).toEqual(['p1']);
+ });
+ });
+
+ describe('settings writes', () => {
+ it('shows new settings optimistically, then confirms from the server', async () => {
+ await loadFromServer([plugin('p1', { setting1: 'old', setting2: 'keep' })]);
+
+ const write = deferred<void>();
+ vi.mocked(pluginService.updatePluginSettings).mockReturnValue(write.promise as any);
+
+ const operation = useToolStore.getState().updatePluginSettings('p1', { setting1: 'new' });
+ // Visible before the server answers, merged over the other fields.
+ expect(pluginSelectors.getPluginSettingsById('p1')(useToolStore.getState())).toEqual({
+ setting1: 'new',
+ setting2: 'keep',
+ });
+
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([
+ plugin('p1', { setting1: 'new', setting2: 'keep' }),
+ ]);
+ await act(async () => {
+ write.resolve();
+ await operation;
+ });
+
+ expect(pluginService.updatePluginSettings).toHaveBeenCalledWith(
+ 'p1',
+ { setting1: 'new', setting2: 'keep' },
+ expect.any(AbortSignal),
+ );
+ expect(useToolStore.getState().installedPlugins[0].settings).toEqual({
+ setting1: 'new',
+ setting2: 'keep',
+ });
+ });
+
+ it('rolls the settings back when the server rejects the write', async () => {
+ await loadFromServer([plugin('p1', { setting1: 'old' })]);
+ vi.mocked(pluginService.updatePluginSettings).mockRejectedValue(new Error('boom'));
+
+ await expect(
+ useToolStore.getState().updatePluginSettings('p1', { setting1: 'new' }),
+ ).rejects.toThrow('boom');
+
+ expect(useToolStore.getState().installedPlugins[0].settings).toEqual({ setting1: 'old' });
+ });
+
+ it('merges a write from the cached list onto the server record, not the projection', async () => {
+ await paintFromCache([plugin('p1', { setting1: 'old', setting2: 'keep' })]);
+ // The cached row has no settings: they never reached IndexedDB.
+ expect(useToolStore.getState().installedPlugins[0].settings).toBeUndefined();
+
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([
+ plugin('p1', { setting1: 'old', setting2: 'keep' }),
+ ]);
+ vi.mocked(pluginService.updatePluginSettings).mockResolvedValue(undefined as any);
+
+ await act(async () => {
+ await useToolStore.getState().updatePluginSettings('p1', { setting1: 'new' });
+ });
+
+ expect(pluginService.updatePluginSettings).toHaveBeenCalledWith(
+ 'p1',
+ { setting1: 'new', setting2: 'keep' },
+ expect.any(AbortSignal),
+ );
+ });
+
+ it('writes nothing when the server record cannot be loaded', async () => {
+ await paintFromCache([plugin('p1')]);
+ vi.mocked(pluginService.getInstalledPlugins).mockRejectedValue(new Error('offline'));
+
+ await expect(
+ useToolStore.getState().updatePluginSettings('p1', { setting1: 'new' }),
+ ).rejects.toThrow('offline');
+
+ expect(pluginService.updatePluginSettings).not.toHaveBeenCalled();
+ });
+
+ it('lets a newer write abort one still waiting for the server record', async () => {
+ await paintFromCache([plugin('p1', { a: 1 })]);
+ const records = deferred<LobeTool[]>();
+ vi.mocked(pluginService.getInstalledPlugins).mockReturnValue(records.promise);
+ vi.mocked(pluginService.updatePluginSettings).mockResolvedValue(undefined as any);
+
+ const first = useToolStore.getState().updatePluginSettings('p1', { a: 2 });
+ const firstSignal = useToolStore.getState().updatePluginSettingsSignal!;
+ const second = useToolStore.getState().updatePluginSettings('p1', { a: 3 });
+
+ // The first controller was published before the await, so the second aborts it.
+ expect(firstSignal.signal.aborted).toBe(true);
+
+ await act(async () => {
+ records.resolve([plugin('p1', { a: 1, b: 'keep' })]);
+ await Promise.all([first, second]);
+ });
+
+ expect(pluginService.updatePluginSettings).toHaveBeenCalledTimes(1);
+ expect(pluginService.updatePluginSettings).toHaveBeenCalledWith(
+ 'p1',
+ { a: 3, b: 'keep' },
+ expect.any(AbortSignal),
+ );
+ });
+
+ it('keeps the connection parameters the projection hid when writing an MCP delta', async () => {
+ const full = mcpPlugin('mcp-1');
+ await paintFromCache([full]);
+ expect(useToolStore.getState().installedPlugins[0].customParams).toEqual({
+ mcp: { type: 'http' },
+ });
+
+ vi.mocked(pluginService.getInstalledPlugins).mockResolvedValue([full]);
+ vi.mocked(pluginService.updatePlugin).mockResolvedValue(undefined as any);
+
+ await act(async () => {
+ await useToolStore.getState().updateInstallMcpPlugin('mcp-1', { env: { EXTRA: '1' } });
+ });
+
+ expect(pluginService.updatePlugin).toHaveBeenCalledWith('mcp-1', {
+ customParams: {
+ mcp: expect.objectContaining({
+ env: { EXTRA: '1', TOKEN: SECRET },
+ headers: { Authorization: `Bearer ${SECRET}` },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ }),
+ },
+ });
+ });
+ });
+});
diff --git a/src/store/tool/slices/plugin/selectors.ts b/src/store/tool/slices/plugin/selectors.ts
index 40cd9cef80c..a518609d230 100644
--- a/src/store/tool/slices/plugin/selectors.ts
+++ b/src/store/tool/slices/plugin/selectors.ts
@@ -1,19 +1,45 @@
-import { type Meta, type ToolManifest } from '@lobechat/types';
+import { type LobeTool, type Meta, type ToolManifest } from '@lobechat/types';
import { isInstalledPluginAvailableInCurrentEnv } from '@/helpers/toolAvailability';
import { type InstallPluginMeta, type LobeToolCustomPlugin } from '@/types/tool/plugin';
import { type ToolStoreState } from '../../initialState';
+import { INSTALLED_PLUGINS_KEY } from './projection';
+const EMPTY_PLUGINS: LobeTool[] = [];
+
+/**
+ * The installed-plugins list for display: identity, manifest and the runtime
+ * discriminators. On a reload it is the persisted display projection until the
+ * network answers, so it never carries `settings` or connection parameters
+ * there — read those through {@link confirmedInstalledPlugins}.
+ */
const installedPlugins = (s: ToolStoreState) => s.installedPlugins;
+/**
+ * Whether the list on screen is only the persisted display projection (hydrated
+ * from IndexedDB, not yet confirmed by the server).
+ */
+const isInstalledPluginsCacheOnly = (s: ToolStoreState) =>
+ s.installedPluginsReplica?.entries[INSTALLED_PLUGINS_KEY]?.source === 'storage';
+
+/**
+ * The full installed-plugin records — settings and MCP connection included —
+ * that tool assembly, tool execution, edit forms and writes may act on. Empty
+ * while only the cached display projection is loaded — the same empty list
+ * these paths saw before the first fetch landed when there was no cache.
+ */
+const confirmedInstalledPlugins = (s: ToolStoreState) =>
+ isInstalledPluginsCacheOnly(s) ? EMPTY_PLUGINS : s.installedPlugins;
+
const isPluginInstalled = (id: string) => (s: ToolStoreState) =>
installedPlugins(s).some((i) => i.identifier === id);
+/** The full record of an installed plugin (see {@link confirmedInstalledPlugins}). */
const getInstalledPluginById = (id?: string) => (s: ToolStoreState) => {
if (!id) return;
- return installedPlugins(s).find((p) => p.identifier === id);
+ return confirmedInstalledPlugins(s).find((p) => p.identifier === id);
};
/**
@@ -55,24 +81,25 @@ export const resolvePluginManifestMeta = (manifest?: ToolManifest | null): Meta
};
const getPluginMetaById = (id: string) => (s: ToolStoreState) => {
- return resolvePluginManifestMeta(getInstalledPluginById(id)(s)?.manifest);
+ return resolvePluginManifestMeta(getToolManifestById(id)(s));
};
const getCustomPluginById = (id: string) => (s: ToolStoreState) =>
- installedPlugins(s).find((i) => i.identifier === id && i.type === 'customPlugin') as
+ confirmedInstalledPlugins(s).find((i) => i.identifier === id && i.type === 'customPlugin') as
LobeToolCustomPlugin | undefined;
const getToolManifestById = (id: string) => (s: ToolStoreState) =>
- getInstalledPluginById(id)(s)?.manifest;
+ installedPlugins(s).find((p) => p.identifier === id)?.manifest;
const getPluginSettingsById = (id: string) => (s: ToolStoreState) =>
getInstalledPluginById(id)(s)?.settings || {};
const storeAndInstallPluginsIdList = (s: ToolStoreState) =>
- s.installedPlugins.map((i) => i.identifier);
+ installedPlugins(s).map((i) => i.identifier);
+/** Manifests offered to the model: only plugins whose full record is loaded. */
const installedPluginManifestList = (s: ToolStoreState) =>
- installedPlugins(s)
+ confirmedInstalledPlugins(s)
.map((i) => i.manifest as ToolManifest)
.filter((i) => !!i);
@@ -104,6 +131,7 @@ const isPluginHasUI = (id: string) => (s: ToolStoreState) => {
};
export const pluginSelectors = {
+ confirmedInstalledPlugins,
getCustomPluginById,
getInstalledPluginById,
getPluginMetaById,
@@ -113,6 +141,7 @@ export const pluginSelectors = {
installedPluginManifestList,
installedPluginMetaList,
installedPlugins,
+ isInstalledPluginsCacheOnly,
isPluginHasUI,
isPluginInstalled,
storeAndInstallPluginsIdList,