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(tool): move the uninstalled builtin tools onto @lobechat/replica (#20585)

Arvin Xu9b3c4fa06c90
diff --git a/src/features/Settings/skill/features/SkillList.tsx b/src/features/Settings/skill/features/SkillList.tsx
index fe7eed8e555..301aa6028f1 100644
--- a/src/features/Settings/skill/features/SkillList.tsx
+++ b/src/features/Settings/skill/features/SkillList.tsx
@@ -137,7 +137,9 @@ const SkillList = memo<SkillListProps>(
void lobehubSkillsSWR.mutate();
void composioSWR.mutate();
void agentSkillsSWR.mutate();
- void builtinToolsSWR.mutate();
+ // The uninstalled-builtin list is a replica now: revalidate re-runs its
+ // network sync without blanking the painted list.
+ void builtinToolsSWR.revalidate();
};
// Load custom connectors (new connector store) so user-added OAuth MCP
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index d590b0ecc30..2a222bdb1a4 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -832,10 +832,6 @@ export const toolKeys = {
]),
composioConnections: def('tool:composioConnections', () => ['tool:composioConnections']),
installedPlugins: def('tool:installedPlugins', () => ['tool:installedPlugins']),
- uninstalledBuiltins: def('tool:uninstalledBuiltins', (workspaceId: string | null | undefined) => [
- 'tool:uninstalledBuiltins',
- workspaceId,
- ]),
};
// ---- global -------------------------------------------------------------
diff --git a/src/store/tool/slices/builtin/action.ts b/src/store/tool/slices/builtin/action.ts
index 0df017383e6..6d1beb3174a 100644
--- a/src/store/tool/slices/builtin/action.ts
+++ b/src/store/tool/slices/builtin/action.ts
@@ -1,54 +1,50 @@
import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
import debug from 'debug';
-import { type SWRResponse } from 'swr';
-import useSWR from 'swr';
import {
getActiveWorkspaceId,
useActiveWorkspaceId,
} from '@/business/client/hooks/useActiveWorkspaceId';
-import { mutate } from '@/libs/swr';
-import { toolKeys } from '@/libs/swr/keys';
+import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';
import { userService } from '@/services/user';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
import { invokeExecutor } from './executors/index';
+import {
+ resolveUninstalledBuiltinTools,
+ UNINSTALLED_BUILTIN_TOOLS_KEY,
+ uninstalledBuiltinToolsResource,
+} from './projection';
import { type BuiltinToolContext, type BuiltinToolResult } from './types';
const n = setNamespace('builtinTool');
const log = debug('lobe-store:builtin-tool');
/**
- * Minimal view of `settings.tool` covering just the builtin-tool install slots.
- * Typed locally so the helpers accept the loosened shape returned by
- * `getUserState()` while still spreading the rest of `tool` through at runtime.
- */
-interface UninstalledBuiltinToolsScope {
- uninstalledBuiltinTools?: string[];
- uninstalledBuiltinToolsByWorkspace?: Record<string, string[] | undefined>;
-}
-
-/**
- * Resolve the uninstalled-builtin-tools list for the active scope.
- *
- * - Personal context (`workspaceId == null`) β†’ the user's personal list.
- * - Workspace context β†’ the per-workspace list; a workspace with no stored
- * entry falls back to the default seed (a clean default state), never the
- * user's personal customization.
- *
- * `undefined` (never configured) maps to the default seed in both scopes.
+ * The uninstalled-tools list keeps its long-standing flat `uninstalledBuiltinTools`
+ * field as the replica view, so every selector keeps reading what it did. The
+ * init flag gates `get`: before the first hydrate / replace the view must read
+ * `undefined`, otherwise the default seed would block hydration from storage.
+ * The default seed stays the first-frame value (what the server resolves for a
+ * never-configured scope), so an un-hydrated replica still reads as "not yet
+ * filled" rather than as "everything is uninstalled".
*/
-const resolveUninstalledBuiltinTools = (
- tool: UninstalledBuiltinToolsScope | undefined,
- workspaceId: string | null,
-): string[] => {
- const stored = workspaceId
- ? tool?.uninstalledBuiltinToolsByWorkspace?.[workspaceId]
- : tool?.uninstalledBuiltinTools;
-
- return stored === undefined ? defaultUninstalledBuiltinTools : stored;
+const uninstalledBuiltinToolsLens: ReplicaLens<ToolStore, string[]> = {
+ clear: () => ({
+ isUninstalledBuiltinToolsInit: false,
+ uninstalledBuiltinTools: defaultUninstalledBuiltinTools,
+ }),
+ get: (state) => (state.isUninstalledBuiltinToolsInit ? state.uninstalledBuiltinTools : undefined),
+ keys: (state) => (state.isUninstalledBuiltinToolsInit ? [UNINSTALLED_BUILTIN_TOOLS_KEY] : []),
+ set: (_state, _key, data) =>
+ data
+ ? { isUninstalledBuiltinToolsInit: true, uninstalledBuiltinTools: data }
+ : {
+ isUninstalledBuiltinToolsInit: false,
+ uninstalledBuiltinTools: defaultUninstalledBuiltinTools,
+ },
};
/**
@@ -62,11 +58,23 @@ export const createBuiltinToolSlice = (set: Setter, get: () => ToolStore, _api?:
export class BuiltinToolActionImpl {
readonly #get: () => ToolStore;
readonly #set: Setter;
+ readonly #uninstalledBuiltinTools;
constructor(set: Setter, get: () => ToolStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#uninstalledBuiltinTools = createReplicaSlice(uninstalledBuiltinToolsResource, {
+ actionPrefix: n('uninstalledBuiltinTools'),
+ fetcher: async ({ workspaceId }) => {
+ const userState = await userService.getUserState();
+ return resolveUninstalledBuiltinTools(userState?.settings?.tool, workspaceId);
+ },
+ get,
+ set,
+ stateKey: 'uninstalledBuiltinToolsReplica',
+ view: uninstalledBuiltinToolsLens,
+ });
}
invokeBuiltinTool = async (
@@ -134,19 +142,28 @@ export class BuiltinToolActionImpl {
// ========== Uninstalled Builtin Tools Management ==========
+ /** The replica scope a request starts under; its result may only land there. */
+ #isCurrentScope = (scope: string): boolean =>
+ this.#uninstalledBuiltinTools.resource.scope.get() === scope;
+
/**
* Toggle a builtin tool's installed state for the active scope (personal or
* workspace), persisting to the matching slot in user settings.
*
* The current list is read fresh from the server so the diff is against the
- * real stored value (not the default seed). Persistence goes through the
- * scope-targeted server-side patch (`updateUninstalledBuiltinTools`), which
- * replaces only this scope's slot atomically β€” writing the whole `tool`
- * column from this snapshot would race with concurrent tool-column writers
- * (e.g. an approvalMode change from another tab) and could revert them.
+ * real stored value (not the default seed, and not a possibly-stale persisted
+ * copy). Persistence goes through the scope-targeted server-side patch
+ * (`updateUninstalledBuiltinTools`), which replaces only this scope's slot
+ * atomically β€” writing the whole `tool` column from a snapshot would race
+ * with concurrent tool-column writers (e.g. an approvalMode change from
+ * another tab) and could revert them.
*/
#toggleBuiltinToolInstalled = async (identifier: string, install: boolean): Promise<void> => {
const workspaceId = getActiveWorkspaceId();
+ // The identity the request starts under. `getUserState()` below can resolve
+ // after the user switched workspace, so the captured scope is re-checked
+ // before the replica is written (see the guard after the read).
+ const scope = this.#uninstalledBuiltinTools.resource.scope.get();
const userState = await userService.getUserState();
const tool = userState?.settings?.tool;
@@ -160,20 +177,35 @@ export class BuiltinToolActionImpl {
? currentUninstalled.filter((id) => id !== identifier)
: [...currentUninstalled, identifier];
- // Optimistic update
- this.#set(
- { uninstalledBuiltinTools: newUninstalled, uninstalledBuiltinToolsLoading: false },
- false,
- n(install ? 'installBuiltinTool' : 'uninstallBuiltinTool'),
- );
+ // The active identity changed while we read the server: keep the write
+ // pinned to the workspace the toggle started in, but never update the
+ // switched-to scope's replica with this list. The optimistic overlay would
+ // paint it into the scope now on screen and persist it there, and a
+ // rejected write would keep that wrong base β€” the follow-up refresh cannot
+ // repair a scope whose sync query is not mounted. Mirrors the connector /
+ // agent-skill actions' late-response guard.
+ if (!this.#isCurrentScope(scope)) {
+ await userService.updateUninstalledBuiltinTools(newUninstalled, workspaceId);
+ return;
+ }
- // Persist the captured scope's slot. The scope is pinned explicitly: the
- // list above was computed for `workspaceId`, and relying on the request's
- // dynamic workspace header instead would write it into whatever workspace
- // the user has switched to while `getUserState()` was in flight.
- await userService.updateUninstalledBuiltinTools(newUninstalled, workspaceId);
+ // Adopt the freshly-read list when the replica has not painted yet: an
+ // un-initialized replica drops an optimistic write, so without this base
+ // the toggle would only appear once the revalidation below lands.
+ if (!this.#get().isUninstalledBuiltinToolsInit) {
+ this.#uninstalledBuiltinTools.update(UNINSTALLED_BUILTIN_TOOLS_KEY, () => currentUninstalled);
+ }
+
+ // The replica shows the new list immediately and rolls it back when the
+ // server rejects the write; the confirmed list is then persisted as this
+ // scope's local-first copy.
+ await this.#uninstalledBuiltinTools.optimistic(
+ UNINSTALLED_BUILTIN_TOOLS_KEY,
+ () => newUninstalled,
+ () => userService.updateUninstalledBuiltinTools(newUninstalled, workspaceId),
+ );
- // Refresh to ensure consistency
+ // Refresh to ensure consistency.
await this.refreshUninstalledBuiltinTools();
};
@@ -192,39 +224,28 @@ export class BuiltinToolActionImpl {
};
/**
- * Refresh uninstalled builtin tools from server (active scope)
+ * Refresh the uninstalled-tools replica: the painted list stays on screen
+ * while the network answers, instead of blanking to the default seed first.
*/
refreshUninstalledBuiltinTools = async (): Promise<void> => {
- await mutate(toolKeys.uninstalledBuiltins(getActiveWorkspaceId()));
+ await this.#uninstalledBuiltinTools.revalidate(UNINSTALLED_BUILTIN_TOOLS_KEY);
};
/**
- * SWR hook to fetch uninstalled builtin tools for the active scope.
+ * Fetch orchestration for the uninstalled-builtin list. The replica is
+ * partitioned by the active identity (personal / each workspace), so a scope
+ * switch paints that scope's persisted copy on the first frame; combined with
+ * the SPA's per-workspace remount this revalidates automatically.
*
- * The cache key carries the active workspace id so personal and each
- * workspace keep independent caches; combined with the SPA's per-workspace
- * remount this revalidates automatically on workspace switch.
+ * Read the list through `builtinToolSelectors.uninstalledBuiltinTools`; this
+ * only schedules the network round-trip.
*/
- useFetchUninstalledBuiltinTools = (enabled: boolean): SWRResponse<string[]> => {
+ useFetchUninstalledBuiltinTools = (enabled: boolean): ReplicaSyncResult => {
const workspaceId = useActiveWorkspaceId();
- return useSWR<string[]>(
- enabled ? toolKeys.uninstalledBuiltins(workspaceId) : null,
- async () => {
- const userState = await userService.getUserState();
- return resolveUninstalledBuiltinTools(userState?.settings?.tool, workspaceId);
- },
- {
- fallbackData: defaultUninstalledBuiltinTools,
- onSuccess: (data) => {
- this.#set(
- { uninstalledBuiltinTools: data, uninstalledBuiltinToolsLoading: false },
- false,
- n('useFetchUninstalledBuiltinTools'),
- );
- },
- revalidateOnFocus: false,
- },
+ return this.#uninstalledBuiltinTools.useSync(
+ { workspaceId },
+ { enabled, revalidateOnFocus: false },
);
};
}
diff --git a/src/store/tool/slices/builtin/index.ts b/src/store/tool/slices/builtin/index.ts
index 279e5868539..e80ec197b2c 100644
--- a/src/store/tool/slices/builtin/index.ts
+++ b/src/store/tool/slices/builtin/index.ts
@@ -1,2 +1,3 @@
export * from './action';
export * from './initialState';
+export * from './projection';
diff --git a/src/store/tool/slices/builtin/initialState.ts b/src/store/tool/slices/builtin/initialState.ts
index 7e0e98cb7c1..b8e55774213 100644
--- a/src/store/tool/slices/builtin/initialState.ts
+++ b/src/store/tool/slices/builtin/initialState.ts
@@ -3,26 +3,36 @@ import { builtinTools, defaultUninstalledBuiltinTools } from '@lobechat/builtin-
import { type BuiltinSkillManifest, type LobeBuiltinTool } from '@lobechat/types';
import { filterBuiltinSkills } from '@/helpers/skillFilters';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
export interface BuiltinToolState {
builtinSkills: BuiltinSkillManifest[];
builtinToolLoading: Record<string, boolean>;
builtinTools: LobeBuiltinTool[];
/**
- * List of uninstalled builtin tool identifiers
- * Empty array means all builtin tools are enabled
+ * Whether the uninstalled-tools view has been filled (from storage or the
+ * server). Gates the replica lens: before the first hydrate / replace the
+ * view must read `undefined`, otherwise the default seed would block
+ * hydration from storage.
*/
- uninstalledBuiltinTools: string[];
+ isUninstalledBuiltinToolsInit: boolean;
/**
- * Loading state for fetching uninstalled builtin tools
+ * List of uninstalled builtin tool identifiers β€” the view of the
+ * `uninstalledBuiltinTools` replica.
+ *
+ * Empty array means all builtin tools are enabled; the default seed lists
+ * the ones the user still has to install explicitly.
*/
- uninstalledBuiltinToolsLoading: boolean;
+ uninstalledBuiltinTools: string[];
+ /** Replica bookkeeping for `uninstalledBuiltinTools`. */
+ uninstalledBuiltinToolsReplica: ReplicaState<string[]>;
}
export const initialBuiltinToolState: BuiltinToolState = {
builtinSkills: filterBuiltinSkills(builtinSkillManifests),
builtinToolLoading: {},
builtinTools,
+ isUninstalledBuiltinToolsInit: false,
uninstalledBuiltinTools: defaultUninstalledBuiltinTools,
- uninstalledBuiltinToolsLoading: true,
+ uninstalledBuiltinToolsReplica: createReplicaState(),
};
diff --git a/src/store/tool/slices/builtin/projection.ts b/src/store/tool/slices/builtin/projection.ts
new file mode 100644
index 00000000000..666edccb1e4
--- /dev/null
+++ b/src/store/tool/slices/builtin/projection.ts
@@ -0,0 +1,68 @@
+import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
+
+import { defineReplica } from '@/libs/replica';
+
+/**
+ * The uninstalled-builtin list is one entry: the active identity
+ * (`${userId}:${workspaceId ?? 'personal'}`) already partitions memory and
+ * storage, so the entry key is a constant and personal / each workspace keep
+ * independent rows automatically.
+ */
+export const UNINSTALLED_BUILTIN_TOOLS_KEY = 'uninstalled';
+
+export interface UninstalledBuiltinToolsParams {
+ /** Active workspace id, or `null` for the personal scope. */
+ workspaceId: string | null;
+}
+
+/**
+ * Uninstalled builtin tools (`settings.tool.uninstalledBuiltinTools` /
+ * `uninstalledBuiltinToolsByWorkspace`): the user's own list, read on the
+ * settings, skill-store and chat-input surfaces and written by install /
+ * uninstall. A local-first replica paints the persisted list on the first
+ * frame and lets the network confirm it in the background.
+ *
+ * The params carry the workspace the list belongs to so the fetch resolves the
+ * matching slot even if the user switches workspace while the request is in
+ * flight; the params do not change the entry key.
+ */
+export const uninstalledBuiltinToolsResource = defineReplica<
+ UninstalledBuiltinToolsParams,
+ string[]
+>({
+ key: () => UNINSTALLED_BUILTIN_TOOLS_KEY,
+ name: 'uninstalledBuiltinTools',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Minimal view of `settings.tool` covering just the builtin-tool install slots.
+ * Typed locally so the helpers accept the loosened shape returned by
+ * `getUserState()` while still spreading the rest of `tool` through at runtime.
+ */
+export interface UninstalledBuiltinToolsScope {
+ uninstalledBuiltinTools?: string[];
+ uninstalledBuiltinToolsByWorkspace?: Record<string, string[] | undefined>;
+}
+
+/**
+ * Resolve the uninstalled-builtin-tools list for the active scope.
+ *
+ * - Personal context (`workspaceId == null`) β†’ the user's personal list.
+ * - Workspace context β†’ the per-workspace list; a workspace with no stored
+ * entry falls back to the default seed (a clean default state), never the
+ * user's personal customization.
+ *
+ * `undefined` (never configured) maps to the default seed in both scopes.
+ */
+export const resolveUninstalledBuiltinTools = (
+ tool: UninstalledBuiltinToolsScope | undefined,
+ workspaceId: string | null,
+): string[] => {
+ const stored = workspaceId
+ ? tool?.uninstalledBuiltinToolsByWorkspace?.[workspaceId]
+ : tool?.uninstalledBuiltinTools;
+
+ return stored === undefined ? defaultUninstalledBuiltinTools : stored;
+};
diff --git a/src/store/tool/slices/builtin/replica.test.ts b/src/store/tool/slices/builtin/replica.test.ts
new file mode 100644
index 00000000000..6059fb8eb3a
--- /dev/null
+++ b/src/store/tool/slices/builtin/replica.test.ts
@@ -0,0 +1,298 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The uninstalled-builtin-tools list is a replica: it paints the persisted copy
+ * on the first frame, the network only confirms, and an install / uninstall
+ * shows in the view immediately β€” rolling back when the server rejects it.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
+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 * as workspaceHooks from '@/business/client/hooks/useActiveWorkspaceId';
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { userService } from '@/services/user';
+
+import { useToolStore } from '../../store';
+import { initialBuiltinToolState } from './initialState';
+import { UNINSTALLED_BUILTIN_TOOLS_KEY, uninstalledBuiltinToolsResource } from './projection';
+
+vi.mock('@/services/user', () => ({
+ userService: {
+ getUserState: vi.fn(),
+ updateUninstalledBuiltinTools: 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 userState = (tool: unknown) => ({ settings: { tool } }) as any;
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {}) as Promise<any>;
+
+const STORAGE_KEY = uninstalledBuiltinToolsResource.storageKey({ workspaceId: null });
+
+describe('uninstalled builtin tools replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`builtin-user-${randomUUID()}:personal`);
+ act(() => useToolStore.setState(initialBuiltinToolState));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].map((value) =>
+ uninstalledBuiltinToolsResource.storage!.remove({ queryKey: STORAGE_KEY, scope: value }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted list before the network answers', async () => {
+ await uninstalledBuiltinToolsResource.storage!.set(
+ { queryKey: STORAGE_KEY, scope },
+ { data: ['lobe-gone'], updatedAt: 1 },
+ );
+ vi.mocked(userService.getUserState).mockImplementation(pending);
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['lobe-gone']),
+ );
+ expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(true);
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ });
+
+ it('falls back to the default seed while nothing has been persisted yet', async () => {
+ vi.mocked(userService.getUserState).mockImplementation(pending);
+
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(defaultUninstalledBuiltinTools);
+ // No persisted copy and no server answer yet: the view is still un-painted.
+ expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(false);
+ });
+
+ it('replaces the list with the server response and persists it', async () => {
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['p1'] }),
+ );
+
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), { wrapper });
+
+ await waitFor(() => expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['p1']));
+ await waitFor(async () =>
+ expect(
+ (await uninstalledBuiltinToolsResource.storage!.get({ queryKey: STORAGE_KEY, scope }))
+ ?.data,
+ ).toEqual(['p1']),
+ );
+ });
+
+ it('resolves the per-workspace slot when a workspace is active', async () => {
+ vi.spyOn(workspaceHooks, 'useActiveWorkspaceId').mockReturnValue('ws-1');
+ vi.spyOn(workspaceHooks, 'getActiveWorkspaceId').mockReturnValue('ws-1');
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({
+ uninstalledBuiltinTools: ['personal-tool'],
+ uninstalledBuiltinToolsByWorkspace: { 'ws-1': ['ws-tool'] },
+ }),
+ );
+
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), { wrapper });
+
+ await waitFor(() =>
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['ws-tool']),
+ );
+ });
+
+ it('drops the previous identity’s list before the next one paints', async () => {
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['lobe-gone'] }),
+ );
+
+ const sync = renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['lobe-gone']),
+ );
+
+ vi.mocked(userService.getUserState).mockImplementation(pending);
+ useScope(`builtin-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(false));
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(defaultUninstalledBuiltinTools);
+ });
+
+ it('does not fetch while the sync is disabled', async () => {
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(false), { wrapper });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(userService.getUserState).not.toHaveBeenCalled();
+ expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(false);
+ });
+
+ it('shows the new list optimistically, then confirms from the server', async () => {
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['a', 'b'] }),
+ );
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), { wrapper });
+ await waitFor(() =>
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['a', 'b']),
+ );
+
+ let resolveWrite!: (value: unknown) => void;
+ const updateSpy = vi
+ .mocked(userService.updateUninstalledBuiltinTools)
+ .mockImplementation(() => new Promise((resolve) => (resolveWrite = resolve)) as any);
+
+ const operation = useToolStore.getState().installBuiltinTool('a');
+ // The overlay is visible before the server answers.
+ await waitFor(() => expect(updateSpy).toHaveBeenCalled());
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['b']);
+
+ // The refresh that follows the write sees the server's new state.
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['b'] }),
+ );
+ await act(async () => {
+ resolveWrite(undefined);
+ await operation;
+ });
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['b']);
+ });
+
+ it('shows a toggle immediately even before the replica has painted', async () => {
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['a', 'b'] }),
+ );
+
+ let resolveWrite!: (value: unknown) => void;
+ const updateSpy = vi
+ .mocked(userService.updateUninstalledBuiltinTools)
+ .mockImplementation(() => new Promise((resolve) => (resolveWrite = resolve)) as any);
+
+ // The replica has never painted (no storage row, no server answer yet).
+ expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(false);
+
+ const operation = useToolStore.getState().installBuiltinTool('a');
+ await waitFor(() => expect(updateSpy).toHaveBeenCalled());
+ // The freshly-read list became the base, so the overlay is visible.
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['b']);
+
+ await act(async () => {
+ resolveWrite(undefined);
+ await operation;
+ });
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['b']);
+ });
+
+ it('does not paint or persist a toggle whose identity changed while it read the server', async () => {
+ // Nothing is persisted and no server answer has landed, so the replica has
+ // not painted: the toggle takes the "adopt the freshly-read list" path that
+ // seeds the replica before the optimistic overlay.
+ expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(false);
+
+ // The toggle's own server read hangs until we release it.
+ let resolveState!: (value: unknown) => void;
+ vi.mocked(userService.getUserState).mockImplementation(
+ () => new Promise((resolve) => (resolveState = resolve)) as any,
+ );
+ vi.mocked(userService.updateUninstalledBuiltinTools).mockResolvedValue(undefined as any);
+
+ const operation = useToolStore.getState().installBuiltinTool('a');
+
+ // The user switches workspace while the server read is in flight.
+ const switched = `builtin-user-${randomUUID()}:personal`;
+ useScope(switched);
+
+ await act(async () => {
+ resolveState(userState({ uninstalledBuiltinTools: ['a', 'b'] }));
+ await operation;
+ });
+
+ // The server write stays pinned to the scope the toggle started in ...
+ expect(userService.updateUninstalledBuiltinTools).toHaveBeenCalledWith(['b'], null);
+ // ... while the switched-to scope is neither painted nor persisted with the
+ // previous identity's list.
+ expect(useToolStore.getState().isUninstalledBuiltinToolsInit).toBe(false);
+ expect(useToolStore.getState().uninstalledBuiltinTools).not.toEqual(['b']);
+ expect(
+ (
+ await uninstalledBuiltinToolsResource.storage!.get({
+ queryKey: STORAGE_KEY,
+ scope: switched,
+ })
+ )?.data,
+ ).toBeUndefined();
+ });
+
+ it('rolls the list back when the server rejects the write', async () => {
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['a', 'b'] }),
+ );
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), { wrapper });
+ await waitFor(() =>
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['a', 'b']),
+ );
+
+ vi.mocked(userService.updateUninstalledBuiltinTools).mockRejectedValue(new Error('boom'));
+
+ await expect(useToolStore.getState().installBuiltinTool('a')).rejects.toThrow('boom');
+
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['a', 'b']);
+ });
+
+ it('revalidates through refreshUninstalledBuiltinTools without clearing the list', async () => {
+ vi.mocked(userService.getUserState).mockResolvedValue(
+ userState({ uninstalledBuiltinTools: ['a'] }),
+ );
+ renderHook(() => useToolStore((s) => s.useFetchUninstalledBuiltinTools)(true), { wrapper });
+ await waitFor(() => expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['a']));
+
+ expect(UNINSTALLED_BUILTIN_TOOLS_KEY).toBe('uninstalled');
+ await act(async () => {
+ await useToolStore.getState().refreshUninstalledBuiltinTools();
+ });
+ // The list survived the revalidation round-trip.
+ expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['a']);
+ });
+});