🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): synchronize on-demand tool policies across chat and profile (#23369)
AmAzing-97a1d178e835
diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.mdindex 2d327256ecf..36f9027a48a 100644--- a/.agents/ux/lobe-design-rules.md+++ b/.agents/ux/lobe-design-rules.md@@ -189,3 +189,15 @@ Source: user corrections while simplifying the conversation Skills panel, includThe chat Tools picker lists services with connection records. Keep authorization actions on pending or failed connections in their existing activation group. First-time connection discovery belongs in connector management.Enforcement: `useControls.test.ts` covers missing connection records, cached unconnected providers, and pending or failed authorization rows. Source: user correction while debugging Kai’s chat Tools picker.++## LOBE-UX-026 — Tool menus expose choices, not fixed loaders++Keep fixed Agent infrastructure (the skill loader and tool activator) out of both loading-policy lists. Hiding the loader must not hide individual skills or the optional Skill Store.++Enforcement: the picker metadata excludes always-on identifiers; builtin selector and AgentToolsEngine tests cover the visible list and the runtime defaults.++## LOBE-UX-027 — One agent, one tool configuration++The profile library picker and chat Tools menu are two views of the same agent configuration. Share the tool inventory, translated names, state and agent-scoped write path, **not the popup**. The profile keeps its searchable checklist; chat keeps its loading-policy filters. Derive profile counts from the same unfiltered options. Agent-owned connector provisioning and the Skills invocation picker are separate tasks.++Enforcement: both surfaces use the same tool controls; regression tests cover the profile summary, runtime-backed settings and fixed-loader exclusions.diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/fixedLoaders.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/fixedLoaders.test.tsnew file mode 100644index 00000000000..79adba78c3f--- /dev/null+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/fixedLoaders.test.ts@@ -0,0 +1,30 @@+// @vitest-environment node+import { getUserDisabledToolIds } from '@lobechat/builtin-tools';+import { expect, it } from 'vitest';++import { createServerAgentToolsEngine } from '../index';++it('preserves fixed loaders despite legacy user preferences, but honors optional tool disables', () => {+ const disabled = ['lobe-skills', 'lobe-activator', 'lobe-skill-store'].map((identifier) => ({+ identifier,+ mode: 'disabled' as const,+ }));+ const engine = createServerAgentToolsEngine(+ { installedPlugins: [], isModelSupportToolUse: () => true },+ {+ agentConfig: { plugins: [] },+ disabledPluginIds: getUserDisabledToolIds(disabled),+ model: 'deepseek-chat',+ provider: 'deepseek',+ },+ );+ const { enabledToolIds } = engine.generateToolsDetailed({+ model: 'deepseek-chat',+ provider: 'deepseek',+ toolIds: [],+ });+ expect(enabledToolIds).toContain('lobe-skills');+ expect(enabledToolIds).toContain('lobe-activator');+ expect(engine.getAvailablePlugins()).not.toContain('lobe-skill-store');+ expect(getUserDisabledToolIds(disabled, { toolMode: 'custom' })).toContain('lobe-skills');+});diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.tsindex 70ee485d871..e97babd971d 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverCallAgent.integration.test.ts@@ -4,7 +4,7 @@* execution flow.** Verifies the full lifecycle end-to-end on the in-memory runtime:- * 1. Parent op LLM emits a `lobe-agent-management____callAgent` tool call.+ * 1. Parent activates agent management, then emits a `lobe-agent-management____callAgent` tool call.* 2. The real server executor parks the parent, creates a pending tool* placeholder, and forks the target agent as a child op.* 3. The child op completes.@@ -55,17 +55,13 @@ const PARENT_FINAL = 'I received the target agent result and the delegated workconst createTestContext = () => ({ jwtPayload: { userId }, userId });-const createCallAgentResponse = () => {- const responseId = `resp_call_agent_${Date.now()}`;- const msgItemId = `msg_call_agent_${Date.now()}`;- const callId = 'call_agent_1';+const createToolCallResponse = (callId: string, name: string, args: Record<string, unknown>) => {+ const responseId = `resp_${callId}`;+ const msgItemId = `msg_${callId}`;const fnCall = {- arguments: JSON.stringify({- agentId: targetAgentId,- instruction: 'Handle the delegated backend integration task.',- }),+ arguments: JSON.stringify(args),call_id: callId,- name: 'lobe-agent-management____callAgent',+ name,type: 'function_call',};@@ -220,13 +216,22 @@ afterEach(async () => {describe('Server callAgent deferred execution', () => {it('parks the parent, runs the target agent, backfills the tool message and resumes', async () => {- let callCount = 0;- mockResponsesCreate.mockImplementation(function () {- callCount++;- if (callCount === 1) return Promise.resolve(createCallAgentResponse() as any);- if (callCount === 2) return Promise.resolve(createFinalTextResponse(TARGET_ANSWER) as any);- return Promise.resolve(createFinalTextResponse(PARENT_FINAL) as any);- });+ mockResponsesCreate+ .mockResolvedValueOnce(+ createToolCallResponse('activate_1', 'lobe-activator____activateTools', {+ identifiers: ['lobe-agent-management'],+ reason: 'Delegate the task to the target agent.',+ }),+ )+ .mockResolvedValueOnce(+ createToolCallResponse('call_agent_1', 'lobe-agent-management____callAgent', {+ agentId: targetAgentId,+ instruction: 'Handle the delegated backend integration task.',+ }),+ )+ .mockResolvedValueOnce(createFinalTextResponse(TARGET_ANSWER))+ .mockResolvedValueOnce(createFinalTextResponse(PARENT_FINAL))+ .mockRejectedValue(new Error('Unexpected extra model call'));const caller = aiAgentRouter.createCaller(createTestContext());@@ -245,7 +250,7 @@ describe('Server callAgent deferred execution', () => {expect(finalState.status).toBe('done');expect(finalState.pendingToolsCalling ?? []).toHaveLength(0);- expect(mockResponsesCreate).toHaveBeenCalledTimes(3);+ expect(mockResponsesCreate).toHaveBeenCalledTimes(4);const childOps = await serverDB.select()diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.tsindex 94ed4d5a317..d9e3b10818c 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts@@ -3,7 +3,8 @@* Integration test for the server `callSubAgent` async suspend/resume flow.** Verifies the full deferred-tool lifecycle end-to-end on the in-memory runtime:- * 1. Parent op LLM emits a `lobe-agent____callSubAgent` tool call.+ * 1. Parent activates `lobe-agent` (loaded on demand), then emits a+ * `lobe-agent____callSubAgent` tool call.* 2. The real server executor parks the parent (`waiting_for_async_tool`),* creates a pending placeholder tool message, and forks a child op.* 3. The child op runs independently and completes.@@ -56,18 +57,14 @@ const PARENT_FINAL = 'Based on the sub-agent result, the final answer is 42.';const createTestContext = () => ({ jwtPayload: { userId }, userId });-/** Mock parent first step: a single `callSubAgent` tool call. */-const createCallSubAgentResponse = () => {- const responseId = `resp_parent_${Date.now()}`;- const msgItemId = `msg_parent_${Date.now()}`;- const callId = `call_subagent_1`;+/** Mock a parent step that emits a single tool call. */+const createToolCallResponse = (callId: string, name: string, args: Record<string, unknown>) => {+ const responseId = `resp_${callId}_${Date.now()}`;+ const msgItemId = `msg_${callId}_${Date.now()}`;const fnCall = {- arguments: JSON.stringify({- description: 'Research the answer',- instruction: 'Find the answer to the ultimate question.',- }),+ arguments: JSON.stringify(args),call_id: callId,- name: 'lobe-agent____callSubAgent',+ name,type: 'function_call',};@@ -226,6 +223,9 @@ describe('Server callSubAgent suspend/resume', () => {const reviewedResults: string[] = [];const fetchHook = vi.fn(async (_url: string, init: RequestInit) => {const payload = JSON.parse(init.body as string);+ // The hook reviews every tool result; only the sub-agent result is under test,+ // so the activation that precedes it passes untouched.+ if (payload.apiName !== 'callSubAgent') return new Response(JSON.stringify({}));const [placeholder] = await serverDB.select().from(messages)@@ -246,15 +246,24 @@ describe('Server callSubAgent suspend/resume', () => {: originalFetch(url, init),);}- // 1: parent emits callSubAgent 2: sub-op final answer 3: parent resume final- let callCount = 0;- mockResponsesCreate.mockImplementation(function () {- callCount++;- if (callCount === 1) return Promise.resolve(createCallSubAgentResponse() as any);- if (callCount === 2)- return Promise.resolve(createFinalTextResponse(SUB_AGENT_ANSWER) as any);- return Promise.resolve(createFinalTextResponse(PARENT_FINAL) as any);- });+ // 1: parent activates lobe-agent 2: parent emits callSubAgent+ // 3: sub-op final answer 4: parent resume final+ mockResponsesCreate+ .mockResolvedValueOnce(+ createToolCallResponse('activate_1', 'lobe-activator____activateTools', {+ identifiers: [LobeAgentIdentifier],+ reason: 'Delegate the research to a sub-agent.',+ }) as any,+ )+ .mockResolvedValueOnce(+ createToolCallResponse('call_subagent_1', 'lobe-agent____callSubAgent', {+ description: 'Research the answer',+ instruction: 'Find the answer to the ultimate question.',+ }) as any,+ )+ .mockResolvedValueOnce(createFinalTextResponse(SUB_AGENT_ANSWER) as any)+ .mockResolvedValueOnce(createFinalTextResponse(PARENT_FINAL) as any)+ .mockRejectedValue(new Error('Unexpected extra model call'));const caller = aiAgentRouter.createCaller(createTestContext());@@ -274,12 +283,16 @@ describe('Server callSubAgent suspend/resume', () => {expect(finalState.status).toBe('done');expect(finalState.pendingToolsCalling ?? []).toHaveLength(0);- expect(mockResponsesCreate.mock.calls[0][0].tools).toContainEqual(- expect.objectContaining({ name: 'lobe-agent____callSubAgent', type: 'function' }),- );+ // lobe-agent loads on demand: absent from the first step, offered once activated+ const callSubAgentTool = expect.objectContaining({+ name: 'lobe-agent____callSubAgent',+ type: 'function',+ });+ expect(mockResponsesCreate.mock.calls[0][0].tools).not.toContainEqual(callSubAgentTool);+ expect(mockResponsesCreate.mock.calls[1][0].tools).toContainEqual(callSubAgentTool);- // Three LLM calls: parent-initial, sub-op, parent-resume- expect(mockResponsesCreate).toHaveBeenCalledTimes(3);+ // Four LLM calls: parent-activate, parent-delegate, sub-op, parent-resume+ expect(mockResponsesCreate).toHaveBeenCalledTimes(4);// A child op was spawned and reconciled to the parentconst childOps = await serverDB@@ -288,7 +301,6 @@ describe('Server callSubAgent suspend/resume', () => {.where(eq(agentOperations.parentOperationId, createResult.operationId));expect(childOps.length).toBeGreaterThanOrEqual(1);if (decision) {- expect(fetchHook).toHaveBeenCalledTimes(1);expect(pendingContents).toEqual(['']);expect(reviewedResults[0]).toContain(SUB_AGENT_ANSWER);expect(reviewedResults[0]).toMatch(/<sub_agent id="[^"]+" \/>$/);@@ -307,7 +319,7 @@ describe('Server callSubAgent suspend/resume', () => {expect(subAgentToolMessage).toBeDefined();if (decision !== 'deny')expect(subAgentToolMessage!.content).toMatch(/<sub_agent id="[^"]+" \/>$/);- const parentInput = JSON.stringify(mockResponsesCreate.mock.calls[2][0]);+ const parentInput = JSON.stringify(mockResponsesCreate.mock.calls[3][0]);expect(parentInput).toContain(decision === 'deny' ? 'Blocked by afterToolCall hook.' : SUB_AGENT_ANSWER,);diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex 15e24e15738..05a31a4d8a6 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -794,7 +794,8 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {});const callArgs = mockCreateOperation.mock.calls[0][0];- expect(callArgs.agentConfig.plugins).toEqual(['lobe-agent-documents']);+ // No page agent without a sandbox; the saved documents pin loads on demand.+ expect(callArgs.agentConfig.plugins).toEqual([]);});it('should inject page-agent runtime for regular agents in page scope', async () => {@@ -822,7 +823,8 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {documentId: 'docs-1',scope: 'page',});- expect(callArgs.agentConfig.plugins).toEqual([PageAgentIdentifier, 'lobe-agent-documents']);+ // The page agent is a runtime addition; the saved documents pin loads on demand.+ expect(callArgs.agentConfig.plugins).toEqual([PageAgentIdentifier]);expect(callArgs.agentConfig.chatConfig.enableHistoryCount).toBe(false);expect(callArgs.agentConfig.systemRole).toContain('Custom role.');expect(callArgs.agentConfig.systemRole).toContain(@@ -833,10 +835,13 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {expect.anything(),expect.objectContaining({agentConfig: expect.objectContaining({- plugins: [PageAgentIdentifier, 'lobe-agent-documents'],+ plugins: [PageAgentIdentifier],}),}),);+ // …and stays discoverable rather than cut as an unselected builtin.+ const engineArgs = vi.mocked(createServerAgentToolsEngine).mock.calls[0][1];+ expect(engineArgs.disabledPluginIds).not.toContain('lobe-agent-documents');});it('should normalize task identifier from appContext before creating runtime operation', async () => {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex d508367d93d..9fa739d8178 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -293,8 +293,12 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {{ deviceId: 'dev-1', hostname: 'Mac', online: true, platform: 'darwin' },]);mockQueryDeviceSystemInfo.mockResolvedValue({ supportedTools });+ // Computer Use is opt-in per agent; the device report gates it after that.mockGetAgentConfig.mockResolvedValue(- createBaseAgentConfig({ agencyConfig: { executionTarget: 'local' } }),+ createBaseAgentConfig({+ agencyConfig: { executionTarget: 'local' },+ plugins: [{ identifier: AuvManifest.identifier, mode: 'auto' }],+ }),);await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', deviceId: 'dev-1' });const map = mockCreateOperation.mock.calls[0][0].toolSet.manifestMap;@@ -302,6 +306,21 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {},);+ it('keeps Computer Use out for an agent that has not turned it on, even on a supporting device', async () => {+ const { deviceGateway } = await import('@/server/services/deviceGateway');+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ mockQueryDeviceList.mockResolvedValue([+ { deviceId: 'dev-1', hostname: 'Mac', online: true, platform: 'darwin' },+ ]);+ mockQueryDeviceSystemInfo.mockResolvedValue({ supportedTools: [AuvManifest.identifier] });+ mockGetAgentConfig.mockResolvedValue(+ createBaseAgentConfig({ agencyConfig: { executionTarget: 'local' } }),+ );+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', deviceId: 'dev-1' });+ const map = mockCreateOperation.mock.calls[0][0].toolSet.manifestMap;+ expect(map[AuvManifest.identifier]).toBeUndefined();+ });+describe('deviceContext forwarded to createServerAgentToolsEngine', () => {it('should pass deviceContext when gateway is configured', async () => {// Override deviceGateway.isConfigureddiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.tsindex 750a79b71cc..6f3e09fff7c 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts@@ -691,6 +691,24 @@ describe('AiAgentService.execAgent - toolModeOverride (/mode command)', () => {service = new AiAgentService(mockDb, userId);});+ it.each([+ { from: 'agent', to: 'chat', expected: ['lobe-image-generation', 'lobe-video-generation'] },+ { from: 'chat', to: 'agent', expected: [] },+ ] as const)(+ 'resolves saved media pins for /mode $to instead of the stored $from mode',+ async ({ from, to, expected }) => {+ mockGetAgentConfig.mockResolvedValue({+ ...defaultAgentConfig,+ chatConfig: { toolMode: from },+ plugins: ['lobe-image-generation', { identifier: 'lobe-video-generation', mode: 'pinned' }],+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello', toolModeOverride: to });++ expect(mockCreateOperation.mock.calls[0][0].agentConfig.plugins).toEqual(expected);+ },+ );+it('/mode chat on an agent-mode agent also disables enableAgentMode for context injection', async () => {mockGetAgentConfig.mockResolvedValue({...defaultAgentConfig,diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex 411308ce9c2..a6e3f683c29 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';@@ -251,7 +252,7 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'expect(toolManifestMapArg()).not.toHaveProperty('plugin-d');});- it('keeps a pinned plugin out of the engine agentConfig.plugins, which only carries pinned builtin tools', async () => {+ it('keeps pinned plugins and pinned on-demand builtins out of the engine agentConfig.plugins in Agent mode', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},id: 'agent-1',@@ -267,16 +268,35 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);- // A pinned plugin is on: found through the activator, not invoked up front.- expect(agentConfigPluginsArg()).toEqual(['lobe-image-generation']);+ // A pinned entry is on: found through the activator, not invoked up front.+ expect(agentConfigPluginsArg()).toEqual([]);expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-a']);expect(toolManifestMapArg()).toHaveProperty('plugin-a');- expect(disabledPluginIdsArg()).toEqual(['plugin-b']);+ expect(disabledPluginIdsArg()).toContain('plugin-b');+ // The pinned builtin stays discoverable; only builtins the agent never chose are cut.+ expect(disabledPluginIdsArg()).not.toContain('lobe-image-generation');+ expect(disabledPluginIdsArg()).toContain('lobe-video-generation');});- it('feeds the plugins that are on into the engine agentConfig.plugins in manual mode, excluding disabled', async () => {+ it('offers a pinned media tool up front in Chat mode, which has no activator', async () => {mockGetAgentConfig.mockResolvedValue({- // Manual mode has no activator, so on is the only way to reach the model.+ chatConfig: { enableAgentMode: false },+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [{ identifier: 'lobe-image-generation', mode: 'pinned' }],+ provider: 'openai',+ systemRole: 'You are a helper',+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);++ expect(agentConfigPluginsArg()).toEqual(['lobe-image-generation']);+ expect(disabledPluginIdsArg()).not.toContain('lobe-image-generation');+ });++ it('treats a legacy manual preference like Agent mode: plugins that are on stay discoverable, disabled ones stay out', async () => {+ mockGetAgentConfig.mockResolvedValue({+ // Manual mode no longer strips the activator, so on means found on demand.chatConfig: { skillActivateMode: 'manual' },id: 'agent-1',model: 'gpt-4',@@ -291,9 +311,11 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);- expect(agentConfigPluginsArg()).toEqual(['plugin-a', 'plugin-c']);+ expect(agentConfigPluginsArg()).toEqual([]);expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-a', 'plugin-c']);- expect(disabledPluginIdsArg()).toEqual(['plugin-b']);+ expect(disabledPluginIdsArg()).toContain('plugin-b');+ expect(disabledPluginIdsArg()).not.toContain('plugin-a');+ expect(disabledPluginIdsArg()).not.toContain('plugin-c');});it('reads a pure string array as the plugins that are on, leaving every other installed plugin off', async () => {@@ -311,7 +333,9 @@ describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)'const installed = installedPluginsArg().map((p) => p.identifier);expect(installed).toEqual(['plugin-a']);expect(agentConfigPluginsArg()).toEqual([]);- expect(disabledPluginIdsArg()).toEqual([]);+ // Only builtins the agent never opted into are cut; the string entry is on.+ expect(disabledPluginIdsArg()).not.toContain('plugin-a');+ expect(disabledPluginIdsArg().every((id) => onDemandBuiltinToolIds.includes(id))).toBe(true);});it('brings in a plugin the agent has off on the turn that @-mentions it', async () => {diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.tsindex 3e139e6e84a..e71fe46e34e 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts@@ -335,16 +335,15 @@ describe('discoverTools — custom MCP connectors are opt-in per agent', () => {{ label: 'turned on', options: ON },{ label: 'pinned', options: { plugins: [YINGMI] } },])(- 'enables a connector the agent $label directly when manual mode strips the activator',+ 'defers a connector the agent $label even with a legacy manual preference',async ({ options }) => {const result = await run({ ...options, chatConfig: { skillActivateMode: 'manual' } });- expect(result.toolsResult.enabledToolIds).toContain(YINGMI);- expect(- offeredToolNames(result).some((name) =>- name.startsWith(`${YINGMI}____BatchGetFundNavHistory`),- ),- ).toBe(true);+ expect(result.toolsResult.enabledToolIds).toContain('lobe-activator');+ expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);+ expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(+ YINGMI,+ );},);diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.tsindex 742bfe4a5c7..6bf46a76dbb 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.installedPlugins.test.ts@@ -141,6 +141,14 @@ const ON = { autoSkillIds: [FEISHU] };const MANUAL = { chatConfig: { skillActivateMode: 'manual' } };describe('discoverTools — installed plugins are opt-in per agent', () => {+ it('only offers a configurable builtin to discovery when this agent opted in', async () => {+ const id = 'lobe-skill-store';+ expect((await run()).toolManifestMap[id]).toBeUndefined();+ const on = await run({ autoSkillIds: [id] });+ expect(availableToolIds(on.toolManifestMap, on.toolsResult.enabledToolIds)).toContain(id);+ expect(on.toolsResult.enabledToolIds).not.toContain(id);+ });+it('keeps an installed plugin the agent never turned on out of the run', async () => {const result = await run();@@ -154,6 +162,8 @@ describe('discoverTools — installed plugins are opt-in per agent', () => {it.each([{ label: 'turned on', options: ON },+ { label: 'turned on with an old manual preference', options: { ...ON, ...MANUAL } },+ { label: 'pinned with an old manual preference', options: { ...MANUAL, plugins: [FEISHU] } },{ label: 'pinned', options: { plugins: [FEISHU] } },])('offers an installed plugin the agent $label to the activator without enabling it',@@ -177,9 +187,6 @@ describe('discoverTools — installed plugins are opt-in per agent', () => {);it.each([- // Manual mode has no activator, so on is the only way to reach the model.- { label: 'the agent turned on, in manual mode', options: { ...ON, ...MANUAL } },- { label: 'the agent pinned, in manual mode', options: { ...MANUAL, plugins: [FEISHU] } },// The turn brings the plugin in itself, whatever the agent's switch says.{ label: 'the turn @-mentions', options: { selectedToolIds: [FEISHU] } },])('enables a plugin $label directly', async ({ options }) => {diff --git a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.tsindex 7246af45684..d91983338cc 100644--- a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts+++ b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts@@ -1,11 +1,17 @@+import { getUserDisabledToolIds, isOnDemandBuiltinTool } from '@lobechat/builtin-tools';import { resolveSubAgentChatConfig } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { type AgentConfigSnapshot, resolveAgentConfig } from '@lobechat/mecha';-import type { AgentModelOverride, LobeAgentAgencyConfig, MessageMapScope } from '@lobechat/types';+import type {+ AgentModelOverride,+ LobeAgentAgencyConfig,+ LobeAgentChatConfig,+ MessageMapScope,+} from '@lobechat/types';import {applyTopicModelToHeterogeneousProvider,getAutoPluginIds,- getDisabledPluginIds,+ getPinnedPluginIds,resolveAgentAgencyConfig,resolveHeterogeneousModelOverride,} from '@lobechat/types';@@ -48,6 +54,17 @@ export interface ResolveRunAgentConfigInput {toolModeOverride?: InternalExecAgentParams['toolModeOverride'];}+// The IM /mode switch controls both the toolset and agentic context injection.+// Returning to Agent mode keeps an explicitly custom toolset instead of widening it.+const withConversationMode = (+ config: LobeAgentChatConfig,+ mode: NonNullable<ResolveRunAgentConfigInput['toolModeOverride']>,+): LobeAgentChatConfig => ({+ ...config,+ enableAgentMode: mode === 'agent',+ toolMode: mode === 'agent' && config?.toolMode === 'custom' ? 'custom' : mode,+});+export interface ResolvedRunAgentConfig {/*** The MUTABLE effective config for this run. Later stages keep appending to@@ -238,7 +255,14 @@ export const resolveRunAgentConfig = async (},agentConfig: row,canManage: canManageAgent,- chatConfig: row.chatConfig,+ // The shared resolver filters saved pins before composing runtime tools.+ // Give it the conversation's mode now; filtered pins cannot be recovered later.+ chatConfig: toolModeOverride+ ? withConversationMode(+ resolveSubAgentChatConfig(row.chatConfig, chatConfigOverride) ?? row.chatConfig,+ toolModeOverride,+ )+ : row.chatConfig,memberModeOverride: overrides.mode,memberModelOverride: overrides.model,slug: row.slug ?? undefined,@@ -264,10 +288,13 @@ export const resolveRunAgentConfig = async (// Capture disabled identifiers off the row before the resolved config// collapses plugins to pinned ids: they later filter the auto-discovery// candidate pool so a disabled plugin can't be rediscovered.- const disabledPluginIds = getDisabledPluginIds(row.plugins);+ const disabledPluginIds = getUserDisabledToolIds(row.plugins, resolved.chatConfig);// Same for the explicit `auto` entries: a library skill is opt-in per agent,// so the skill pool needs the ones this agent opted into without pinning.- const autoSkillIds = getAutoPluginIds(row.plugins);+ const autoSkillIds = [+ ...getAutoPluginIds(row.plugins),+ ...getPinnedPluginIds(row.plugins).filter(isOnDemandBuiltinTool),+ ];// One mutable object from here on — later stages append to `systemRole` and// `createOperation` must see those writes.@@ -315,26 +342,10 @@ export const resolveRunAgentConfig = async (agentConfig.subAgentChatConfigOverride = chatConfigOverride;}- // Explicit per-conversation mode switch (IM `/mode` command). Applied last- // so it wins over the agent's own chatConfig, workspace member-mode- // overrides, and sub-agent chatConfig patches alike. `enableAgentMode` is- // kept in sync because the context engine gates agentic-only injectors- // (skill discovery, agent documents, agent-management context) on it, not- // on `toolMode` — otherwise `/mode chat` would keep agentic context while- // `/mode agent` on a chat-default agent would run tools without it.- if (toolModeOverride) {- // `custom` is agent-side (the `/mode` picker reports it as Agent Mode)- // but means "exactly the agent's declared plugins". Returning to Agent- // Mode must restore that hand-picked set, not widen it to the full- // default toolset by overwriting `custom` with `agent`.- const storedToolMode = agentConfig.chatConfig?.toolMode;- agentConfig.chatConfig = {- ...agentConfig.chatConfig,- enableAgentMode: toolModeOverride === 'agent',- toolMode:- toolModeOverride === 'agent' && storedToolMode === 'custom' ? 'custom' : toolModeOverride,- };- }+ // Builtin and sub-agent patches can also declare a mode. The conversation+ // switch wins for the final context just as it does for saved pin selection.+ if (toolModeOverride)+ agentConfig.chatConfig = withConversationMode(agentConfig.chatConfig, toolModeOverride);// Persistence-attribution agent id. Background Agent Signal runs (memory /// skill / self-reflection) execute under a builtin slug, so `resolvedAgentId`diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.tsindex 84e82a7ffed..6d92e9041d7 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts@@ -390,17 +390,15 @@ describe('discoverTools — connectors are opt-in per agent', () => {expect(resolveByIdentifiers.mock.calls[0][0]).toEqual(['custom-mcp']);});- it('invokes a connector that is on directly when manual mode strips the activator', async () => {+ it('keeps opted-in connectors discoverable despite a legacy manual preference', async () => {const result = await run({...sources,agentConfig: { chatConfig: { skillActivateMode: 'manual' }, plugins: ['lobehub-notion'] },autoSkillIds: ['community-mcp'],}).promise;- expect(result.agentPlugins).toEqual(- expect.arrayContaining(['lobehub-notion', 'community-mcp']),- );- expect(result.agentPlugins).not.toContain('composio-gmail');+ expect(result.agentPlugins).toEqual([]);+ expect(engineInstalledIds()).toEqual(['community-mcp']);expect(engineManifestIds()).toEqual(['lobehub-notion']);});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.tsindex 430965e358f..6ccd75d3156 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts@@ -9,7 +9,7 @@ import {SELF_FEEDBACK_INTENT_IDENTIFIER,shouldExposeSelfFeedbackIntentTool,} from '@lobechat/builtin-tool-self-iteration';-import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';+import { getUnselectedBuiltinToolIds } from '@lobechat/builtin-tools';import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';import type {AgentGroupConfig,@@ -512,6 +512,13 @@ export const discoverTools = async (agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);}+ // The runtime may itself require a tool (e.g. a mention or media fallback).+ // Share runs have a separate grant-based discovery pool and allowlist.+ if (!shareGate)+ disabledPluginIds.push(+ ...getUnselectedBuiltinToolIds([...optedInIds, ...agentPlugins, ...boundConnectorIds]),+ );+// Resolve THE device decision for this run; see `resolveDevicePlan`.const devicePlan = await resolveDevicePlan(deps, ctx, input, {boundDeviceId,@@ -634,10 +641,7 @@ export const discoverTools = async (});log('execAgent: agent configured plugins: %O', pluginIds);- const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';-toolsResult = toolsEngine.generateToolsDetailed({- excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,model,provider,skipDefaultTools: !!exclusivePluginIds,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.tsindex 130204f9b23..5e53877c34c 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts@@ -233,10 +233,18 @@ describe('resolveOrInstallMarketPlugin — server-side marketplace install', ()expect(restored.enabledToolIds).toContain(IDENTIFIER);expect(offeredToolNames(restored.tools)).toContain(TOOL_NAME);- // Manual mode has no activator, so there the run is offered the tool directly+ // A legacy manual preference keeps the activator, so the install is still deferredconst manualRun = await nextRun({ manual: true });- expect(manualRun.toolsResult.enabledToolIds).toContain(IDENTIFIER);- expect(offeredToolNames(manualRun.tools)).toContain(TOOL_NAME);+ expect(manualRun.toolsResult.enabledToolIds).not.toContain(IDENTIFIER);+ expect(offeredToolNames(manualRun.tools)).not.toContain(TOOL_NAME);+ expect(+ (+ buildToolDiscoveryConfig(+ { manifestMap: manualRun.toolManifestMap } as never,+ manualRun.toolsResult.enabledToolIds,+ )?.availableTools ?? []+ ).map((tool) => tool.identifier),+ ).toContain(IDENTIFIER);},);diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex bbad6bb5dee..25bd447629e 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -2428,11 +2428,9 @@"taskLabels.tabs.task": "Task labels","taskLabels.usage": "{{count}} tasks","tools.activation.action.auto": "Auto",- "tools.activation.action.disable": "Disable","tools.activation.action.pin": "Pin","tools.activation.auto": "Auto","tools.activation.auto.desc": "Smart",- "tools.activation.disabled": "Disabled","tools.activation.disabled.desc": "Turned Off","tools.activation.fixed.hint": "Always on — managed by the app and can’t be turned off","tools.activation.pinned": "Pinned",@@ -2468,6 +2466,7 @@"tools.builtins.lobe-calculator.description": "Perform mathematical calculations, solve equations, and work with symbolic expressions","tools.builtins.lobe-calculator.readme": "Advanced mathematical calculator supporting basic arithmetic, algebraic equations, calculus operations, and symbolic math. Includes base conversion, equation solving, differentiation, integration, and more.","tools.builtins.lobe-calculator.title": "Calculator",+ "tools.builtins.lobe-canvas.title": "Canvas","tools.builtins.lobe-cloud-sandbox.description": "Execute code, run commands, and manage files in a secure cloud environment","tools.builtins.lobe-cloud-sandbox.readme": "Execute Python, JavaScript, and TypeScript code in an isolated cloud environment. Run shell commands, manage files, search content with regex, and export results securely.","tools.builtins.lobe-cloud-sandbox.title": "Cloud Sandbox",@@ -2616,6 +2615,8 @@"tools.connectorPolicy.updateFailed": "Couldn't update who can manage connectors. Please try again.","tools.legacyConnector.configure": "Configure","tools.legacyConnector.upgradeDesc": "This connector still uses the legacy plugin format. Configure it to finish upgrading, then manage its tool permissions here.",+ "tools.loading.never": "Never load",+ "tools.loading.onDemand": "Load on demand","tools.lobehubSkill.authorize": "Authorize","tools.lobehubSkill.connect": "Connect","tools.lobehubSkill.connected": "Connected",@@ -2642,7 +2643,9 @@"tools.notInstalled": "Not Installed","tools.notInstalledWarning": "This skill is not currently installed, which may affect agent functionality.","tools.picker.disabled": "This model does not support tool calling.",+ "tools.picker.emptyGroup": "No tools in this group","tools.picker.management": "Manage tools",+ "tools.picker.noMatches": "No matching tools","tools.picker.search": "Search tools…","tools.picker.title": "Tools","tools.plugins.enabled": "Enabled: {{num}}",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex b5666458412..1eba149f284 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -2428,11 +2428,9 @@"taskLabels.tabs.task": "任务标签","taskLabels.usage": "{{count}} 个任务","tools.activation.action.auto": "自动",- "tools.activation.action.disable": "禁用","tools.activation.action.pin": "固定","tools.activation.auto": "自动","tools.activation.auto.desc": "智能调用",- "tools.activation.disabled": "禁用","tools.activation.disabled.desc": "不会启用","tools.activation.fixed.hint": "由应用强制开启,始终可用,无法关闭","tools.activation.pinned": "固定启用",@@ -2468,6 +2466,7 @@"tools.builtins.lobe-calculator.description": "执行数学计算、解方程,并处理符号表达式","tools.builtins.lobe-calculator.readme": "高级数学计算器,支持基础算术、代数方程、微积分运算和符号数学。包括进制转换、方程求解、微分、积分等更多功能。","tools.builtins.lobe-calculator.title": "计算器",+ "tools.builtins.lobe-canvas.title": "画布","tools.builtins.lobe-cloud-sandbox.description": "在安全的云端环境中执行代码、运行命令和管理文件","tools.builtins.lobe-cloud-sandbox.readme": "在隔离的云端环境中执行 Python、JavaScript 和 TypeScript 代码。运行 Shell 命令、管理文件、使用正则搜索内容并安全导出结果。","tools.builtins.lobe-cloud-sandbox.title": "云沙盒",@@ -2616,6 +2615,8 @@"tools.connectorPolicy.updateFailed": "没能更新连接器管理权限,请重试","tools.legacyConnector.configure": "配置","tools.legacyConnector.upgradeDesc": "此连接器仍在使用旧的插件格式。点击「配置」完成升级后,即可在此管理它的工具权限。",+ "tools.loading.never": "不加载",+ "tools.loading.onDemand": "按需加载","tools.lobehubSkill.authorize": "授权","tools.lobehubSkill.connect": "连接","tools.lobehubSkill.connected": "已连接",@@ -2642,7 +2643,9 @@"tools.notInstalled": "未安装","tools.notInstalledWarning": "当前技能暂未安装,可能会影响助理使用","tools.picker.disabled": "当前模型不支持工具调用。",+ "tools.picker.emptyGroup": "此分组暂无工具","tools.picker.management": "工具管理",+ "tools.picker.noMatches": "未找到匹配的工具","tools.picker.search": "搜索工具…","tools.picker.title": "工具","tools.plugins.enabled": "已启用 {{num}}",diff --git a/packages/builtin-agents/src/agents/web-onboarding/index.ts b/packages/builtin-agents/src/agents/web-onboarding/index.tsindex 1ca16ab2df5..a9036522690 100644--- a/packages/builtin-agents/src/agents/web-onboarding/index.ts+++ b/packages/builtin-agents/src/agents/web-onboarding/index.ts@@ -25,6 +25,7 @@ export const WEB_ONBOARDING: BuiltinAgentDefinition = {},searchMode: 'off',skillActivateMode: 'manual',+ toolMode: 'custom',},plugins: [WebOnboardingIdentifier, UserInteractionIdentifier, ...(ctx.plugins || [])],systemRole: createSystemRole(ctx.userLocale, { isDev: ctx.isDev }),diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 5ea7dbccd8b..9c05d8e6e09 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -58,7 +58,13 @@ import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { WebOnboardingManifest } from '@lobechat/builtin-tool-web-onboarding';import { WebhookManifest } from '@lobechat/builtin-tool-webhook';import { isDesktop, RECOMMENDED_SKILLS, RecommendedSkillType } from '@lobechat/const';-import { type LobeBuiltinTool } from '@lobechat/types';+import {+ type AgentPluginEntry,+ getDisabledPluginIds,+ type LobeAgentChatConfig,+ type LobeBuiltinTool,+ resolveToolMode,+} from '@lobechat/types';import { resolveCloudSandboxInPageScope } from './pageScope';@@ -85,15 +91,21 @@ export const defaultToolIds = [/*** Builtins enabled by default in Agent mode. The activator loads other tools- * on demand, and Skills loads skill instructions. Manual mode omits the activator.+ * on demand, and Skills loads skill instructions.*/export const alwaysOnToolIds = [LobeActivatorManifest.identifier, SkillsManifest.identifier];-/**- * Runtime tools represented by the skill activation mode control itself. They remain part- * of the engine defaults but should not appear as independently configurable tool rows.- */-export const activationModeControlledToolIds = [LobeActivatorManifest.identifier];+/** Ignore stale picker preferences for fixed infrastructure in ordinary Agent mode.+ * Only use for saved user choices, never for a share allowlist or runtime exclusion. */+export const getUserDisabledToolIds = (+ plugins: AgentPluginEntry[] | undefined,+ chatConfig?: Pick<LobeAgentChatConfig, 'toolMode' | 'enableAgentMode'> | null,+) => {+ const disabled = getDisabledPluginIds(plugins);+ return resolveToolMode(chatConfig) === 'agent'+ ? disabled.filter((id) => !alwaysOnToolIds.includes(id))+ : disabled;+};/*** Tool IDs to exclude from defaults when in manual skill-activate mode.@@ -626,6 +638,25 @@ export const builtinTools: LobeBuiltinTool[] = builtinToolRegistry.map((tool) =>title: tool.manifest?.meta?.title,}));+// A saved pin on a user-selectable tool predates on-demand loading. Runtime additions+// (mentions, media fallback, exact toolsets) are not user preferences and bypass this filter.+export const onDemandBuiltinToolIds = builtinTools+ .filter(+ (tool) =>+ (tool.discoverable !== false || tool.identifier === AuvManifest.identifier) &&+ !alwaysOnToolIds.includes(tool.identifier) &&+ !runtimeManagedToolIds.includes(tool.identifier),+ )+ .map((tool) => tool.identifier);+const onDemandBuiltinIds = new Set(onDemandBuiltinToolIds);++/** An installed tool is not permission to offer it to every agent. */+export const getUnselectedBuiltinToolIds = (available: Iterable<string>) => {+ const allowed = new Set(available);+ return onDemandBuiltinToolIds.filter((id) => !allowed.has(id));+};+export const isOnDemandBuiltinTool = (identifier: string) => onDemandBuiltinIds.has(identifier);+const recommendedBuiltinIds = new Set(RECOMMENDED_SKILLS.filter((s) => s.type === RecommendedSkillType.Builtin).map((s) => s.id),);diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 7e796256c22..9612414f023 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4307,6 +4307,7 @@ When I am ___, I need ___'tools.builtins.lobe-artifacts.readme':'Generate and live-preview interactive UI components, data visualizations, charts, SVG graphics, and web applications. Create rich visual content that users can interact with directly.','tools.builtins.lobe-artifacts.title': 'Artifacts',+ 'tools.builtins.lobe-canvas.title': 'Canvas','tools.builtins.lobe-calculator.title': 'Calculator','tools.builtins.lobe-calculator.description':'Perform mathematical calculations, solve equations, and work with symbolic expressions',@@ -4665,6 +4666,8 @@ When I am ___, I need ___'This skill is not currently installed, which may affect agent functionality.','tools.picker.disabled': 'This model does not support tool calling.','tools.picker.management': 'Manage tools',+ 'tools.picker.emptyGroup': 'No tools in this group',+ 'tools.picker.noMatches': 'No matching tools','tools.picker.search': 'Search tools…','tools.picker.title': 'Tools','tools.plugins.enabled': 'Enabled: {{num}}',@@ -4673,12 +4676,12 @@ When I am ___, I need ___'tools.plugins.noEnabled': 'No skills enabled','tools.plugins.store': 'Add skill','tools.search': 'Search skills...',+ 'tools.loading.onDemand': 'Load on demand','tools.activation.action.auto': 'Auto',- 'tools.activation.action.disable': 'Disable',+ 'tools.loading.never': 'Never load','tools.activation.action.pin': 'Pin','tools.activation.auto': 'Auto','tools.activation.auto.desc': 'Smart',- 'tools.activation.disabled': 'Disabled','tools.activation.disabled.desc': 'Turned Off','tools.activation.fixed.hint': 'Always on — managed by the app and can’t be turned off','tools.activation.pinned': 'Pinned',diff --git a/packages/mecha/src/resolveAgentConfig.ts b/packages/mecha/src/resolveAgentConfig.tsindex 3c4c01dd8c6..a490e04c0b5 100644--- a/packages/mecha/src/resolveAgentConfig.ts+++ b/packages/mecha/src/resolveAgentConfig.ts@@ -6,6 +6,7 @@ import {} from '@lobechat/builtin-agents';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { TaskIdentifier } from '@lobechat/builtin-tool-task';+import { isOnDemandBuiltinTool } from '@lobechat/builtin-tools';import { type LobeToolManifest } from '@lobechat/context-engine';import {type AgentModelConfig,@@ -16,6 +17,7 @@ import {type LobeAgentConfig,type MessageMapScope,resolveAgentModelConfig,+ resolveToolMode,} from '@lobechat/types';import debug from 'debug';import { produce } from 'immer';@@ -326,7 +328,11 @@ export const resolveAgentConfig = (: { ...sharedChatConfig, enableAgentMode: memberModeOverride };// Base plugins from agent config (pinned identifiers only — disabled entries excluded)- const basePlugins = getActivePluginIds(agentConfig?.plugins);+ const savedPlugins = getActivePluginIds(agentConfig?.plugins);+ const basePlugins =+ resolveToolMode(chatConfig) === 'agent'+ ? savedPlugins.filter((id) => !isOnDemandBuiltinTool(id))+ : savedPlugins;// Check if this is a builtin agent// Priority: supervisor check (when in group scope) > agent store slugdiff --git a/packages/mecha/src/toolSet/connectorActivation.test.ts b/packages/mecha/src/toolSet/connectorActivation.test.tsindex 1262402065b..ed2e4313e62 100644--- a/packages/mecha/src/toolSet/connectorActivation.test.ts+++ b/packages/mecha/src/toolSet/connectorActivation.test.ts@@ -13,8 +13,8 @@ describe('hasConnectorActivator', () => {expect(hasConnectorActivator({ skillActivateMode: 'auto' })).toBe(true);});- it('has none once manual skill-activate mode strips it', () => {- expect(hasConnectorActivator({ skillActivateMode: 'manual' })).toBe(false);+ it('ignores the retired tool discovery switch', () => {+ expect(hasConnectorActivator({ skillActivateMode: 'manual' })).toBe(true);});it('has none in custom mode, which exposes exactly the declared plugins', () => {diff --git a/packages/mecha/src/toolSet/connectorActivation.ts b/packages/mecha/src/toolSet/connectorActivation.tsindex b805f2a2966..d884e6b3e34 100644--- a/packages/mecha/src/toolSet/connectorActivation.ts+++ b/packages/mecha/src/toolSet/connectorActivation.ts@@ -10,8 +10,7 @@ export const hasConnectorActivator = (pluginIds: readonly string[] = [],disabledIds: readonly string[] = [],): boolean => {- if (chatConfig?.skillActivateMode === 'manual' || disabledIds.includes(LobeActivatorIdentifier))- return false;+ if (disabledIds.includes(LobeActivatorIdentifier)) return false;const mode = resolveToolMode(chatConfig);return mode === 'agent' || (mode === 'custom' && pluginIds.includes(LobeActivatorIdentifier));};diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsxindex 73921db31ac..e481bf189fd 100644--- a/src/features/ChatInput/ActionBar/Plus/index.tsx+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx@@ -2,7 +2,6 @@import { validateVideoFileSize } from '@lobechat/utils/client';import { Icon, Popover, toast, Upload } from '@lobehub/ui';-import { SkillsIcon } from '@lobehub/ui/icons';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import {@@ -13,6 +12,7 @@ import {Settings2Icon,TargetIcon,TypeIcon,+ WrenchIcon,} from 'lucide-react';import type { ReactNode } from 'react';import { memo, Suspense, useCallback, useMemo, useRef } from 'react';@@ -22,7 +22,7 @@ import { openAttachKnowledgeModal } from '@/features/LibraryModal';import { useMediaUploadAbility } from '@/hooks/useMediaUploadAbility';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useAgentStore } from '@/store/agent';-import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { agentSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';@@ -202,9 +202,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI],);const isParamsPanelActive = Boolean(showRightPanel) && workingSidebarTab === 'params';- const skillActivateMode = useAgentStore((s) =>- chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),- );const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);const editor = useChatInputStore((s) => s.editor);@@ -227,12 +224,10 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIconst closeDropdown = useCallback(() => close(), [close]);const skillsMenuItem = useSkillsMenuItem(closeDropdown);const {- autoCount: skillAutoCount,isPolicyMenuOpen: isSkillPolicyMenuOpen,marketFooter: skillMarketFooter,marketHeader: skillMarketHeader,marketItems: skillItems,- pinnedCount: skillPinnedCount,} = useToolsControls({ closeDropdown });const handleToggleParams = useCallback(() => {@@ -311,11 +306,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI},];- // In auto mode every installed skill is callable, so show pinned + auto.- // In manual mode only the pinned ones are active, so show pinned only.- const activeSkillCount =- skillActivateMode === 'auto' ? skillPinnedCount + skillAutoCount : skillPinnedCount;-const toolsItems: ActionDropdownMenuItems =isAgentModeEnabled && enableFC? [@@ -326,9 +316,9 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIextra: <SubmenuChevron />,footer: skillMarketFooter,header: skillMarketHeader,- icon: SkillsIcon,+ icon: WrenchIcon,key: 'tools',- label: renderLabelWithCount(tSetting('tools.picker.title'), activeSkillCount),+ label: tSetting('tools.picker.title'),} as ActionDropdownMenuItems[number],]: [];@@ -447,9 +437,6 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuIknowledgeEnabledCount,setShowTypoBar,showTypoBar,- skillActivateMode,- skillAutoCount,- skillPinnedCount,knowledgeItems,knowledgeFooter,t,diff --git a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.tsindex f5f33466927..4ad6e84e7be 100644--- a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts+++ b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts@@ -28,7 +28,7 @@ import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useTopicId } from '../../hooks/useTopicId';import { useStoreApi } from '../../store';import type { ContextWindow } from '../../store/initialState';-import { getToolContextRefreshKey, getToolExcludeDefaultToolIds } from './utils';+import { getToolContextRefreshKey } from './utils';const toolNameResolver = new ToolNameResolver();@@ -200,7 +200,6 @@ export const useTokenBreakdown = (): TokenBreakdown => {enableAgentMode,searchMode,useModelBuiltinSearch,- skillActivateMode,agentMemoryEnabled,runtimeMode,hasEnabledKnowledgeBases,@@ -213,7 +212,6 @@ export const useTokenBreakdown = (): TokenBreakdown => {chatConfig.enableAgentMode,chatConfig.searchMode,chatConfig.useModelBuiltinSearch,- chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),chatConfig.memory?.enabled,chatConfigByIdSelectors.getRuntimeModeById(agentId)(s),agentByIdSelectors@@ -239,7 +237,6 @@ export const useTokenBreakdown = (): TokenBreakdown => {memoryEnabled: effectiveMemoryEnabled,runtimeMode,searchMode,- skillActivateMode,useModelBuiltinSearch,});@@ -257,7 +254,6 @@ export const useTokenBreakdown = (): TokenBreakdown => {const toolsEngine = createAgentToolsEngine({ model, provider });const { tools, enabledManifests } = toolsEngine.generateToolsDetailed({- excludeDefaultToolIds: getToolExcludeDefaultToolIds(skillActivateMode),model,provider,toolIds: pluginIds,@@ -285,15 +281,7 @@ export const useTokenBreakdown = (): TokenBreakdown => {// createAgentToolsEngine inputs read via getState() (tool manifests plus// agent/user/aiInfra config), so the engine only re-runs when they change// instead of on every render.- }, [- hasRequest,- installedPlugins,- model,- pluginIds,- provider,- skillActivateMode,- toolContextRefreshKey,- ]);+ }, [hasRequest, installedPlugins, model, pluginIds, provider, toolContextRefreshKey]);const toolsSchemaToken = useTokenCount(canUseTool ? toolsSchema : '');const toolsSystemRoleToken = useTokenCount(canUseTool ? toolsSystemRole : '');diff --git a/src/features/ChatInput/ActionBar/Token/utils.test.ts b/src/features/ChatInput/ActionBar/Token/utils.test.tsindex 58f2ac102c1..c3e73a51559 100644--- a/src/features/ChatInput/ActionBar/Token/utils.test.ts+++ b/src/features/ChatInput/ActionBar/Token/utils.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { getToolContextRefreshKey, getToolExcludeDefaultToolIds } from './utils';+import { getToolContextRefreshKey } from './utils';describe('Token tool utils', () => {describe('getToolContextRefreshKey', () => {@@ -50,14 +50,4 @@ describe('Token tool utils', () => {).not.toBe(chatModeKey);});});-- describe('getToolExcludeDefaultToolIds', () => {- it('excludes discovery tools in manual skill mode', () => {- expect(getToolExcludeDefaultToolIds('manual')).toEqual(['lobe-activator']);- });-- it('keeps default tools in auto skill mode', () => {- expect(getToolExcludeDefaultToolIds('auto')).toBeUndefined();- });- });});diff --git a/src/features/ChatInput/ActionBar/Token/utils.ts b/src/features/ChatInput/ActionBar/Token/utils.tsindex dca66b3d76c..bed19ea7ee9 100644--- a/src/features/ChatInput/ActionBar/Token/utils.ts+++ b/src/features/ChatInput/ActionBar/Token/utils.ts@@ -1,4 +1,3 @@-import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';import type { LobeAgentChatConfig, RuntimeEnvMode } from '@lobechat/types';interface ToolContextRefreshKeyOptions {@@ -11,14 +10,9 @@ interface ToolContextRefreshKeyOptions {memoryEnabled?: boolean;runtimeMode?: RuntimeEnvMode;searchMode?: LobeAgentChatConfig['searchMode'];- skillActivateMode?: LobeAgentChatConfig['skillActivateMode'];useModelBuiltinSearch?: boolean;}-export const getToolExcludeDefaultToolIds = (- skillActivateMode?: LobeAgentChatConfig['skillActivateMode'],-) => (skillActivateMode === 'manual' ? manualModeExcludeToolIds : undefined);-export const getToolContextRefreshKey = ({agentId,enableAgentMode,@@ -29,7 +23,6 @@ export const getToolContextRefreshKey = ({memoryEnabled,runtimeMode,searchMode,- skillActivateMode,useModelBuiltinSearch,}: ToolContextRefreshKeyOptions) =>[@@ -37,7 +30,6 @@ export const getToolContextRefreshKey = ({enableAgentMode === false ? 'chat' : 'agent',searchMode || 'auto',useModelBuiltinSearch ? 'model-search' : 'app-search',- skillActivateMode || 'auto',memoryEnabled ? 'memory-on' : 'memory-off',hasEnabledKnowledgeBases ? 'knowledge-on' : 'knowledge-off',runtimeMode || 'none',diff --git a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsxindex d19eff5c2e1..9404ae20008 100644--- a/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx+++ b/src/features/ChatInput/ActionBar/Tools/PopoverContent.tsx@@ -1,9 +1,9 @@import { type ItemType } from '@lobehub/ui';-import { Flexbox, Icon, SearchBar, stopPropagation, usePopoverContext } from '@lobehub/ui';+import { Flexbox, Icon, usePopoverContext } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { Pin, Settings, Zap } from 'lucide-react';-import { memo, useMemo, useState } from 'react';+import { Settings, Zap } from 'lucide-react';+import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { buildAgentProfileTabPath } from '@/features/AgentProfileTabs/tabOptions';@@ -11,7 +11,6 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useAgentId } from '../../hooks/useAgentId';import { ScrollSignalProvider } from './ScrollSignalContext';-import SkillActivateMode from './SkillActivateMode';import ToolsList from './ToolsList';const styles = stylex.create({@@ -57,105 +56,56 @@ const styles = stylex.create({},});-const filterItems = (items: ItemType[], keyword: string): ItemType[] => {- const lower = keyword.toLowerCase();-- return items- .map((item) => {- if (!item) return null;-- if (item.type === 'group' && 'children' in item && item.children) {- const filtered = item.children.filter((child) => {- if (!child) return false;- const key = String(child.key || '').toLowerCase();- return key.includes(lower);- });- if (filtered.length === 0) return null;- return { ...item, children: filtered };- }-- if (item.type === 'divider') return item;-- const key = String('key' in item ? item.key : '').toLowerCase();- return key.includes(lower) ? item : null;- })- .filter(Boolean) as ItemType[];-};-interface PopoverContentProps {autoCount: number;detailPopoverDisabled?: boolean;+ header: ReactNode;items: ItemType[];- pinnedCount: number;+ showFooter?: boolean;}const PopoverContent = memo<PopoverContentProps>(- ({ autoCount, detailPopoverDisabled, items, pinnedCount }) => {+ ({ autoCount, detailPopoverDisabled, header, items, showFooter = true }) => {const { t } = useTranslation('setting');const agentId = useAgentId();const navigate = useWorkspaceAwareNavigate();- const [searchKeyword, setSearchKeyword] = useState('');const { close: closePopover } = usePopoverContext();- const filteredItems = useMemo(- () => (searchKeyword ? filterItems(items, searchKeyword) : items),- [items, searchKeyword],- );-return (<Flexbox gap={0}>- <Flexbox- horizontal- align="center"- className={stylex.props(styles.header).className}- gap={4}- >- <SearchBar- allowClear- placeholder={t('tools.picker.search')}- size="small"- style={{ flex: 1 }}- value={searchKeyword}- variant="borderless"- onChange={(e) => setSearchKeyword(e.target.value)}- onKeyDown={stopPropagation}- />- <SkillActivateMode />- </Flexbox>+ <div {...stylex.props(styles.header)}>{header}</div><ScrollSignalProviderstyle={{- height: 480,+ maxHeight: 'min(50vh, 480px)',overflowY: 'auto',}}>- <ToolsList detailPopoverDisabled={detailPopoverDisabled} items={filteredItems} />+ <ToolsList detailPopoverDisabled={detailPopoverDisabled} items={items} /></ScrollSignalProvider>- <div {...stylex.props(styles.footer)}>- <span {...stylex.props(styles.statsItem)}>- <Icon icon={Pin} size={12} />- {pinnedCount}- </span>- <span {...stylex.props(styles.statsItem)}>- <Icon icon={Zap} size={12} />- {autoCount}- </span>- <Flexbox horizontal align="center" gap={2} style={{ marginInlineStart: 'auto' }}>- <button- aria-label={t('tools.picker.management')}- {...stylex.props(styles.iconButton)}- disabled={!agentId}- type="button"- onClick={() => {- if (!agentId) return;- closePopover();- navigate(buildAgentProfileTabPath(agentId, 'tools'));- }}- >- <Icon icon={Settings} size={14} />- </button>- </Flexbox>- </div>+ {showFooter && (+ <div {...stylex.props(styles.footer)}>+ <span {...stylex.props(styles.statsItem)}>+ <Icon icon={Zap} size={12} />+ {autoCount}+ </span>+ <Flexbox horizontal align="center" gap={2} style={{ marginInlineStart: 'auto' }}>+ <button+ aria-label={t('tools.picker.management')}+ {...stylex.props(styles.iconButton)}+ disabled={!agentId}+ type="button"+ onClick={() => {+ if (!agentId) return;+ closePopover();+ navigate(buildAgentProfileTabPath(agentId, 'tools'));+ }}+ >+ <Icon icon={Settings} size={14} />+ </button>+ </Flexbox>+ </div>+ )}</Flexbox>);},diff --git a/src/features/ChatInput/ActionBar/Tools/SkillActivateMode.tsx b/src/features/ChatInput/ActionBar/Tools/SkillActivateMode.tsxdeleted file mode 100644index b480db56177..00000000000--- a/src/features/ChatInput/ActionBar/Tools/SkillActivateMode.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { Icon, Tabs, Tooltip } from '@lobehub/ui';-import { SlidersHorizontal, Sparkles } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useAgentStore } from '@/store/agent';-import { chatConfigByIdSelectors } from '@/store/agent/selectors';--import { useAgentId } from '../../hooks/useAgentId';-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';--const SkillActivateMode = memo(() => {- const { t } = useTranslation('setting');- const agentId = useAgentId();- const { updateAgentChatConfig } = useUpdateAgentConfig();- const currentMode = useAgentStore((s) =>- chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),- );-- return (- <Tabs- activeKey={currentMode}- size="small"- items={[- {- key: 'auto',- label: (- <Tooltip title={t('tools.skillActivateMode.auto.desc')}>- <Icon icon={Sparkles} />- </Tooltip>- ),- },- {- key: 'manual',- label: (- <Tooltip title={t('tools.skillActivateMode.manual.desc')}>- <Icon icon={SlidersHorizontal} />- </Tooltip>- ),- },- ]}- onChange={async (key) => {- await updateAgentChatConfig({ skillActivateMode: key as 'auto' | 'manual' });- }}- />- );-});--export default SkillActivateMode;diff --git a/src/features/ChatInput/ActionBar/Tools/ToolPickerHeader.tsx b/src/features/ChatInput/ActionBar/Tools/ToolPickerHeader.tsxnew file mode 100644index 00000000000..692ed8fee48--- /dev/null+++ b/src/features/ChatInput/ActionBar/Tools/ToolPickerHeader.tsx@@ -0,0 +1,58 @@+import { Flexbox, SearchBar, Segmented, Text } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++type Filter = 'auto' | 'disabled';++interface ToolPickerHeaderProps {+ empty: boolean;+ filter: Filter;+ onFilterChange: (filter: Filter) => void;+ onSearchChange: (query: string) => void;+ query: string;+}++export const ToolPickerHeader = memo<ToolPickerHeaderProps>(+ ({ empty, filter, query, onFilterChange, onSearchChange }) => {+ const { t } = useTranslation('setting');+ const searching = Boolean(query.trim());++ return (+ <Flexbox className="lobe-tool-picker-header" gap={6}>+ <SearchBar+ allowClear+ aria-label={t('tools.picker.search')}+ placeholder={t('tools.picker.search')}+ size="small"+ value={query}+ variant="borderless"+ onChange={(event) => onSearchChange(event.target.value)}+ onKeyDown={(event) => {+ if (!['Escape', 'Tab', 'ArrowDown'].includes(event.key)) event.stopPropagation();+ }}+ />+ {!searching && (+ <Segmented+ block+ size="small"+ value={filter}+ options={[+ { label: t('tools.loading.onDemand'), value: 'auto' },+ { label: t('tools.loading.never'), value: 'disabled' },+ ]}+ onChange={(value) => onFilterChange(value === 'disabled' ? 'disabled' : 'auto')}+ />+ )}+ {empty && (+ <Flexbox align="center" paddingBlock={16} role="status">+ <Text fontSize={13} type="secondary">+ {searching ? t('tools.picker.noMatches') : t('tools.picker.emptyGroup')}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);++ToolPickerHeader.displayName = 'ToolPickerHeader';diff --git a/src/features/ChatInput/ActionBar/Tools/index.tsx b/src/features/ChatInput/ActionBar/Tools/index.tsxindex 78e998b02af..779fec0b262 100644--- a/src/features/ChatInput/ActionBar/Tools/index.tsx+++ b/src/features/ChatInput/ActionBar/Tools/index.tsx@@ -12,7 +12,7 @@ import { useControls } from './useControls';const Tools = memo(() => {const { t } = useTranslation('setting');- const { marketItems, pinnedCount, autoCount, isPolicyMenuOpen } = useControls();+ const { marketItems, marketHeader, autoCount, isPolicyMenuOpen } = useControls();const agentId = useAgentId();const { model, provider } = useEffectiveModel(agentId);@@ -40,8 +40,8 @@ const Tools = memo(() => {<PopoverContentautoCount={autoCount}detailPopoverDisabled={isPolicyMenuOpen}+ header={marketHeader}items={marketItems}- pinnedCount={pinnedCount}/>),maxWidth: 320,diff --git a/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts b/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.tsindex e71f9248c89..e5f60658c61 100644--- a/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts+++ b/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts@@ -18,7 +18,9 @@ describe('resolveActivationSets', () => {it('lists a connector the agent never turned on under Disabled', () => {const { checkedSet, disabledIdSet } = resolve([]);- expect([...disabledIdSet].sort()).toEqual(['excalidraw', 'gmail', 'linear', 'slack']);+ expect([...disabledIdSet]).toEqual(+ expect.arrayContaining(['excalidraw', 'gmail', 'linear', 'slack', 'lobe-skill-store']),+ );expect(checkedSet.size).toBe(0);});@@ -34,8 +36,9 @@ describe('resolveActivationSets', () => {expect(checkedSet.has('gmail')).toBe(false);expect(disabledIdSet.has('gmail')).toBe(false);- // A builtin tool keeps its pin.- expect(checkedSet.has('lobe-image-generation')).toBe(true);+ // Legacy pins on configurable builtins also mean on demand.+ expect(checkedSet.has('lobe-image-generation')).toBe(false);+ expect(disabledIdSet.has('lobe-image-generation')).toBe(false);});it('keeps an explicitly disabled connector under Disabled', () => {@@ -48,6 +51,6 @@ describe('resolveActivationSets', () => {const { optInIds } = resolve([]);expect(resolveImplicitMode('gmail', optInIds)).toBe('disabled');- expect(resolveImplicitMode('lobe-image-generation', optInIds)).toBe('auto');+ expect(resolveImplicitMode('lobe-image-generation', optInIds)).toBe('disabled');});});diff --git a/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts b/src/features/ChatInput/ActionBar/Tools/useActivationSets.tsindex 27681fd20e0..a1143044862 100644--- a/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts+++ b/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts@@ -1,3 +1,4 @@+import { onDemandBuiltinToolIds } from '@lobechat/builtin-tools';import { type AgentPluginEntry, type AgentPluginMode } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { useMemo } from 'react';@@ -34,10 +35,12 @@ export const resolveActivationSets = ({rawPlugins: AgentPluginEntry[] | undefined;}) => {const connectorIds = new Set(connectorIdList);- const optInIds = new Set([...librarySkillIds, ...connectorIdList]);+ const optInIds = new Set([...onDemandBuiltinToolIds, ...librarySkillIds, ...connectorIdList]);return {- checkedSet: new Set(pinnedIds.filter((id) => !connectorIds.has(id))),+ checkedSet: new Set(+ pinnedIds.filter((id) => !connectorIds.has(id) && !onDemandBuiltinToolIds.includes(id)),+ ),connectorIds,disabledIdSet: new Set(resolveDisabledIds(rawPlugins, optInIds)),/** Identifiers that are off without an entry, so Auto must be written explicitly. */diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.styles.ts b/src/features/ChatInput/ActionBar/Tools/useControls.styles.tsindex 2ea2c1f1d84..f68537e7bf4 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.styles.ts+++ b/src/features/ChatInput/ActionBar/Tools/useControls.styles.ts@@ -3,64 +3,11 @@ import * as stylex from '@stylexjs/stylex';// StyleX can only fold constants declared in this module (or in a `.stylex.ts` file), so// these mirror ./constants — keep the two in sync.-const SKILL_ICON_SIZE = 18;const SKILL_ICON_GAP = 14;const SKILL_TRAILING_CONTROL_SIZE = 20;// Shared by the policy menu rows; kept in one place so hover/disabled stay in sync.export const styles = stylex.create({- activationGroupActions: { display: 'flex', flex: 'none', gap: '8px', alignItems: 'center' },- activationGroupChevron: {- display: 'flex',- flex: 'none',- alignItems: 'center',- justifyContent: 'center',- width: `${SKILL_TRAILING_CONTROL_SIZE}px`,- height: `${SKILL_TRAILING_CONTROL_SIZE}px`,- color: cssVar.colorTextTertiary,- },- activationGroupHeader: {- cursor: 'pointer',- display: 'flex',- gap: '12px',- alignItems: 'center',- justifyContent: 'space-between',- width: '100%',- minWidth: '0',- paddingBlock: '4px',- },- activationGroupIcon: {- display: 'flex',- flex: 'none',- alignItems: 'center',- justifyContent: 'center',- width: `${SKILL_ICON_SIZE}px`,- },- activationGroupTitleBlock: {- display: 'flex',- gap: `${SKILL_ICON_GAP}px`,- alignItems: 'center',- minWidth: '0',- },- activationGroupTitleBody: {- display: 'flex',- flexGrow: '0',- flexShrink: '1',- flexBasis: 'auto',- gap: '6px',- alignItems: 'center',- minWidth: '0',- },- activationGroupTitleText: {- overflow: 'hidden',- minWidth: '0',- fontSize: '14px',- fontWeight: 500,- color: cssVar.colorText,- textOverflow: 'ellipsis',- textTransform: 'none',- whiteSpace: 'nowrap',- },addSkillLabel: { flex: '1', textAlign: 'start' },addSkillRow: {display: 'flex',@@ -81,7 +28,6 @@ export const styles = stylex.create({backgroundImage: { 'default': 'none', ':hover': 'none' },transition: `background 150ms ${cssVar.motionEaseOut}`,},- count: { flex: 'none', color: cssVar.colorTextTertiary },deleteButton: {cursor: { 'default': 'pointer', ':disabled': 'not-allowed' },display: 'flex',@@ -194,7 +140,6 @@ export const styles = stylex.create({// standalone popovers instead of the compact 132px policy list.policyPanelWide: { width: '320px' },policyText: { flex: '1', textAlign: 'start' },- switchWrap: { display: 'inline-flex', flex: 'none', alignItems: 'center' },toolLabel: {display: 'flex',flex: '1',diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts b/src/features/ChatInput/ActionBar/Tools/useControls.test.tsindex 65447a9add9..03711c75be2 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts+++ b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts@@ -24,12 +24,13 @@ const mocks = vi.hoisted(() => ({composioServers: [] as Pick<ComposioServer, 'identifier' | 'status'>[],lobehubEnabled: false,lobehubSkillServers: [] as LobehubSkillServer[],- mode: 'auto',+ chatMode: false,plugins: [] as { identifier: string; mode: string }[],skills: [{ id: 'market-row', identifier: 'excel-analysis', name: 'Excel Analysis', source: 'market' },{ id: 'user-row', identifier: 'custom-writing', name: 'Custom Writing', source: 'user' },],+ updateConfig: vi.fn(),togglePlugin: vi.fn(),setPluginMode: vi.fn(),}));@@ -40,7 +41,7 @@ vi.mock('../../hooks/useEffectiveModel', () => ({useEffectiveModel: () => ({ model: 'model', provider: 'provider' }),}));vi.mock('../../hooks/useUpdateAgentConfig', () => ({- useUpdateAgentConfig: () => ({ updateAgentChatConfig: vi.fn() }),+ useUpdateAgentConfig: () => ({ updateAgentConfig: mocks.updateConfig }),}));vi.mock('../Memory/useMemoryEnabled', () => ({ useMemoryEnabled: () => false }));vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({@@ -52,8 +53,9 @@ vi.mock('@/features/Connectors/CustomConnectorModal/useConnectorConfigure', () =vi.mock('@/hooks/useFetchInstalledPlugins', () => ({ useFetchInstalledPlugins: vi.fn() }));vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));vi.mock('@/store/agent', () => ({- useAgentStore: (selector: (state: unknown) => unknown) =>- selector({ setPluginMode: mocks.setPluginMode, togglePlugin: mocks.togglePlugin }),+ useAgentStore: Object.assign((selector: (state: unknown) => unknown) => selector({}), {+ getState: () => ({}),+ }),}));vi.mock('@/store/agent/selectors', () => ({agentByIdSelectors: {@@ -62,7 +64,7 @@ vi.mock('@/store/agent/selectors', () => ({},chatConfigByIdSelectors: {getSearchModeById: () => () => 'off',- getSkillActivateModeById: () => () => mocks.mode,+ isChatModeById: () => () => mocks.chatMode,},}));vi.mock('@/store/aiInfra', () => ({@@ -94,7 +96,7 @@ vi.mock('@/store/tool/selectors', () => ({getUserAgentSkills: () => mocks.skills.filter((skill) => skill.source === 'user'),},builtinToolSelectors: {- fixedDisplayMetaList: () => () => [],+ fixedDisplayMetaList: () => () => [{ identifier: 'lobe-skills', meta: { title: 'Skills' } }],installedBuiltinSkills: () => mocks.builtinSkills,// The real metadata inventory mixes tools and skill manifests.metaList: () => [@@ -147,14 +149,14 @@ describe('chat input tool picker', () => {mocks.lobehubEnabled = false;mocks.lobehubSkillServers = [];mocks.plugins = [];- mocks.mode = 'auto';+ mocks.chatMode = false;});afterEach(cleanup);it.each([{ id: 'gmail', pin: false },- { id: 'builtin-tool', pin: true },+ { id: 'builtin-tool', pin: false },])('offers the applicable activation actions on the $id row', async ({ id, pin }) => {mocks.composioEnabled = true;mocks.composioServers = [{ identifier: 'gmail', status: ComposioServerStatus.ACTIVE }];@@ -162,21 +164,46 @@ describe('chat input tool picker', () => {const Row = () => {const { marketItems } = useControls();- const group = marketItems.find((item) => item?.key === 'auto');- const row = group?.type === 'group' && group.children?.find((item) => item?.key === id);+ const row = marketItems.find((item) => item?.key === id);if (!row || !('label' in row)) throw new Error(`Missing row ${id}`);return createElement(Fragment, null, row.label);};render(createElement(Row));fireEvent.contextMenu(screen.getByRole('button', { name: 'tools.skillActivateMode.title' }));- expect(- await screen.findByRole('button', { name: 'tools.activation.action.auto' }),- ).toBeTruthy();- expect(screen.getByRole('button', { name: 'tools.activation.action.disable' })).toBeTruthy();+ expect(await screen.findByRole('button', { name: 'tools.loading.onDemand' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'tools.loading.never' })).toBeTruthy();expect(!!screen.queryByRole('button', { name: 'tools.activation.action.pin' })).toBe(pin);});+ it('does not list the fixed skill loader as a configurable tool, even with a legacy disable', () => {+ mocks.plugins = [{ identifier: 'lobe-skills', mode: 'disabled' }];+ const { result } = renderHook(() => useControls());+ act(() => result.current.marketHeader.props.onSearchChange('lobe-skills'));+ expect(leafKeys(result.current.marketItems)).not.toContain('lobe-skills');+ });++ it.each(['lobe-image-generation', 'lobe-video-generation'])(+ 're-enables %s as a pin in either mode, so a later switch to Chat keeps it callable',+ async (id) => {+ mocks.plugins = [{ identifier: id, mode: 'disabled' }];+ const { result } = renderHook(() => useControls());++ // Agent mode: Chat requires a pin, and switching modes does not rewrite plugins.+ mocks.chatMode = false;+ await act(() => result.current.setPolicy(id, 'auto'));+ expect(mocks.updateConfig).toHaveBeenLastCalledWith({+ plugins: [{ identifier: id, mode: 'pinned' }],+ });++ mocks.chatMode = true;+ await act(() => result.current.setPolicy(id, 'auto'));+ expect(mocks.updateConfig).toHaveBeenLastCalledWith({+ plugins: [{ identifier: id, mode: 'pinned' }],+ });+ },+ );+it('only shows connectors with connection records and keeps rows needing authorization', () => {mocks.composioEnabled = true;mocks.composioServers = [@@ -207,28 +234,55 @@ describe('chat input tool picker', () => {const { result } = renderHook(() => useControls());const { autoCount, marketItems } = result.current;- const autoGroup = marketItems.find((item) => item?.key === 'auto');- expect(autoGroup?.type).toBe('group');- if (autoGroup?.type !== 'group') throw new Error('Missing Auto group');- expect(leafKeys(autoGroup.children ?? []).sort()).toEqual(- [...toolIds, 'gmail', 'vercel'].sort(),- );+ expect(leafKeys(marketItems).sort()).toEqual([...toolIds, 'gmail', 'vercel'].sort());expect(autoCount).toBe(toolIds.length + 2);- const disabledGroup = marketItems.find((item) => item?.key === 'disabled');- expect(disabledGroup?.type).toBe('group');- if (disabledGroup?.type !== 'group') throw new Error('Missing Disabled group');- expect(leafKeys(disabledGroup.children ?? [])).toEqual(+ act(() => result.current.marketHeader.props.onFilterChange('disabled'));+ expect(leafKeys(result.current.marketItems)).toEqual(expect.arrayContaining(['airtable', 'slack']),);const keys = leafKeys(marketItems);for (const identifier of ['google-drive', 'notion', 'twitter'])expect(keys).not.toContain(identifier);- act(() => result.current.marketHeader.props.onChange({ target: { value: 'Google Drive' } }));+ act(() => result.current.marketHeader.props.onSearchChange('builtin-tool'));+ expect(leafKeys(result.current.marketItems)).toEqual(['builtin-tool']);+ act(() => result.current.marketHeader.props.onSearchChange(''));+ expect(leafKeys(result.current.marketItems)).toContain('slack');+ act(() => result.current.marketHeader.props.onSearchChange('Google Drive'));+ expect(result.current.marketHeader.props.empty).toBe(true);expect(leafKeys(result.current.marketItems)).toEqual([]);expect(result.current.autoCount).toBe(toolIds.length + 2);});+ it('writes web browsing to the search setting, clearing only its stale plugin override', async () => {+ const other = { identifier: 'my-skill', mode: 'pinned' };+ mocks.plugins = [other, { identifier: 'lobe-web-browsing', mode: 'disabled' }];+ const { result } = renderHook(() => useControls());+ await act(() => result.current.setPolicy('lobe-web-browsing', 'auto'));+ expect(mocks.updateConfig).toHaveBeenCalledExactlyOnceWith({+ chatConfig: { searchMode: 'auto' },+ plugins: [other],+ });+ });++ it('derives the profile summary from the same unfiltered options as chat', () => {+ const { result } = renderHook(() => useControls());+ const active = leafKeys(result.current.marketItems);+ expect(result.current.activeTools.map((item) => item.id)).toEqual(active);+ act(() => result.current.marketHeader.props.onFilterChange('disabled'));+ const disabled = leafKeys(result.current.marketItems);+ expect(disabled).toContain('lobe-web-browsing');+ const options = result.current.toolOptions;+ expect(options.filter((tool) => tool.enabled).map((tool) => tool.id)).toEqual(active);+ expect(options.filter((tool) => !tool.enabled).map((tool) => tool.id)).toEqual(disabled);+ expect(options.find((tool) => tool.id === 'lobe-web-browsing')?.title).toBe(+ 'tools.builtins.lobe-web-browsing.title',+ );+ expect(result.current.totalCount).toBe(active.length + disabled.length);+ act(() => result.current.marketHeader.props.onSearchChange('no such tool'));+ expect(result.current.activeTools.map((item) => item.id)).toEqual(active);+ });+it('offers only tool management in the footer, without an add-tools action', () => {const { result } = renderHook(() => useControls());@@ -271,32 +325,18 @@ describe('chat input tool picker', () => {const keys = leafKeys(result.current.marketItems);expect(keys).toEqual(expect.arrayContaining(toolIds));for (const id of libraryIds) expect(keys).not.toContain(id);- expect(result.current.pinnedCount).toBe(0);+ expect(result.current.marketItems.some((item) => item?.key === 'pinned')).toBe(false);expect(result.current.autoCount).toBe(toolIds.length);expect(mocks.togglePlugin).not.toHaveBeenCalled();expect(mocks.setPluginMode).not.toHaveBeenCalled();},);- it('also excludes builtin and user skills from the installed picker in manual mode', () => {- mocks.mode = 'manual';- mocks.checked = [...toolIds, ...libraryIds];- mocks.plugins = mocks.checked.map((identifier) => ({ identifier, mode: 'pinned' }));- const { result } = renderHook(() => useControls());-- expect(leafKeys(result.current.installedPluginItems)).toEqual(expect.arrayContaining(toolIds));- for (const id of libraryIds) {- expect(leafKeys(result.current.marketItems)).not.toContain(id);- expect(leafKeys(result.current.installedPluginItems)).not.toContain(id);- }- expect(result.current.pinnedCount).toBe(toolIds.length);- });-it.each(['Excel Analysis', 'lobe-agent-browser', 'lobe-artifacts', 'lobehub'])('does not reveal skills through search for %s',(value) => {const { result } = renderHook(() => useControls());- act(() => result.current.marketHeader.props.onChange({ target: { value } }));+ act(() => result.current.marketHeader.props.onSearchChange(value));expect(leafKeys(result.current.marketItems)).toEqual([]);},);diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsxindex e6eb2d9ec45..788da1b5b6d 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx@@ -1,19 +1,11 @@+import { ImageGenerationIdentifier } from '@lobechat/builtin-tool-image-generation';import { MemoryManifest } from '@lobechat/builtin-tool-memory';+import { VideoGenerationIdentifier } from '@lobechat/builtin-tool-video-generation';import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { getConnectorCatalog } from '@lobechat/const';-import { type AgentPluginMode } from '@lobechat/types';+import { parsePluginEntry, upsertPluginMode } from '@lobechat/types';import type { ItemType } from '@lobehub/ui';-import {- Avatar,- confirmModal,- Icon,- Popover,- SearchBar,- stopPropagation,- Switch,- Tag,- Tooltip,-} from '@lobehub/ui';+import { Avatar, confirmModal, Icon, Popover, Tag, Tooltip } from '@lobehub/ui';import { McpIcon, SkillsIcon } from '@lobehub/ui/icons';import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';@@ -21,11 +13,8 @@ import {BadgeCheck,Ban,Check,- ChevronDown,- ChevronRight,MoreHorizontal,Package,- Pin,Settings,Trash2,Wrench,@@ -64,11 +53,7 @@ import { closeToolDetailPopovers } from '../components/useDetailPopoverState';import { MemoryEffortControl } from '../Memory/Controls';import { useMemoryEnabled } from '../Memory/useMemoryEnabled';import { SearchAdvancedControls } from '../Search/Controls';-import {- isCapabilityTool,- resolveCapabilityConfigPatch,- resolveCapabilityMode,-} from './capabilityTools';+import { isCapabilityTool, resolveCapabilityConfigPatch } from './capabilityTools';import ComposioServerItem from './ComposioServerItem';import ComposioSkillIcon from './ComposioSkillIcon';import { SKILL_ICON_SIZE } from './constants';@@ -76,9 +61,9 @@ import { resolveImplicitMode } from './librarySkillPolicy';import LobehubSkillIcon from './LobehubSkillIcon';import LobehubSkillServerItem from './LobehubSkillServerItem';import SkillRow from './SkillRow';-import ToolItem from './ToolItem';import ToolItemDetailPopover from './ToolItemDetailPopover';-import { CONNECTOR_MODES, useActivationSets } from './useActivationSets';+import { ToolPickerHeader } from './ToolPickerHeader';+import { useActivationSets } from './useActivationSets';import { styles } from './useControls.styles';import { usePluginRowUninstall } from './usePluginRowUninstall';@@ -88,13 +73,13 @@ const officialTag = (</Tooltip>);-type SkillPolicyMode = AgentPluginMode;+type SkillPolicyMode = 'auto' | 'disabled';// Capability rows offer the same three states as any other skill row. A model whose// built-in search can never be turned off has no Disabled state to offer — the write// would be overridden by the runtime — so its search row keeps Pinned/Auto only.-const CAPABILITY_MODES: SkillPolicyMode[] = ['pinned', 'auto', 'disabled'];-const CAPABILITY_MODES_WITHOUT_DISABLE: SkillPolicyMode[] = ['pinned', 'auto'];+const CAPABILITY_MODES: SkillPolicyMode[] = ['auto', 'disabled'];+const CAPABILITY_MODES_WITHOUT_DISABLE: SkillPolicyMode[] = ['auto'];interface SkillDeleteConfig {displayName: string;@@ -133,7 +118,7 @@ interface SkillPolicyMenuOptions {*/panelExtra?: ReactNode;/**- * @default ['pinned', 'auto', 'disabled']+ * @default ['auto', 'disabled']*/supportedModes?: SkillPolicyMode[];}@@ -142,19 +127,20 @@ type SkillMenuItem = NonNullable<ItemType> & {extra?: ReactNode;popoverContent?: ReactNode;searchText?: string;+ canDisable?: boolean;+ optionTitle?: ReactNode;+ optionIcon?: ReactNode;+ detailContent?: ReactNode;};export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } = {}) => {const { t } = useTranslation('setting');const agentId = useAgentId();const navigate = useWorkspaceAwareNavigate();- const { updateAgentChatConfig } = useUpdateAgentConfig();- const [pinnedOpen, setPinnedOpen] = useState(true);- const [autoOpen, setAutoOpen] = useState(true);- const [disabledOpen, setDisabledOpen] = useState(true);+ const { updateAgentConfig } = useUpdateAgentConfig();+ const [filter, setFilter] = useState<SkillPolicyMode>('auto');const [policyOpenId, setPolicyOpenId] = useState<string | null>(null);const [searchKeyword, setSearchKeyword] = useState('');- const [autoModeLoading, setAutoModeLoading] = useState(false);const { allowed: canEdit } = usePermission('edit_own_content');const list = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);const uninstallPluginRow = usePluginRowUninstall();@@ -163,39 +149,15 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =s.uninstallBuiltinTool,s.deleteConnector,]);- const [checked, togglePlugin, setPluginMode] = useAgentStore((s) => [- // Pinned identifiers only (getAgentPluginsById already excludes disabled).- agentByIdSelectors.getAgentPluginsById(agentId)(s),- s.togglePlugin,- s.setPluginMode,- ]);+ const checked = useAgentStore(agentByIdSelectors.getAgentPluginsById(agentId), isEqual);const rawPlugins = useAgentStore((s) => agentByIdSelectors.getAgentConfigById(agentId)(s)?.plugins,);const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);const activationSets = useActivationSets(checked, rawPlugins);- const { checkedSet, connectorIds, disabledIdSet, optInIds } = activationSets;- // In manual skill-activate mode, surface hidden builtin tools (web-browsing,- // cloud-sandbox, knowledge-base, etc.) so users can explicitly enable/disable them.- // In auto mode the activator handles those tools transparently, so they remain hidden.- // NOTE: must read by `agentId` (not via the activeAgentId-based selector) so that- // embedded / group-member chat inputs render the right agent's mode.- const isManualSkillMode = useAgentStore(- (s) => chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s) === 'manual',- );- const isAutoSkillMode = !isManualSkillMode;- const builtinList = useToolStore(- isManualSkillMode- ? builtinToolSelectors.metaListIncludingHidden- : builtinToolSelectors.metaList,- isEqual,- );- // Default-pinned builtins have their own rows; the activation switch represents the activator.- const fixedDisplayList = useToolStore(- builtinToolSelectors.fixedDisplayMetaList({ isManualMode: isManualSkillMode }),- isEqual,- );+ const { disabledIdSet, optInIds } = activationSets;+ const builtinList = useToolStore(builtinToolSelectors.metaListIncludingHidden, isEqual);// Memory and web browsing are runtime-managed builtin tools: `hidden` keeps them// out of `metaList`, and the shared engine rules force their enabled state from@@ -224,24 +186,35 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =const updateSkillPolicy = useCallback(async (id: string, mode: SkillPolicyMode) => {- if (!canEdit) return;-- const currentMode: SkillPolicyMode = checkedSet.has(id)- ? 'pinned'- : disabledIdSet.has(id)- ? 'disabled'- : 'auto';- if (currentMode === mode) return;-- // A capability has two homes. chatConfig carries the on/off state the engine- // reads (`resolveToolRules`), so the row, the injection and the wiring can never- // disagree; `agents.plugins` carries the explicit Pinned/Disabled choice, which- // is what puts the row in the Pinned or Disabled group.+ if (!canEdit || !agentId) return;+ const state = useAgentStore.getState();+ const plugins = agentByIdSelectors.getAgentConfigById(agentId)(state)?.plugins;const patch = isCapabilityTool(id) ? resolveCapabilityConfigPatch(id, mode) : undefined;- if (patch) await updateAgentChatConfig(patch);- await setPluginMode(id, mode, resolveImplicitMode(id, optInIds));+ if (patch) {+ // Capabilities have their own source of truth. Remove any old plugin+ // override in the same write, without touching unrelated choices.+ const hasLegacyEntry = plugins?.some((entry) => parsePluginEntry(entry).identifier === id);+ await updateAgentConfig({+ chatConfig: patch,+ ...(hasLegacyEntry && { plugins: upsertPluginMode(plugins, id, 'auto') }),+ });+ } else {+ // Chat has no activator: media generation reaches the model there only when pinned.+ // Pin it in every mode — the mode can switch later without rewriting plugins, and+ // Agent mode still loads a pinned on-demand builtin through the activator.+ const pinMediaTool =+ mode === 'auto' && (id === ImageGenerationIdentifier || id === VideoGenerationIdentifier);+ await updateAgentConfig({+ plugins: upsertPluginMode(+ plugins,+ id,+ pinMediaTool ? 'pinned' : mode,+ resolveImplicitMode(id, optInIds),+ ),+ });+ }},- [canEdit, checkedSet, disabledIdSet, optInIds, setPluginMode, updateAgentChatConfig],+ [agentId, canEdit, optInIds, updateAgentConfig],);const openSkillPolicyMenu = useCallback((id: string) => {@@ -258,11 +231,10 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =deleteOnly = false,modeOverride,panelExtra,- supportedModes = connectorIds.has(id) ? CONNECTOR_MODES : CAPABILITY_MODES,+ supportedModes = CAPABILITY_MODES,} = options;const mode: SkillPolicyMode =- modeOverride ??- (checkedSet.has(id) ? 'pinned' : disabledIdSet.has(id) ? 'disabled' : defaultMode);+ modeOverride ?? (disabledIdSet.has(id) ? 'disabled' : defaultMode);const renderCheck = (value: SkillPolicyMode) =>mode === value ? (<span {...stylex.props(styles.policyCheck)}>@@ -276,9 +248,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =// status readout — group headers still use the state labels below.// `as const` keeps literal keys so `t()` stays typed against setting resources.const policyActionKey = {- auto: 'tools.activation.action.auto',- disabled: 'tools.activation.action.disable',- pinned: 'tools.activation.action.pin',+ auto: 'tools.loading.onDemand',+ disabled: 'tools.loading.never',} as const satisfies Record<SkillPolicyMode, string>;const renderPolicyItem = (value: SkillPolicyMode, icon: ReactNode) => (@@ -305,18 +276,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =onClick={(event) => event.stopPropagation()}onContextMenu={(event) => event.stopPropagation()}>- {!deleteOnly &&- supportedModes.includes('pinned') &&- renderPolicyItem(- 'pinned',- <Icon- icon={Pin}- size={15}- className={- stylex.props(mode === 'pinned' ? styles.iconPinned : styles.iconDefault).className- }- />,- )}{!deleteOnly &&supportedModes.includes('auto') &&renderPolicyItem(@@ -436,16 +395,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =</Popover>);},- [- canEdit,- checkedSet,- connectorIds,- disabledIdSet,- openSkillPolicyMenu,- policyOpenId,- t,- updateSkillPolicy,- ],+ [canEdit, disabledIdSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],);const renderToolLabel = useCallback(@@ -519,6 +469,10 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =title: ReactNode;}): SkillMenuItem =>({+ optionTitle: title,+ optionIcon: icon,+ detailContent: popoverContent,+ canDisable: !supportedModes || supportedModes.includes('disabled'),closeOnClick: false,key: id,label: renderToolLabel(@@ -655,12 +609,12 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =// Best-effort cleanup: dropping the optimistic plugin id must never break// the delete itself, so swallow any failure here.try {- await togglePlugin(identifier, false);+ await updateSkillPolicy(identifier, 'disabled');} catch (error) {console.error('[Composio] Failed to unpin plugin after delete:', error);}},- [removeComposioConnection, togglePlugin],+ [removeComposioConnection, updateSkillPolicy],);const composioServerItems = useMemo(@@ -848,11 +802,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =[filteredBuiltinList, t, createManagedSkillItem, uninstallBuiltinTool],);- // Memory / web browsing rows. Both are builtin tools the engine turns on from- // chatConfig, so their on/off state is derived from — and written back to — that- // same config, while the optional pin is recorded in `agents.plugins` like every- // other skill: they get the full Pinned/Auto/Disable policy. Their own settings- // travel with the row (`panelExtra`), because the "+" menu no longer hosts them.+ // Search and memory expose their own settings alongside the on/off choice.const capabilityItems: SkillMenuItem[] = useMemo(() =>[@@ -881,7 +831,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =<Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />),id: identifier,- modeOverride: resolveCapabilityMode(enabled, checkedSet.has(identifier)),+ modeOverride: enabled ? 'auto' : 'disabled',panelExtra,popoverContent: (<ToolItemDetailPopover@@ -906,7 +856,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =});}),[- checkedSet,createManagedSkillItem,isMemoryCapabilityEnabled,isSearchCapabilityEnabled,@@ -915,57 +864,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =],);- // Builtin runtime tools support an explicit pinned/disabled policy. They intentionally- // do not support "auto": when enabled, these foundational capabilities stay pinned.- const fixedItems = useMemo(- () =>- fixedDisplayList.map((item) => {- const title = t(`tools.builtins.${item.identifier}.title` as any, {- defaultValue: item.meta?.title || item.identifier,- });- const icon = item.meta?.avatar ? (- <Avatar avatar={item.meta.avatar} shape={'square'} size={SKILL_ICON_SIZE} />- ) : (- <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />- );- const popoverContent = (- <ToolItemDetailPopover- identifier={item.identifier}- sourceLabel={t('skillStore.tabs.lobehub')}- title={title}- description={t(`tools.builtins.${item.identifier}.description` as any, {- defaultValue: item.meta?.description || '',- })}- icon={- item.meta?.avatar ? (- <Avatar- avatar={item.meta.avatar}- shape={'square'}- size={36}- style={{ flex: 'none', marginInlineEnd: 0 }}- />- ) : (- <Icon icon={SkillsIcon} size={36} />- )- }- />- );-- return createManagedSkillItem({- badge: <Icon icon={Wrench} size={12} />,- defaultMode: 'pinned',- extraTag: officialTag,- icon,- id: item.identifier,- popoverContent,- searchText: `${title} ${item.identifier}`,- supportedModes: ['pinned', 'disabled'],- title,- });- }),- [createManagedSkillItem, fixedDisplayList, t],- );-// Connector MCP list items (custom ones and marketplace installs).// Toggling adds the connector identifier to agents.plugins[] — the same field// the runtime resolves connectors from, so they become callable immediately.@@ -994,7 +892,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =// Mirror removeComposioServer: drop the identifier from agent.plugins so// no orphaned pin survives the connector deletion.try {- await togglePlugin(connector.identifier, false);+ await updateSkillPolicy(connector.identifier, 'disabled');} catch (error) {console.error('[Connector] Failed to unpin plugin after delete:', error);}@@ -1007,7 +905,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =title,});}),- [customConnectors, t, createManagedSkillItem, deleteConnector, getConfigure, togglePlugin],+ [customConnectors, t, createManagedSkillItem, deleteConnector, getConfigure, updateSkillPolicy],);// Distinguish community plugins and custom plugins.@@ -1116,122 +1014,53 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =.includes(normalizedSearchKeyword),);};- const allPinnedItems = allSkillItems.filter((item) => checkedSet.has(String(item.key)));- // Capability rows split on the same two states as every other row: Pinned (the- // explicit pin, stored in `plugins`) and the on/off half that lives in chatConfig.- const capabilityPinnedItems = capabilityItems.filter((item) => checkedSet.has(String(item.key)));const capabilityAutoItems = capabilityItems.filter(- (item) => !checkedSet.has(String(item.key)) && !disabledCapabilityIds.has(String(item.key)),+ (item) => !disabledCapabilityIds.has(String(item.key)),);- const capabilityDisabledItems = capabilityItems.filter(- (item) => !checkedSet.has(String(item.key)) && disabledCapabilityIds.has(String(item.key)),- );- const activeSkillItems = allSkillItems.filter(- (item) => !checkedSet.has(String(item.key)) && !disabledIdSet.has(String(item.key)),+ const capabilityDisabledItems = capabilityItems.filter((item) =>+ disabledCapabilityIds.has(String(item.key)),);+ const activeSkillItems = allSkillItems.filter((item) => !disabledIdSet.has(String(item.key)));const allAutoItems = [...capabilityAutoItems, ...activeSkillItems];const allDisabledItems = [...capabilityDisabledItems,...allSkillItems.filter((item) => disabledIdSet.has(String(item.key))),];- const fixedPinnedItems = fixedItems.filter((item) => !disabledIdSet.has(String(item.key)));- const fixedDisabledItems = fixedItems.filter((item) => disabledIdSet.has(String(item.key)));- // Fixed tools lead the pinned section, then pinned capabilities, then every pinned- // skill. All disabled tools and skills live in their own section so "Auto" remains- // semantically accurate.- const pinnedItems = filterBySearch([- ...fixedPinnedItems,- ...capabilityPinnedItems,- ...allPinnedItems,- ]);const autoItems = filterBySearch(allAutoItems);- const disabledItems = filterBySearch([...fixedDisabledItems, ...allDisabledItems]);-- const renderActivationGroupLabel = ({- autoSwitch,- count,- icon,- open,- title,- onToggle,- }: {- autoSwitch?: boolean;- count?: number;- icon: ReactNode;- open: boolean;- title: string;- onToggle: () => void;- }) => (- <div- data-skill-activation-group- {...stylex.props(styles.activationGroupHeader)}- role="button"- tabIndex={0}- onClick={(event) => {- event.stopPropagation();- onToggle();- }}- >- <div {...stylex.props(styles.activationGroupTitleBlock)}>- <span {...stylex.props(styles.activationGroupIcon)}>{icon}</span>- <span {...stylex.props(styles.activationGroupTitleBody)}>- <span {...stylex.props(styles.activationGroupTitleText)}>{title}</span>- {typeof count === 'number' && <span {...stylex.props(styles.count)}>{count}</span>}- </span>- </div>- <div {...stylex.props(styles.activationGroupActions)}>- {autoSwitch && (- <span- {...stylex.props(styles.switchWrap)}- onClick={(event) => {- event.stopPropagation();- }}- >- <Switch- checked={isAutoSkillMode}- disabled={!canEdit}- loading={autoModeLoading}- size="small"- onClick={(_, event) => event.stopPropagation()}- onChange={async (checked, event) => {- event?.stopPropagation?.();- if (!canEdit) return;- setAutoModeLoading(true);- try {- await updateAgentChatConfig({- skillActivateMode: checked ? 'auto' : 'manual',- });- } finally {- setAutoModeLoading(false);- }- }}- />- </span>- )}- <div {...stylex.props(styles.activationGroupChevron)}>- <Icon icon={open ? ChevronDown : ChevronRight} size={13} />- </div>- </div>- </div>- );+ const disabledItems = filterBySearch(allDisabledItems);++ const groups = [+ {+ children: autoItems,+ key: 'auto',+ label: t('tools.loading.onDemand'),+ type: 'group' as const,+ },+ {+ children: disabledItems,+ key: 'disabled',+ label: t('tools.loading.never'),+ type: 'group' as const,+ },+ ];+ const marketItems: ItemType[] = normalizedSearchKeyword+ ? groups.filter((group) => group.children.length > 0)+ : filter === 'auto'+ ? autoItems+ : disabledItems;const marketHeader = (- <SearchBar- allowClear- className="lobe-skill-submenu-search"- placeholder={t('tools.picker.search')}- size="small"- style={{ width: '100%' }}- value={searchKeyword}- variant="borderless"- onChange={(event) => setSearchKeyword(event.target.value)}- onClick={stopPropagation}- onKeyDown={stopPropagation}+ <ToolPickerHeader+ empty={!marketItems.length}+ filter={filter}+ query={searchKeyword}+ onFilterChange={setFilter}+ onSearchChange={setSearchKeyword}/>);const marketFooter =- allSkillItems.length > 0 || fixedItems.length > 0 ? (+ allSkillItems.length > 0 || capabilityItems.length > 0 ? (<buttonaria-label={t('tools.picker.management')}{...stylex.props(styles.addSkillRow)}@@ -1249,291 +1078,34 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =</button>) : undefined;- const marketItems: ItemType[] = [- ...(pinnedItems.length > 0- ? [- {- children: pinnedOpen ? pinnedItems : [],- key: 'pinned',- label: renderActivationGroupLabel({- count: fixedPinnedItems.length + capabilityPinnedItems.length + allPinnedItems.length,- icon: <Icon icon={Pin} size={14} />,- open: pinnedOpen,- title: t('tools.activation.pinned'),- onToggle: () => setPinnedOpen((open) => !open),- }),- type: 'group' as const,- } as ItemType,- ]- : []),- ...(pinnedItems.length > 0 && autoItems.length > 0- ? [- {- key: 'skill-activation-divider',- type: 'divider' as const,- } as ItemType,- ]- : []),- ...(autoItems.length > 0- ? [- {- children: autoOpen ? autoItems : [],- key: 'auto',- label: renderActivationGroupLabel({- autoSwitch: true,- count: allAutoItems.length,- icon: <Icon icon={Zap} size={14} />,- open: autoOpen,- title: t('tools.activation.auto'),- onToggle: () => setAutoOpen((open) => !open),- }),- type: 'group' as const,- } as ItemType,- ]- : []),- ...(disabledItems.length > 0 && (pinnedItems.length > 0 || autoItems.length > 0)- ? [- {- key: 'skill-disabled-divider',- type: 'divider' as const,- } as ItemType,- ]- : []),- ...(disabledItems.length > 0- ? [- {- children: disabledOpen ? disabledItems : [],- key: 'disabled',- label: renderActivationGroupLabel({- count: fixedDisabledItems.length + allDisabledItems.length,- icon: <Icon icon={Ban} size={14} />,- open: disabledOpen,- title: t('tools.activation.disabled'),- onToggle: () => setDisabledOpen((open) => !open),- }),- type: 'group' as const,- } as ItemType,- ]- : []),- ];-- // Items for the installed tab - only show installed plugins- const installedPluginItems: ItemType[] = useMemo(() => {- const installedItems: ItemType[] = [];-- // Installed builtin tools- const enabledBuiltinItems = filteredBuiltinList- .filter((item) => checked.includes(item.identifier))- .map((item) => ({- icon: item.meta?.avatar ? (- <Avatar avatar={item.meta.avatar} shape={'square'} size={SKILL_ICON_SIZE} />- ) : (- <Icon icon={SkillsIcon} size={SKILL_ICON_SIZE} />- ),- key: item.identifier,- label: (- <ToolItem- checked={true}- disabled={!canEdit}- id={item.identifier}- label={item.meta?.title}- onUpdate={async () => {- if (!canEdit) return;- await togglePlugin(item.identifier);- }}- />- ),- popoverContent: (- <ToolItemDetailPopover- identifier={item.identifier}- sourceLabel={t('skillStore.tabs.lobehub')}- description={t(`tools.builtins.${item.identifier}.description` as any, {- defaultValue: item.meta?.description || '',- })}- icon={- item.meta?.avatar ? (- <Avatar- avatar={item.meta.avatar}- shape={'square'}- size={36}- style={{ flex: 'none', marginInlineEnd: 0 }}- />- ) : (- <Icon icon={SkillsIcon} size={36} />- )- }- title={t(`tools.builtins.${item.identifier}.title` as any, {- defaultValue: item.meta?.title || item.identifier,- })}- />- ),- }));-- // Connected Composio servers- const connectedComposioItems = composioServerItems.filter((item) =>- checked.includes(item.key as string),- );-- // Connected LobeHub Skill Providers- const connectedLobehubSkillItems = lobehubSkillItems.filter((item) =>- checked.includes(item.key as string),- );-- // Merge enabled LobeHub Skill and Composio (as builtin skills)- const enabledSkillItems = [...connectedLobehubSkillItems, ...connectedComposioItems];-- // Installed builtin tools and service integrations, without Skill instruction bundles.- const allBuiltinItems: ItemType[] = [- ...enabledBuiltinItems,- ...(enabledBuiltinItems.length > 0 && enabledSkillItems.length > 0- ? [{ key: 'installed-divider-builtin-skill', type: 'divider' as const }]- : []),- ...enabledSkillItems,- ];-- if (allBuiltinItems.length > 0) {- installedItems.push({- children: allBuiltinItems,- key: 'installed-lobehub',- label: t('skillStore.tabs.lobehub'),- type: 'group',- });- }-- // Enabled community plugins- const enabledCommunityPlugins = communityPlugins- .filter((item) => checked.includes(item.identifier))- .map((item) => {- const hasRealAvatar = !!item?.avatar && item.avatar !== 'MCP_AVATAR';- return {- icon: hasRealAvatar ? (- <Avatar avatar={item.avatar} shape={'square'} size={SKILL_ICON_SIZE} />- ) : (- <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />- ),- key: item.identifier,- label: (- <ToolItem- checked={true}- disabled={!canEdit}- id={item.identifier}- label={item.title}- onUpdate={async () => {- if (!canEdit) return;- await togglePlugin(item.identifier);- }}- />- ),- popoverContent: (- <ToolItemDetailPopover- description={item.description}- identifier={item.identifier}- sourceLabel={t('skillStore.tabs.community')}- title={item.title}- icon={- hasRealAvatar ? (- <Avatar- avatar={item.avatar}- shape={'square'}- size={36}- style={{ flex: 'none', marginInlineEnd: 0 }}- />- ) : (- <Icon icon={McpIcon} size={36} />- )- }- />- ),- };- });-- // Enabled custom plugins- const enabledCustomPlugins = customPlugins- .filter((item) => checked.includes(item.identifier))- .map((item) => {- const hasRealAvatar = !!item?.avatar && item.avatar !== 'MCP_AVATAR';- return {- icon: hasRealAvatar ? (- <Avatar avatar={item.avatar} shape={'square'} size={SKILL_ICON_SIZE} />- ) : (- <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />- ),- key: item.identifier,- label: (- <ToolItem- checked={true}- disabled={!canEdit}- id={item.identifier}- label={item.title}- onUpdate={async () => {- if (!canEdit) return;- await togglePlugin(item.identifier);- }}- />- ),- popoverContent: (- <ToolItemDetailPopover- description={item.description}- identifier={item.identifier}- sourceLabel={t('skillStore.tabs.custom')}- title={item.title}- icon={- hasRealAvatar ? (- <Avatar- avatar={item.avatar}- shape={'square'}- size={36}- style={{ flex: 'none', marginInlineEnd: 0 }}- />- ) : (- <Icon icon={McpIcon} size={36} />- )- }- />- ),- };- });-- const allCommunityItems = enabledCommunityPlugins;- if (allCommunityItems.length > 0) {- installedItems.push({- children: allCommunityItems,- key: 'installed-community',- label: t('skillStore.tabs.community'),- type: 'group',- });- }-- const allCustomItems = enabledCustomPlugins;- if (allCustomItems.length > 0) {- installedItems.push({- children: allCustomItems,- key: 'installed-custom',- label: t('skillStore.tabs.custom'),- type: 'group',- });- }-- return installedItems;- }, [- filteredBuiltinList,- communityPlugins,- customPlugins,- composioServerItems,- lobehubSkillItems,- checked,- togglePlugin,- canEdit,- t,- ]);-return {autoCount: allAutoItems.length,- installedPluginItems,+ // Stable inventory order: toggling a checkbox must not move its row.+ toolOptions: [...capabilityItems, ...allSkillItems].map((item) => ({+ canDisable: !!item.canDisable,+ enabled: allAutoItems.includes(item),+ group: communityGroupChildren.includes(item)+ ? 'community'+ : customGroupChildren.includes(item)+ ? 'custom'+ : 'lobehub',+ icon: item.optionIcon,+ id: String(item.key),+ connectionAction: item.optionTitle === undefined && 'label' in item ? item.label : undefined,+ detail: item.detailContent ?? item.popoverContent,+ searchText: item.searchText,+ title: item.optionTitle,+ })),+ activeTools: allAutoItems.map((item) => ({+ canDisable: !!item.canDisable,+ id: String(item.key),+ })),+ canEdit,+ setPolicy: updateSkillPolicy,+ totalCount: allAutoItems.length + allDisabledItems.length,isPolicyMenuOpen: policyOpenId !== null,marketFooter,marketHeader,marketItems,- pinnedCount: allPinnedItems.length + fixedPinnedItems.length + capabilityPinnedItems.length,};};diff --git a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsxindex 6767dd1ed12..e50eface1f5 100644--- a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx+++ b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx@@ -81,13 +81,9 @@ const SubmenuScrollStyle = createGlobalStyle`padding-block-end: 4px;}- /* The skill submenu (the one with the search header) has collapsible groups,- so shrink-to-fit makes it resize every time a group opens or closes —- measured 243px collapsed vs 400px expanded, the jump driven by whichever- title happens to be longest. Pin the width so the container stays put and- the rows ellipsize into it. */- [data-submenu] > [role='menu']:has(.lobe-skill-submenu-search) {- width: min(90vw, 400px);+ /* A stable width keeps switching filters and searching from moving the menu. */+ [data-submenu] > [role='menu']:has(.lobe-tool-picker-header) {+ width: min(90vw, 320px);}/* base-ui menu-item internal containers are flex by default but don't set@@ -104,24 +100,8 @@ const SubmenuScrollStyle = createGlobalStyle`background: ${cssVarValue.colorBorderSecondary};}- /* base-ui group label is rendered inside a [role='presentation'] with its- own default vertical padding, which stacks with our activationGroupHeader- padding and inflates the gap above/below group headers. Reset only the- vertical padding for skill activation groups; other groups (e.g. the- Knowledge submenu's Libraries/Files headers) keep their default padding. */- [data-submenu] > [role='menu'] [role='group']:has([data-skill-activation-group]) > [role='presentation'] {- padding-block: 0;- }-- /* The skill submenu is the only submenu that uses a header slot (the search- bar). renderDropdownMenuItems wraps it in DropdownMenuHeader's default- 8px/12px padding — which can't be reached via props — leaving the borderless- search floating in a tall gap and indented past the rows below. Trim the- padding so the search sits snug against the divider and its icon lines up- with the 16px icon column shared by the menu rows. */- [data-submenu] > [role='menu'] > *:has(.lobe-skill-submenu-search) {- padding-block: 4px;- padding-inline: 4px;+ [data-submenu] > [role='menu'] > *:has(> .lobe-tool-picker-header) {+ padding: 8px;}/* Submenu triggers that opt into a custom trailing chevron (the Plus menu'sdiff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex 2ad7ea901d6..8d216163250 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -847,6 +847,20 @@ describe('AgentWorkingSidebar — tab strip', () => {expect(tabs[0]).toHaveAttribute('aria-pressed', 'true');});+ it('does not offer Files for the implicit desktop directory when no folder is selected', () => {+ agentStore.activeAgentId = 'agent';+ effectiveConfig.agencyConfig = { executionTarget: 'local' };+ reviewState.workingDirectory = '/Users/me/Desktop';+ reviewState.isHomeFallback = true;+ localStorageState.openTabsByContext = {};+ globalStore.status.workingSidebarTab = 'overview';++ render(<AgentWorkingSidebar />);++ expect(document.querySelector('button[data-tab-key="files"]')).toBeNull();+ expect(document.querySelector('button[data-tab-key="skills"]')).not.toBeNull();+ });+it('opens Claude Code memory by default once a project folder is selected', () => {agentStore.activeAgentId = 'agent';agentStore.heterogeneousType = 'claude-code';diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 916da3872b3..7f1af9c9b5a 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -266,11 +266,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })activeAgentId ? chatConfigByIdSelectors.isChatModeById(activeAgentId)(s) : false,);const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- // Unified precedence (topic > per-device choice > legacy > device default), so- // the sidebar resolves the same directory the runtime bar / git status do.- // The old `topicCwd || legacy agentCwd` pattern missed `workingDirByDevice`,- // landing on the home fallback for device-bound agents and hiding Review.- const workingDirectory = useEffectiveWorkingDirectory(activeAgentId);+ // Match the folder picker: the runtime's implicit desktop/home cwd isn't a selected workspace.+ const workingDirectory = useEffectiveWorkingDirectory(activeAgentId, { homeFallback: false });// Effective target device for git ops — bound device for remote agents, this// machine otherwise. Resolved the same way WorkingDirectoryPicker / GitStatus do.const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(activeAgentId);diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex 96a036ba0c3..b1b76795192 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -1,5 +1,6 @@'use client';+import { isOnDemandBuiltinTool } from '@lobechat/builtin-tools';import { getConnectorCatalog } from '@lobechat/const';import { parsePluginEntry, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';import type { ItemType } from '@lobehub/ui';@@ -263,7 +264,7 @@ const AgentTool = memo<AgentToolProps>(// dropped from the array.await updateAgentConfigById(effectiveAgentId, {plugins:- shouldEnable && connectorIds.has(pluginId)+ shouldEnable && (connectorIds.has(pluginId) || isOnDemandBuiltinTool(pluginId))? upsertConnectorEnabled(config?.plugins, pluginId, true): upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),});@@ -570,11 +571,16 @@ const AgentTool = memo<AgentToolProps>(/>),key: item.identifier,+ searchText: t(`tools.builtins.${item.identifier}.title` as any, {+ defaultValue: item.meta?.title || item.identifier,+ }),label: (<ToolItemchecked={isToolEnabled(item.identifier)}id={item.identifier}- label={item.meta?.title}+ label={t(`tools.builtins.${item.identifier}.title` as any, {+ defaultValue: item.meta?.title || item.identifier,+ })}onUpdate={async () => {setUpdating(true);await handleToggleTool(item.identifier);@@ -905,9 +911,10 @@ const AgentTool = memo<AgentToolProps>(const setPluginEnabled = (pluginId: string, enabled: boolean) => {if (!canEdit || !effectiveAgentId) return;return updateAgentConfigById(effectiveAgentId, {- plugins: connectorIds.has(pluginId)- ? upsertConnectorEnabled(config?.plugins, pluginId, enabled)- : upsertPluginMode(config?.plugins, pluginId, enabled ? 'pinned' : 'disabled'),+ plugins:+ connectorIds.has(pluginId) || isOnDemandBuiltinTool(pluginId)+ ? upsertConnectorEnabled(config?.plugins, pluginId, enabled)+ : upsertPluginMode(config?.plugins, pluginId, enabled ? 'pinned' : 'disabled'),});};@@ -963,6 +970,7 @@ const AgentTool = memo<AgentToolProps>(popupRender={() => (<PopoverContentitems={pickerItems}+ toolsOnly={kind === 'tools'}onClose={() => setDropdownOpen(false)}onOpenStore={() => {setDropdownOpen(false);diff --git a/src/features/ProfileEditor/AgentUserTools/ProfileToolPicker.tsx b/src/features/ProfileEditor/AgentUserTools/ProfileToolPicker.tsxnew file mode 100644index 00000000000..f88df2d404d--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/ProfileToolPicker.tsx@@ -0,0 +1,115 @@+'use client';++import { Button, type ItemType } from '@lobehub/ui';+import { PlusIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import ActionDropdown from '@/features/ChatInput/ActionBar/components/ActionDropdown';+import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';+import { useControls } from '@/features/ChatInput/ActionBar/Tools/useControls';+import { createStore, Provider } from '@/features/ChatInput/store';+import { createSkillStoreModal } from '@/features/SkillStore';++import type { AgentToolProps } from '../AgentTool';+import PluginTag from '../PluginTag';+import ProfilePopoverContent from '../PopoverContent';+import ToolListGroup, { type ToolGroupMeta } from '../ToolListGroup';++interface Props extends Pick<AgentToolProps, 'onOpenDetail' | 'showAuthor'> {+ agentId: string;+ group: ToolGroupMeta;+}++const LibraryTools = ({ group, onOpenDetail, showAuthor }: Omit<Props, 'agentId'>) => {+ const { t } = useTranslation('setting');+ const tools = useControls();+ const [open, setOpen] = useState(false);+ const items: ItemType[] = (['lobehub', 'community', 'custom'] as const).flatMap((source) => {+ const children = tools.toolOptions+ .filter((tool) => tool.group === source)+ .map((tool) => ({+ key: tool.id,+ icon: tool.icon,+ searchText: tool.searchText,+ popoverContent: tool.detail,+ label: tool.connectionAction ?? (+ <ToolItem+ checked={tool.enabled}+ disabled={!tools.canEdit || !tool.canDisable}+ id={tool.id}+ label={tool.title}+ onUpdate={(id, enabled) => tools.setPolicy(id, enabled ? 'auto' : 'disabled')}+ />+ ),+ }));+ return children.length+ ? [{ children, key: source, label: t(`skillStore.tabs.${source}`), type: 'group' as const }]+ : [];+ });+ return (+ <ToolListGroup+ {...group}+ activeCount={tools.autoCount}+ emptyText={t('settingAgent.tools.level.libraryEmpty')}+ total={tools.totalCount}+ addControl={+ <ActionDropdown+ maxWidth={400}+ menu={{ items: [], style: { maxHeight: 'unset', overflowY: 'visible' } }}+ minWidth={400}+ open={open}+ placement="bottomLeft"+ popupProps={{ style: { padding: 0 } }}+ trigger="click"+ popupRender={() => (+ <ProfilePopoverContent+ toolsOnly+ items={items}+ onClose={() => setOpen(false)}+ onOpenStore={() => {+ setOpen(false);+ createSkillStoreModal();+ }}+ />+ )}+ positionerProps={{+ collisionAvoidance: { align: 'flip', fallbackAxisSide: 'end', side: 'flip' },+ collisionBoundary:+ typeof document === 'undefined' ? undefined : document.documentElement,+ positionMethod: 'fixed',+ }}+ onOpenChange={setOpen}+ >+ <Button disabled={!tools.canEdit} icon={PlusIcon} size="small" type="text">+ {t('settingAgent.agentTools.add')}+ </Button>+ </ActionDropdown>+ }+ rows={tools.activeTools.map(({ id, canDisable }) => (+ <PluginTag+ enabled+ useAllMetaList+ disabled={!tools.canEdit || !canDisable}+ key={id}+ pluginId={id}+ removable={false}+ showAuthor={showAuthor}+ variant="row"+ onOpen={onOpenDetail}+ onToggle={(on) => void tools.setPolicy(id, on ? 'auto' : 'disabled')}+ />+ ))}+ />+ );+};++// The picker and its nested search/memory settings must read and write the+// profile being edited, even when another agent is open in the composer.+const ProfileToolPicker = ({ agentId, ...props }: Props) => (+ <Provider createStore={() => createStore({ agentId })} key={agentId}>+ <LibraryTools {...props} />+ </Provider>+);++export default ProfileToolPicker;diff --git a/src/features/ProfileEditor/AgentUserTools/index.tsx b/src/features/ProfileEditor/AgentUserTools/index.tsxindex 04b63604afc..513de2cb909 100644--- a/src/features/ProfileEditor/AgentUserTools/index.tsx+++ b/src/features/ProfileEditor/AgentUserTools/index.tsx@@ -16,6 +16,7 @@ import { useToolStore } from '@/store/tool';import { connectorSelectors } from '@/store/tool/slices/connector';import AgentToolsSection from './AgentToolsSection';+import ProfileToolPicker from './ProfileToolPicker';import RunPriorityHint from './RunPriorityHint';import UserToolsSection from './UserToolsSection';@@ -130,18 +131,27 @@ const AgentUserTools = memo<AgentToolProps & { variant?: 'chip' | 'list' }>((proonStartCopy={() => setCopyMode(true)}/>)}- <UserToolsSection- {...toolProps}- agentId={effectiveAgentId}- copyMode={copyMode}- copying={copying}- group={libraryGroup}- selected={selected}- toggleSelected={toggleSelected}- variant={'list'}- onCancelCopy={resetCopy}- onConfirmCopy={handleConfirmCopy}- />+ {toolProps.kind === 'tools' && !copyMode ? (+ <ProfileToolPicker+ agentId={effectiveAgentId}+ group={libraryGroup}+ showAuthor={!!activeWorkspaceId}+ onOpenDetail={toolProps.onOpenDetail}+ />+ ) : (+ <UserToolsSection+ {...toolProps}+ agentId={effectiveAgentId}+ copyMode={copyMode}+ copying={copying}+ group={libraryGroup}+ selected={selected}+ toggleSelected={toggleSelected}+ variant={'list'}+ onCancelCopy={resetCopy}+ onConfirmCopy={handleConfirmCopy}+ />+ )}</Flexbox>);}diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsxindex c73a7ec4b62..0af906a3cdb 100644--- a/src/features/ProfileEditor/PluginTag.tsx+++ b/src/features/ProfileEditor/PluginTag.tsx@@ -318,9 +318,13 @@ const PluginTag = memo<PluginTagProps>(return {availableInWeb,avatar: builtinMeta.meta.avatar,- description: builtinMeta.meta.description,+ description: t(`tools.builtins.${identifier}.description` as any, {+ defaultValue: builtinMeta.meta.description || '',+ }),isInstalled: true,- title: builtinMeta.meta.title,+ title: t(`tools.builtins.${identifier}.title` as any, {+ defaultValue: builtinMeta.meta.title || identifier,+ }),type: 'builtin' as const,};}@@ -382,6 +386,7 @@ const PluginTag = memo<PluginTagProps>(allLobehubSkillServers,customConnectors,marketplaceConnectors,+ t,useAllMetaList,]);diff --git a/src/features/ProfileEditor/PopoverContent.tsx b/src/features/ProfileEditor/PopoverContent.tsxindex 5b5ac2a8609..b062e00993d 100644--- a/src/features/ProfileEditor/PopoverContent.tsx+++ b/src/features/ProfileEditor/PopoverContent.tsx@@ -23,7 +23,10 @@ const filterItems = (items: ItemType[], keyword: string): ItemType[] => {const filtered = item.children.filter((child) => {if (!child) return false;const key = String(child.key || '').toLowerCase();- return key.includes(lower);+ return (+ key.includes(lower) ||+ ('searchText' in child && String(child.searchText).toLowerCase().includes(lower))+ );});if (filtered.length === 0) return null;return { ...item, children: filtered };@@ -60,9 +63,10 @@ interface PopoverContentProps {items: ItemType[];onClose?: () => void;onOpenStore: () => void;+ toolsOnly?: boolean;}-const PopoverContent = memo<PopoverContentProps>(({ items, onOpenStore, onClose }) => {+const PopoverContent = memo<PopoverContentProps>(({ items, onOpenStore, onClose, toolsOnly }) => {const { t } = useTranslation('setting');const navigate = useWorkspaceAwareNavigate();const [searchKeyword, setSearchKeyword] = useState('');@@ -79,7 +83,7 @@ const PopoverContent = memo<PopoverContentProps>(({ items, onOpenStore, onClose<div className={styles.header} onClick={stopPropagation}><SearchBarallowClear- placeholder={t('tools.search')}+ placeholder={t(toolsOnly ? 'tools.picker.search' : 'tools.search')}size="small"style={{ flex: 1 }}value={searchKeyword}@@ -111,7 +115,9 @@ const PopoverContent = memo<PopoverContentProps>(({ items, onOpenStore, onClose<div className={toolsListStyles.itemIcon}><Icon icon={Settings} size={SKILL_ICON_SIZE} /></div>- <div className={toolsListStyles.itemContent}>{t('tools.plugins.management')}</div>+ <div className={toolsListStyles.itemContent}>+ {t(toolsOnly ? 'tools.picker.management' : 'tools.plugins.management')}+ </div><Icon className={styles.trailingIcon} icon={ExternalLink} size={16} /></div></div>diff --git a/src/helpers/toolEngineering/connectorActivation.test.ts b/src/helpers/toolEngineering/connectorActivation.test.tsindex ccde67f33ba..5f6bcf4590f 100644--- a/src/helpers/toolEngineering/connectorActivation.test.ts+++ b/src/helpers/toolEngineering/connectorActivation.test.ts@@ -85,7 +85,7 @@ describe('applyAgentConnectorActivation', () => {).toEqual(['lobe-image-generation', 'library-skill']);});- it('invokes a connector that is on directly in manual mode', () => {+ it('keeps an opted-in connector discoverable despite a legacy manual preference', () => {const connectors = resolveAgentConnectorActivation({chatConfig: { skillActivateMode: 'manual' },@@ -95,7 +95,8 @@ describe('applyAgentConnectorActivation', () => {toolState,);- expect(applyAgentConnectorActivation([], connectors)).toEqual(['linear']);+ expect(connectors.offIds).not.toContain('linear');+ expect(applyAgentConnectorActivation(['linear'], connectors)).toEqual([]);});it('keeps a connector this turn mentions', () => {diff --git a/src/helpers/toolEngineering/connectorActivation.ts b/src/helpers/toolEngineering/connectorActivation.tsindex c397e049e62..44e6d817c2d 100644--- a/src/helpers/toolEngineering/connectorActivation.ts+++ b/src/helpers/toolEngineering/connectorActivation.ts@@ -1,15 +1,11 @@+import { getUserDisabledToolIds } from '@lobechat/builtin-tools';import {applyConnectorActivation,type ConnectorActivation,hasConnectorActivator,resolveConnectorActivation,} from '@lobechat/mecha';-import {- type AgentPluginEntry,- getActivePluginIds,- getDisabledPluginIds,- getOptedInPluginIds,-} from '@lobechat/types';+import { type AgentPluginEntry, getActivePluginIds, getOptedInPluginIds } from '@lobechat/types';import { getToolStoreState } from '@/store/tool';import type { ToolStoreState } from '@/store/tool/initialState';@@ -69,7 +65,7 @@ export const resolveAgentConnectorActivation = (hasActivator: hasConnectorActivator(agent.chatConfig,[...(agent.enabledPluginIds ?? getActivePluginIds(agent.plugins)), ...turnIds],- getDisabledPluginIds(agent.plugins),+ getUserDisabledToolIds(agent.plugins, agent.chatConfig),),optedInIds: getOptedInPluginIds(agent.plugins),turnIds,diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsindex 020a1a2c389..fea0fd62ab0 100644--- a/src/helpers/toolEngineering/index.test.ts+++ b/src/helpers/toolEngineering/index.test.ts@@ -301,8 +301,9 @@ describe('toolEngineering', () => {});describe('feature-flagged tools', () => {- const generate = () =>+ const generate = (explicit = false) =>createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }).generateToolsDetailed({+ context: { isExplicitActivation: explicit },toolIds: [DashboardManifest.identifier],model: 'gpt-4',provider: 'openai',@@ -314,10 +315,11 @@ describe('toolEngineering', () => {expect(generate().enabledToolIds).not.toContain(DashboardManifest.identifier);});- it('offers a pinned builtin-dashboard once the flag is on', () => {+ it('offers the previously pinned dashboard only after activation once the flag is on', () => {mockCurrentAgentPlugins = [DashboardManifest.identifier];mockFeatureFlags = { enableDashboard: true };- expect(generate().enabledToolIds).toContain(DashboardManifest.identifier);+ expect(generate().enabledToolIds).not.toContain(DashboardManifest.identifier);+ expect(generate(true).enabledToolIds).toContain(DashboardManifest.identifier);});});@@ -622,6 +624,10 @@ describe('toolEngineering', () => {skipDefaultTools: true,toolIds: ['lobe-agent'],};+ expect(+ createAgentToolsEngine(model).generateToolsDetailed(activation).enabledToolIds,+ ).toEqual([]);+ mockCurrentAgentAutoPlugins = ['lobe-agent'];const engine = createAgentToolsEngine(model);expect(engine.generateToolsDetailed({ ...model, toolIds: [] }).enabledToolIds).not.toContain(@@ -655,7 +661,7 @@ describe('toolEngineering', () => {expect(result.enabledToolIds).toEqual([]);expect(result.filteredTools).toContainEqual({id: 'lobe-agent',- reason: 'incompatible',+ reason: 'not_found',});expect(result.filteredTools).toContainEqual({id: 'lobe-web-browsing',@@ -678,7 +684,8 @@ describe('toolEngineering', () => {expect(result.enabledToolIds).not.toContain('lobe-image-generation');});- it('should allow image generation explicit activation in agent mode', () => {+ it('should allow opted-in image generation explicit activation in agent mode', () => {+ mockCurrentAgentAutoPlugins = ['lobe-image-generation'];const toolsEngine = createAgentToolsEngine({model: 'gpt-4',provider: 'openai',@@ -913,11 +920,12 @@ describe('toolEngineering', () => {expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);});- it('invokes a connector that is on directly when manual mode strips the activator', () => {+ it('defers an enabled connector despite a legacy manual preference', () => {mockCurrentAgentAutoPlugins = ['gmail-mcp'];mockCurrentChatConfig = { skillActivateMode: 'manual' };- expect(generate().enabledToolIds).toEqual(['gmail-mcp']);+ expect(generate().enabledToolIds).toEqual([]);+ expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);});it('invokes a connector that is on directly in custom mode, which has no activator either', () => {@@ -1001,6 +1009,7 @@ describe('toolEngineering', () => {describe('Computer Use activation', () => {it('loads the native API only after activation in standalone Electron', () => {desktopEnv.enabled = true;+ mockCurrentAgentAutoPlugins = [AuvManifest.identifier];const engine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });expect(engine.generateToolsDetailed({ model: 'gpt-4', provider: 'openai', toolIds: [] })@@ -1017,6 +1026,7 @@ describe('Computer Use activation', () => {});it('does not let explicit activation bypass the Web platform restriction', () => {desktopEnv.enabled = false;+ mockCurrentAgentAutoPlugins = [AuvManifest.identifier];const engine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });expect(engine.generateToolsDetailed({diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex 76d3dc2b785..993c170f004 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -2,6 +2,11 @@* Tools Engineering - Unified tools processing using ToolsEngine*/import { AuvManifest } from '@lobechat/builtin-tool-auv';+import {+ getUnselectedBuiltinToolIds,+ getUserDisabledToolIds,+ isOnDemandBuiltinTool,+} from '@lobechat/builtin-tools';import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';import { serverOnlyToolIds } from '@lobechat/builtin-tools/serverOnly';import {@@ -16,8 +21,9 @@ import {type BuiltinToolResolveContext,type ChatCompletionTool,getActivePluginIds,- getDisabledPluginIds,+ getOptedInPluginIds,type LobeAgentChatConfig,+ resolveToolMode,type ToolManifest,type WorkingModel,} from '@lobechat/types';@@ -189,15 +195,23 @@ export const createAgentToolsEngine = (agent: {chatConfig,plugins: applyAgentConnectorActivation(- options.runAgent?.enabledPluginIds ?? getActivePluginIds(agent.plugins),+ options.runAgent?.enabledPluginIds ??+ getActivePluginIds(agent.plugins).filter(+ (id) => resolveToolMode(chatConfig) !== 'agent' || !isOnDemandBuiltinTool(id),+ ),connectors,),},// Feature-flagged tools (e.g. builtin-dashboard) leave the pool while their// flag is off for this user.disabledPluginIds: [- ...getDisabledPluginIds(agent.plugins),+ ...getUserDisabledToolIds(agent.plugins, chatConfig),...connectors.offIds,+ ...getUnselectedBuiltinToolIds([+ ...getOptedInPluginIds(agent.plugins),+ ...(options.runAgent?.enabledPluginIds ?? []),+ ...(pluginIds ?? []),+ ]),...getFeatureDisabledToolIds(getServerConfigStoreState()?.featureFlags),// This engine serves runs the browser executes; server-only tools have nothing to run here....serverOnlyToolIds,diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex d0811538ad3..d3e1e1acab7 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -1,4 +1,5 @@import { stripAssistantReasoningForReplay } from '@lobechat/agent-runtime';+import { getUnselectedBuiltinToolIds, getUserDisabledToolIds } from '@lobechat/builtin-tools';import {REQUEST_AGENT_ID_HEADER,REQUEST_OPERATION_ID_HEADER,@@ -14,7 +15,7 @@ import {ChatErrorType,type ChatMessageError,getAutoPluginIds,- getDisabledPluginIds,+ getOptedInPluginIds,type RequestTrigger,type RuntimeAdditionalContextFragment,type RuntimeInitialContext,@@ -235,7 +236,11 @@ class ChatService {// A connector the agent has not turned on is off for it, so it leaves the// discovery list too; one this turn already enabled (an @-mention) stays.disabledPluginIds: [- ...getDisabledPluginIds(agentConfig.plugins),+ ...getUserDisabledToolIds(agentConfig.plugins, chatConfig),+ ...getUnselectedBuiltinToolIds([+ ...getOptedInPluginIds(agentConfig.plugins),+ ...(enabledToolIds ?? []),+ ]),...resolveAgentConnectorActivation({ chatConfig, plugins: agentConfig.plugins },enabledToolIds,diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.tsindex 91a671193ca..c7fdb0f8f0c 100644--- a/src/services/chat/mecha/agentConfigResolver.test.ts+++ b/src/services/chat/mecha/agentConfigResolver.test.ts@@ -1229,66 +1229,24 @@ describe('resolveAgentConfig', () => {});});- // lobe-agent's sub-agent / group trimming moved into resolveLobeAgentManifest- // (manifest resolver, applied at tools-engine build time). resolveAgentConfig no- // longer drops lobe-agent from the plugins list based on isSubAgent — it stays so- // its plan / todo / visual-media APIs remain available; only callSubAgent is hidden- // downstream (covered by resolveManifest.test.ts).- describe('isSubAgent keeps lobe-agent in plugins (trimming moved to manifest resolver)', () => {+ describe('on-demand tool pins and runtime-provided tools', () => {beforeEach(() => {vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(() => undefined);});- it('keeps lobe-agent when isSubAgent is true for regular agent', () => {- vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(- () =>- ({- ...mockAgentConfig,- plugins: ['lobe-agent', 'plugin-a', 'plugin-b'],- }) as any,- );-- const result = resolveAgentConfig({- agentId: 'test-agent',- isSubAgent: true,- });-- expect(result.plugins).toEqual(['lobe-agent', 'plugin-a', 'plugin-b']);- });-- it('should keep lobe-agent when isSubAgent is false', () => {- vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(- () =>- ({- ...mockAgentConfig,- plugins: ['lobe-agent', 'plugin-a', 'plugin-b'],- }) as any,- );-- const result = resolveAgentConfig({- agentId: 'test-agent',- isSubAgent: false,- });-- expect(result.plugins).toContain('lobe-agent');- expect(result.plugins).toEqual(['lobe-agent', 'plugin-a', 'plugin-b']);- });-- it('should keep lobe-agent when isSubAgent is undefined', () => {- vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(- () =>- ({- ...mockAgentConfig,- plugins: ['lobe-agent', 'plugin-a'],- }) as any,- );-- const result = resolveAgentConfig({ agentId: 'test-agent' });-- expect(result.plugins).toContain('lobe-agent');- });+ it.each([true, false, undefined])(+ 'keeps saved lobe-agent pins on demand while loading other pins (isSubAgent: %s)',+ (isSubAgent) => {+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(+ () =>+ ({ ...mockAgentConfig, plugins: [LobeAgentIdentifier, 'plugin-a', 'plugin-b'] }) as any,+ );+ const result = resolveAgentConfig({ agentId: 'test-agent', isSubAgent });+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ },+ );- it('keeps lobe-agent in page scope when isSubAgent is true (and still injects page-agent)', () => {+ it('injects page-agent in page scope while leaving the saved lobe-agent pin on demand', () => {vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(() =>({@@ -1306,8 +1264,8 @@ describe('resolveAgentConfig', () => {isSubAgent: true,});- expect(result.plugins).toContain('lobe-agent');- expect(result.plugins).toContain(PageAgentIdentifier);+ expect(result.plugins).toEqual(expect.arrayContaining([PageAgentIdentifier, 'plugin-a']));+ expect(result.plugins).not.toContain(LobeAgentIdentifier);});it('keeps lobe-agent for builtin agent when isSubAgent is true', () => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex c71bc56b04d..1fca59d6083 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -1473,10 +1473,15 @@ describe('StreamingExecutor actions', () => {);});- it.each([true, false])(- 'keeps manual-mode tools callable while omitting the activator (builtin: %s)',- (isBuiltinAgent) => {- const chatConfig = createMockChatConfig({ skillActivateMode: 'manual' });+ it.each([+ { isBuiltinAgent: true, skillActivateMode: 'manual' },+ { isBuiltinAgent: false, skillActivateMode: 'manual' },+ { isBuiltinAgent: true, skillActivateMode: 'auto' },+ { isBuiltinAgent: false, skillActivateMode: 'auto' },+ ] as const)(+ 'keeps the activator and skill loader callable with $skillActivateMode preferences (builtin: $isBuiltinAgent)',+ ({ isBuiltinAgent, skillActivateMode }) => {+ const chatConfig = createMockChatConfig({ skillActivateMode });const plugins = ['lobe-skill-store'];vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({agentConfig: createMockAgentConfig({ plugins }),@@ -1493,50 +1498,10 @@ describe('StreamingExecutor actions', () => {});expect(agentConfig.enabledToolIds).toContain('lobe-skill-store');expect(agentConfig.enabledToolIds).toContain('lobe-skills');- expect(agentConfig.enabledToolIds).not.toContain('lobe-activator');+ expect(agentConfig.enabledToolIds).toContain('lobe-activator');},);- it('should not set excludeDefaultToolIds in auto mode', () => {- act(() => {- useChatStore.setState({ executeClientAgent: realExecAgentRuntime });- });-- const { result } = renderHook(() => useChatStore());- const userMessage = createUserMessage();-- const generateToolsDetailed = vi.fn().mockReturnValue({- enabledManifests: [],- enabledToolIds: [],- tools: [],- });-- vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({- agentConfig: createMockAgentConfig(),- chatConfig: createMockChatConfig(),- isBuiltinAgent: true,- plugins: [],- });- vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({- generateToolsDetailed,- } as any);-- result.current.internal_createAgentState({- messages: [userMessage],- parentMessageId: userMessage.id,- agentId: TEST_IDS.SESSION_ID,- topicId: TEST_IDS.TOPIC_ID,- });-- // In auto mode, no tools should be excluded from defaults- expect(generateToolsDetailed).toHaveBeenCalledWith(- expect.objectContaining({- skipDefaultTools: undefined,- excludeDefaultToolIds: undefined,- }),- );- });-it('should preserve default model/provider payload when initialContext is provided', () => {act(() => {useChatStore.setState({ executeClientAgent: realExecAgentRuntime });diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 4cacef8df26..e4e61f3ff67 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -14,7 +14,6 @@ import {} from '@lobechat/agent-runtime';import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';-import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';import {getSubAgentChatConfigOverride,isDesktop,@@ -293,11 +292,7 @@ export class StreamingExecutorActionImpl {{ executionEnv: isDesktop ? 'local' : undefined, isSubAgent, scope },{ hasOversizedFiles: hasPreviewableFiles(messages), runAgent: { ...runAgent, connectors } },);- // Manual mode omits the activator and keeps explicit pins and runtime tools.- const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';-const toolsDetailed = toolsEngine.generateToolsDetailed({- excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,model: agentConfigData.model,provider: agentConfigData.provider!,skipDefaultTools: disableTools || undefined,diff --git a/src/store/tool/slices/builtin/selectors.test.ts b/src/store/tool/slices/builtin/selectors.test.tsindex c1fa911f1bc..3e58cc2c593 100644--- a/src/store/tool/slices/builtin/selectors.test.ts+++ b/src/store/tool/slices/builtin/selectors.test.ts@@ -112,30 +112,16 @@ describe('builtinToolSelectors', () => {});});- describe('fixedDisplayMetaList', () => {- it.each([false, true])(- 'lists Lobe Agent and Skill Store as configurable instead of fixed (manual: %s)',- (isManualMode) => {- const fixed = builtinToolSelectors.fixedDisplayMetaList({ isManualMode })(initialState);- const visible = isManualMode- ? builtinToolSelectors.metaListIncludingHidden(initialState)- : builtinToolSelectors.metaList(initialState);-- expect(fixed.map((tool) => tool.identifier)).toEqual(['lobe-skills']);- expect(visible.map((tool) => tool.identifier)).toEqual(- expect.arrayContaining(['lobe-agent', 'lobe-skill-store']),- );- },- );-- it('should skip fixed ids that are not registered in builtinTools', () => {- const state = {- ...initialState,- builtinTools: [],- } as unknown as ToolStoreState;-- expect(builtinToolSelectors.fixedDisplayMetaList()(state)).toEqual([]);- });+ it('keeps fixed loaders out of both tool pickers but leaves Skill Store configurable', () => {+ for (const select of [+ builtinToolSelectors.metaList,+ builtinToolSelectors.metaListIncludingHidden,+ ]) {+ const ids = select(initialState).map((tool) => tool.identifier);+ expect(ids).not.toContain('lobe-skills');+ expect(ids).not.toContain('lobe-activator');+ expect(ids).toContain('lobe-skill-store');+ }});describe('installedAllMetaList', () => {diff --git a/src/store/tool/slices/builtin/selectors.ts b/src/store/tool/slices/builtin/selectors.tsindex 4dd91a9ecde..9a5e818e719 100644--- a/src/store/tool/slices/builtin/selectors.ts+++ b/src/store/tool/slices/builtin/selectors.ts@@ -1,5 +1,4 @@import {- activationModeControlledToolIds,alwaysOnToolIds,manualModeExcludeToolIds,runtimeManagedToolIds,@@ -124,6 +123,7 @@ const buildVisibleMetaList = (const builtinMetas = s.builtinTools.filter((item) => {+ if (ALWAYS_ON_TOOL_IDS.has(item.identifier)) return false;// Filter hidden tools (unless caller opts in)if (item.hidden && !includeHidden) return false;// Even when `includeHidden` is true, never expose pure infra tools.@@ -295,33 +295,6 @@ const nonProfileConfigurableBuiltinToolIds =.filter((tool) => !isProfileConfigurableBuiltinTool(tool, options)).map((tool) => tool.identifier);-const ACTIVATION_MODE_CONTROLLED_TOOL_IDS = new Set(activationModeControlledToolIds);--/**- * Get meta for builtin runtime tools that default to pinned and should be shown in the- * chat-input Tools popover. Their per-agent policy supports pinned or disabled.- *- * These tools are normally `hidden` (and some are `discoverable: false`), so they never- * appear in `metaList` / `metaListIncludingHidden`. Here we read them directly from- * `builtinTools` by identifier, preserving the `alwaysOnToolIds` order and dropping any- * that aren't available in the current environment.- *- * The list must match what the engine actually enables: in manual skill-activate mode the- * discovery tools in `manualModeExcludeToolIds` are stripped from- * the defaults before the enable checker runs, so they are NOT on — exclude them here too,- * otherwise the UI would claim a fixed tool that the runtime omits.- */-const fixedDisplayMetaList =- ({ isManualMode }: { isManualMode: boolean } = { isManualMode: false }) =>- (s: ToolStoreState): LobeToolMeta[] =>- alwaysOnToolIds- .filter((id) => !ACTIVATION_MODE_CONTROLLED_TOOL_IDS.has(id))- .filter((id) => !(isManualMode && MANUAL_MODE_EXCLUDE_TOOL_IDS.has(id)))- .map((id) => s.builtinTools.find((tool) => tool.identifier === id))- .filter((tool): tool is ToolStoreState['builtinTools'][number] => !!tool)- .filter((tool) => isBuiltinToolAvailableInCurrentEnv(tool.identifier))- .map(toBuiltinMeta);-/*** Get installed builtin skills (excludes uninstalled ones)*/@@ -347,7 +320,6 @@ const isBuiltinToolInstalled = (identifier: string) => (s: ToolStoreState) =>export const builtinToolSelectors = {allMetaList,discoverableMetaList,- fixedDisplayMetaList,installedAllMetaList,installedBuiltinSkills,installedProfileConfigurableMetaList,