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.

πŸ› fix(agent): respect scoped builtin settings before tool discovery (#23458)

AmAzing-d731e455ac99
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index 05a31a4d8a6..ac60233147d 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -175,6 +175,7 @@ vi.mock('@/database/models/user', () => ({
UserModel: class {
static getInfoForAIGeneration = mockGetInfoForAIGeneration;
getUserPreference = mockGetUserPreference;
+ getUserSettings = vi.fn().mockResolvedValue(undefined);
},
}));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index ab25dffde63..6a820814629 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -218,7 +218,9 @@ const createBaseAgentConfig = (overrides: Record<string, any> = {}) => ({
describe('AiAgentService.execAgent - device tool pipeline ()', () => {
let service: AiAgentService;
- const mockDb = {} as any;
+ const mockDb = {
+ query: { userSettings: { findFirst: vi.fn().mockResolvedValue(undefined) } },
+ } as never;
const userId = 'test-user-id';
beforeEach(() => {
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
index 5b83c8a11b8..460d6ff2185 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
@@ -1,3 +1,4 @@
+import { onDemandBuiltinToolIds } from '@lobechat/builtin-tools';
import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -202,9 +203,11 @@ const toolManifestMapArg = () =>
describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)', () => {
let service: AiAgentService;
+ const readUserSettings = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
+ readUserSettings.mockResolvedValue(undefined);
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
mockCreateOperation.mockResolvedValue({
autoStarted: true,
@@ -218,7 +221,23 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'
pluginManifest('plugin-c'),
pluginManifest('plugin-d'),
]);
- service = new AiAgentService({} as any, 'test-user-id');
+ service = new AiAgentService(
+ { query: { userSettings: { findFirst: readUserSettings } } } as never,
+ 'test-user-id',
+ );
+ });
+
+ it('withholds all on-demand builtins when the settings read fails', async () => {
+ readUserSettings.mockRejectedValue(new Error('settings unavailable'));
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ });
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+ expect(disabledPluginIdsArg()).toEqual(expect.arrayContaining(onDemandBuiltinToolIds));
});
it('keeps only the installed plugins that are on, in a mixed-shape array: a disabled entry and a missing entry are both left out', async () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/runSettings.ts b/apps/server/src/services/aiAgent/pipeline/runSettings.ts
index 5ff41d4e530..28615d89c6d 100644
--- a/apps/server/src/services/aiAgent/pipeline/runSettings.ts
+++ b/apps/server/src/services/aiAgent/pipeline/runSettings.ts
@@ -1,4 +1,5 @@
import {
+ onDemandBuiltinToolIds,
resolveUninstalledBuiltinTools,
type UninstalledBuiltinToolsScope,
} from '@lobechat/builtin-tools';
@@ -36,7 +37,8 @@ export const resolveRunSettings = async ({
const agentMemoryEnabled = agentConfig.chatConfig?.memory?.enabled;
let globalMemoryEnabled = agentMemoryEnabled ?? false;
let enableExpertise = false;
- let uninstalledBuiltinIds: string[] = [];
+ // A failed settings read cannot confirm any optional builtin is installed.
+ let uninstalledBuiltinIds = onDemandBuiltinToolIds;
let userTimezone: string | undefined;
try {
const settings = await runFacts.userSettings();
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index 5c27ca10c8e..39eda2f418b 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -19,6 +19,11 @@ afterEach(() => {
desktopEnv.enabled = false;
});
+vi.mock(import('@/store/tool/slices/builtin/projection'), async (importOriginal) => ({
+ ...(await importOriginal()),
+ runtimeUninstalledBuiltinTools: () => [],
+}));
+
// Mock the store and helper dependencies
vi.mock('@/store/tool', () => ({
getToolStoreState: () => ({
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 8fa926440a8..c2f90dcad1d 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -44,6 +44,7 @@ import {
lobehubSkillStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { runtimeUninstalledBuiltinTools } from '@/store/tool/slices/builtin/projection';
import { connectorSelectors } from '@/store/tool/slices/connector';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -167,6 +168,7 @@ export const createAgentToolsEngine = (
* `readAttachment` so the preview can be paged, as the server's tool discovery does.
*/
hasOversizedFiles?: boolean;
+ uninstalledBuiltinTools?: string[];
/** Resolved for the executing agent, which can differ from the agent open in the UI. */
runAgent?: {
id?: string;
@@ -219,7 +221,7 @@ export const createAgentToolsEngine = (
...(pluginIds ?? []),
],
chatConfig,
- getToolStoreState().uninstalledBuiltinTools,
+ options.uninstalledBuiltinTools ?? runtimeUninstalledBuiltinTools(getToolStoreState()),
),
...getFeatureDisabledToolIds(getServerConfigStoreState()?.featureFlags),
// This engine serves runs the browser executes; server-only tools have nothing to run here.
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 355983a119e..ca6fd1a0fb3 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -36,6 +36,7 @@ import { getAgentStoreState } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
import { aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
import { getToolStoreState } from '@/store/tool';
+import { runtimeUninstalledBuiltinTools } from '@/store/tool/slices/builtin/projection';
import { getUserStoreState, useUserStore } from '@/store/user';
import {
settingsSelectors,
@@ -244,7 +245,8 @@ class ChatService {
...getUnavailableBuiltinToolIds(
[...getOptedInPluginIds(agentConfig.plugins), ...(enabledToolIds ?? [])],
chatConfig,
- getToolStoreState().uninstalledBuiltinTools,
+ // A running conversation already has a scope-filtered manifest map.
+ discoveryManifests ? [] : runtimeUninstalledBuiltinTools(getToolStoreState()),
),
...resolveAgentConnectorActivation(
{ chatConfig, plugins: agentConfig.plugins },
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 1fca59d6083..9907d1a66ec 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -1472,7 +1472,6 @@ describe('StreamingExecutor actions', () => {
}),
);
});
-
it.each([
{ isBuiltinAgent: true, skillActivateMode: 'manual' },
{ isBuiltinAgent: false, skillActivateMode: 'manual' },
@@ -1495,6 +1494,7 @@ describe('StreamingExecutor actions', () => {
agentId: TEST_IDS.SESSION_ID,
messages: [userMessage],
parentMessageId: userMessage.id,
+ uninstalledBuiltinTools: [],
});
expect(agentConfig.enabledToolIds).toContain('lobe-skill-store');
expect(agentConfig.enabledToolIds).toContain('lobe-skills');
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 875a892cf9f..f92a1f393b9 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -30,7 +30,7 @@ import { useUserStore } from '@/store/user';
import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';
import { type RunScope } from '../lifecycle/types';
-import { readClientRunMessages } from './ensureFullHistoryForClientRun';
+import { readClientRunInputs } from './ensureFullHistoryForClientRun';
import {
shouldUseConfiguredGatewayResume as resolveConfiguredGatewayResume,
shouldUseGatewayResume as resolveGatewayResume,
@@ -782,15 +782,15 @@ export class ConversationControlActionImpl {
// 3. Get current messages for state construction using context
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
- const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
+ const runInputs = await readClientRunInputs(this.#get, effectiveContext, chatKey);
const currentRequestMetadata = this.#getRequestMetadataFromMessageChain(
toolMessageId,
- currentMessages,
+ runInputs.messages,
);
// 4. Create agent state and context with user intervention config
const { state, context: initialContext } = this.#get().internal_createAgentState({
- messages: currentMessages,
+ ...runInputs,
parentMessageId: toolMessageId,
agentId,
topicId,
@@ -813,7 +813,7 @@ export class ConversationControlActionImpl {
try {
await executeClientAgent({
context: effectiveContext,
- messages: currentMessages,
+ ...runInputs,
parentMessageId: toolMessageId, // Start from tool message
parentMessageType: 'tool', // Type is 'tool'
initialState: state,
@@ -1162,14 +1162,14 @@ export class ConversationControlActionImpl {
// A completed interaction result resumes without a synthetic user message or tool re-execution.
if (!shouldCreateUserMessage) {
- const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
+ const runInputs = await readClientRunInputs(this.#get, effectiveContext, chatKey);
const requestMetadata = this.#getRequestMetadataFromMessageChain(
toolMessageId,
- currentMessages,
+ runInputs.messages,
);
const { state, context: initialContext } = this.#get().internal_createAgentState({
- messages: currentMessages,
+ ...runInputs,
parentMessageId: toolMessageId,
agentId,
topicId,
@@ -1189,7 +1189,7 @@ export class ConversationControlActionImpl {
try {
await executeClientAgent({
context: effectiveContext,
- messages: currentMessages,
+ ...runInputs,
parentMessageId: toolMessageId,
parentMessageType: 'tool',
initialState: state,
@@ -1239,12 +1239,12 @@ export class ConversationControlActionImpl {
// optimisticCreateMessage above is another await round-trip after the earlier
// guard, and executeClientAgent would otherwise start a fresh child run that
// wasn't present when the cancellation propagated.
- const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
+ const runInputs = await readClientRunInputs(this.#get, effectiveContext, chatKey);
if (this.#wasInterimOpStopped(operationId)) return;
// 3. Resume agent from user message (not tool re-execution)
const { state, context: initialContext } = this.#get().internal_createAgentState({
- messages: currentMessages,
+ ...runInputs,
parentMessageId: userMsg.id,
agentId,
topicId,
@@ -1255,7 +1255,7 @@ export class ConversationControlActionImpl {
try {
await executeClientAgent({
context: effectiveContext,
- messages: currentMessages,
+ ...runInputs,
parentMessageId: userMsg.id,
parentMessageType: 'user',
initialState: state,
@@ -1447,12 +1447,12 @@ export class ConversationControlActionImpl {
// optimisticCreateMessage above is another await round-trip after the guard
// before it, and executeClientAgent would otherwise start a fresh child run
// that wasn't present when the cancellation propagated.
- const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
+ const runInputs = await readClientRunInputs(this.#get, effectiveContext, chatKey);
if (this.#wasInterimOpStopped(operationId)) return;
// 3. Resume agent from user message
const { state, context: initialContext } = this.#get().internal_createAgentState({
- messages: currentMessages,
+ ...runInputs,
parentMessageId: userMsg.id,
agentId,
topicId,
@@ -1463,7 +1463,7 @@ export class ConversationControlActionImpl {
try {
await executeClientAgent({
context: effectiveContext,
- messages: currentMessages,
+ ...runInputs,
parentMessageId: userMsg.id,
parentMessageType: 'user',
initialState: state,
@@ -2141,12 +2141,12 @@ export class ConversationControlActionImpl {
// Get current messages for state construction using context
const chatKey = messageMapKey({ agentId, topicId, threadId, scope });
- const currentMessages = await readClientRunMessages(this.#get, effectiveContext, chatKey);
- const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId, currentMessages);
+ const runInputs = await readClientRunInputs(this.#get, effectiveContext, chatKey);
+ const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId, runInputs.messages);
// Create agent state and context to continue from rejected tool message
const { state, context: initialContext } = this.#get().internal_createAgentState({
- messages: currentMessages,
+ ...runInputs,
parentMessageId: messageId,
agentId,
topicId,
@@ -2164,7 +2164,7 @@ export class ConversationControlActionImpl {
try {
await executeClientAgent({
context: effectiveContext,
- messages: currentMessages,
+ ...runInputs,
parentMessageId: messageId,
parentMessageType: 'tool',
initialState: state,
diff --git a/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts
index e59e3a94bcd..1b5dcf1be90 100644
--- a/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.test.ts
@@ -4,7 +4,11 @@ import { isPartialHeadWindow } from '@/services/message/roundCursorPage';
import { displayMessageSelectors } from '@/store/chat/selectors';
import type { ChatStore } from '@/store/chat/store';
-import { readClientRunMessages } from './ensureFullHistoryForClientRun';
+import { readClientRunInputs } from './ensureFullHistoryForClientRun';
+
+vi.mock('@/store/tool', () => ({
+ getToolStoreState: () => ({ getUninstalledBuiltinToolsForRun: async () => ['lobe-calculator'] }),
+}));
vi.mock('@/services/message/roundCursorPage', () => ({ isPartialHeadWindow: vi.fn() }));
vi.mock('@/store/chat/selectors', () => ({
@@ -26,7 +30,7 @@ const setup = () => {
return { get: () => store, store };
};
-describe('readClientRunMessages', () => {
+describe('readClientRunInputs', () => {
beforeEach(() => {
vi.clearAllMocks();
});
@@ -35,8 +39,13 @@ describe('readClientRunMessages', () => {
vi.mocked(isPartialHeadWindow).mockReturnValue(true);
const { get, store } = setup();
- const messages = await readClientRunMessages(get, context, 'main_agt_1_tpc_1');
+ const { messages, uninstalledBuiltinTools } = await readClientRunInputs(
+ get,
+ context,
+ 'main_agt_1_tpc_1',
+ );
+ expect(uninstalledBuiltinTools).toEqual(['lobe-calculator']);
expect(store.refreshMessages).toHaveBeenCalledWith(context);
expect(messages.map((message) => message.id)).toEqual(['msg_oldest', 'msg_newest']);
expect(displayMessageSelectors.getDisplayMessagesByKey).toHaveBeenCalledWith(
@@ -48,8 +57,13 @@ describe('readClientRunMessages', () => {
vi.mocked(isPartialHeadWindow).mockReturnValue(false);
const { get, store } = setup();
- const messages = await readClientRunMessages(get, context, 'main_agt_1_tpc_1');
+ const { messages, uninstalledBuiltinTools } = await readClientRunInputs(
+ get,
+ context,
+ 'main_agt_1_tpc_1',
+ );
+ expect(uninstalledBuiltinTools).toEqual(['lobe-calculator']);
expect(store.refreshMessages).not.toHaveBeenCalled();
expect(messages.map((message) => message.id)).toEqual(['msg_newest']);
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts
index ed593ae2983..04a8fb34223 100644
--- a/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/ensureFullHistoryForClientRun.ts
@@ -3,6 +3,7 @@ import type { ConversationContext } from '@lobechat/types';
import { isPartialHeadWindow } from '@/services/message/roundCursorPage';
import { displayMessageSelectors } from '@/store/chat/selectors';
import type { ChatStore } from '@/store/chat/store';
+import { getToolStoreState } from '@/store/tool';
// Returns whether the history was re-read, so callers re-select their message list.
export const ensureFullHistoryForClientRun = async (
@@ -19,11 +20,17 @@ export const ensureFullHistoryForClientRun = async (
return true;
};
-export const readClientRunMessages = async (
+export const readClientRunInputs = async (
get: () => ChatStore,
context: ConversationContext,
chatKey: string,
) => {
- await ensureFullHistoryForClientRun(context, get().refreshMessages);
- return displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get());
+ const [uninstalledBuiltinTools] = await Promise.all([
+ getToolStoreState().getUninstalledBuiltinToolsForRun(),
+ ensureFullHistoryForClientRun(context, get().refreshMessages),
+ ]);
+ return {
+ messages: displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get()),
+ uninstalledBuiltinTools,
+ };
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index bbc3b7eb565..58fd52245c2 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -134,7 +134,9 @@ export class StreamingExecutorActionImpl {
isSubAgent,
modelOverride,
chatConfigOverride,
+ uninstalledBuiltinTools,
}: {
+ uninstalledBuiltinTools?: string[];
messages: UIChatMessage[];
parentMessageId: string;
agentId?: string;
@@ -293,7 +295,11 @@ export class StreamingExecutorActionImpl {
// sub-agent runs. Desktop client runs also need the local environment so
// local-system can advertise IPC-only capabilities such as direct image reads.
{ executionEnv: isDesktop ? 'local' : undefined, isSubAgent, scope },
- { hasOversizedFiles: hasPreviewableFiles(messages), runAgent: { ...runAgent, connectors } },
+ {
+ hasOversizedFiles: hasPreviewableFiles(messages),
+ runAgent: { ...runAgent, connectors },
+ uninstalledBuiltinTools,
+ },
);
const toolsDetailed = toolsEngine.generateToolsDetailed({
model: agentConfigData.model,
@@ -477,6 +483,8 @@ export class StreamingExecutorActionImpl {
};
executeClientAgent = async (params: {
+ /** Already resolved for a resumed run and its initial operation tool set. */
+ uninstalledBuiltinTools?: string[];
context: ConversationContext;
disableTools?: boolean;
initialContext?: AgentRuntimeContext;
@@ -604,11 +612,15 @@ export class StreamingExecutorActionImpl {
// bodies, so put the stored payloads back first. Ids come from the raw
// store list too: a folded tool result no longer carries `payloadOmitted`.
// Also returns a new array, so the caller's messages are never mutated.
- const messages = await hydrateProjectedConversation(
- [...originalMessages],
- this.#get().dbMessagesMap[messageKey],
- messageService.getToolResultPayloads,
- );
+ const [messages, uninstalledBuiltinTools] = await Promise.all([
+ hydrateProjectedConversation(
+ [...originalMessages],
+ this.#get().dbMessagesMap[messageKey],
+ messageService.getToolResultPayloads,
+ ),
+ params.uninstalledBuiltinTools ??
+ (disableTools ? undefined : getToolStoreState().getUninstalledBuiltinToolsForRun()),
+ ]);
// Decide tool / function-calling capability from real data, not a guess.
// The enabled-model list hydrates asynchronously (auth session β†’ aiProvider
@@ -633,6 +645,7 @@ export class StreamingExecutorActionImpl {
messages,
parentMessageId: params.parentMessageId,
agentId,
+ uninstalledBuiltinTools,
disableTools,
topicId,
threadId: threadId ?? undefined,
diff --git a/src/store/tool/slices/builtin/action.ts b/src/store/tool/slices/builtin/action.ts
index 6d1beb3174a..b86336b6cca 100644
--- a/src/store/tool/slices/builtin/action.ts
+++ b/src/store/tool/slices/builtin/action.ts
@@ -1,4 +1,4 @@
-import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
+import { defaultUninstalledBuiltinTools, onDemandBuiltinToolIds } from '@lobechat/builtin-tools';
import debug from 'debug';
import {
@@ -13,7 +13,9 @@ import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
import { invokeExecutor } from './executors/index';
import {
+ confirmedUninstalledBuiltinTools,
resolveUninstalledBuiltinTools,
+ runtimeUninstalledBuiltinTools,
UNINSTALLED_BUILTIN_TOOLS_KEY,
uninstalledBuiltinToolsResource,
} from './projection';
@@ -146,6 +148,22 @@ export class BuiltinToolActionImpl {
#isCurrentScope = (scope: string): boolean =>
this.#uninstalledBuiltinTools.resource.scope.get() === scope;
+ getUninstalledBuiltinToolsForRun = async (): Promise<string[]> => {
+ const scope = this.#uninstalledBuiltinTools.resource.scope.get();
+ const confirmed = confirmedUninstalledBuiltinTools(this.#get());
+ if (confirmed) return confirmed;
+
+ try {
+ await this.#uninstalledBuiltinTools.fetch({ workspaceId: getActiveWorkspaceId() }, { scope });
+ } catch (error) {
+ log('Failed to read builtin tool settings for this run: %O', error);
+ return onDemandBuiltinToolIds;
+ }
+ return this.#isCurrentScope(scope)
+ ? runtimeUninstalledBuiltinTools(this.#get())
+ : onDemandBuiltinToolIds;
+ };
+
/**
* Toggle a builtin tool's installed state for the active scope (personal or
* workspace), persisting to the matching slot in user settings.
diff --git a/src/store/tool/slices/builtin/projection.ts b/src/store/tool/slices/builtin/projection.ts
index 8b99e073fa7..eae444cd7da 100644
--- a/src/store/tool/slices/builtin/projection.ts
+++ b/src/store/tool/slices/builtin/projection.ts
@@ -1,5 +1,9 @@
+import { onDemandBuiltinToolIds } from '@lobechat/builtin-tools';
+
import { defineReplica } from '@/libs/replica';
+import type { BuiltinToolState } from './initialState';
+
export { resolveUninstalledBuiltinTools } from '@lobechat/builtin-tools';
/**
@@ -35,3 +39,20 @@ export const uninstalledBuiltinToolsResource = defineReplica<
storage: 'indexedDB',
version: 1,
});
+
+/** A persisted or previous scope's projection may paint the UI before this scope is confirmed. */
+export const confirmedUninstalledBuiltinTools = (state: BuiltinToolState) => {
+ if (!state.isUninstalledBuiltinToolsInit) return undefined;
+ const replica = state.uninstalledBuiltinToolsReplica;
+ const entry = replica.entries[UNINSTALLED_BUILTIN_TOOLS_KEY];
+ if (entry?.source !== 'server' || replica.scope !== uninstalledBuiltinToolsResource.scope.get()) {
+ return undefined;
+ }
+ // Apply an uninstall immediately, but keep an installation unavailable until its write commits.
+ return entry.base
+ ? [...new Set([...entry.base, ...state.uninstalledBuiltinTools])]
+ : state.uninstalledBuiltinTools;
+};
+
+export const runtimeUninstalledBuiltinTools = (state: BuiltinToolState) =>
+ confirmedUninstalledBuiltinTools(state) ?? onDemandBuiltinToolIds;
diff --git a/src/store/tool/slices/builtin/replica.test.ts b/src/store/tool/slices/builtin/replica.test.ts
index 6059fb8eb3a..6629aa0cfbd 100644
--- a/src/store/tool/slices/builtin/replica.test.ts
+++ b/src/store/tool/slices/builtin/replica.test.ts
@@ -7,7 +7,7 @@
*/
import { randomUUID } from 'node:crypto';
-import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';
+import { defaultUninstalledBuiltinTools, onDemandBuiltinToolIds } from '@lobechat/builtin-tools';
import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import type { PropsWithChildren } from 'react';
import { createElement, useEffect } from 'react';
@@ -79,6 +79,39 @@ describe('uninstalled builtin tools replica', () => {
vi.clearAllMocks();
});
+ it('waits for confirmed settings and reuses them across sends in the same scope', async () => {
+ const settings = Promise.withResolvers<ReturnType<typeof userState>>();
+ vi.mocked(userService.getUserState).mockReturnValue(settings.promise);
+ const read = useToolStore.getState().getUninstalledBuiltinToolsForRun;
+ const first = read();
+ const second = read();
+ settings.resolve(userState({ uninstalledBuiltinTools: ['lobe-calculator'] }));
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ ['lobe-calculator'],
+ ['lobe-calculator'],
+ ]);
+ await expect(read()).resolves.toEqual(['lobe-calculator']);
+ expect(userService.getUserState).toHaveBeenCalledTimes(1);
+ });
+
+ it('withholds on-demand tools after a failed read and retries on the next send', async () => {
+ vi.mocked(userService.getUserState)
+ .mockRejectedValueOnce(new Error('settings unavailable'))
+ .mockResolvedValueOnce(userState({ uninstalledBuiltinTools: [] }));
+ const read = useToolStore.getState().getUninstalledBuiltinToolsForRun;
+ await expect(read()).resolves.toEqual(onDemandBuiltinToolIds);
+ await expect(read()).resolves.toEqual([]);
+ });
+
+ it('discards the settings response when the active scope changes during a send', async () => {
+ const settings = Promise.withResolvers<ReturnType<typeof userState>>();
+ vi.mocked(userService.getUserState).mockReturnValue(settings.promise);
+ const pendingRead = useToolStore.getState().getUninstalledBuiltinToolsForRun();
+ useScope(`other-${randomUUID()}:personal`);
+ settings.resolve(userState({ uninstalledBuiltinTools: [] }));
+ await expect(pendingRead).resolves.toEqual(onDemandBuiltinToolIds);
+ });
+
it('paints the persisted list before the network answers', async () => {
await uninstalledBuiltinToolsResource.storage!.set(
{ queryKey: STORAGE_KEY, scope },
@@ -189,6 +222,11 @@ describe('uninstalled builtin tools replica', () => {
await waitFor(() => expect(updateSpy).toHaveBeenCalled());
expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['b']);
+ await expect(useToolStore.getState().getUninstalledBuiltinToolsForRun()).resolves.toEqual([
+ 'a',
+ 'b',
+ ]);
+
// The refresh that follows the write sees the server's new state.
vi.mocked(userService.getUserState).mockResolvedValue(
userState({ uninstalledBuiltinTools: ['b'] }),
@@ -198,6 +236,9 @@ describe('uninstalled builtin tools replica', () => {
await operation;
});
expect(useToolStore.getState().uninstalledBuiltinTools).toEqual(['b']);
+ await expect(useToolStore.getState().getUninstalledBuiltinToolsForRun()).resolves.toEqual([
+ 'b',
+ ]);
});
it('shows a toggle immediately even before the replica has painted', async () => {