Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(connector): make connectors two-state and opt-in per agent (#23329)

AmAzing-0ac5f31c40c9
diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.md
index cf7253941a9..2d327256ecf 100644
--- a/.agents/ux/lobe-design-rules.md
+++ b/.agents/ux/lobe-design-rules.md
@@ -183,3 +183,9 @@ User-skill enablement belongs in a separate management view entered through the
The title itself states the task and scope: “Choose the skills this agent can use” / 「选择当前助理可以使用的技能」. Merge useful explanatory copy into that title rather than dropping the scope or repeating it in a subtitle. Counts describe selected skills, not checked boxes; do not foreground checkbox mechanics or add uninstall disclaimers to this selection surface. Fixed-height virtual skill lists use the same row-height constant for the rendered rows, virtualizer, and short-list viewport, rather than reserving an estimated extra row.
Source: user corrections while simplifying the conversation Skills panel, including removal of redundant status tabs, the text management button, and checkbox-centric copy.
+
+## LOBE-UX-025 — Chat tools show existing connector records
+
+The 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.
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index 5506cdc2c3b..59876aed5a6 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -14,7 +14,7 @@ import {
CONTEXT_ENGINEERING_SPAN_NAME,
tracer as agentRuntimeTracer,
} from '@lobechat/observability-otel/modules/agent-runtime';
-import type { UIChatMessage } from '@lobechat/types';
+import { getOptedInPluginIds, type UIChatMessage } from '@lobechat/types';
import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';
import {
@@ -135,6 +135,7 @@ export const buildServerCallLlmContext = async ({
},
agentId,
disabledPluginIds: state.world?.disabledPluginIds,
+ discoverableTools: toolDiscoveryConfig?.availableTools,
editingAgentId: state.origin?.editingAgentId,
editingGroupId,
enabledToolIds: resolved.enabledToolIds,
@@ -144,6 +145,12 @@ export const buildServerCallLlmContext = async ({
isSubAgent: state.origin?.lineage?.isSubAgent === true,
mentionedAgents: (state as any).initialContext?.initialContext?.mentionedAgents,
messages: messagesForContext,
+ // `agent.plugins` is collapsed to pinned ids; the `auto` entries ride on
+ // the world. Together they are what the agent turned on.
+ optedInPluginIds: [
+ ...getOptedInPluginIds(agentConfig.plugins ?? undefined),
+ ...(state.world?.autoSkillIds ?? []),
+ ],
shareVisitor: state.principal?.actor?.shareVisitor ?? ctx.agentShareVisitor,
topicId,
workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
index 9655452b296..06fd63058da 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
@@ -618,62 +618,66 @@ describe('createServerAgentToolsEngine', () => {
expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);
});
- it('should enable lobe-agent by default since it is always-on', () => {
- const context = createMockContext();
- const engine = createServerAgentToolsEngine(context, {
- agentConfig: { plugins: [] },
- model: 'deepseek-chat',
- provider: 'deepseek',
- });
-
- const result = engine.generateToolsDetailed(deepseekToolInput());
-
- // lobe-agent is in alwaysOnToolIds, so its core capabilities are on for every agent-mode turn.
- expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);
-
- // Without a manifest context, the full static manifest is used — callSubAgent stays.
- const lobeAgent = result.enabledManifests.find(
- (m) => m.identifier === LobeAgentManifest.identifier,
- );
- expect(lobeAgent?.api.map((a) => a.name)).toContain(LobeAgentApiName.callSubAgent);
- });
-
- it('should honor an explicit disabled policy for an always-on builtin tool', () => {
- const context = createMockContext();
- const engine = createServerAgentToolsEngine(context, {
- agentConfig: { plugins: [] },
- disabledPluginIds: [LobeAgentManifest.identifier],
- model: 'deepseek-chat',
- provider: 'deepseek',
- });
-
- const result = engine.generateToolsDetailed(deepseekToolInput());
-
- expect(result.enabledToolIds).not.toContain(LobeAgentManifest.identifier);
- expect(result.enabledManifests).not.toContainEqual(
- expect.objectContaining({ identifier: LobeAgentManifest.identifier }),
- );
- });
-
- it('hides lobe-agent callSubAgent when manifestContext.isSubAgent is true', () => {
- const context = createMockContext();
- const engine = createServerAgentToolsEngine(context, {
- agentConfig: { plugins: [] },
- manifestContext: { isSubAgent: true },
- model: 'deepseek-chat',
- provider: 'deepseek',
- });
-
- const result = engine.generateToolsDetailed(deepseekToolInput());
+ it.each(['lobe-agent', 'lobe-skill-store'])(
+ 'exposes %s only after activation or pinning',
+ (id) => {
+ const options = {
+ agentConfig: { plugins: [] },
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ };
+ const input = { ...deepseekToolInput(), toolIds: [id] };
+ const engine = createServerAgentToolsEngine(createMockContext(), options);
+
+ expect(engine.generateToolsDetailed(deepseekToolInput()).enabledToolIds).not.toContain(id);
+ expect(
+ engine.generateToolsDetailed({
+ ...input,
+ context: { isExplicitActivation: true },
+ skipDefaultTools: true,
+ }).enabledToolIds,
+ ).toEqual([id]);
+
+ const pinned = createServerAgentToolsEngine(createMockContext(), {
+ ...options,
+ agentConfig: { plugins: [id] },
+ });
+ expect(pinned.generateToolsDetailed(input).enabledToolIds).toContain(id);
- // lobe-agent's other capabilities (plan / todo / visual-media) stay on...
- expect(result.enabledToolIds).toContain(LobeAgentManifest.identifier);
- const lobeAgent = result.enabledManifests.find(
- (m) => m.identifier === LobeAgentManifest.identifier,
- );
- // ...but callSubAgent is stripped so a nested sub-agent cannot recurse.
- expect(lobeAgent?.api.map((a) => a.name)).not.toContain(LobeAgentApiName.callSubAgent);
- });
+ const disabled = createServerAgentToolsEngine(createMockContext(), {
+ ...options,
+ disabledPluginIds: [id],
+ });
+ expect(
+ disabled.generateToolsDetailed({
+ ...input,
+ context: { isExplicitActivation: true },
+ skipDefaultTools: true,
+ }).enabledToolIds,
+ ).toEqual([]);
+ },
+ );
+
+ it.each([{ isSubAgent: true }, { scope: 'group' }])(
+ 'hides callSubAgent after discovery with %o',
+ (manifestContext) => {
+ const engine = createServerAgentToolsEngine(createMockContext(), {
+ agentConfig: { plugins: [] },
+ manifestContext,
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ });
+ const { enabledManifests } = engine.generateToolsDetailed({
+ ...deepseekToolInput(),
+ context: { isExplicitActivation: true },
+ skipDefaultTools: true,
+ toolIds: [LobeAgentManifest.identifier],
+ });
+ const names = enabledManifests[0].api.map((api) => api.name);
+ expect(names).toContain(LobeAgentApiName.createPlan);
+ expect(names).not.toContain(LobeAgentApiName.callSubAgent);
+ },
+ );
it('rewrites lobe-skills exec descriptions when manifestContext.executionEnv is device-unrouted', () => {
const context = createMockContext();
@@ -699,23 +703,6 @@ describe('createServerAgentToolsEngine', () => {
).not.toContain('offline');
});
- it('hides lobe-agent callSubAgent inside a group run (scope=group)', () => {
- const context = createMockContext();
- const engine = createServerAgentToolsEngine(context, {
- agentConfig: { plugins: [] },
- manifestContext: { scope: 'group' },
- model: 'deepseek-chat',
- provider: 'deepseek',
- });
-
- const result = engine.generateToolsDetailed(deepseekToolInput());
-
- const lobeAgent = result.enabledManifests.find(
- (m) => m.identifier === LobeAgentManifest.identifier,
- );
- expect(lobeAgent?.api.map((a) => a.name)).not.toContain(LobeAgentApiName.callSubAgent);
- });
-
it('should enable KnowledgeBase when hasEnabledKnowledgeBases is true', () => {
const context = createMockContext();
const engine = createServerAgentToolsEngine(context, {
@@ -828,7 +815,7 @@ describe('createServerAgentToolsEngine', () => {
toolIds: ['test-plugin', LobeAgentManifest.identifier, WebBrowsingManifest.identifier],
});
- // Exactly the declared plugin — no always-on lobe-agent, no default web/KB.
+ // Exactly the declared plugin — no default web/KB.
expect(result.enabledToolIds).toContain('test-plugin');
expect(result.enabledToolIds).not.toContain(LobeAgentManifest.identifier);
expect(result.enabledToolIds).not.toContain(WebBrowsingManifest.identifier);
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index 53a503d9466..30fa6844f8e 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -213,6 +213,8 @@ export const createServerAgentToolsEngine = (
manifestContext,
enableChecker: createEnableChecker({
allowExplicitActivation: resolved.allowExplicitActivation,
+ explicitActivationIds:
+ resolved.toolMode === 'custom' ? params.allowedConnectorIds : undefined,
rules: resolved.rules,
}),
});
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
index d993eeb6165..eb2a2811f9b 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/types.ts
@@ -88,6 +88,8 @@ export interface ServerCreateAgentToolsEngineParams {
/** Plugin IDs enabled for this agent */
plugins?: string[];
};
+ /** Configured connectors a custom toolset can load after explicit activation. */
+ allowedConnectorIds?: ReadonlySet<string>;
/**
* Whether device tools (local-system / remote-device) are allowed this turn.
* Computed by `resolveDeviceAccessPolicy` from the caller identity:
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.ts
index 9da67258fd0..94ed4d5a317 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
@@ -11,7 +11,7 @@
* sub-agent's answer and resumes the parent.
* 5. The parent op runs one more LLM step and reaches `done`.
*/
-import { stripSubAgentReference } from '@lobechat/builtin-tool-lobe-agent';
+import { LobeAgentIdentifier, stripSubAgentReference } from '@lobechat/builtin-tool-lobe-agent';
import { type LobeChatDatabase } from '@lobechat/database';
import { agentOperations, agents, messages } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
@@ -190,7 +190,8 @@ beforeEach(async () => {
},
chatConfig: {},
model: 'gpt-5-pro',
- plugins: [],
+ // The scripted first response delegates immediately, before any activation step.
+ plugins: [LobeAgentIdentifier],
provider: 'openai',
systemRole: 'You are a supervisor that can delegate work to sub-agents.',
title: 'Supervisor',
@@ -273,6 +274,10 @@ 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' }),
+ );
+
// Three LLM calls: parent-initial, sub-op, parent-resume
expect(mockResponsesCreate).toHaveBeenCalledTimes(3);
@@ -323,5 +328,6 @@ describe('Server callSubAgent suspend/resume', () => {
expect(JSON.stringify(persisted)).not.toContain(SUB_AGENT_ANSWER);
}
},
+ 30_000,
);
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index b18555c1e35..d508367d93d 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -592,7 +592,16 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
mockGetLobehubSkillManifests.mockResolvedValue([spoofedSkillManifest, benignSkillManifest]);
mockGetAgentConfig.mockResolvedValue(
- createBaseAgentConfig({ agencyConfig: { executionTarget: 'auto' } }),
+ createBaseAgentConfig({
+ agencyConfig: { executionTarget: 'auto' },
+ // Connectors are opt-in per agent. Both manifests are turned on the
+ // same way, so the spoofed one gets past the opt-in cut and only the
+ // ingest wall is left to stop it.
+ plugins: [
+ { identifier: RemoteDeviceManifest.identifier, mode: 'auto' },
+ { identifier: 'my-normal-skill', mode: 'auto' },
+ ],
+ }),
);
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
index f7e3a02440a..411308ce9c2 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
@@ -29,7 +29,7 @@ const {
}));
// Feature-gated builtin tools (e.g. builtin-dashboard) join the disabled set
-// when their flag is off; this suite covers the agent's own tri-state config,
+// when their flag is off; this suite covers the agent's own plugin entries,
// so run it with every gate open. Gating has its own coverage in
// pipeline/__tests__/toolDiscovery.featureGate.test.ts.
vi.mock('@/server/featureFlags', async (importOriginal) => ({
@@ -200,7 +200,7 @@ const generateToolsArg = () =>
const toolManifestMapArg = () =>
mockCreateOperation.mock.calls[0][0].toolSet.manifestMap as Record<string, unknown>;
-describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disabled)', () => {
+describe('AiAgentService.execAgent - agent plugin entries (on / off / disabled)', () => {
let service: AiAgentService;
beforeEach(() => {
@@ -216,17 +216,23 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disa
pluginManifest('plugin-a'),
pluginManifest('plugin-b'),
pluginManifest('plugin-c'),
+ pluginManifest('plugin-d'),
]);
service = new AiAgentService({} as any, 'test-user-id');
});
- it('excludes a disabled entry from the installed-plugins auto-discovery pool, in a mixed-shape array', async () => {
+ it('keeps only the installed plugins that are on, in a mixed-shape array: a disabled entry and a missing entry are both left out', async () => {
mockGetAgentConfig.mockResolvedValue({
chatConfig: {},
id: 'agent-1',
model: 'gpt-4',
- // legacy string (implicit pinned) + explicit disabled object + untouched auto (plugin-c absent)
- plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }],
+ // legacy string (implicit pinned) + explicit disabled object + explicit
+ // auto object; plugin-d has no entry, which is off
+ plugins: [
+ 'plugin-a',
+ { identifier: 'plugin-b', mode: 'disabled' },
+ { identifier: 'plugin-c', mode: 'auto' },
+ ],
provider: 'openai',
systemRole: 'You are a helper',
});
@@ -234,12 +240,18 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disa
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
const installed = installedPluginsArg().map((p) => p.identifier);
- expect(installed).toContain('plugin-a');
- expect(installed).toContain('plugin-c');
+ expect(installed).toEqual(['plugin-a', 'plugin-c']);
expect(installed).not.toContain('plugin-b');
+ expect(installed).not.toContain('plugin-d');
+ // The activator's map follows the same cut.
+ expect(Object.keys(toolManifestMapArg())).toEqual(
+ expect.arrayContaining(['plugin-a', 'plugin-c']),
+ );
+ expect(toolManifestMapArg()).not.toHaveProperty('plugin-b');
+ expect(toolManifestMapArg()).not.toHaveProperty('plugin-d');
});
- it('only feeds pinned identifiers into the engine agentConfig.plugins, excluding disabled', async () => {
+ it('keeps a pinned plugin out of the engine agentConfig.plugins, which only carries pinned builtin tools', async () => {
mockGetAgentConfig.mockResolvedValue({
chatConfig: {},
id: 'agent-1',
@@ -247,6 +259,31 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disa
plugins: [
{ identifier: 'plugin-a', mode: 'pinned' },
{ identifier: 'plugin-b', mode: 'disabled' },
+ { identifier: 'lobe-image-generation', mode: 'pinned' },
+ ],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+
+ 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']);
+ expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-a']);
+ expect(toolManifestMapArg()).toHaveProperty('plugin-a');
+ expect(disabledPluginIdsArg()).toEqual(['plugin-b']);
+ });
+
+ it('feeds the plugins that are on into the engine agentConfig.plugins in manual mode, excluding disabled', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ // Manual mode has no activator, so on is the only way to reach the model.
+ chatConfig: { skillActivateMode: 'manual' },
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [
+ { identifier: 'plugin-a', mode: 'pinned' },
+ { identifier: 'plugin-b', mode: 'disabled' },
+ { identifier: 'plugin-c', mode: 'auto' },
],
provider: 'openai',
systemRole: 'You are a helper',
@@ -254,11 +291,12 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disa
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
- expect(agentConfigPluginsArg()).toEqual(['plugin-a']);
+ expect(agentConfigPluginsArg()).toEqual(['plugin-a', 'plugin-c']);
+ expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-a', 'plugin-c']);
expect(disabledPluginIdsArg()).toEqual(['plugin-b']);
});
- it('behaves identically to a pure string array when no entry is disabled', async () => {
+ it('reads a pure string array as the plugins that are on, leaving every other installed plugin off', async () => {
mockGetAgentConfig.mockResolvedValue({
chatConfig: {},
id: 'agent-1',
@@ -271,8 +309,29 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disa
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
const installed = installedPluginsArg().map((p) => p.identifier);
- expect(installed).toEqual(['plugin-a', 'plugin-b', 'plugin-c']);
- expect(agentConfigPluginsArg()).toEqual(['plugin-a']);
+ expect(installed).toEqual(['plugin-a']);
+ expect(agentConfigPluginsArg()).toEqual([]);
+ expect(disabledPluginIdsArg()).toEqual([]);
+ });
+
+ it('brings in a plugin the agent has off on the turn that @-mentions it', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Hello',
+ selectedToolIds: ['plugin-d'],
+ } as any);
+
+ expect(installedPluginsArg().map((p) => p.identifier)).toEqual(['plugin-d']);
+ expect(agentConfigPluginsArg()).toEqual(['plugin-d']);
});
it('restricts an orchestration turn to the exclusive plugin set', async () => {
@@ -306,15 +365,33 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disa
plugins: [
{ identifier: 'composio-disabled', mode: 'disabled' },
{ identifier: 'skill-disabled', mode: 'disabled' },
+ { identifier: 'composio-on', mode: 'auto' },
+ { identifier: 'skill-on', mode: 'auto' },
],
provider: 'openai',
systemRole: 'You are a helper',
});
- mockGetComposioManifests.mockResolvedValue([toolManifest('composio-disabled')]);
- mockGetLobehubSkillManifests.mockResolvedValue([toolManifest('skill-disabled')]);
+ mockGetComposioManifests.mockResolvedValue([
+ toolManifest('composio-disabled'),
+ toolManifest('composio-on'),
+ toolManifest('composio-off'),
+ ]);
+ mockGetLobehubSkillManifests.mockResolvedValue([
+ toolManifest('skill-disabled'),
+ toolManifest('skill-on'),
+ toolManifest('skill-off'),
+ ]);
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+ // The manifests that are on do reach the map, so the absences below are
+ // the disabled entry's doing rather than an empty source.
+ expect(toolManifestMapArg()).toHaveProperty('composio-on');
+ expect(toolManifestMapArg()).toHaveProperty('skill-on');
+ // No entry is off, the same as disabled for a connector.
+ expect(toolManifestMapArg()).not.toHaveProperty('composio-off');
+ expect(toolManifestMapArg()).not.toHaveProperty('skill-off');
+
// The disabled entries must not resurface in the map the activator uses
// to build <available_tools> — even though they're excluded from the
// actual invocation pool (additionalManifests), a separate ingest loop
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
index dc73da91ba9..2221f854fc2 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts
@@ -85,17 +85,31 @@ const connectorTools = [
},
];
-const run = (plugins: string[]) =>
- discoverTools(
+interface RunOptions {
+ /** The agent's `auto` entries: on without a legacy pin. */
+ autoSkillIds?: string[];
+ /** The agent's legacy pinned entries, which also read as on. */
+ plugins?: string[];
+ /** This turn's @-mention picks. */
+ selectedToolIds?: string[];
+}
+
+const connectorModel = {
+ resolveAll: vi.fn(),
+ resolveByIdentifiers: vi.fn(),
+};
+
+const run = (options: RunOptions = {}) => {
+ connectorModel.resolveAll.mockReset().mockResolvedValue([oauthConnector]);
+ connectorModel.resolveByIdentifiers
+ .mockReset()
+ .mockImplementation(async (ids: string[]) => (ids.includes(XMIND) ? [oauthConnector] : []));
+
+ return discoverTools(
{
agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },
- connectorModel: {
- resolveAll: vi.fn().mockResolvedValue([oauthConnector]),
- resolveByIdentifiers: vi.fn(async (ids: string[]) =>
- ids.includes(XMIND) ? [oauthConnector] : [],
- ),
- },
+ connectorModel,
connectorToolModel: {
queryAllByConnectorIds: vi.fn().mockResolvedValue(connectorTools),
queryByConnector: vi.fn().mockResolvedValue([]),
@@ -109,8 +123,9 @@ const run = (plugins: string[]) =>
userId: 'creator-1',
} as never,
{
- agentConfig: { chatConfig: {}, plugins },
+ agentConfig: { chatConfig: {}, plugins: options.plugins ?? [] },
appContext: undefined,
+ autoSkillIds: options.autoSkillIds ?? [],
canUseDevice: false,
model: 'test-model',
prompt: 'make a mind map',
@@ -127,9 +142,11 @@ const run = (plugins: string[]) =>
hasMentionedAgents: false,
isFixedDeviceTarget: false,
loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ selectedToolIds: options.selectedToolIds,
throwIfExecutionAborted: vi.fn(),
} as never,
);
+};
const manifestToken = (manifest: unknown) =>
(manifest as { mcpParams?: { auth?: { accessToken?: string } } })?.mcpParams?.auth?.accessToken;
@@ -137,16 +154,32 @@ const manifestToken = (manifest: unknown) =>
// A single-account manifest carries that account's token for the whole run, so
// an expired-but-refreshable token used to 401 on the first call after expiry.
describe('discoverTools — connector OAuth token refresh', () => {
- it('builds a pinned connector manifest from refreshed credentials', async () => {
- const result = await run([XMIND]);
+ it.each([
+ // Both entries turn the connector on, so it is read with the discoverable ones.
+ { label: 'the agent pinned', options: { plugins: [XMIND] } },
+ { label: 'the agent turned on', options: { autoSkillIds: [XMIND] } },
+ // The turn brings it in, so it is resolved straight into the invocation set.
+ { label: 'the turn @-mentions', options: { selectedToolIds: [XMIND] } },
+ ])(
+ 'builds the manifest of a connector $label from refreshed credentials',
+ async ({ options }) => {
+ vi.mocked(refreshExpiredLinkTokens).mockClear();
- expect(refreshExpiredLinkTokens).toHaveBeenCalled();
- expect(manifestToken(result.toolManifestMap[XMIND])).toBe('fresh');
- });
+ const result = await run(options);
+
+ expect(refreshExpiredLinkTokens).toHaveBeenCalled();
+ expect(manifestToken(result.toolManifestMap[XMIND])).toBe('fresh');
+ },
+ );
+
+ it('neither resolves nor refreshes a connector the agent never turned on', async () => {
+ vi.mocked(refreshExpiredLinkTokens).mockClear();
- it('builds an unpinned connector manifest from refreshed credentials', async () => {
- const result = await run([]);
+ const result = await run();
- expect(manifestToken(result.toolManifestMap[XMIND])).toBe('fresh');
+ expect(result.toolManifestMap[XMIND]).toBeUndefined();
+ expect(connectorModel.resolveAll).not.toHaveBeenCalled();
+ expect(connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();
+ expect(refreshExpiredLinkTokens).not.toHaveBeenCalled();
});
});
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.ts
index 789037126f6..3e139e6e84a 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
@@ -69,11 +69,14 @@ const connectorTools = [
interface RunOptions {
agentId?: string;
+ /** The agent's `auto` entries: what turns a connector on without a legacy pin. */
+ autoSkillIds?: string[];
+ chatConfig?: Record<string, unknown>;
/** Override the connector's transport (`http` by default). */
connection?: { mcpConnectionType: string; mcpServerUrl: string | null };
installed?: boolean;
metadata?: Record<string, unknown>;
- /** The agent's own `plugins` config — i.e. what the user pinned. */
+ /** The agent's legacy pinned entries, which also read as on. */
plugins?: string[];
/** This turn's @-mention picks. */
selectedToolIds?: string[];
@@ -121,8 +124,9 @@ const run = (options: RunOptions = {}) => {
userId: 'user-1',
} as never,
{
- agentConfig: { chatConfig: {}, plugins: options.plugins ?? [] },
+ agentConfig: { chatConfig: options.chatConfig ?? {}, plugins: options.plugins ?? [] },
appContext: undefined,
+ autoSkillIds: options.autoSkillIds ?? [],
canUseDevice: false,
model: 'test-model',
prompt: '470008 呢',
@@ -158,9 +162,12 @@ const availableToolIds = (
const offeredToolNames = (result: { tools?: { function: { name: string } }[] }) =>
(result.tools ?? []).map((tool) => tool.function.name);
-describe('discoverTools — unpinned custom MCP connectors', () => {
+/** The agent turned the connector on: an `auto` entry in its plugins. */
+const ON = { autoSkillIds: [YINGMI] };
+
+describe('discoverTools — custom MCP connectors are opt-in per agent', () => {
it.each([
- {},
+ ON,
{ plugins: [YINGMI] },
{ selectedToolIds: [YINGMI] },
{
@@ -183,7 +190,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
);
it.each([
- { label: 'auto', options: {} },
+ { label: 'on', options: ON },
{ label: 'pinned', options: { plugins: [YINGMI] } },
{ label: 'mentioned', options: { selectedToolIds: [YINGMI] } },
{
@@ -209,7 +216,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
});
it('keeps a completed marketplace install discoverable and explicitly activatable', async () => {
- const result = await run({ installed: true, sourceType: 'marketplace' });
+ const result = await run({ ...ON, installed: true, sourceType: 'marketplace' });
expect(result.toolManifestMap[YINGMI]).toBeDefined();
const activated = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
expect(activated.enabledToolIds).toContain(YINGMI);
@@ -221,6 +228,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
])('treats a connector-only marketplace install as installed: $label', async ({ connection }) => {
// No user_installed_plugins row: the connector's own mark is the install
const result = await run({
+ ...ON,
connection,
installed: false,
metadata: { marketplaceInstalled: true },
@@ -244,6 +252,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
// disconnected until its tools sync: the old tools must not run against it
it('rejects a pending reinstall over a plugin row until its connector is connected', async () => {
const result = await run({
+ ...ON,
installed: true,
sourceType: 'marketplace',
status: 'disconnected',
@@ -253,6 +262,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
it('keeps an endpoint-less plugin projection on its plugin row whatever its status', async () => {
const result = await run({
+ ...ON,
connection: { mcpConnectionType: null as never, mcpServerUrl: null },
installed: true,
sourceType: 'marketplace',
@@ -266,6 +276,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
// callback connects it: the client already hides it, so must a server run
it('rejects a finished install while it is not connected', async () => {
const result = await run({
+ ...ON,
installed: false,
metadata: { marketplaceInstalled: true },
sourceType: 'marketplace',
@@ -276,6 +287,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
it('rejects an unfinished cloud marketplace install that has no plugin row', async () => {
const result = await run({
+ ...ON,
connection: { mcpConnectionType: 'cloud', mcpServerUrl: null },
installed: false,
sourceType: 'marketplace',
@@ -283,11 +295,33 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
expect(result.toolManifestMap[YINGMI]).toBeUndefined();
});
- it('keeps an unmentioned, unpinned connector discoverable without enabling it', async () => {
- // The follow-up turn after an @-mention: no mention, nothing pinned. The
- // activator used to answer "Not found: yingmi" here.
+ it('keeps a connector the agent never turned on out of the run', async () => {
const result = await run();
+ expect(result.toolManifestMap[YINGMI]).toBeUndefined();
+ expect(result.toolSourceMap[YINGMI]).toBeUndefined();
+ expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);
+ // Off means never read: its credentials are not decrypted for this run.
+ expect(connectorModel.resolveAll).not.toHaveBeenCalled();
+ expect(connectorModel.resolveByIdentifiers).not.toHaveBeenCalled();
+ // …and a previous turn's activation cannot bring it back.
+ const restored = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
+ expect(restored.enabledToolIds).not.toContain(YINGMI);
+ });
+
+ it.each([
+ { label: 'turned on', options: ON },
+ { label: 'pinned', options: { plugins: [YINGMI] } },
+ ])('keeps a connector the agent $label discoverable without enabling it', async ({ options }) => {
+ // The follow-up turn after an @-mention: no mention this turn. The
+ // activator used to answer "Not found: yingmi" here.
+ const result = await run(options);
+
+ // Resolved by identifier only — never the user's whole connector list.
+ expect(connectorModel.resolveAll).not.toHaveBeenCalled();
+ expect(connectorModel.resolveByIdentifiers).toHaveBeenCalledTimes(1);
+ expect(connectorModel.resolveByIdentifiers.mock.calls[0][0]).toEqual([YINGMI]);
+
expect(result.toolManifestMap[YINGMI]).toBeDefined();
expect(result.toolSourceMap[YINGMI]).toBe('mcp');
expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(
@@ -297,8 +331,59 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
expect(offeredToolNames(result).some((name) => name.startsWith(`${YINGMI}____`))).toBe(false);
});
+ it.each([
+ { label: 'turned on', options: ON },
+ { label: 'pinned', options: { plugins: [YINGMI] } },
+ ])(
+ 'enables a connector the agent $label directly when manual mode strips the activator',
+ 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);
+ },
+ );
+
+ it.each([ON, { plugins: [YINGMI] }])(
+ 'offers an enabled connector directly in a custom toolset without an activator: %j',
+ async (options) => {
+ const result = await run({ ...options, chatConfig: { toolMode: 'custom' } });
+
+ expect(result.toolsResult.enabledToolIds).not.toContain('lobe-activator');
+ expect(offeredToolNames(result)).toContain(`${YINGMI}____BatchGetFundNavHistory____mcp`);
+ },
+ );
+
+ it('lets a custom toolset with an explicit activator restore its configured connector', async () => {
+ const result = await run({
+ ...ON,
+ chatConfig: { toolMode: 'custom' },
+ plugins: ['lobe-activator'],
+ });
+
+ expect(result.toolsResult.enabledToolIds).toContain('lobe-activator');
+ expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);
+ const activated = result.toolsEngine!.generateToolsDetailed(explicitConnectorInput(YINGMI));
+ expect(offeredToolNames(activated)).toContain(`${YINGMI}____BatchGetFundNavHistory____mcp`);
+ expect(
+ result.toolsEngine!.generateToolsDetailed(explicitConnectorInput('lobe-skills'))
+ .enabledToolIds,
+ ).toEqual([]);
+ });
+
+ it('keeps a connector the agent never turned on out of a manual-mode run too', async () => {
+ const result = await run({ chatConfig: { skillActivateMode: 'manual' } });
+
+ expect(result.toolManifestMap[YINGMI]).toBeUndefined();
+ expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);
+ });
+
it('lets the next operation restore a previous turn’s activation', async () => {
- const result = await run();
+ const result = await run(ON);
// The cross-turn restore in `operationPrep` re-checks historical
// activations through the engine with explicit activation.
@@ -319,7 +404,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
expect(call).toMatchObject({ apiName: 'BatchGetFundNavHistory', identifier: YINGMI });
});
- it('still enables the connector on the turn that @-mentions it', async () => {
+ it('enables a connector the agent has off on the turn that @-mentions it', async () => {
const result = await run({ selectedToolIds: [YINGMI] });
expect(result.toolsResult.enabledToolIds).toContain(YINGMI);
@@ -330,10 +415,10 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
).toBe(true);
});
- it('schedules the stale-tool refresh for an unpinned connector too', async () => {
+ it('schedules the stale-tool refresh for a connector that is on but not invoked', async () => {
vi.mocked(scheduleStaleConnectorToolsRefresh).mockClear();
- await run();
+ await run(ON);
// An activatable connector whose upstream tools changed must not keep
// offering the old list until someone re-syncs it by hand.
@@ -352,7 +437,7 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
visitorUserId: 'visitor-1',
});
- it('does not resolve or decrypt an ungranted unpinned connector', async () => {
+ it('does not resolve or decrypt an ungranted connector', async () => {
vi.mocked(scheduleStaleConnectorToolsRefresh).mockClear();
const result = await run({
@@ -368,7 +453,9 @@ describe('discoverTools — unpinned custom MCP connectors', () => {
expect(connectors.map((c) => c.identifier)).not.toContain(YINGMI);
});
- it('makes a granted unpinned connector activatable without enabling it', async () => {
+ // The share's grants cut the run, not the agent's own switches: the
+ // creator's agent has no entry for the connector here.
+ it('makes a granted connector activatable without enabling it', async () => {
const result = await run({ shareGate: shareGateFor([{ identifier: YINGMI }]) });
// Resolved by identifier only — never the creator's whole connector list.
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.ts
index 5e4e67a979f..742bfe4a5c7 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
@@ -61,11 +61,16 @@ const installedPlugin = (identifier: string, transport: 'http' | 'stdio' = 'http
});
interface RunOptions {
+ /** The agent's `auto` entries: what turns a plugin on without a legacy pin. */
+ autoSkillIds?: string[];
+ chatConfig?: Record<string, unknown>;
disabledPluginIds?: string[];
/** A device gateway is configured for the deployment. */
gatewayConfigured?: boolean;
- /** The agent's own `plugins` config — i.e. what the user pinned. */
+ /** The agent's legacy pinned entries, which also read as on. */
plugins?: string[];
+ /** This turn's @-mention picks. */
+ selectedToolIds?: string[];
/** Transport the installed plugin row reports. */
transport?: 'http' | 'stdio';
}
@@ -93,8 +98,9 @@ const run = (options: RunOptions = {}) => {
userId: 'user-1',
} as never,
{
- agentConfig: { chatConfig: {}, plugins: options.plugins ?? [] },
+ agentConfig: { chatConfig: options.chatConfig ?? {}, plugins: options.plugins ?? [] },
appContext: undefined,
+ autoSkillIds: options.autoSkillIds ?? [],
canUseDevice: false,
model: 'test-model',
prompt: 'send a message to the team chat',
@@ -112,6 +118,7 @@ const run = (options: RunOptions = {}) => {
hasMentionedAgents: false,
isFixedDeviceTarget: false,
loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ selectedToolIds: options.selectedToolIds,
throwIfExecutionAborted: vi.fn(),
} as never,
);
@@ -129,27 +136,54 @@ const availableToolIds = (
const offeredToolNames = (result: { tools?: { function: { name: string } }[] }) =>
(result.tools ?? []).map((tool) => tool.function.name);
-describe('discoverTools — installed-but-not-pinned plugins (three-state `auto`)', () => {
- it('offers an installed `auto` plugin to the activator without enabling it', async () => {
- const result = await run();
+/** The agent turned the plugin on: an `auto` entry in its plugins. */
+const ON = { autoSkillIds: [FEISHU] };
+const MANUAL = { chatConfig: { skillActivateMode: 'manual' } };
- // Discoverable: the activator resolves against `toolManifestMap`, so a
- // missing entry here is exactly the "Not found: tituwork-feishu-mcp" the
- // model used to get.
- expect(result.toolManifestMap[FEISHU]).toBeDefined();
- expect(result.toolSourceMap[FEISHU]).toBe('mcp');
- expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(
- FEISHU,
- );
+describe('discoverTools — installed plugins are opt-in per agent', () => {
+ it('keeps an installed plugin the agent never turned on out of the run', async () => {
+ const result = await run();
- // …but NOT enabled: the pinned-only rules still decide the default tool
- // set, so the APIs are not offered up-front and the model has to activate.
+ expect(result.toolManifestMap[FEISHU]).toBeUndefined();
expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);
+ expect(
+ availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds),
+ ).not.toContain(FEISHU);
expect(offeredToolNames(result).some((name) => name.startsWith(`${FEISHU}____`))).toBe(false);
});
- it('enables the same plugin directly once the agent pins it', async () => {
- const result = await run({ plugins: [FEISHU] });
+ it.each([
+ { label: 'turned on', options: ON },
+ { label: 'pinned', options: { plugins: [FEISHU] } },
+ ])(
+ 'offers an installed plugin the agent $label to the activator without enabling it',
+ async ({ options }) => {
+ const result = await run(options);
+
+ // Discoverable: the activator resolves against `toolManifestMap`, so a
+ // missing entry here is exactly the "Not found: tituwork-feishu-mcp" the
+ // model used to get.
+ expect(result.toolManifestMap[FEISHU]).toBeDefined();
+ expect(result.toolSourceMap[FEISHU]).toBe('mcp');
+ expect(availableToolIds(result.toolManifestMap, result.toolsResult.enabledToolIds)).toContain(
+ FEISHU,
+ );
+
+ // …but NOT enabled: a plugin that is on is found on demand, so the APIs
+ // are not offered up-front and the model has to activate.
+ expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);
+ expect(offeredToolNames(result).some((name) => name.startsWith(`${FEISHU}____`))).toBe(false);
+ },
+ );
+
+ 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 }) => {
+ const result = await run(options);
expect(result.toolsResult.enabledToolIds).toContain(FEISHU);
// `<identifier>____<api>____mcp` — the MCP plugin type rides on the name.
@@ -162,8 +196,21 @@ describe('discoverTools — installed-but-not-pinned plugins (three-state `auto`
).not.toContain(FEISHU);
});
- it('keeps a disabled plugin out of both paths', async () => {
- const result = await run({ disabledPluginIds: [FEISHU] });
+ it('keeps an installed plugin that is off out of a manual-mode run', async () => {
+ const result = await run(MANUAL);
+
+ expect(result.toolManifestMap[FEISHU]).toBeUndefined();
+ expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);
+ });
+
+ it.each([
+ { label: 'with no other entry', options: {} },
+ // A disabled id wins over every way the plugin could otherwise be on.
+ { label: 'that is also on', options: ON },
+ { label: 'that is also pinned in manual mode', options: { ...MANUAL, plugins: [FEISHU] } },
+ { label: 'that the turn @-mentions', options: { selectedToolIds: [FEISHU] } },
+ ])('keeps a disabled plugin $label out of both paths', async ({ options }) => {
+ const result = await run({ ...options, disabledPluginIds: [FEISHU] });
expect(result.toolManifestMap[FEISHU]).toBeUndefined();
expect(result.toolsResult.enabledToolIds).not.toContain(FEISHU);
@@ -205,7 +252,7 @@ const activateAfterDiscovery = (
describe('discoverTools — executor routing for a discoverable MCP plugin', () => {
it('keeps a discoverable stdio plugin client-executed across activation', async () => {
- const result = await run({ transport: 'stdio' });
+ const result = await run({ ...ON, transport: 'stdio' });
// A stdio MCP runs as a local process on the user's machine, so it must
// never be dispatched to the self-hosted server.
@@ -217,17 +264,19 @@ describe('discoverTools — executor routing for a discoverable MCP plugin', ()
});
it('leaves a discoverable http plugin on the server execution path', async () => {
- const result = await run({ transport: 'http' });
+ const result = await run({ ...ON, transport: 'http' });
+ expect(result.toolManifestMap[FEISHU]).toBeDefined();
expect(result.toolExecutorMap[FEISHU]).toBeUndefined();
expect(activateAfterDiscovery(result, FEISHU).executorMap?.[FEISHU]).toBeUndefined();
});
it('lets a configured device gateway own the route', async () => {
- const result = await run({ gatewayConfigured: true, transport: 'stdio' });
+ const result = await run({ ...ON, gatewayConfigured: true, transport: 'stdio' });
// With a gateway every caller converges on the device-gateway path, so no
// client executor is set — the remote-device proxy resolves the route.
+ expect(result.toolManifestMap[FEISHU]).toBeDefined();
expect(result.toolExecutorMap[FEISHU]).toBeUndefined();
});
});
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.ts
index fd39dd5a8f7..84e82a7ffed 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
@@ -134,6 +134,8 @@ const skillManifest = (identifier: string) => ({
interface RunOptions {
agentConfig?: Record<string, unknown>;
appContext?: Record<string, unknown>;
+ /** The `auto` entries of the agent's plugins — what turns a connector on. */
+ autoSkillIds?: string[];
canUseDevice?: boolean;
composioManifests?: unknown[];
connectorResolve?: (ids: string[]) => unknown[];
@@ -179,6 +181,7 @@ const run = (options: RunOptions = {}) => {
agentConfig: { chatConfig: {}, id: 'agent-1', plugins: [], ...options.agentConfig },
appContext: options.appContext,
assistantMessageId: 'assistant-1',
+ autoSkillIds: options.autoSkillIds ?? [],
canUseDevice: options.canUseDevice ?? false,
model: 'test-model',
prompt: 'hello',
@@ -281,6 +284,7 @@ describe('discoverTools — connector permissions and ownership', () => {
manifest: skillManifest('community-mcp'),
};
const result = await run({
+ autoSkillIds: ['lobehub-notion', 'composio-gmail', 'community-mcp'],
composioManifests: [skillManifest('composio-gmail')],
connectorResolve: (ids) =>
ids.map((identifier, index) => ({ id: `conn-${index}`, identifier })),
@@ -320,6 +324,120 @@ describe('discoverTools — connector permissions and ownership', () => {
});
});
+describe('discoverTools — connectors are opt-in per agent', () => {
+ const plugin = (identifier: string) => ({
+ customParams: {},
+ identifier,
+ manifest: skillManifest(identifier),
+ });
+ const sources = {
+ composioManifests: [skillManifest('composio-gmail')],
+ installedPlugins: [plugin('community-mcp')],
+ lobehubSkillManifests: [skillManifest('lobehub-notion')],
+ };
+ const engineManifestIds = () =>
+ lastEngineOptions().additionalManifests.map((m: any) => m.identifier);
+ const engineInstalledIds = () =>
+ (vi.mocked(createServerAgentToolsEngine).mock.calls.at(-1)?.[0] as any).installedPlugins.map(
+ (p: any) => p.identifier,
+ );
+
+ it('keeps a connector the agent never turned on out of the run', async () => {
+ const result = await run(sources).promise;
+
+ expect(engineManifestIds()).toEqual([]);
+ expect(engineInstalledIds()).toEqual([]);
+ expect(result.lobehubSkillManifests).toEqual([]);
+ expect(result.composioManifests).toEqual([]);
+ expect(Object.keys(result.toolManifestMap)).not.toContain('community-mcp');
+ });
+
+ it('lets a connector that is on be discovered without invoking it up front', async () => {
+ const result = await run({
+ ...sources,
+ autoSkillIds: ['lobehub-notion', 'composio-gmail', 'community-mcp'],
+ }).promise;
+
+ expect(engineManifestIds()).toEqual(['lobehub-notion', 'composio-gmail']);
+ expect(engineInstalledIds()).toEqual(['community-mcp']);
+ expect(result.agentPlugins).not.toContain('lobehub-notion');
+ expect(result.agentPlugins).not.toContain('composio-gmail');
+ expect(result.agentPlugins).not.toContain('community-mcp');
+ });
+
+ it('reads a connector pinned before the two-state switch as on, not invoked up front', async () => {
+ const result = await run({
+ ...sources,
+ agentConfig: { plugins: ['lobehub-notion', 'community-mcp', 'lobe-image-generation'] },
+ }).promise;
+
+ expect(engineManifestIds()).toEqual(['lobehub-notion']);
+ expect(engineInstalledIds()).toEqual(['community-mcp']);
+ // A pinned builtin tool keeps its pin; only connectors lost that state.
+ expect(result.agentPlugins).toEqual(['lobe-image-generation']);
+ });
+
+ it('resolves only the connectors that are on as discoverable', async () => {
+ const resolveByIdentifiers = vi.fn((_ids: string[]) => []);
+
+ await run({
+ ...sources,
+ autoSkillIds: ['custom-mcp'],
+ connectorResolve: resolveByIdentifiers,
+ }).promise;
+
+ expect(resolveByIdentifiers).toHaveBeenCalledTimes(1);
+ expect(resolveByIdentifiers.mock.calls[0][0]).toEqual(['custom-mcp']);
+ });
+
+ it('invokes a connector that is on directly when manual mode strips the activator', 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(engineManifestIds()).toEqual(['lobehub-notion']);
+ });
+
+ it('invokes a connector that is on directly in custom mode, which has no activator either', async () => {
+ const result = await run({
+ ...sources,
+ agentConfig: { chatConfig: { toolMode: 'custom' }, plugins: ['lobehub-notion'] },
+ autoSkillIds: ['community-mcp'],
+ }).promise;
+
+ expect(result.agentPlugins).toEqual(
+ expect.arrayContaining(['lobehub-notion', 'community-mcp']),
+ );
+ expect(result.agentPlugins).not.toContain('composio-gmail');
+ });
+
+ it('keeps a connector the turn mentions even when the agent has it off', async () => {
+ const result = await run({
+ ...sources,
+ input: { selectedToolIds: ['community-mcp'] },
+ }).promise;
+
+ expect(engineInstalledIds()).toEqual(['community-mcp']);
+ expect(result.agentPlugins).toContain('community-mcp');
+ });
+
+ it('leaves an exact toolset untouched by the agent switches', async () => {
+ const result = await run({
+ ...sources,
+ input: { exclusivePluginIds: ['community-mcp'] },
+ }).promise;
+
+ expect(engineInstalledIds()).toEqual(['community-mcp']);
+ expect(result.agentPlugins).toEqual(['community-mcp']);
+ });
+});
+
describe('discoverTools — turn-scoped builtins', () => {
it('adds the message tool and a participant group context for bot conversations', async () => {
const result = await run({
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
index fbabe2b6255..430965e358f 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -19,8 +19,11 @@ import type {
ToolSource,
} from '@lobechat/context-engine';
import {
+ applyConnectorActivation,
dropInvalidManifests,
+ hasConnectorActivator,
resolveClientExecutors,
+ resolveConnectorActivation,
resolveDiscoveryPool,
resolveInvocationToolIds,
} from '@lobechat/mecha';
@@ -212,6 +215,39 @@ export const discoverTools = async (
if (shareGate) {
agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);
}
+
+ // Connectors are opt-in per agent and two-state (see
+ // `resolveConnectorActivation`): on is every entry that is not disabled, off
+ // is everything else. An exact toolset (verify agent, goal supervisor) names
+ // its tools itself, so the agent's switches do not apply to it.
+ const optedInIds = [...getActivePluginIds(agentConfig?.plugins), ...(ctx.autoSkillIds ?? [])];
+ const connectorActivation =
+ exclusivePluginIds || isGoalTurn
+ ? undefined
+ : resolveConnectorActivation({
+ hasActivator: hasConnectorActivator(
+ agentConfig.chatConfig,
+ agentPlugins,
+ disabledPluginIds,
+ ),
+ optedInIds,
+ turnIds: [
+ ...(additionalPluginIds || []),
+ ...(selectedToolIds || []),
+ ...(shareGate ? getShareGrantActivatedPluginIds(shareGate) : []),
+ // An eval binds its connectors to the run by snapshot.
+ ...boundConnectorIds,
+ ],
+ });
+ // The connectors resolved straight into the invocation set. One that is on
+ // is found on demand instead, so it is read with the discoverable ones.
+ const injectedConnectorCandidateIds = connectorActivation
+ ? [...new Set([...agentPlugins, ...optedInIds])].filter(
+ (identifier) =>
+ connectorActivation.isInjected(identifier) &&
+ (!shareGate || filterPluginsByShareGate([identifier], shareGate).length > 0),
+ )
+ : agentPlugins;
// The unpinned sources the activator may discover (connectors, Composio,
// LobeHub Skills, installed plugins) need the same early cut for a share
// run: only granted identifiers are read. A grant the owner later disabled
@@ -236,12 +272,19 @@ export const discoverTools = async (
: startToolReads(deps, {
agentConfig,
attachedFileIds,
- candidateIds: agentPlugins.filter((identifier) => !boundConnectorIds.has(identifier)),
+ candidateIds: injectedConnectorCandidateIds.filter(
+ (identifier) => !boundConnectorIds.has(identifier),
+ ),
// Bound eval tools must not auto-discover unrelated credential-bearing
// connectors. This limits reads only; progressive activation remains enabled.
exclusivePluginIds:
exclusivePluginIds ?? (evalConnectorSnapshots ? agentPlugins : undefined),
isGoalTurn,
+ // A share run reads what the share grants instead.
+ optedInExtensionIds:
+ connectorActivation && !shareGate
+ ? new Set(optedInIds.filter((identifier) => !disabledPluginIds.includes(identifier)))
+ : undefined,
projectId: appContext?.projectId,
requestedDeviceId,
resolvedAgentId,
@@ -270,10 +313,16 @@ export const discoverTools = async (
// A share run keeps only granted plugins, so an ungranted one never reaches
// the connector permission lookup or the activator pool below.
const disabledPluginIdSet = new Set(disabledPluginIds);
+ // A connector the agent has not turned on is off for it: it leaves every
+ // connector source here, so neither the engine nor the activator sees it.
+ // A share run is cut to its grants above instead.
+ const isConnectorOn = (identifier: string) =>
+ !connectorActivation || !!shareGate || connectorActivation.isAllowed(identifier);
const installedPlugins = (await toolReads.installedPlugins).filter(
(p) =>
!boundConnectorIds.has(p.identifier) &&
!disabledPluginIdSet.has(p.identifier) &&
+ isConnectorOn(p.identifier) &&
(!shareGrantedExtensionIds || shareGrantedExtensionIds.has(p.identifier)),
);
log(
@@ -298,7 +347,12 @@ export const discoverTools = async (
// borrowed tool runs on (see `buildOwnershipNote`).
connectorOwnershipNote = await buildOwnershipNote(
deps,
- connectors.map((c) => connectorsMcp.find((mcp) => mcp.id === c.id) ?? c),
+ [
+ ...connectors.map((c) => connectorsMcp.find((mcp) => mcp.id === c.id) ?? c),
+ // A connector that is on is found on demand, so it is read with the
+ // discoverable ones; the model still needs to know whose account it is.
+ ...discoverableConnectorsMcp,
+ ],
!!shareGate,
);
@@ -349,9 +403,13 @@ export const discoverTools = async (
};
// 5c / 5d. LobeHub Skills and Composio manifests, read in the wave above.
- lobehubSkillManifests = await toolReads.lobehubSkillManifests;
+ lobehubSkillManifests = (await toolReads.lobehubSkillManifests).filter((m) =>
+ isConnectorOn(m.identifier),
+ );
log('execAgent: got %d lobehub skill manifests', lobehubSkillManifests.length);
- composioManifests = await toolReads.composioManifests;
+ composioManifests = (await toolReads.composioManifests).filter((m) =>
+ isConnectorOn(m.identifier),
+ );
log('execAgent: got %d composio manifests', composioManifests.length);
// 5d-1. Patch Lobehub/Composio manifests AND community-MCP plugin manifests
@@ -393,6 +451,26 @@ export const discoverTools = async (
isModelSupportToolUse,
};
+ // A connector that is on is found on demand rather than invoked up front:
+ // it leaves the invocation candidates here and stays in the discovery pool
+ // below. Runs without an activator need it in the initial tool set.
+ let allowedConnectorIds: Set<string> | undefined;
+ if (connectorActivation) {
+ const connectorIds = [
+ ...installedPlugins,
+ ...connectorManifests,
+ ...discoverableConnectorManifests,
+ ...lobehubSkillManifests,
+ ...composioManifests,
+ ]
+ .map((item) => item.identifier)
+ .filter((id) => !disabledPluginIdSet.has(id));
+ agentPlugins = applyConnectorActivation(agentPlugins, connectorIds, connectorActivation);
+ if (agentConfig.chatConfig?.toolMode === 'custom') {
+ allowedConnectorIds = new Set(connectorIds.filter(connectorActivation.isAllowed));
+ }
+ }
+
// Dynamically inject turn-scoped builtin tools.
const modelAbilities =
builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??
@@ -514,6 +592,7 @@ export const discoverTools = async (
: (agentConfig.chatConfig ?? undefined),
plugins: agentPlugins,
},
+ allowedConnectorIds,
canUseDevice,
deviceContext: gatewayConfigured
? {
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
index a085d6e6418..e4c0da45a3c 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
@@ -61,6 +61,13 @@ export interface ToolReadsContext {
candidateIds: string[];
exclusivePluginIds?: string[];
isGoalTurn: boolean;
+ /**
+ * The identifiers the agent turned on. A connector is opt-in per agent, so
+ * only these are resolved as discoverable; an off connector never has its
+ * credentials decrypted. `undefined` = no opt-in cut (an exact toolset, or a
+ * share run, which reads `shareGrantedExtensionIds` instead).
+ */
+ optedInExtensionIds?: Set<string>;
/** Project the run belongs to (`appContext.projectId`). */
projectId?: string;
requestedDeviceId?: string;
@@ -177,6 +184,16 @@ const readConnectors = async (
const onRefreshTimeout = () => {
refreshTimeouts += 1;
};
+ // Started with the read below, not after it: a connector that is on is
+ // resolved here, so this is the common path and must not queue behind the
+ // invocation set's own resolution. Never rejects.
+ const discoverableRead = readDiscoverableConnectors(
+ deps,
+ ctx,
+ connectorGateKeeper,
+ onRefreshTimeout,
+ installedPluginIds,
+ );
const [resolved, installedIds] = await Promise.all([
candidateIds.length > 0
? deps.connectorModel.resolveByIdentifiers(
@@ -211,13 +228,7 @@ const readConnectors = async (
? await deps.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id))
: [];
- const discoverable = await readDiscoverableConnectors(
- deps,
- ctx,
- connectorGateKeeper,
- onRefreshTimeout,
- installedIds,
- );
+ const discoverable = await discoverableRead;
markDegradedStage(span, refreshTimeouts, 'connector token refreshes');
return {
@@ -237,12 +248,13 @@ const readConnectors = async (
};
/**
- * Connectors the agent has not pinned — `auto` in the three-state plugin
- * config, which is simply "absent from `plugins`". A custom MCP is stored as
- * a connector, so without this source an unpinned one is resolvable only on
- * the turn that @-mentions it: the next turn's activator answers
- * "Not found" and the model's direct call is rejected as an unknown name.
- * Like installed plugins they are discoverable but never enabled.
+ * Connectors the agent turned on. A connector is two-state: on means the model
+ * finds it through the activator, so it is resolved here rather than into the
+ * invocation set. A custom MCP is stored as a connector, so without this
+ * source one that is on is resolvable only on the turn that @-mentions it: the
+ * next turn's activator answers "Not found" and the model's direct call is
+ * rejected as an unknown name. Like installed plugins they are discoverable
+ * but never enabled.
*
* A share run resolves only the connectors the share grants, by identifier:
* `resolveAll` would decrypt every creator connector for a visitor turn.
@@ -253,7 +265,7 @@ const readDiscoverableConnectors = async (
ctx: ToolReadsContext,
gateKeeper: KeyVaultsGateKeeper | undefined,
onRefreshTimeout: () => void,
- installedIds: Set<string>,
+ installedPluginIds: Promise<Set<string>>,
): Promise<{
connectorsMcp: DecryptedConnector[];
manifests: LobeToolManifest[];
@@ -263,20 +275,19 @@ const readDiscoverableConnectors = async (
if (ctx.exclusivePluginIds || ctx.isGoalTurn) return none;
try {
const candidates = new Set(ctx.candidateIds);
- let resolved: DecryptedConnector[];
- if (ctx.shareGrantedExtensionIds) {
- const grantedUnpinnedIds = [...ctx.shareGrantedExtensionIds].filter(
- (identifier) => !candidates.has(identifier),
- );
- if (grantedUnpinnedIds.length === 0) return none;
- resolved = await deps.connectorModel.resolveByIdentifiers(
- grantedUnpinnedIds,
- ctx.resolvedAgentId,
- gateKeeper,
- );
- } else {
- resolved = await deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper);
- }
+ // Both cuts name what the run may discover: a share's grants, or the
+ // connectors the agent turned on.
+ const discoverableIds = ctx.shareGrantedExtensionIds ?? ctx.optedInExtensionIds;
+ const unresolvedIds = discoverableIds
+ ? [...discoverableIds].filter((identifier) => !candidates.has(identifier))
+ : undefined;
+ if (unresolvedIds?.length === 0) return none;
+ const [resolved, installedIds] = await Promise.all([
+ unresolvedIds
+ ? deps.connectorModel.resolveByIdentifiers(unresolvedIds, ctx.resolvedAgentId, gateKeeper)
+ : deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper),
+ installedPluginIds,
+ ]);
const connectorsMcp = filterInstalledMarketplaceConnectors(resolved, installedIds).filter(
(c) => !candidates.has(c.identifier) && hasCallableMcpEndpoint(c),
);
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.ts
index 9c68616055e..130204f9b23 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
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { ToolResolver } from '@lobechat/context-engine';
import { getTestDB } from '@lobechat/database/test-utils';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -13,6 +14,7 @@ import {
workspaceMembers,
workspaces,
} from '@/database/schemas';
+import { buildToolDiscoveryConfig } from '@/server/modules/AgentRuntime/executorHelpers';
import { discoverTools } from '@/server/services/aiAgent/pipeline/toolDiscovery';
import {
installMarketplaceMcpConnector,
@@ -87,8 +89,15 @@ const installFromServer = (
{ agentId: AGENT_ID, source: 'market' },
);
+interface NextRunOptions {
+ /** Manual skill-activate mode: the run has no activator. */
+ manual?: boolean;
+ /** The agent's `plugins`; the install pins the MCP on the agent by default. */
+ plugins?: string[];
+}
+
/** The next run of the agent the install pinned the MCP on. */
-const nextRun = () =>
+const nextRun = (options: NextRunOptions = {}) =>
discoverTools(
{
agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
@@ -104,7 +113,10 @@ const nextRun = () =>
userId,
} as never,
{
- agentConfig: { chatConfig: {}, plugins: [IDENTIFIER] },
+ agentConfig: {
+ chatConfig: options.manual ? { skillActivateMode: 'manual' } : {},
+ plugins: options.plugins ?? [IDENTIFIER],
+ },
appContext: undefined,
canUseDevice: false,
model: 'test-model',
@@ -126,6 +138,11 @@ const nextRun = () =>
} as never,
);
+const TOOL_NAME = `${IDENTIFIER}____fetch____mcp`;
+
+const offeredToolNames = (tools: { function: { name: string } }[] | undefined) =>
+ (tools ?? []).map((tool) => tool.function.name);
+
beforeEach(async () => {
await db.delete(users);
await db.insert(users).values({ id: userId });
@@ -148,7 +165,7 @@ describe('resolveOrInstallMarketPlugin — server-side marketplace install', ()
},
},
])(
- 'installs a manifest with $label into user_connectors only, and the next run can call it',
+ 'installs a manifest with $label into user_connectors only, and the next run can activate and call it',
async ({ served }) => {
const { installedNow, resolution } = await installFromServer(served);
@@ -169,14 +186,70 @@ describe('resolveOrInstallMarketPlugin — server-side marketplace install', ()
api: [expect.objectContaining({ name: 'fetch' })],
mcpParams: expect.objectContaining({ type: 'cloud' }),
});
- expect(run.toolsResult.enabledToolIds).toContain(IDENTIFIER);
- // The model is offered the connector's tool by name
- expect((run.tools ?? []).map((tool) => tool.function.name)).toContain(
- `${IDENTIFIER}____fetch____mcp`,
+ // The pin turns the connector on: the run lists it for the activator
+ // instead of offering its tools up front.
+ expect(run.toolSourceMap[IDENTIFIER]).toBe('mcp');
+ expect(run.toolsResult.enabledToolIds).not.toContain(IDENTIFIER);
+ expect(offeredToolNames(run.tools)).not.toContain(TOOL_NAME);
+ expect(
+ (
+ buildToolDiscoveryConfig(
+ { manifestMap: run.toolManifestMap } as never,
+ run.toolsResult.enabledToolIds,
+ )?.availableTools ?? []
+ ).map((tool) => tool.identifier),
+ ).toContain(IDENTIFIER);
+
+ // Activating it offers the model the connector's tool by name
+ const activated = new ToolResolver().resolve(
+ {
+ enabledToolIds: run.toolsResult.enabledToolIds,
+ executorMap: run.toolExecutorMap,
+ manifestMap: run.toolManifestMap,
+ sourceMap: run.toolSourceMap,
+ tools: run.tools ?? [],
+ },
+ {
+ activatedTools: [
+ {
+ activatedAtStep: 1,
+ id: IDENTIFIER,
+ manifest: run.toolManifestMap[IDENTIFIER],
+ source: 'discovery',
+ },
+ ],
+ },
);
+ expect(activated.enabledToolIds).toContain(IDENTIFIER);
+ expect(offeredToolNames(activated.tools)).toContain(TOOL_NAME);
+ // …and a later operation can restore that activation through the engine
+ const restored = run.toolsEngine!.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'test-model',
+ provider: 'test-provider',
+ skipDefaultTools: true,
+ toolIds: [IDENTIFIER],
+ });
+ 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
+ const manualRun = await nextRun({ manual: true });
+ expect(manualRun.toolsResult.enabledToolIds).toContain(IDENTIFIER);
+ expect(offeredToolNames(manualRun.tools)).toContain(TOOL_NAME);
},
);
+ it('keeps the install out of the run of an agent that has not turned it on', async () => {
+ await installFromServer();
+
+ const run = await nextRun({ plugins: [] });
+
+ expect(run.toolManifestMap[IDENTIFIER]).toBeUndefined();
+ expect(run.toolsResult.enabledToolIds).not.toContain(IDENTIFIER);
+ expect(offeredToolNames(run.tools)).not.toContain(TOOL_NAME);
+ });
+
it('refuses a stdio MCP the market does not host, writing nothing', async () => {
const { installedNow, resolution } = await installFromServer(manifest, {
haveCloudEndpoint: false,
diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.ts
index 32ef1a063b5..4067d0191ab 100644
--- a/packages/builtin-tool-activator/src/systemRole.ts
+++ b/packages/builtin-tool-activator/src/systemRole.ts
@@ -31,43 +31,7 @@ const toolSelectionGuidelines = ({
${withSkills ? toolSelectionSkill : ''}</tool_selection_guidelines>`;
const skillStoreDiscovery = `<skill_store_discovery>
-**CRITICAL: Always activate \`lobe-skill-store\` FIRST when ANY of the following conditions are met:**
-
-**Trigger keywords/patterns (MUST activate lobe-skill-store immediately):**
-- User mentions: "SKILL.md", "LobeHub Skills", "skill store", "install skill", "search skill"
-- User provides a GitHub link to install a skill (e.g., github.com/xxx/xxx containing SKILL.md)
-- User mentions installing from LobeHub marketplace
-- User provides LobeHub skill URLs like: \`https://lobehub.com/skills/{identifier}/skill.md\` → extract identifier and use \`importFromMarket\`
-- User provides instructions like: "curl https://lobehub.com/skills/..." → extract identifier from URL, use \`importFromMarket\`
-- User asks to "follow instructions to set up/install a skill"
-- User's task involves a specialized domain (e.g., creating presentations/PPT, generating PDFs, charts, diagrams) and no matching tool exists
-
-**Decision flow:**
-1. **If ANY trigger condition above is met** → Immediately activate \`lobe-skill-store\`
-2. **For LobeHub skill URLs** (e.g., \`https://lobehub.com/skills/{identifier}/skill.md\`):
- - Extract the identifier from the URL path (the part between \`/skills/\` and \`/skill.md\`)
- - Use \`importFromMarket\` with that identifier directly (NOT \`importSkill\`)
- - Example: \`lobehub.com/skills/openclaw-openclaw-github/skill.md\` → identifier is \`openclaw-openclaw-github\`
-3. For GitHub repository URLs → use \`importSkill\` with type "url"
-4. For marketplace searches → use \`searchSkill\` then \`importFromMarket\`
-5. Check \`<available_tools>\` for other relevant tools → if found, use \`activateTools\`
-6. Fall back to generic tools (web browsing, cloud sandbox, etc.) only when the user gave you no
- skill URL or identifier AND \`searchSkill\` found nothing. Holding a skill URL is never a reason
- to browse — import it.
-
-**Install priority — go down this ladder, never skip up it:**
-1. \`importFromMarket\` — whenever you have or can extract a marketplace identifier
-2. \`importSkill\` — any other skill URL (GitHub repo, raw SKILL.md, ZIP)
-3. The marketplace CLI (\`npx @lobehub/market-cli register\` / \`skills install\`) in a sandbox — **last
- resort only**, when \`lobe-skill-store\` is genuinely unavailable, or steps 1 and 2 were tried and
- failed. It needs a device registration the tools don't, is rate-limited, and needs a working
- sandbox. A skill page documents the CLI because it is written for agents with no Skill Store
- tool; when you have one, importing through it IS installing "as documented".
-
-**Important:**
-- Do NOT manually curl/fetch SKILL.md files or try to parse them yourself
-- For \`lobehub.com/skills/xxx/skill.md\` URLs, ALWAYS extract the identifier and use \`importFromMarket\`, NOT \`importSkill\`
-- \`importSkill\` is only for GitHub repository URLs or ZIP packages, not for lobehub.com skill URLs
+For marketplace skill searches, skill install requests (including SKILL.md, GitHub or LobeHub skill URLs), or a specialized task that needs a capability missing from the available tools and skills, use the Skill Store. If lobe-skill-store is in <available_tools>, activate it before browsing or trying a CLI. If already active, call it directly.
</skill_store_discovery>`;
const credentialsManagement = `<credentials_management>
@@ -115,21 +79,13 @@ When \`{{creds_sandbox_reachable}}\` is \`false\` (this run is routed to a devic
</credential_usage_by_runtime>
</credentials_management>`;
-const bestPracticesSkillFirst = `- **SKILL-FIRST: Any mention of skills, SKILL.md, GitHub skill links, or LobeHub marketplace → activate \`lobe-skill-store\` FIRST, no exceptions.**
-- **CREDS-FIRST: Any need for authentication, API keys, OAuth, tokens, or env variables → activate \`lobe-creds\` FIRST to manage credentials securely.**
-`;
-
-const bestPracticesSkillMarketplace = `- For specialized tasks, search the Skill Marketplace first — a dedicated skill is almost always better than a generic approach
+const bestPracticesCreds = `- **CREDS-FIRST: Any need for authentication, API keys, OAuth, tokens, or env variables → activate \`lobe-creds\` FIRST to manage credentials securely.**
`;
-const bestPractices = ({
- withSkillStoreAndCreds,
-}: {
- withSkillStoreAndCreds: boolean;
-}) => `<best_practices>
+const bestPractices = ({ withCreds }: { withCreds: boolean }) => `<best_practices>
- **IMPORTANT: Plan ahead and activate all needed tools upfront in a single call.** Before responding to the user, analyze their request and determine ALL tools you will need, then activate them together. Do NOT activate tools incrementally during a multi-step task.
-${withSkillStoreAndCreds ? bestPracticesSkillFirst : ''}- Check the \`<available_tools>\` list before activating tools
-${withSkillStoreAndCreds ? bestPracticesSkillMarketplace : ''}- Only activate tools that are relevant to the user's current request
+${withCreds ? bestPracticesCreds : ''}- Check the \`<available_tools>\` list before activating tools
+- Only activate tools that are relevant to the user's current request
- After activation, use the tools' APIs directly — no need to call activateTools again for the same tools
</best_practices>`;
@@ -143,7 +99,7 @@ ${skillStoreDiscovery}
${credentialsManagement}
-${bestPractices({ withSkillStoreAndCreds: true })}
+${bestPractices({ withCreds: true })}
`;
/**
@@ -160,5 +116,5 @@ ${howItWorks({ withSkills })}
${toolSelectionGuidelines({ withSkills })}
-${bestPractices({ withSkillStoreAndCreds: false })}
+${bestPractices({ withCreds: false })}
`;
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.test.ts b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
index ea3ca3d9368..7f5ff5ce186 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.test.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
@@ -4,11 +4,11 @@ import { LobeAgentManifest } from './manifest';
import { LobeAgentApiName } from './types';
describe('LobeAgentManifest', () => {
- it('should keep the package metadata generic for future Lobe Agent capabilities', () => {
+ it('describes the capabilities the model can discover before activation', () => {
expect(LobeAgentManifest.meta.avatar).toBe('🤖');
- expect(LobeAgentManifest.meta.description).toBe(
- 'Run built-in Lobe Agent capabilities: plan + todo management, sub-agent dispatch, and multimodal media analysis.',
- );
+ for (const capability of ['plans', 'todos', 'question', 'media', 'sub-agent']) {
+ expect(LobeAgentManifest.meta.description).toContain(capability);
+ }
expect(LobeAgentManifest.meta.readme).toContain(
'built-in assistant capabilities that can be expanded over time',
);
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.ts
index d2a0130cf29..84cf8f4db9e 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts
@@ -369,7 +369,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {
meta: {
avatar: '🤖',
description:
- 'Run built-in Lobe Agent capabilities: plan + todo management, sub-agent dispatch, and multimodal media analysis.',
+ 'Create and update conversation plans and todos, ask the user a structured question, analyze media, report a platform blocker, or delegate work to a sub-agent when available.',
readme: 'Lobe Agent provides built-in assistant capabilities that can be expanded over time.',
title: 'Lobe Agent',
},
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index b53a00bb538..5ea7dbccd8b 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -63,13 +63,12 @@ import { type LobeBuiltinTool } from '@lobechat/types';
import { resolveCloudSandboxInPageScope } from './pageScope';
/**
- * Default tool IDs that will always be added to the tools list.
+ * Default candidates evaluated by the tool enable rules.
* Shared between frontend (createAgentToolsEngine) and server (createServerAgentToolsEngine).
*/
export const defaultToolIds = [
LobeActivatorManifest.identifier,
SkillsManifest.identifier,
- SkillStoreManifest.identifier,
WebBrowsingManifest.identifier,
KnowledgeBaseManifest.identifier,
AttachmentsManifest.identifier,
@@ -79,31 +78,16 @@ export const defaultToolIds = [
CloudSandboxManifest.identifier,
AgentDocumentsManifest.identifier,
TaskManifest.identifier,
+ // A runtime media fallback can enable this candidate even without a user pin.
LobeAgentManifest.identifier,
CanvasManifest.identifier,
];
/**
- * Tool IDs that are always enabled regardless of user selection.
- * These are core system tools that the agent needs to function properly.
- *
- * `lobe-agent` is listed first: its built-in capabilities (plan + todo management,
- * sub-agent dispatch, multimodal fallback) should be available on every agent-mode turn,
- * not gated behind explicit injection. NOTE: these rules only apply in agent mode — chat
- * mode (`enableAgentMode === false`) drops `alwaysOnToolIds` entirely. In manual
- * skill-activate mode the discovery tools in `manualModeExcludeToolIds` are still removed
- * from the defaults before the enable checker runs, so they end up disabled there.
- *
- * This list is also the source for builtin entries in the chat-input Tools popover.
- * They default to pinned but can be explicitly disabled per agent; entries represented by
- * the activation mode control itself are excluded from that menu.
+ * Builtins enabled by default in Agent mode. The activator loads other tools
+ * on demand, and Skills loads skill instructions. Manual mode omits the activator.
*/
-export const alwaysOnToolIds = [
- LobeAgentManifest.identifier,
- LobeActivatorManifest.identifier,
- SkillsManifest.identifier,
- SkillStoreManifest.identifier,
-];
+export const alwaysOnToolIds = [LobeActivatorManifest.identifier, SkillsManifest.identifier];
/**
* Runtime tools represented by the skill activation mode control itself. They remain part
@@ -116,10 +100,7 @@ export const activationModeControlledToolIds = [LobeActivatorManifest.identifier
* These are the tool/skill discovery tools that should be disabled when user wants precise control.
* Other default tools (sandbox, web browsing, etc.) remain available if enabled externally.
*/
-export const manualModeExcludeToolIds = [
- LobeActivatorManifest.identifier,
- SkillStoreManifest.identifier,
-];
+export const manualModeExcludeToolIds = [LobeActivatorManifest.identifier];
/**
* Tool IDs allowed when the agent runs in chat mode
@@ -192,7 +173,6 @@ export const runtimeManagedToolIds = [
LocalSystemManifest.identifier,
MemoryManifest.identifier,
RemoteDeviceManifest.identifier,
- LobeAgentManifest.identifier,
WebBrowsingManifest.identifier,
];
@@ -347,7 +327,6 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
type: 'builtin',
},
{
- hidden: true,
identifier: SkillStoreManifest.identifier,
manifest: SkillStoreManifest,
type: 'builtin',
@@ -620,7 +599,6 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
type: 'builtin',
},
{
- hidden: true,
identifier: LobeAgentManifest.identifier,
manifest: LobeAgentManifest,
// Context-aware: hides the `callSubAgent` API inside group / sub-agent runs.
diff --git a/packages/const/src/recommendedSkill.ts b/packages/const/src/recommendedSkill.ts
index 57901562467..5c124849ea0 100644
--- a/packages/const/src/recommendedSkill.ts
+++ b/packages/const/src/recommendedSkill.ts
@@ -11,6 +11,8 @@ export interface RecommendedSkillItem {
export const RECOMMENDED_SKILLS: RecommendedSkillItem[] = [
// Builtin skills
+ { id: 'lobe-agent', type: RecommendedSkillType.Builtin },
+ { id: 'lobe-skill-store', type: RecommendedSkillType.Builtin },
{ id: 'lobe-artifacts', type: RecommendedSkillType.Builtin },
{ id: 'lobe-user-memory', type: RecommendedSkillType.Builtin },
{ id: 'lobe-cloud-sandbox', type: RecommendedSkillType.Builtin },
diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
index c297c1d1246..0184d00938d 100644
--- a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
+++ b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
@@ -1101,13 +1101,12 @@ describe('ToolsEngine', () => {
const defaultToolIds = [
'lobe-activator',
'lobe-skills',
- 'lobe-skill-store',
'lobe-web-browsing',
'lobe-cloud-sandbox',
];
- const alwaysOnToolIds = ['lobe-activator', 'lobe-skills', 'lobe-skill-store'];
- const manualModeExcludeToolIds = ['lobe-activator', 'lobe-skill-store'];
+ const alwaysOnToolIds = ['lobe-activator', 'lobe-skills'];
+ const manualModeExcludeToolIds = ['lobe-activator'];
it('should NOT inject lobe-activator and lobe-skill-store in manual mode', () => {
const engine = new ToolsEngine({
@@ -1139,7 +1138,7 @@ describe('ToolsEngine', () => {
expect(result.enabledToolIds).toContain('lobe-cloud-sandbox');
});
- it('should inject lobe-activator and lobe-skill-store in auto mode (no excludeDefaultToolIds)', () => {
+ it('should inject the activator but defer Skill Store in auto mode', () => {
const engine = new ToolsEngine({
manifestSchemas: builtinManifests,
defaultToolIds,
@@ -1162,7 +1161,7 @@ describe('ToolsEngine', () => {
// All default tools should be injected in auto mode
expect(result.enabledToolIds).toContain('lobe-activator');
- expect(result.enabledToolIds).toContain('lobe-skill-store');
+ expect(result.enabledToolIds).not.toContain('lobe-skill-store');
expect(result.enabledToolIds).toContain('lobe-skills');
expect(result.enabledToolIds).toContain('lobe-web-browsing');
expect(result.enabledToolIds).toContain('lobe-cloud-sandbox');
diff --git a/packages/context-engine/src/engine/tools/enableCheckerFactory.ts b/packages/context-engine/src/engine/tools/enableCheckerFactory.ts
index 9d31c69e28b..cdc6f70c271 100644
--- a/packages/context-engine/src/engine/tools/enableCheckerFactory.ts
+++ b/packages/context-engine/src/engine/tools/enableCheckerFactory.ts
@@ -6,6 +6,8 @@ export interface EnableCheckerConfig {
* When true, tools with `context.isExplicitActivation` skip all filters.
*/
allowExplicitActivation?: boolean;
+ /** A restricted toolset may activate only these additional ids after platform checks. */
+ explicitActivationIds?: ReadonlySet<string>;
/**
* Platform-specific filter extension point.
@@ -41,6 +43,8 @@ export function createEnableChecker(config: EnableCheckerConfig): PluginEnableCh
const platformResult = config.platformFilter?.({ context, manifest, pluginId });
if (platformResult !== undefined) return platformResult;
+ if (context?.isExplicitActivation && config.explicitActivationIds?.has(pluginId)) return true;
+
// 3. Tool-specific rules
if (config.rules && pluginId in config.rules) {
return config.rules[pluginId];
diff --git a/packages/mecha/package.json b/packages/mecha/package.json
index 87d45ffad44..a11337aa55c 100644
--- a/packages/mecha/package.json
+++ b/packages/mecha/package.json
@@ -15,6 +15,7 @@
"@lobechat/agent-runtime": "workspace:*",
"@lobechat/builtin-agents": "workspace:*",
"@lobechat/builtin-skills": "workspace:*",
+ "@lobechat/builtin-tool-activator": "workspace:*",
"@lobechat/builtin-tool-agent-account": "workspace:*",
"@lobechat/builtin-tool-agent-builder": "workspace:*",
"@lobechat/builtin-tool-agent-documents": "workspace:*",
diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts
index 478c3bd827e..5778b26310d 100644
--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts
+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts
@@ -103,7 +103,16 @@ describe('gatherContextFacts', () => {
expect(facts.step.planTodo?.todos?.items.map((t) => t.text)).toEqual(['from history']);
});
- it('does not read the plan document without lobe-agent', async () => {
+ it('keeps an existing topic plan available before Lobe Agent is activated', async () => {
+ const facts = await gatherContextFacts(
+ request({ discoverableTools: [{ identifier: 'lobe-agent' }] }),
+ providers,
+ );
+
+ expect(facts.step.planTodo?.plan?.goal).toBe('Ship it');
+ });
+
+ it('does not read the plan document when Lobe Agent is unavailable', async () => {
const getPlanDocument = vi.fn(providers.getPlanDocument);
const facts = await gatherContextFacts(request(), { getPlanDocument });
@@ -145,6 +154,19 @@ describe('gatherContextFacts', () => {
expect(list).toContain('gmail');
expect(list).not.toContain('slack');
});
+
+ it('does not offer a connected Composio service the agent has not turned on', async () => {
+ const listConnectedConnectorIds = vi.fn(async () => ['gmail', 'slack']);
+
+ const facts = await gatherContextFacts(
+ request({ enabledToolIds: ['lobe-creds'], optedInPluginIds: ['gmail'] }),
+ { listConnectedConnectorIds },
+ );
+ const list = facts.variables.COMPOSIO_SERVICES_LIST as string;
+
+ expect(list).toContain('gmail');
+ expect(list).not.toContain('slack');
+ });
});
describe('document references', () => {
diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
index f57ff519f32..28da7362f53 100644
--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts
@@ -276,7 +276,8 @@ const gatherPlanTodo = async (
// document is a best-effort mirror the run keeps with `lobe-agent`.
const messageTodos = extractTodosFromMessages(request.messages);
const canReadPlan =
- request.enabledToolIds.includes(LobeAgentIdentifier) &&
+ (request.enabledToolIds.includes(LobeAgentIdentifier) ||
+ request.discoverableTools?.some((tool) => tool.identifier === LobeAgentIdentifier)) &&
!!request.topicId &&
!!providers.getPlanDocument;
const planDoc = canReadPlan
@@ -331,8 +332,13 @@ const gatherComposioServices = async (
// Disabled services are dropped from both lists — neither "connected, use
// directly" nor "available to connect" — the agent isn't meant to see them.
const disabledIdSet = new Set(request.disabledPluginIds ?? []);
+ // A connector is opt-in per agent: a service that is connected but that this
+ // agent has not turned on cannot be reached, so it is not listed as usable.
+ const optedIn = request.optedInPluginIds && new Set(request.optedInPluginIds);
const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(
- COMPOSIO_APP_TYPES.filter((tool) => connectedIds.has(tool.identifier)),
+ COMPOSIO_APP_TYPES.filter(
+ (tool) => connectedIds.has(tool.identifier) && (!optedIn || optedIn.has(tool.identifier)),
+ ),
disabledIdSet,
).map((tool) => ({ identifier: tool.identifier, name: tool.label }));
const available = resolveAvailableComposioServices(
diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.ts
index 7d9a82c435f..4ace2e15e21 100644
--- a/packages/mecha/src/contextEngineering/facts/types.ts
+++ b/packages/mecha/src/contextEngineering/facts/types.ts
@@ -93,6 +93,8 @@ export interface ContextFactRequest {
agentId?: string;
/** Plugin identifiers the agent explicitly disabled (tri-state entries). */
disabledPluginIds?: string[];
+ /** Tools offered for activation in the current step. */
+ discoverableTools?: ReadonlyArray<{ identifier: string }>;
/** Agent being edited in the Profile panel, when the agent builder is active. */
editingAgentId?: string;
/** Group being edited in the group Profile panel, when the group builder is active. */
@@ -114,6 +116,12 @@ export interface ContextFactRequest {
mentionedAgents?: RuntimeMentionedAgent[];
/** Conversation as the engine will see it (history hints already applied). */
messages: UIChatMessage[];
+ /**
+ * Identifiers the agent turned on (every `plugins` entry that is not
+ * disabled). A connector is opt-in per agent, so a connected service absent
+ * from it is not offered as usable. Omitted = no opt-in cut.
+ */
+ optedInPluginIds?: string[];
/** Present only on a shared-agent visitor run. */
shareVisitor?: Pick<AgentShareVisitorContext, 'agentId' | 'visitorUserId'>;
topicId?: string;
diff --git a/packages/mecha/src/toolSet/connectorActivation.test.ts b/packages/mecha/src/toolSet/connectorActivation.test.ts
new file mode 100644
index 00000000000..1262402065b
--- /dev/null
+++ b/packages/mecha/src/toolSet/connectorActivation.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyConnectorActivation,
+ hasConnectorActivator,
+ resolveConnectorActivation,
+} from './connectorActivation';
+
+describe('hasConnectorActivator', () => {
+ it('has the activator in agent mode, the default', () => {
+ expect(hasConnectorActivator(undefined)).toBe(true);
+ expect(hasConnectorActivator({})).toBe(true);
+ expect(hasConnectorActivator({ skillActivateMode: 'auto' })).toBe(true);
+ });
+
+ it('has none once manual skill-activate mode strips it', () => {
+ expect(hasConnectorActivator({ skillActivateMode: 'manual' })).toBe(false);
+ });
+
+ it('has none in custom mode, which exposes exactly the declared plugins', () => {
+ expect(hasConnectorActivator({ toolMode: 'custom' })).toBe(false);
+ });
+
+ it('has none in chat mode', () => {
+ expect(hasConnectorActivator({ enableAgentMode: false })).toBe(false);
+ expect(hasConnectorActivator({ toolMode: 'chat' })).toBe(false);
+ });
+});
+
+describe('resolveConnectorActivation', () => {
+ it('leaves a connector the agent never turned on out of reach', () => {
+ const activation = resolveConnectorActivation({ hasActivator: true, optedInIds: ['gmail'] });
+
+ expect(activation.isAllowed('gmail')).toBe(true);
+ expect(activation.isAllowed('slack')).toBe(false);
+ });
+
+ it('keeps a connector that is on discoverable rather than injected', () => {
+ const activation = resolveConnectorActivation({ hasActivator: true, optedInIds: ['gmail'] });
+
+ expect(activation.isInjected('gmail')).toBe(false);
+ });
+
+ it('injects a connector that is on when the run has no activator', () => {
+ const activation = resolveConnectorActivation({ hasActivator: false, optedInIds: ['gmail'] });
+
+ expect(activation.isInjected('gmail')).toBe(true);
+ expect(activation.isInjected('slack')).toBe(false);
+ });
+
+ it('reaches and injects a connector the turn brings in, even when it is off', () => {
+ const activation = resolveConnectorActivation({
+ hasActivator: true,
+ optedInIds: [],
+ turnIds: ['slack'],
+ });
+
+ expect(activation.isAllowed('slack')).toBe(true);
+ expect(activation.isInjected('slack')).toBe(true);
+ });
+});
+
+describe('applyConnectorActivation', () => {
+ it('drops a pinned connector from the invocation set and keeps other tools', () => {
+ const activation = resolveConnectorActivation({
+ hasActivator: true,
+ optedInIds: ['gmail', 'lobe-image-generation'],
+ });
+
+ expect(
+ applyConnectorActivation(['lobe-image-generation', 'gmail'], ['gmail', 'slack'], activation),
+ ).toEqual(['lobe-image-generation']);
+ });
+
+ it('adds a connector that is on to the invocation set without the activator', () => {
+ const activation = resolveConnectorActivation({
+ hasActivator: false,
+ optedInIds: ['gmail', 'a-skill'],
+ });
+
+ expect(applyConnectorActivation(['a-pinned-skill'], ['gmail', 'slack'], activation)).toEqual([
+ 'a-pinned-skill',
+ 'gmail',
+ ]);
+ });
+
+ it('keeps a connector the turn mentions', () => {
+ const activation = resolveConnectorActivation({
+ hasActivator: true,
+ optedInIds: [],
+ turnIds: ['slack'],
+ });
+
+ expect(applyConnectorActivation(['slack'], ['gmail', 'slack'], activation)).toEqual(['slack']);
+ });
+});
diff --git a/packages/mecha/src/toolSet/connectorActivation.ts b/packages/mecha/src/toolSet/connectorActivation.ts
new file mode 100644
index 00000000000..b805f2a2966
--- /dev/null
+++ b/packages/mecha/src/toolSet/connectorActivation.ts
@@ -0,0 +1,84 @@
+import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
+import { type LobeAgentChatConfig, resolveToolMode } from '@lobechat/types';
+
+/** Agent mode provides the activator by default. Custom toolsets can declare it explicitly. */
+export const hasConnectorActivator = (
+ chatConfig:
+ | Pick<LobeAgentChatConfig, 'enableAgentMode' | 'skillActivateMode' | 'toolMode'>
+ | null
+ | undefined,
+ pluginIds: readonly string[] = [],
+ disabledIds: readonly string[] = [],
+): boolean => {
+ if (chatConfig?.skillActivateMode === 'manual' || disabledIds.includes(LobeActivatorIdentifier))
+ return false;
+ const mode = resolveToolMode(chatConfig);
+ return mode === 'agent' || (mode === 'custom' && pluginIds.includes(LobeActivatorIdentifier));
+};
+
+export interface ConnectorActivationRequest {
+ /**
+ * The run has the activator, so a connector can be found on demand (see
+ * {@link hasConnectorActivator}). Without it a connector that is on has no
+ * other way to reach the model than joining the invocation set.
+ */
+ hasActivator: boolean;
+ /**
+ * Identifiers the agent turned on — every `plugins` entry that is not
+ * disabled. A connector absent from it is off for this agent.
+ */
+ optedInIds: Iterable<string>;
+ /**
+ * Identifiers this turn brings in by itself (an @-mention, an internal
+ * addition, a share grant that activates a tool). They are reachable and
+ * invoked whatever the agent's own switch says.
+ */
+ turnIds?: Iterable<string>;
+}
+
+export interface ConnectorActivation {
+ /** Whether the run may reach the connector at all. Off connectors are not. */
+ isAllowed: (identifier: string) => boolean;
+ /** Whether the connector joins the invocation set without being activated first. */
+ isInjected: (identifier: string) => boolean;
+}
+
+/**
+ * Connectors — MCP connectors, Composio and LobeHub connections, installed
+ * plugins — are opt-in per agent and have two states. On means the model finds
+ * the connector on demand through the activator; off means the run never sees
+ * it. Both runtimes apply this one rule to the connector identifiers they hold;
+ * builtin tools and skills keep their own three-state policy.
+ */
+export const resolveConnectorActivation = (
+ request: ConnectorActivationRequest,
+): ConnectorActivation => {
+ const optedIn = new Set(request.optedInIds);
+ const turn = new Set(request.turnIds ?? []);
+
+ return {
+ isAllowed: (identifier) => optedIn.has(identifier) || turn.has(identifier),
+ isInjected: (identifier) =>
+ turn.has(identifier) || (!request.hasActivator && optedIn.has(identifier)),
+ };
+};
+
+/**
+ * The invocation candidates once the connector rule is applied: a connector
+ * stays only when it is injected, and one that is injected is added even if it
+ * was not a candidate. Every other identifier — builtin tools, skills — is
+ * left exactly as the caller listed it.
+ */
+export const applyConnectorActivation = (
+ candidateIds: readonly string[],
+ connectorIds: Iterable<string>,
+ activation: ConnectorActivation,
+): string[] => {
+ const connectors = new Set(connectorIds);
+ const kept = candidateIds.filter(
+ (identifier) => !connectors.has(identifier) || activation.isInjected(identifier),
+ );
+ const injected = [...connectors].filter((identifier) => activation.isInjected(identifier));
+
+ return [...new Set([...kept, ...injected])];
+};
diff --git a/packages/mecha/src/toolSet/discoveryPool.test.ts b/packages/mecha/src/toolSet/discoveryPool.test.ts
index d9a8cd8ace8..4590f0b3463 100644
--- a/packages/mecha/src/toolSet/discoveryPool.test.ts
+++ b/packages/mecha/src/toolSet/discoveryPool.test.ts
@@ -6,7 +6,8 @@ import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
-import type { LobeToolManifest } from '@lobechat/context-engine';
+import { builtinTools } from '@lobechat/builtin-tools';
+import { type LobeToolManifest, ToolResolver } from '@lobechat/context-engine';
import { describe, expect, it } from 'vitest';
import {
@@ -67,6 +68,24 @@ describe('resolveInvocationToolIds', () => {
});
describe('resolveDiscoveryPool', () => {
+ it.each([
+ ['lobe-agent', 'createTodos'],
+ ['lobe-skill-store', 'searchSkill'],
+ ])('makes %s discoverable and exposes its functions on the step after activation', (id, api) => {
+ const pool = resolveDiscoveryPool(request({ builtinTools, enabledManifests: new Map() }));
+ const operation = { ...pool, enabledToolIds: [], tools: [] };
+ const resolver = new ToolResolver();
+ const cold = resolver.resolve(operation, { activatedTools: [] });
+ const manifest = pool.manifestMap[id];
+
+ expect(manifest.meta?.description).toBeTruthy();
+ expect(cold.promptManifestMap[id]).toBeUndefined();
+ const next = resolver.resolve(operation, {
+ activatedTools: [{ id, manifest, source: 'discovery' }],
+ });
+ expect(next.tools.map((tool) => tool.function.name)).toContain(`${id}____${api}`);
+ });
+
it('seeds with the enabled manifests and appends discoverable builtins only', () => {
const pool = resolveDiscoveryPool(request());
expect(Object.keys(pool.manifestMap)).toEqual([
diff --git a/packages/mecha/src/toolSet/index.ts b/packages/mecha/src/toolSet/index.ts
index 37bf58804c3..ba3b9ab78ca 100644
--- a/packages/mecha/src/toolSet/index.ts
+++ b/packages/mecha/src/toolSet/index.ts
@@ -1,4 +1,5 @@
export * from './builtinSkillGate';
+export * from './connectorActivation';
export * from './deviceTools';
export * from './discoveryPool';
export * from './manifestPool';
diff --git a/packages/mecha/src/toolSet/resolveToolRules.test.ts b/packages/mecha/src/toolSet/resolveToolRules.test.ts
index cf43dce9e9d..33acf5d371f 100644
--- a/packages/mecha/src/toolSet/resolveToolRules.test.ts
+++ b/packages/mecha/src/toolSet/resolveToolRules.test.ts
@@ -74,7 +74,9 @@ describe('resolveToolRules', () => {
expect(resolved.allowExplicitActivation).toBe(true);
expect(resolved.rules['my-plugin']).toBe(true);
expect(resolved.rules['scope-plugin']).toBe(true);
- expect(resolved.rules['lobe-agent']).toBe(true);
+ expect(resolved.rules['lobe-activator']).toBe(true);
+ expect(resolved.rules['lobe-agent']).toBeUndefined();
+ expect(resolved.rules['lobe-skill-store']).toBeUndefined();
for (const id of groupSupervisorToolIds) {
expect(resolved.rules[id]).toBe(true);
expect(resolved.defaultToolIds).toContain(id);
diff --git a/packages/types/src/agent/pluginConfig.test.ts b/packages/types/src/agent/pluginConfig.test.ts
index 7b89da3dbca..d338291f15c 100644
--- a/packages/types/src/agent/pluginConfig.test.ts
+++ b/packages/types/src/agent/pluginConfig.test.ts
@@ -3,11 +3,14 @@ import { describe, expect, it } from 'vitest';
import {
getActivePluginIds,
getAutoPluginIds,
+ getConnectorMode,
getDisabledPluginIds,
getLibrarySkillMode,
+ getOptedInPluginIds,
getPinnedPluginIds,
getPluginMode,
parsePluginEntry,
+ upsertConnectorEnabled,
upsertPluginMode,
} from './pluginConfig';
@@ -185,3 +188,48 @@ describe('library skills', () => {
).toEqual(['a']);
});
});
+
+describe('connectors', () => {
+ it('resolves a connector the agent has no entry for as off', () => {
+ expect(getConnectorMode(undefined, 'gmail')).toBe('disabled');
+ expect(getConnectorMode(['other'], 'gmail')).toBe('disabled');
+ });
+
+ it('reads an explicit auto entry as on and a disabled entry as off', () => {
+ expect(getConnectorMode([{ identifier: 'gmail', mode: 'auto' }], 'gmail')).toBe('auto');
+ expect(getConnectorMode([{ identifier: 'gmail', mode: 'disabled' }], 'gmail')).toBe('disabled');
+ });
+
+ it('reads an entry pinned before connectors became two-state as on', () => {
+ expect(getConnectorMode(['gmail'], 'gmail')).toBe('auto');
+ expect(getConnectorMode([{ identifier: 'gmail', mode: 'pinned' }], 'gmail')).toBe('auto');
+ });
+
+ it('collects every identifier that is not disabled as opted in', () => {
+ expect(
+ getOptedInPluginIds([
+ 'a',
+ { identifier: 'b', mode: 'auto' },
+ { identifier: 'c', mode: 'disabled' },
+ { identifier: 'd', mode: 'pinned' },
+ ]),
+ ).toEqual(['a', 'b', 'd']);
+ expect(getOptedInPluginIds(undefined)).toEqual([]);
+ });
+
+ it('turns a connector on with an explicit auto entry and off with a disabled one', () => {
+ expect(upsertConnectorEnabled(['a'], 'gmail', true)).toEqual([
+ 'a',
+ { identifier: 'gmail', mode: 'auto' },
+ ]);
+ expect(upsertConnectorEnabled([{ identifier: 'gmail', mode: 'auto' }], 'gmail', false)).toEqual(
+ [{ identifier: 'gmail', mode: 'disabled' }],
+ );
+ });
+
+ it('rewrites a connector pinned before the two-state switch as auto when turned on again', () => {
+ expect(upsertConnectorEnabled(['gmail'], 'gmail', true)).toEqual([
+ { identifier: 'gmail', mode: 'auto' },
+ ]);
+ });
+});
diff --git a/packages/types/src/agent/pluginConfig.ts b/packages/types/src/agent/pluginConfig.ts
index 806ddc71385..2be0a1a1a7f 100644
--- a/packages/types/src/agent/pluginConfig.ts
+++ b/packages/types/src/agent/pluginConfig.ts
@@ -80,6 +80,31 @@ export const getLibrarySkillMode = (
return entry ? parsePluginEntry(entry).mode : LIBRARY_SKILL_IMPLICIT_MODE;
};
+/**
+ * Connectors — the user's MCP connectors, Composio and LobeHub connections and
+ * installed plugins — are opt-in per agent and have two states. The agent's
+ * profile is where one is turned on, so a connector the agent has no entry for
+ * is off there, exactly like a library skill.
+ */
+export const CONNECTOR_IMPLICIT_MODE: AgentPluginMode = 'disabled';
+
+/** The mode the two-state connector switch writes for "on". */
+export const CONNECTOR_ON_MODE: AgentPluginMode = 'auto';
+
+/**
+ * A connector's state for this agent: `'auto'` (on — the model finds it on
+ * demand) or `'disabled'` (off). A `'pinned'` entry written before connectors
+ * lost that state reads as on, so no stored row needs rewriting.
+ */
+export const getConnectorMode = (
+ plugins: AgentPluginEntry[] | undefined,
+ identifier: string,
+): 'auto' | 'disabled' => {
+ const entry = plugins?.find((item) => parsePluginEntry(item).identifier === identifier);
+ if (!entry) return 'disabled';
+ return parsePluginEntry(entry).mode === 'disabled' ? 'disabled' : 'auto';
+};
+
const getPluginIdsByMode = (
plugins: AgentPluginEntry[] | undefined,
mode: AgentPluginMode,
@@ -103,6 +128,17 @@ export const getAutoPluginIds = (plugins: AgentPluginEntry[] | undefined): strin
export const getDisabledPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
getPluginIdsByMode(plugins, 'disabled');
+/**
+ * Every identifier the agent turned on, pinned or `auto`. This is the opt-in
+ * list for the kinds that are off without an entry — library skills and
+ * connectors ({@link CONNECTOR_IMPLICIT_MODE}).
+ */
+export const getOptedInPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
+ (plugins ?? [])
+ .map((item) => parsePluginEntry(item))
+ .filter((item) => item.mode !== 'disabled')
+ .map((item) => item.identifier);
+
/**
* Pinned identifiers — the drop-in replacement for runtime boundaries that
* used to read `agentConfig?.plugins ?? []` directly as the enabled-tool
@@ -149,3 +185,18 @@ export const upsertPluginMode = (
return list;
};
+
+/**
+ * Writes the two-state connector switch. On is an explicit `auto` entry —
+ * without one the connector is off. Off keeps a `disabled` entry rather than
+ * dropping it, so the connector stays listed on the agent and can be turned
+ * back on; removing it from the agent is `upsertPluginMode(…, 'auto')`.
+ */
+export const upsertConnectorEnabled = (
+ plugins: AgentPluginEntry[] | undefined,
+ identifier: string,
+ enabled: boolean,
+): AgentPluginEntry[] =>
+ enabled
+ ? upsertPluginMode(plugins, identifier, CONNECTOR_ON_MODE, CONNECTOR_IMPLICIT_MODE)
+ : upsertPluginMode(plugins, identifier, 'disabled');
diff --git a/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts b/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts
index eae26f066fd..292e61f685e 100644
--- a/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts
+++ b/src/features/AgentMarketSubmission/useAgentMarketSubmission.ts
@@ -1,4 +1,4 @@
-import { getActivePluginIds, type LobeAgentConfig } from '@lobechat/types';
+import { getOptedInPluginIds, type LobeAgentConfig } from '@lobechat/types';
import { confirmModal, toast } from '@lobehub/ui';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -86,7 +86,9 @@ export const useAgentMarketSubmission = ({ agentId, canSubmit, getPrompt }: Opti
parameters: snapshot.params,
provider: snapshot.provider,
},
- plugins: getActivePluginIds(snapshot.plugins),
+ // Everything turned on, not only what is pinned: a connector is
+ // on through an `auto` entry and has no pinned state.
+ plugins: getOptedInPluginIds(snapshot.plugins),
systemRole: snapshot.systemRole,
},
description: meta.description || '',
diff --git a/src/features/AgentSetting/AgentConnectors/index.tsx b/src/features/AgentSetting/AgentConnectors/index.tsx
index f15ee4688da..4d840993dc6 100644
--- a/src/features/AgentSetting/AgentConnectors/index.tsx
+++ b/src/features/AgentSetting/AgentConnectors/index.tsx
@@ -1,4 +1,4 @@
-import { getActivePluginIds } from '@lobechat/types';
+import { getConnectorMode } from '@lobechat/types';
import { Switch } from '@lobehub/ui';
import { LinkIcon } from 'lucide-react';
import { memo, useEffect } from 'react';
@@ -12,8 +12,8 @@ import { useStore } from '../store';
const AgentConnectors = memo(() => {
const { t } = useTranslation('setting');
- const [userEnabledPlugins, toggleAgentPlugin] = useStore((s) => [
- getActivePluginIds(s.config.plugins),
+ const [agentPlugins, toggleAgentPlugin] = useStore((s) => [
+ s.config.plugins,
s.toggleAgentPlugin,
]);
@@ -38,7 +38,8 @@ const AgentConnectors = memo(() => {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{connectors.map((connector) => {
- const isEnabled = userEnabledPlugins.includes(connector.identifier);
+ // A connector is two-state: on is any entry that is not disabled.
+ const isEnabled = getConnectorMode(agentPlugins, connector.identifier) === 'auto';
const enabledCount = connector.tools.filter((t) => t.permission !== 'disabled').length;
return (
@@ -62,7 +63,7 @@ const AgentConnectors = memo(() => {
<Switch
checked={isEnabled}
size="small"
- onChange={() => toggleAgentPlugin(connector.identifier)}
+ onChange={() => toggleAgentPlugin(connector.identifier, !isEnabled)}
/>
</div>
);
diff --git a/src/features/AgentSkillStore/useAgentComposioConnect.ts b/src/features/AgentSkillStore/useAgentComposioConnect.ts
index 70933abffc4..f2aa29d3f69 100644
--- a/src/features/AgentSkillStore/useAgentComposioConnect.ts
+++ b/src/features/AgentSkillStore/useAgentComposioConnect.ts
@@ -1,6 +1,6 @@
'use client';
-import { upsertPluginMode } from '@lobechat/types';
+import { upsertConnectorEnabled } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import { useCallback, useEffect, useRef, useState } from 'react';
@@ -99,10 +99,10 @@ export const useAgentComposioConnect = ({ agentId, appSlug, identifier, label }:
tools,
});
- // Pin the tool for this agent so the runtime actually resolves it.
+ // Turn the tool on for this agent so the runtime actually resolves it.
const config = agentSelectors.getAgentConfigById(agentId)(useAgentStore.getState());
await updateAgentConfigById(agentId, {
- plugins: upsertPluginMode(config?.plugins, identifier, 'pinned'),
+ plugins: upsertConnectorEnabled(config?.plugins, identifier, true),
});
await fetchAgentConnectors(agentId);
diff --git a/src/features/ChatInput/ActionBar/Token/utils.test.ts b/src/features/ChatInput/ActionBar/Token/utils.test.ts
index 7de3dfe049c..58f2ac102c1 100644
--- a/src/features/ChatInput/ActionBar/Token/utils.test.ts
+++ b/src/features/ChatInput/ActionBar/Token/utils.test.ts
@@ -53,9 +53,7 @@ describe('Token tool utils', () => {
describe('getToolExcludeDefaultToolIds', () => {
it('excludes discovery tools in manual skill mode', () => {
- expect(getToolExcludeDefaultToolIds('manual')).toEqual(
- expect.arrayContaining(['lobe-activator', 'lobe-skill-store']),
- );
+ expect(getToolExcludeDefaultToolIds('manual')).toEqual(['lobe-activator']);
});
it('keeps default tools in auto skill mode', () => {
diff --git a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx
index a5870148a1d..a2e081e8573 100644
--- a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx
@@ -1,3 +1,4 @@
+import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';
import { Checkbox, Flexbox, Icon, Spin, stopPropagation } from '@lobehub/ui';
import { SquareArrowOutUpRight } from 'lucide-react';
import type { ReactNode } from 'react';
@@ -191,20 +192,20 @@ const ComposioServerItem = memo<ComposioServerItemProps>(
// Get plugin ID for this server (use identifier as pluginId)
const pluginId = server ? server.identifier : '';
- const plugins =
- useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins || [];
- const checked = plugins.includes(pluginId);
+ const plugins = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins;
+ // A connector is two-state: on is any entry that is not disabled.
+ const checked = getConnectorMode(plugins, pluginId) === 'auto';
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
// Toggle plugin for the effective agent
const togglePlugin = useCallback(
async (pluginIdToToggle: string) => {
if (!effectiveAgentId) return;
- const currentPlugins = plugins;
- const hasPlugin = currentPlugins.includes(pluginIdToToggle);
- const newPlugins = hasPlugin
- ? currentPlugins.filter((id) => id !== pluginIdToToggle)
- : [...currentPlugins, pluginIdToToggle];
+ // Turning it on writes the explicit entry; turning it off here takes it off the agent.
+ const isOn = getConnectorMode(plugins, pluginIdToToggle) === 'auto';
+ const newPlugins = isOn
+ ? upsertPluginMode(plugins, pluginIdToToggle, 'auto')
+ : upsertConnectorEnabled(plugins, pluginIdToToggle, true);
await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });
},
[effectiveAgentId, plugins, updateAgentConfigById],
diff --git a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
index e236028e385..7dc6975bfb3 100644
--- a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
@@ -1,3 +1,4 @@
+import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';
import { Checkbox, Flexbox, Icon, Spin, stopPropagation } from '@lobehub/ui';
import { SquareArrowOutUpRight } from 'lucide-react';
import type { ReactNode } from 'react';
@@ -153,20 +154,20 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(
);
const pluginId = server ? server.identifier : '';
- const plugins =
- useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins || [];
- const checked = plugins.includes(pluginId);
+ const plugins = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins;
+ // A connector is two-state: on is any entry that is not disabled.
+ const checked = getConnectorMode(plugins, pluginId) === 'auto';
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
// Toggle plugin for the effective agent
const togglePlugin = useCallback(
async (pluginIdToToggle: string) => {
if (!effectiveAgentId) return;
- const currentPlugins = plugins;
- const hasPlugin = currentPlugins.includes(pluginIdToToggle);
- const newPlugins = hasPlugin
- ? currentPlugins.filter((id) => id !== pluginIdToToggle)
- : [...currentPlugins, pluginIdToToggle];
+ // Turning it on writes the explicit entry; turning it off here takes it off the agent.
+ const isOn = getConnectorMode(plugins, pluginIdToToggle) === 'auto';
+ const newPlugins = isOn
+ ? upsertPluginMode(plugins, pluginIdToToggle, 'auto')
+ : upsertConnectorEnabled(plugins, pluginIdToToggle, true);
await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });
},
[effectiveAgentId, plugins, updateAgentConfigById],
@@ -197,10 +198,10 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(
.lobehubSkillServers?.find((s) => s.identifier === provider);
if (latestServer?.status === LobehubSkillStatus.CONNECTED) {
const newPluginId = latestServer.identifier;
- const currentAgentPlugins =
- agentSelectors.getAgentConfigById(effectiveAgentId)(useAgentStore.getState())
- ?.plugins || [];
- const isAlreadyEnabled = currentAgentPlugins.includes(newPluginId);
+ const currentAgentPlugins = agentSelectors.getAgentConfigById(effectiveAgentId)(
+ useAgentStore.getState(),
+ )?.plugins;
+ const isAlreadyEnabled = getConnectorMode(currentAgentPlugins, newPluginId) === 'auto';
if (canEdit && !isAlreadyEnabled) {
console.info('[LobehubSkill] Auto-enabling plugin:', newPluginId);
togglePlugin(newPluginId);
diff --git a/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts b/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts
new file mode 100644
index 00000000000..e71f9248c89
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/useActivationSets.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveImplicitMode } from './librarySkillPolicy';
+import { resolveActivationSets } from './useActivationSets';
+
+const resolve = (rawPlugins: Parameters<typeof resolveActivationSets>[0]['rawPlugins']) =>
+ resolveActivationSets({
+ connectorIds: ['gmail', 'slack', 'linear'],
+ librarySkillIds: ['excalidraw'],
+ // What `getActivePluginIds` yields: the entries that carry a pin.
+ pinnedIds: (rawPlugins ?? []).flatMap((entry) =>
+ typeof entry === 'string' ? [entry] : entry.mode === 'pinned' ? [entry.identifier] : [],
+ ),
+ rawPlugins,
+ });
+
+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(checkedSet.size).toBe(0);
+ });
+
+ it('lists a connector that is on under Auto: neither Pinned nor Disabled', () => {
+ const { checkedSet, disabledIdSet } = resolve([{ identifier: 'gmail', mode: 'auto' }]);
+
+ expect(checkedSet.has('gmail')).toBe(false);
+ expect(disabledIdSet.has('gmail')).toBe(false);
+ });
+
+ it('never lists a connector under Pinned, even one pinned before the two-state switch', () => {
+ const { checkedSet, disabledIdSet } = resolve(['gmail', 'lobe-image-generation']);
+
+ 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);
+ });
+
+ it('keeps an explicitly disabled connector under Disabled', () => {
+ const { disabledIdSet } = resolve([{ identifier: 'slack', mode: 'disabled' }]);
+
+ expect(disabledIdSet.has('slack')).toBe(true);
+ });
+
+ it('writes Auto explicitly for a connector, since no entry means off', () => {
+ const { optInIds } = resolve([]);
+
+ expect(resolveImplicitMode('gmail', optInIds)).toBe('disabled');
+ expect(resolveImplicitMode('lobe-image-generation', optInIds)).toBe('auto');
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts b/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts
new file mode 100644
index 00000000000..27681fd20e0
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/useActivationSets.ts
@@ -0,0 +1,69 @@
+import { type AgentPluginEntry, type AgentPluginMode } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+
+import { getConnectorIdentifiers } from '@/helpers/toolEngineering/connectorActivation';
+import { useToolStore } from '@/store/tool';
+import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';
+
+import { resolveDisabledIds } from './librarySkillPolicy';
+
+/** A connector is two-state: on (found on demand) or off. It cannot be pinned. */
+export const CONNECTOR_MODES: AgentPluginMode[] = ['auto', 'disabled'];
+
+/**
+ * The identifier sets the Tools popover groups its rows by.
+ *
+ * Library skills and connectors are opt-in per agent — the profile is where one
+ * is turned on — so having no entry means Disabled for them, where it means
+ * Auto for a builtin tool or a builtin skill. A connector also has no Pinned
+ * state: an entry pinned before it lost that state reads as on, so it is listed
+ * under Auto rather than Pinned.
+ */
+export const resolveActivationSets = ({
+ connectorIds: connectorIdList,
+ librarySkillIds,
+ pinnedIds,
+ rawPlugins,
+}: {
+ connectorIds: readonly string[];
+ librarySkillIds: readonly string[];
+ /** The agent's pinned identifiers. */
+ pinnedIds: readonly string[];
+ /** The agent's raw `plugins` field, disabled and `auto` entries included. */
+ rawPlugins: AgentPluginEntry[] | undefined;
+}) => {
+ const connectorIds = new Set(connectorIdList);
+ const optInIds = new Set([...librarySkillIds, ...connectorIdList]);
+
+ return {
+ checkedSet: new Set(pinnedIds.filter((id) => !connectorIds.has(id))),
+ connectorIds,
+ disabledIdSet: new Set(resolveDisabledIds(rawPlugins, optInIds)),
+ /** Identifiers that are off without an entry, so Auto must be written explicitly. */
+ optInIds,
+ };
+};
+
+/** {@link resolveActivationSets} over the tool store. */
+export const useActivationSets = (
+ pinnedIds: string[],
+ rawPlugins: AgentPluginEntry[] | undefined,
+) => {
+ const connectorIds = useToolStore(getConnectorIdentifiers, isEqual);
+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
+
+ return useMemo(
+ () =>
+ resolveActivationSets({
+ connectorIds,
+ librarySkillIds: [...marketAgentSkills, ...userAgentSkills].map(
+ (skill) => skill.identifier,
+ ),
+ pinnedIds,
+ rawPlugins,
+ }),
+ [connectorIds, marketAgentSkills, userAgentSkills, pinnedIds, rawPlugins],
+ );
+};
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts
index 64e08c3b167..65447a9add9 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts
@@ -1,6 +1,13 @@
import type { ItemType } from '@lobehub/ui';
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react';
+import { createElement, Fragment } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type ComposioServer, ComposioServerStatus } from '@/store/tool/slices/composioStore/types';
+import {
+ type LobehubSkillServer,
+ LobehubSkillStatus,
+} from '@/store/tool/slices/lobehubSkillStore/types';
import { useControls } from './useControls';
@@ -13,6 +20,10 @@ const mocks = vi.hoisted(() => ({
{ identifier: 'lobehub', name: 'LobeHub' },
],
checked: [] as string[],
+ composioEnabled: false,
+ composioServers: [] as Pick<ComposioServer, 'identifier' | 'status'>[],
+ lobehubEnabled: false,
+ lobehubSkillServers: [] as LobehubSkillServer[],
mode: 'auto',
plugins: [] as { identifier: string; mode: string }[],
skills: [
@@ -59,13 +70,18 @@ vi.mock('@/store/aiInfra', () => ({
useAiInfraStore: (selector: (state: unknown) => unknown) => selector({}),
}));
vi.mock('@/store/serverConfig', () => ({
- serverConfigSelectors: { enableComposio: () => false, enableLobehubSkill: () => false },
+ serverConfigSelectors: {
+ enableComposio: () => mocks.composioEnabled,
+ enableLobehubSkill: () => mocks.lobehubEnabled,
+ },
useServerConfigStore: (selector: (state: unknown) => unknown) => selector({}),
}));
vi.mock('@/store/tool', () => ({
useToolStore: (selector: (state: unknown) => unknown) =>
selector({
+ composioServers: mocks.composioServers,
isConnectorsInit: true,
+ lobehubSkillServers: mocks.lobehubSkillServers,
useFetchAgentSkills: vi.fn(),
useFetchLobehubSkillConnections: vi.fn(),
useFetchUninstalledBuiltinTools: vi.fn(),
@@ -92,8 +108,8 @@ vi.mock('@/store/tool/selectors', () => ({
...mocks.skills,
],
},
- composioStoreSelectors: { getServers: () => [] },
- lobehubSkillStoreSelectors: { getServers: () => [] },
+ composioStoreSelectors: { getServers: () => mocks.composioServers },
+ lobehubSkillStoreSelectors: { getServers: () => mocks.lobehubSkillServers },
pluginSelectors: {
installedPluginMetaList: () => [
{ identifier: 'community-mcp', title: 'Community MCP', type: 'plugin' },
@@ -126,10 +142,93 @@ describe('chat input tool picker', () => {
vi.clearAllMocks();
mocks.agentId = 'agent-1';
mocks.checked = [];
+ mocks.composioEnabled = false;
+ mocks.composioServers = [];
+ mocks.lobehubEnabled = false;
+ mocks.lobehubSkillServers = [];
mocks.plugins = [];
mocks.mode = 'auto';
});
+ afterEach(cleanup);
+
+ it.each([
+ { id: 'gmail', pin: false },
+ { id: 'builtin-tool', pin: true },
+ ])('offers the applicable activation actions on the $id row', async ({ id, pin }) => {
+ mocks.composioEnabled = true;
+ mocks.composioServers = [{ identifier: 'gmail', status: ComposioServerStatus.ACTIVE }];
+ mocks.plugins = [{ identifier: 'gmail', mode: 'auto' }];
+
+ 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);
+ 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(!!screen.queryByRole('button', { name: 'tools.activation.action.pin' })).toBe(pin);
+ });
+
+ it('only shows connectors with connection records and keeps rows needing authorization', () => {
+ mocks.composioEnabled = true;
+ mocks.composioServers = [
+ { identifier: 'gmail', status: ComposioServerStatus.ACTIVE },
+ { identifier: 'slack', status: ComposioServerStatus.ERROR },
+ { identifier: 'airtable', status: ComposioServerStatus.PENDING_AUTH },
+ ];
+ mocks.lobehubEnabled = true;
+ mocks.lobehubSkillServers = [
+ {
+ identifier: 'notion',
+ isConnected: false,
+ name: 'Notion',
+ status: LobehubSkillStatus.NOT_CONNECTED,
+ },
+ {
+ identifier: 'vercel',
+ isConnected: true,
+ name: 'Vercel',
+ status: LobehubSkillStatus.CONNECTED,
+ },
+ ];
+ mocks.plugins = [
+ { identifier: 'gmail', mode: 'auto' },
+ { identifier: 'vercel', mode: 'auto' },
+ { identifier: 'google-drive', mode: 'disabled' },
+ ];
+ 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(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(
+ 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' } }));
+ expect(leafKeys(result.current.marketItems)).toEqual([]);
+ expect(result.current.autoCount).toBe(toolIds.length + 2);
+ });
+
it('offers only tool management in the footer, without an add-tools action', () => {
const { result } = renderHook(() => useControls());
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 32461042982..e6eb2d9ec45 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -1,6 +1,6 @@
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { getConnectorCatalog, RECOMMENDED_SKILLS, RecommendedSkillType } from '@lobechat/const';
+import { getConnectorCatalog } from '@lobechat/const';
import { type AgentPluginMode } from '@lobechat/types';
import type { ItemType } from '@lobehub/ui';
import {
@@ -72,12 +72,13 @@ import {
import ComposioServerItem from './ComposioServerItem';
import ComposioSkillIcon from './ComposioSkillIcon';
import { SKILL_ICON_SIZE } from './constants';
-import { resolveDisabledIds, resolveImplicitMode } from './librarySkillPolicy';
+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 { styles } from './useControls.styles';
import { usePluginRowUninstall } from './usePluginRowUninstall';
@@ -168,23 +169,13 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
s.togglePlugin,
s.setPluginMode,
]);
- const checkedSet = useMemo(() => new Set(checked), [checked]);
- // Disabled identifiers, read from the raw (unfiltered) plugins config —
- // needed to render the dedicated Disabled group and policy-menu state.
const rawPlugins = useAgentStore(
(s) => agentByIdSelectors.getAgentConfigById(agentId)(s)?.plugins,
);
const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
- // Library skills are opt-in per agent: one this agent never turned on is Disabled.
- const librarySkillIds = useMemo(
- () => new Set([...marketAgentSkills, ...userAgentSkills].map((skill) => skill.identifier)),
- [marketAgentSkills, userAgentSkills],
- );
- const disabledIdSet = useMemo(
- () => new Set(resolveDisabledIds(rawPlugins, librarySkillIds)),
- [rawPlugins, librarySkillIds],
- );
+ 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.
@@ -200,10 +191,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
: builtinToolSelectors.metaList,
isEqual,
);
- // Application-fixed tools (always-on, not user-controllable, e.g. lobe-agent).
- // Rendered read-only at the top of the "Pinned" section so users can see what the
- // app keeps active for every conversation. Mode-aware: in manual skill-activate mode the
- // discovery tools the engine strips (activator, skill-store) are dropped from the list.
+ // Default-pinned builtins have their own rows; the activation switch represents the activator.
const fixedDisplayList = useToolStore(
builtinToolSelectors.fixedDisplayMetaList({ isManualMode: isManualSkillMode }),
isEqual,
@@ -251,9 +239,9 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// is what puts the row in the Pinned or Disabled group.
const patch = isCapabilityTool(id) ? resolveCapabilityConfigPatch(id, mode) : undefined;
if (patch) await updateAgentChatConfig(patch);
- await setPluginMode(id, mode, resolveImplicitMode(id, librarySkillIds));
+ await setPluginMode(id, mode, resolveImplicitMode(id, optInIds));
},
- [canEdit, checkedSet, disabledIdSet, librarySkillIds, setPluginMode, updateAgentChatConfig],
+ [canEdit, checkedSet, disabledIdSet, optInIds, setPluginMode, updateAgentChatConfig],
);
const openSkillPolicyMenu = useCallback((id: string) => {
@@ -270,7 +258,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
deleteOnly = false,
modeOverride,
panelExtra,
- supportedModes = ['pinned', 'auto', 'disabled'],
+ supportedModes = connectorIds.has(id) ? CONNECTOR_MODES : CAPABILITY_MODES,
} = options;
const mode: SkillPolicyMode =
modeOverride ??
@@ -448,7 +436,16 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
</Popover>
);
},
- [canEdit, checkedSet, disabledIdSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],
+ [
+ canEdit,
+ checkedSet,
+ connectorIds,
+ disabledIdSet,
+ openSkillPolicyMenu,
+ policyOpenId,
+ t,
+ updateSkillPolicy,
+ ],
);
const renderToolLabel = useCallback(
@@ -587,14 +584,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// Load user's LobeHub Skill connections via SWR
useFetchLobehubSkillConnections(isLobehubSkillEnabled);
- // Get connected server by identifier
- const getServerByName = useCallback(
- (identifier: string) => {
- return allComposioServers.find((server) => server.identifier === identifier);
- },
- [allComposioServers],
- );
-
const connectorCatalog = useMemo(
() =>
getConnectorCatalog({
@@ -628,60 +617,30 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
return list.filter((item) => !allSkillIdentifiers.has(item.identifier));
}, [builtinList, connectorIdentifiers, allSkillIdentifiers]);
- // Get recommended Composio skill IDs
- const recommendedComposioIds = useMemo(
- () =>
- new Set(
- RECOMMENDED_SKILLS.filter((s) => s.type === RecommendedSkillType.Composio).map((s) => s.id),
- ),
- [],
- );
-
- // Get recommended Lobehub skill IDs
- const recommendedLobehubIds = useMemo(
+ // The chat picker lists existing connections, including those that need authorization.
+ const composioConnections = useMemo(
() =>
- new Set(
- RECOMMENDED_SKILLS.filter((s) => s.type === RecommendedSkillType.Lobehub).map((s) => s.id),
- ),
- [],
- );
-
- // Get installed Composio server IDs
- const installedComposioIds = useMemo(
- () => new Set(allComposioServers.map((s) => s.identifier)),
- [allComposioServers],
- );
-
- // Get installed Lobehub skill IDs
- const installedLobehubIds = useMemo(
- () => new Set(allLobehubSkillServers.map((s) => s.identifier)),
- [allLobehubSkillServers],
- );
-
- const visibleComposioTypes = useMemo(
- () =>
- connectorCatalog
- .filter((item) => item.type === 'composio')
- .map(({ serverType }) => serverType)
- .filter(
- (type) =>
- installedComposioIds.has(type.identifier) ||
- recommendedComposioIds.has(type.identifier) ||
- checkedSet.has(type.identifier) ||
- disabledIdSet.has(type.identifier),
- ),
- [connectorCatalog, installedComposioIds, recommendedComposioIds, checkedSet, disabledIdSet],
+ connectorCatalog.flatMap((item) => {
+ if (item.type !== 'composio') return [];
+ const server = allComposioServers.find(
+ (server) => server.identifier === item.serverType.identifier,
+ );
+ return server ? [{ server, type: item.serverType }] : [];
+ }),
+ [connectorCatalog, allComposioServers],
);
- const visibleLobehubProviders = useMemo(
+ const lobehubConnections = useMemo(
() =>
- connectorCatalog
- .filter((item) => item.type === 'lobehub')
- .map(({ provider }) => provider)
- .filter(
- (provider) =>
- installedLobehubIds.has(provider.id) || recommendedLobehubIds.has(provider.id),
- ),
- [connectorCatalog, installedLobehubIds, recommendedLobehubIds],
+ connectorCatalog.flatMap((item) => {
+ if (item.type !== 'lobehub') return [];
+ const server = allLobehubSkillServers.find(
+ (server) => server.identifier === item.provider.id,
+ );
+ // A status probe can cache a provider even when there is no connection.
+ if (!server || server.status === LobehubSkillStatus.NOT_CONNECTED) return [];
+ return [{ provider: item.provider, server }];
+ }),
+ [connectorCatalog, allLobehubSkillServers],
);
// Remove a Composio connection AND drop its identifier from the agent's
@@ -704,15 +663,10 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
[removeComposioConnection, togglePlugin],
);
- // Composio server list items - show installed, recommended, or any id that
- // still lingers in the agent's plugins (so an orphaned, never-authorized
- // entry can be removed even when it isn't a recommended app). "Lingers"
- // means present at all — pinned or disabled, not just pinned.
const composioServerItems = useMemo(
() =>
isComposioEnabledInEnv
- ? visibleComposioTypes.map((type) => {
- const server = getServerByName(type.identifier);
+ ? composioConnections.map(({ server, type }) => {
const icon = (
<ComposioSkillIcon icon={type.icon} label={type.label} size={SKILL_ICON_SIZE} />
);
@@ -728,7 +682,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
/>
);
- if (server?.status === ComposioServerStatus.ACTIVE) {
+ if (server.status === ComposioServerStatus.ACTIVE) {
return createManagedSkillItem({
badge: <Icon icon={McpIcon} size={12} />,
deleteConfig: {
@@ -744,80 +698,55 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
});
}
- const serverItem = (
- <ComposioServerItem
- agentId={agentId}
- appSlug={type.appSlug}
- icon={icon}
- identifier={type.identifier}
- label={type.label}
- server={server}
- />
- );
-
- // Expose a delete-only menu (via the "..." button and right-click)
- // whenever the entry is removable but not yet connected, while
- // keeping the Connect/Re-authorize action. This covers two states:
- // - a server exists but isn't ACTIVE (pending auth / re-authorize)
- // - no server yet, but the id already lingers in the agent's
- // plugins (added optimistically, never authorized)
- // so an accidental or failed authorization can always be cleaned up.
- const removableId = server?.identifier ?? type.identifier;
- if (server || checkedSet.has(type.identifier) || disabledIdSet.has(type.identifier)) {
- return {
- extra: renderPolicyMenu(removableId, {
- deleteConfig: {
- displayName: type.label,
- onDelete: () => removeComposioServer(removableId),
- },
- deleteOnly: true,
- }),
- key: removableId,
- label: (
- <span
- onContextMenu={(event) => {
- event.preventDefault();
- event.stopPropagation();
- openSkillPolicyMenu(removableId);
- }}
- >
- {serverItem}
- </span>
- ),
- popoverContent,
- searchText: `${type.label} ${removableId}`,
- } as SkillMenuItem;
- }
-
+ // Keep the reauthorization action and deletion available on unfinished connections.
return {
- key: type.identifier,
- label: serverItem,
+ extra: renderPolicyMenu(server.identifier, {
+ deleteConfig: {
+ displayName: type.label,
+ onDelete: () => removeComposioServer(server.identifier),
+ },
+ deleteOnly: true,
+ }),
+ key: server.identifier,
+ label: (
+ <span
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openSkillPolicyMenu(server.identifier);
+ }}
+ >
+ <ComposioServerItem
+ agentId={agentId}
+ appSlug={type.appSlug}
+ icon={icon}
+ identifier={type.identifier}
+ label={type.label}
+ server={server}
+ />
+ </span>
+ ),
popoverContent,
- searchText: type.label,
+ searchText: `${type.label} ${server.identifier}`,
} as SkillMenuItem;
})
: [],
[
isComposioEnabledInEnv,
- visibleComposioTypes,
+ composioConnections,
agentId,
t,
createManagedSkillItem,
- getServerByName,
removeComposioServer,
renderPolicyMenu,
openSkillPolicyMenu,
- checkedSet,
- disabledIdSet,
],
);
- // LobeHub Skill Provider list items - only show installed or recommended
const lobehubSkillItems = useMemo(
() =>
isLobehubSkillEnabled
- ? visibleLobehubProviders.map((provider) => {
- const server = allLobehubSkillServers.find((s) => s.identifier === provider.id);
+ ? lobehubConnections.map(({ provider, server }) => {
const icon = (
<LobehubSkillIcon
icon={provider.icon}
@@ -837,7 +766,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
/>
);
- if (server?.status === LobehubSkillStatus.CONNECTED || server?.isConnected) {
+ if (server.status === LobehubSkillStatus.CONNECTED || server.isConnected) {
return createManagedSkillItem({
badge: <Icon icon={McpIcon} size={12} />,
extraTag: provider.author === 'LobeHub' ? officialTag : undefined,
@@ -864,14 +793,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
};
})
: [],
- [
- isLobehubSkillEnabled,
- visibleLobehubProviders,
- allLobehubSkillServers,
- agentId,
- t,
- createManagedSkillItem,
- ],
+ [isLobehubSkillEnabled, lobehubConnections, agentId, t, createManagedSkillItem],
);
// Builtin tool list items (excluding Composio and LobeHub Skill)
@@ -1088,41 +1010,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
[customConnectors, t, createManagedSkillItem, deleteConnector, getConfigure, togglePlugin],
);
- // Skills list items (including LobeHub Skill and Composio)
- // Connected items listed first, deduplicated by key (LobeHub takes priority)
- const skillItems = useMemo(() => {
- // Deduplicate by key - LobeHub items take priority over Composio
- const seenKeys = new Set<string>();
- const allItems: typeof lobehubSkillItems = [];
-
- // Add LobeHub items first (they take priority)
- for (const item of lobehubSkillItems) {
- if (!seenKeys.has(item.key as string)) {
- seenKeys.add(item.key as string);
- allItems.push(item);
- }
- }
-
- // Add Composio items only if not already present
- for (const item of composioServerItems) {
- if (!seenKeys.has(item.key as string)) {
- seenKeys.add(item.key as string);
- allItems.push(item);
- }
- }
-
- return allItems.sort((a, b) => {
- const isConnectedA =
- installedLobehubIds.has(a.key as string) || installedComposioIds.has(a.key as string);
- const isConnectedB =
- installedLobehubIds.has(b.key as string) || installedComposioIds.has(b.key as string);
-
- if (isConnectedA && !isConnectedB) return -1;
- if (!isConnectedA && isConnectedB) return 1;
- return 0;
- });
- }, [lobehubSkillItems, composioServerItems, installedLobehubIds, installedComposioIds]);
-
// Distinguish community plugins and custom plugins.
// Whitelist `type === 'plugin'` (matching /settings/skill) so connected
// integrations (Composio/LobeHub Skill gateway plugins with other sources like
@@ -1191,7 +1078,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
};
// Only builtin tools and service integrations belong in this activation picker.
- const lobehubGroupChildren: ItemType[] = [...builtinItems, ...skillItems];
+ const lobehubGroupChildren: ItemType[] = [
+ ...builtinItems,
+ ...lobehubSkillItems,
+ ...composioServerItems,
+ ];
// User-installed skills are selected in the Skills panel, not enabled here.
const communityGroupChildren: ItemType[] = communityPlugins.map(mapPluginToItem);
@@ -1203,11 +1094,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
];
const normalizedSearchKeyword = searchKeyword.trim().toLowerCase();
- // Deduplicate by key: the same app can be sourced from more than one list
- // (e.g. a Composio/LobeHub integration item plus an installed plugin sharing
- // the same identifier), which would otherwise render the row twice. Keep the
- // first occurrence so the richer integration item (LobeHub group, listed
- // first) wins over a generic plugin duplicate.
+ // Keep the richer integration row ahead of any installed plugin with the same identifier.
const seenSkillKeys = new Set<string>();
const allSkillItems = [
...lobehubGroupChildren,
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index 83578fe8fc1..96a036ba0c3 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -1,7 +1,7 @@
'use client';
import { getConnectorCatalog } from '@lobechat/const';
-import { getActivePluginIds, parsePluginEntry, upsertPluginMode } from '@lobechat/types';
+import { parsePluginEntry, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';
import type { ItemType } from '@lobehub/ui';
import { Avatar, Button, cssVar, Flexbox, Icon } from '@lobehub/ui';
import { McpIcon, SkillsIcon } from '@lobehub/ui/icons';
@@ -23,6 +23,7 @@ import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';
import ToolItemDetailPopover from '@/features/ChatInput/ActionBar/Tools/ToolItemDetailPopover';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { createSkillStoreModal } from '@/features/SkillStore';
+import { getConnectorIdentifiers } from '@/helpers/toolEngineering/connectorActivation';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
@@ -130,12 +131,11 @@ const AgentTool = memo<AgentToolProps>(
isPrivateAgent ? undefined : effectiveAgentId || undefined,
);
- // Plugin state management — pinned identifiers only (a disabled entry
- // is a distinct, valid config state; this component has no tri-state UI
- // and treats it as "not enabled", matching pre-tri-state semantics).
- const plugins = getActivePluginIds(config?.plugins);
- // Everything switched on for this agent: pinned entries, plus a library skill set to Auto
- // from the chat input — the only kind of entry that carries an explicit `auto`.
+ // A connector is two-state: this page turns it on (found on demand) or off, never pinned.
+ const connectorIdList = useToolStore(getConnectorIdentifiers, isEqual);
+ const connectorIds = useMemo(() => new Set(connectorIdList), [connectorIdList]);
+ // Everything switched on for this agent: pinned entries, plus the entries that carry an
+ // explicit `auto` — a connector turned on here, a library skill set to Auto in the chat input.
const enabledIds = useMemo(
() =>
new Set(
@@ -258,14 +258,17 @@ const AgentTool = memo<AgentToolProps>(
);
if (shouldEnable ? hasPlugin : !hasEntry) return;
- // upsertPluginMode operates on the raw (possibly mixed-shape) config
- // — not the pinned-only `plugins` above — so an existing disabled
- // entry is flipped in place instead of being dropped from the array.
+ // upsertPluginMode operates on the raw (possibly mixed-shape) config,
+ // so an existing disabled entry is flipped in place instead of being
+ // dropped from the array.
await updateAgentConfigById(effectiveAgentId, {
- plugins: upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),
+ plugins:
+ shouldEnable && connectorIds.has(pluginId)
+ ? upsertConnectorEnabled(config?.plugins, pluginId, true)
+ : upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),
});
},
- [canEdit, effectiveAgentId, enabledIds, config?.plugins, updateAgentConfigById],
+ [canEdit, effectiveAgentId, enabledIds, connectorIds, config?.plugins, updateAgentConfigById],
);
// Check if a profile-managed tool is on for this agent.
@@ -636,7 +639,7 @@ const AgentTool = memo<AgentToolProps>(
key: item.identifier,
label: (
<ToolItem
- checked={plugins.includes(item.identifier)}
+ checked={enabledIds.has(item.identifier)}
id={item.identifier}
label={item.title}
onUpdate={async () => {
@@ -668,7 +671,7 @@ const AgentTool = memo<AgentToolProps>(
),
};
},
- [plugins, togglePlugin, t],
+ [enabledIds, togglePlugin, t],
);
// Community plugin list items
@@ -698,7 +701,7 @@ const AgentTool = memo<AgentToolProps>(
key: connector.identifier,
label: (
<ToolItem
- checked={plugins.includes(connector.identifier)}
+ checked={enabledIds.has(connector.identifier)}
id={connector.identifier}
label={connector.name || connector.identifier}
onUpdate={async () => {
@@ -719,7 +722,7 @@ const AgentTool = memo<AgentToolProps>(
),
};
}),
- [customConnectors, plugins, togglePlugin, t],
+ [customConnectors, enabledIds, togglePlugin, t],
);
// Custom group children (User Agent Skills + custom plugins + custom connectors)
@@ -853,14 +856,14 @@ const AgentTool = memo<AgentToolProps>(
// managed entries remain untouched in config for compatibility with other
// flows, but do not inflate this section's count or render misleading chips.
const allEnabledTools = useMemo(() => {
- const visible = getVisibleProfileToolIds(plugins, {
+ const visible = getVisibleProfileToolIds([...enabledIds], {
agentConnectorIdentifiers,
nonConfigurableBuiltinToolIdentifiers: nonProfileConfigurableBuiltinToolIdentifiers,
});
if (kind === 'all') return visible;
return visible.filter((id) => allSkillIdentifiers.has(id) === (kind === 'skills'));
}, [
- plugins,
+ enabledIds,
agentConnectorIdentifiers,
nonProfileConfigurableBuiltinToolIdentifiers,
kind,
@@ -902,7 +905,9 @@ const AgentTool = memo<AgentToolProps>(
const setPluginEnabled = (pluginId: string, enabled: boolean) => {
if (!canEdit || !effectiveAgentId) return;
return updateAgentConfigById(effectiveAgentId, {
- plugins: upsertPluginMode(config?.plugins, pluginId, enabled ? 'pinned' : 'disabled'),
+ plugins: connectorIds.has(pluginId)
+ ? upsertConnectorEnabled(config?.plugins, pluginId, enabled)
+ : upsertPluginMode(config?.plugins, pluginId, enabled ? 'pinned' : 'disabled'),
});
};
diff --git a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx
index b64e95adb32..a22ac0e0c04 100644
--- a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx
@@ -1,6 +1,6 @@
'use client';
-import { getPluginMode, upsertPluginMode } from '@lobechat/types';
+import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';
import { Button, confirmModal, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { CopyIcon, PlugZapIcon, PlusIcon } from 'lucide-react';
@@ -93,7 +93,7 @@ const AgentToolsSection = memo<{
const agentPlugins = useAgentStore((s) => agentSelectors.getAgentConfigById(agentId)(s)?.plugins);
const setEnabled = (identifier: string, enabled: boolean) =>
updateAgentConfigById(agentId, {
- plugins: upsertPluginMode(agentPlugins, identifier, enabled ? 'pinned' : 'disabled'),
+ plugins: upsertConnectorEnabled(agentPlugins, identifier, enabled),
});
const tags = agentConnectors.map((connector) => {
@@ -109,7 +109,7 @@ const AgentToolsSection = memo<{
<PluginTag
agentId={agentId}
disabled={!canEdit}
- enabled={getPluginMode(agentPlugins, connector.identifier) !== 'disabled'}
+ enabled={getConnectorMode(agentPlugins, connector.identifier) === 'auto'}
key={connector.id}
pluginId={connector.identifier}
removable={canManageRow}
@@ -133,7 +133,7 @@ const AgentToolsSection = memo<{
rows={tags}
activeCount={
agentConnectors.filter(
- (connector) => getPluginMode(agentPlugins, connector.identifier) !== 'disabled',
+ (connector) => getConnectorMode(agentPlugins, connector.identifier) === 'auto',
).length
}
/>
diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx
index 4e9900e493c..b1804637d33 100644
--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx
@@ -128,45 +128,35 @@ describe('UserToolsSection — Workspace/User tool count', () => {
expect(labelText()).toContain('· 1');
});
- it('does not count Web Browsing even when a legacy plugin entry is pinned', () => {
+ it('counts a connector turned on with an auto entry and leaves out one turned off', () => {
+ // A connector is two-state: on is an explicit `auto` entry, never a pin.
mocks.agentConfig = {
plugins: [
- { identifier: 'lobe-web-browsing', mode: 'pinned' },
- { identifier: 'some-user-plugin', mode: 'pinned' },
+ { identifier: 'gmail', mode: 'auto' },
+ { identifier: 'slack', mode: 'disabled' },
],
};
- mocks.toolState.builtinTools = [
- {
- hidden: true,
- identifier: 'lobe-web-browsing',
- manifest: {
- api: [],
- identifier: 'lobe-web-browsing',
- meta: { title: 'Web Browsing' },
- systemRole: '',
- },
- type: 'builtin',
- },
- ];
renderSection();
expect(labelText()).toContain('· 1');
});
- it('does not count pinned Skill Store in auto activation mode', () => {
+ it('does not count Web Browsing even when a legacy plugin entry is pinned', () => {
mocks.agentConfig = {
- chatConfig: { skillActivateMode: 'auto' },
- plugins: [{ identifier: 'lobe-skill-store', mode: 'pinned' }],
+ plugins: [
+ { identifier: 'lobe-web-browsing', mode: 'pinned' },
+ { identifier: 'some-user-plugin', mode: 'pinned' },
+ ],
};
mocks.toolState.builtinTools = [
{
hidden: true,
- identifier: 'lobe-skill-store',
+ identifier: 'lobe-web-browsing',
manifest: {
api: [],
- identifier: 'lobe-skill-store',
- meta: { title: 'Skill Store' },
+ identifier: 'lobe-web-browsing',
+ meta: { title: 'Web Browsing' },
systemRole: '',
},
type: 'builtin',
@@ -175,30 +165,33 @@ describe('UserToolsSection — Workspace/User tool count', () => {
renderSection();
- expect(labelText()).toContain('· 0');
+ expect(labelText()).toContain('· 1');
});
- it('counts pinned Skill Store in manual activation mode', () => {
- mocks.agentConfig = {
- chatConfig: { skillActivateMode: 'manual' },
- plugins: [{ identifier: 'lobe-skill-store', mode: 'pinned' }],
- };
- mocks.toolState.builtinTools = [
- {
- hidden: true,
- identifier: 'lobe-skill-store',
- manifest: {
- api: [],
+ it.each(['auto', 'manual'] as const)(
+ 'counts a pinned Skill Store in %s mode',
+ (skillActivateMode) => {
+ mocks.agentConfig = {
+ chatConfig: { skillActivateMode },
+ plugins: [{ identifier: 'lobe-skill-store', mode: 'pinned' }],
+ };
+ mocks.toolState.builtinTools = [
+ {
+ hidden: true,
identifier: 'lobe-skill-store',
- meta: { title: 'Skill Store' },
- systemRole: '',
+ manifest: {
+ api: [],
+ identifier: 'lobe-skill-store',
+ meta: { title: 'Skill Store' },
+ systemRole: '',
+ },
+ type: 'builtin',
},
- type: 'builtin',
- },
- ];
+ ];
- renderSection();
+ renderSection();
- expect(labelText()).toContain('· 1');
- });
+ expect(labelText()).toContain('· 1');
+ },
+ );
});
diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx
index 4e8e4b7d49b..42895a59159 100644
--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx
@@ -1,6 +1,6 @@
'use client';
-import { getActivePluginIds } from '@lobechat/types';
+import { getOptedInPluginIds } from '@lobechat/types';
import { Button, Flexbox, Text } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { memo, useMemo } from 'react';
@@ -69,7 +69,7 @@ const UserToolsSection = memo<Props>(
() => new Set(nonProfileConfigurableBuiltinToolIds),
[nonProfileConfigurableBuiltinToolIds],
);
- const userToolCount = getVisibleProfileToolIds(getActivePluginIds(config?.plugins), {
+ const userToolCount = getVisibleProfileToolIds(getOptedInPluginIds(config?.plugins), {
agentConnectorIdentifiers,
nonConfigurableBuiltinToolIdentifiers: nonProfileConfigurableBuiltinToolIdentifiers,
}).length;
diff --git a/src/features/ProfileEditor/AgentUserTools/index.tsx b/src/features/ProfileEditor/AgentUserTools/index.tsx
index e7a05d062fd..04b63604afc 100644
--- a/src/features/ProfileEditor/AgentUserTools/index.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { upsertPluginMode } from '@lobechat/types';
+import { upsertConnectorEnabled } from '@lobechat/types';
import { Button, Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { memo, useEffect, useState } from 'react';
@@ -70,14 +70,14 @@ const AgentUserTools = memo<AgentToolProps & { variant?: 'chip' | 'list' }>((pro
await copyConnectorToAgent(id, effectiveAgentId);
identifiers.push(conn.identifier);
}
- // Pin the copied tools for the agent so the runtime resolves them.
+ // Turn the copied tools on for the agent so the runtime resolves them.
if (identifiers.length > 0) {
const config = agentSelectors.getAgentConfigById(effectiveAgentId)(
useAgentStore.getState(),
);
let plugins = config?.plugins;
for (const identifier of identifiers)
- plugins = upsertPluginMode(plugins, identifier, 'pinned');
+ plugins = upsertConnectorEnabled(plugins, identifier, true);
await updateAgentConfigById(effectiveAgentId, { plugins });
}
resetCopy();
diff --git a/src/helpers/toolEngineering/connectorActivation.test.ts b/src/helpers/toolEngineering/connectorActivation.test.ts
new file mode 100644
index 00000000000..ccde67f33ba
--- /dev/null
+++ b/src/helpers/toolEngineering/connectorActivation.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ToolStoreState } from '@/store/tool/initialState';
+
+import {
+ applyAgentConnectorActivation,
+ getConnectorIdentifiers,
+ resolveAgentConnectorActivation,
+} from './connectorActivation';
+
+const toolState = {
+ agentConnectors: { 'agent-1': [{ identifier: 'agent-only-mcp' }] },
+ agentSkillListMap: { all: [{ identifier: 'library-skill' }] },
+ builtinSkills: [{ identifier: 'builtin-skill' }],
+ builtinTools: [{ identifier: 'lobe-image-generation' }],
+ composioServers: [{ identifier: 'gmail' }],
+ connectors: [{ identifier: 'custom-mcp' }, { identifier: 'lobe-image-generation' }],
+ installedPlugins: [{ identifier: 'community-mcp' }, { identifier: 'library-skill' }],
+ lobehubSkillServers: [{ identifier: 'linear' }],
+} as unknown as ToolStoreState;
+
+describe('getConnectorIdentifiers', () => {
+ it('collects every connector source and leaves builtin tools and skills out', () => {
+ expect(getConnectorIdentifiers(toolState).sort()).toEqual([
+ 'agent-only-mcp',
+ 'community-mcp',
+ 'custom-mcp',
+ 'gmail',
+ 'linear',
+ ]);
+ });
+});
+
+describe('resolveAgentConnectorActivation', () => {
+ it('turns every connector off for an agent that has no entry for it', () => {
+ const { offIds } = resolveAgentConnectorActivation({ plugins: [] }, [], toolState);
+
+ expect(offIds.sort()).toEqual([
+ 'agent-only-mcp',
+ 'community-mcp',
+ 'custom-mcp',
+ 'gmail',
+ 'linear',
+ ]);
+ });
+
+ it('keeps a connector on for an auto entry and for one pinned before the switch', () => {
+ const { offIds } = resolveAgentConnectorActivation(
+ {
+ plugins: [
+ 'gmail',
+ { identifier: 'linear', mode: 'auto' },
+ { identifier: 'custom-mcp', mode: 'disabled' },
+ ],
+ },
+ [],
+ toolState,
+ );
+
+ expect(offIds).not.toContain('gmail');
+ expect(offIds).not.toContain('linear');
+ expect(offIds).toContain('custom-mcp');
+ });
+
+ it('keeps a connector the turn mentions reachable even when it is off', () => {
+ const { offIds } = resolveAgentConnectorActivation({ plugins: [] }, ['custom-mcp'], toolState);
+
+ expect(offIds).not.toContain('custom-mcp');
+ });
+});
+
+describe('applyAgentConnectorActivation', () => {
+ it('leaves a connector that is on to the activator and keeps pinned tools and skills', () => {
+ const connectors = resolveAgentConnectorActivation(
+ { plugins: ['gmail', 'lobe-image-generation', 'library-skill'] },
+ [],
+ toolState,
+ );
+
+ expect(
+ applyAgentConnectorActivation(
+ ['gmail', 'lobe-image-generation', 'library-skill'],
+ connectors,
+ ),
+ ).toEqual(['lobe-image-generation', 'library-skill']);
+ });
+
+ it('invokes a connector that is on directly in manual mode', () => {
+ const connectors = resolveAgentConnectorActivation(
+ {
+ chatConfig: { skillActivateMode: 'manual' },
+ plugins: [{ identifier: 'linear', mode: 'auto' }],
+ },
+ [],
+ toolState,
+ );
+
+ expect(applyAgentConnectorActivation([], connectors)).toEqual(['linear']);
+ });
+
+ it('keeps a connector this turn mentions', () => {
+ const connectors = resolveAgentConnectorActivation({ plugins: [] }, ['custom-mcp'], toolState);
+
+ expect(applyAgentConnectorActivation(['custom-mcp'], connectors)).toEqual(['custom-mcp']);
+ });
+});
diff --git a/src/helpers/toolEngineering/connectorActivation.ts b/src/helpers/toolEngineering/connectorActivation.ts
new file mode 100644
index 00000000000..c397e049e62
--- /dev/null
+++ b/src/helpers/toolEngineering/connectorActivation.ts
@@ -0,0 +1,95 @@
+import {
+ applyConnectorActivation,
+ type ConnectorActivation,
+ hasConnectorActivator,
+ resolveConnectorActivation,
+} from '@lobechat/mecha';
+import {
+ type AgentPluginEntry,
+ getActivePluginIds,
+ getDisabledPluginIds,
+ getOptedInPluginIds,
+} from '@lobechat/types';
+
+import { getToolStoreState } from '@/store/tool';
+import type { ToolStoreState } from '@/store/tool/initialState';
+import { agentSkillsSelectors } from '@/store/tool/slices/agentSkills/selectors';
+import type { LobeAgentChatConfig } from '@/types/agent';
+
+/**
+ * Every identifier the browser knows as a connector: MCP connectors, Composio
+ * and LobeHub connections, installed plugins. A builtin tool or a skill that
+ * shares a row with one of those sources is not a connector — it keeps its own
+ * three-state policy.
+ */
+export const getConnectorIdentifiers = (s: ToolStoreState = getToolStoreState()): string[] => {
+ const notConnectors = new Set([
+ ...(s.builtinTools || []).map((tool) => tool.identifier),
+ ...(s.builtinSkills || []).map((skill) => skill.identifier),
+ ...agentSkillsSelectors.getAgentSkills(s).map((skill) => skill.identifier),
+ ]);
+
+ return [
+ ...new Set([
+ ...(s.connectors ?? []).map((connector) => connector.identifier),
+ ...Object.values(s.agentConnectors ?? {}).flatMap((connectors) =>
+ connectors.map((connector) => connector.identifier),
+ ),
+ ...(s.installedPlugins || []).map((plugin) => plugin.identifier),
+ ...(s.composioServers || []).map((server) => server.identifier),
+ ...(s.lobehubSkillServers || []).map((server) => server.identifier),
+ ]),
+ ].filter((identifier) => !notConnectors.has(identifier));
+};
+
+export interface AgentConnectorActivation {
+ activation: ConnectorActivation;
+ connectorIds: string[];
+ /** Connectors the agent has off: they leave every pool the run reads. */
+ offIds: string[];
+}
+
+/**
+ * The connector rule (`resolveConnectorActivation`) over the browser's stores:
+ * a connector is on only when the agent's `plugins` carries an entry for it
+ * that is not disabled.
+ */
+export const resolveAgentConnectorActivation = (
+ agent: {
+ chatConfig?: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'skillActivateMode' | 'toolMode'>;
+ enabledPluginIds?: readonly string[];
+ /** The raw `plugins` field, before it is collapsed to pinned identifiers. */
+ plugins?: AgentPluginEntry[];
+ },
+ /** Identifiers this turn brings in by itself (an @-mention, a runtime addition). */
+ turnIds: readonly string[] = [],
+ toolState: ToolStoreState = getToolStoreState(),
+): AgentConnectorActivation => {
+ const activation = resolveConnectorActivation({
+ hasActivator: hasConnectorActivator(
+ agent.chatConfig,
+ [...(agent.enabledPluginIds ?? getActivePluginIds(agent.plugins)), ...turnIds],
+ getDisabledPluginIds(agent.plugins),
+ ),
+ optedInIds: getOptedInPluginIds(agent.plugins),
+ turnIds,
+ });
+ const connectorIds = getConnectorIdentifiers(toolState);
+
+ return {
+ activation,
+ connectorIds,
+ offIds: connectorIds.filter((identifier) => !activation.isAllowed(identifier)),
+ };
+};
+
+/**
+ * The invocation candidates once the connector rule is applied: a connector
+ * that is on leaves them (the activator finds it) unless the turn brings it in
+ * or the run has no activator. Builtin tools and skills are left as listed.
+ */
+export const applyAgentConnectorActivation = (
+ candidateIds: readonly string[],
+ connectors: AgentConnectorActivation,
+): string[] =>
+ applyConnectorActivation(candidateIds, connectors.connectorIds, connectors.activation);
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index cc93ed9410a..020a1a2c389 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -4,7 +4,7 @@ import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import { WebhookManifest } from '@lobechat/builtin-tool-webhook';
import type * as ConstModule from '@lobechat/const';
import { type ToolManifest } from '@lobechat/types';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createAgentToolsEngine, createToolsEngine, getEnabledTools } from './index';
@@ -23,6 +23,13 @@ afterEach(() => {
vi.mock('@/store/tool', () => ({
getToolStoreState: () => ({
connectors: [],
+ // The rows behind `installedPluginManifestList`: an installed plugin is a
+ // connector, so the agent's on/off switch applies to it.
+ get installedPlugins() {
+ return mockInstalledPluginManifestList().map((manifest) => ({
+ identifier: manifest.identifier,
+ }));
+ },
builtinTools: [
{ identifier: AuvManifest.identifier, manifest: AuvManifest, type: 'builtin' as const },
{
@@ -213,7 +220,14 @@ vi.mock('../isCanUseFC', () => ({
let mockCurrentAgentPlugins: string[] = [];
let mockCurrentAgentDisabledPlugins: string[] = [];
-let mockCurrentChatConfig: { enableAgentMode?: boolean; memory?: { enabled?: boolean } } = {};
+/** Explicit `auto` entries: what turns a connector on without pinning it. */
+let mockCurrentAgentAutoPlugins: string[] = [];
+let mockCurrentChatConfig: {
+ enableAgentMode?: boolean;
+ memory?: { enabled?: boolean };
+ skillActivateMode?: 'auto' | 'manual';
+ toolMode?: 'agent' | 'chat' | 'custom';
+} = {};
let mockImageOutputSupport = false;
vi.mock('@/store/agent', () => ({
@@ -222,6 +236,13 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
+ currentAgentConfig: () => ({
+ plugins: [
+ ...mockCurrentAgentPlugins,
+ ...mockCurrentAgentAutoPlugins.map((identifier) => ({ identifier, mode: 'auto' })),
+ ...mockCurrentAgentDisabledPlugins.map((identifier) => ({ identifier, mode: 'disabled' })),
+ ],
+ }),
currentAgentDisabledPlugins: () => mockCurrentAgentDisabledPlugins,
currentAgentPlugins: () => mockCurrentAgentPlugins,
hasEnabledKnowledgeBases: () => false,
@@ -271,6 +292,7 @@ describe('toolEngineering', () => {
mockUseApplicationBuiltinSearchTool = true;
mockCurrentAgentPlugins = [];
mockCurrentAgentDisabledPlugins = [];
+ mockCurrentAgentAutoPlugins = [];
mockIsCanUseFC = true;
mockCurrentChatConfig = {};
mockImageOutputSupport = false;
@@ -558,9 +580,7 @@ describe('toolEngineering', () => {
provider: 'openai',
});
- // lobe-agent is always-on (alwaysOnToolIds), so it rides along with user tools.
- expect(result.enabledToolIds).toEqual(['search', 'lobe-web-browsing', 'lobe-agent']);
- expect(result.enabledToolIds).toHaveLength(3);
+ expect(result.enabledToolIds).toEqual(['search', 'lobe-web-browsing']);
});
it('should enable lobe-agent when it is injected into runtime plugin ids', () => {
@@ -594,36 +614,25 @@ describe('toolEngineering', () => {
expect(result.enabledToolIds.includes('lobe-attachments')).toBe(flag);
});
- it('should enable lobe-agent by default since it is always-on', () => {
- const toolsEngine = createAgentToolsEngine({
- model: 'deepseek-chat',
- provider: 'deepseek',
- });
-
- const result = toolsEngine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
+ it('makes Lobe Agent callable after discovery and honors an explicit disable', () => {
+ const model = { model: 'deepseek-chat', provider: 'deepseek' };
+ const activation = {
+ ...model,
+ context: { isExplicitActivation: true },
+ skipDefaultTools: true,
+ toolIds: ['lobe-agent'],
+ };
+ const engine = createAgentToolsEngine(model);
- expect(result.enabledToolIds).toContain('lobe-agent');
- });
+ expect(engine.generateToolsDetailed({ ...model, toolIds: [] }).enabledToolIds).not.toContain(
+ 'lobe-agent',
+ );
+ expect(engine.generateToolsDetailed(activation).enabledToolIds).toEqual(['lobe-agent']);
- it('should honor an explicit disabled policy for an always-on builtin tool', () => {
mockCurrentAgentDisabledPlugins = ['lobe-agent'];
-
- const toolsEngine = createAgentToolsEngine({
- model: 'deepseek-chat',
- provider: 'deepseek',
- });
-
- const result = toolsEngine.generateToolsDetailed({
- model: 'deepseek-chat',
- provider: 'deepseek',
- toolIds: [],
- });
-
- expect(result.enabledToolIds).not.toContain('lobe-agent');
+ expect(
+ createAgentToolsEngine(model).generateToolsDetailed(activation).enabledToolIds,
+ ).toEqual([]);
});
it('should keep agent-mode defaults and mark every tool incompatible when the model cannot call functions', () => {
@@ -838,10 +847,12 @@ describe('toolEngineering', () => {
id === 'http-mcp-plugin'
? { customParams: { mcp: { type: 'http' } }, identifier: id }
: undefined;
- mockCurrentAgentPlugins = ['http-mcp-plugin'];
+ mockCurrentAgentAutoPlugins = ['http-mcp-plugin'];
const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
const result = toolsEngine.generateToolsDetailed({
+ // A connector that is on is found through the activator.
+ context: { isExplicitActivation: true },
toolIds: ['http-mcp-plugin'],
model: 'gpt-4',
provider: 'openai',
@@ -851,6 +862,113 @@ describe('toolEngineering', () => {
});
});
+ describe('connectors are opt-in per agent', () => {
+ const connectorManifest = {
+ api: [
+ {
+ description: 'Run the tool',
+ name: 'run',
+ parameters: { properties: {}, required: [], type: 'object' },
+ },
+ ],
+ identifier: 'gmail-mcp',
+ meta: { title: 'Gmail MCP' },
+ type: 'default',
+ } as unknown as ToolManifest;
+
+ const generate = (
+ options: { explicit?: boolean; pluginIds?: string[]; toolIds?: string[] } = {},
+ ) =>
+ createAgentToolsEngine(
+ { model: 'gpt-4', provider: 'openai' },
+ options.pluginIds,
+ ).generateToolsDetailed({
+ context: options.explicit ? { isExplicitActivation: true } : undefined,
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ toolIds: options.toolIds ?? ['gmail-mcp'],
+ });
+
+ beforeEach(() => {
+ mockInstalledPluginManifestList = () => [connectorManifest];
+ });
+
+ it('keeps a connector the agent never turned on out of reach, even for the activator', () => {
+ expect(generate().enabledToolIds).toEqual([]);
+ expect(generate({ explicit: true }).enabledToolIds).toEqual([]);
+ });
+
+ it('leaves a connector that is on to the activator instead of invoking it up front', () => {
+ mockCurrentAgentAutoPlugins = ['gmail-mcp'];
+
+ expect(generate().enabledToolIds).toEqual([]);
+ expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);
+ });
+
+ it('reads a connector pinned before the two-state switch as on, not invoked up front', () => {
+ mockCurrentAgentPlugins = ['gmail-mcp'];
+
+ expect(generate().enabledToolIds).toEqual([]);
+ expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);
+ });
+
+ it('invokes a connector that is on directly when manual mode strips the activator', () => {
+ mockCurrentAgentAutoPlugins = ['gmail-mcp'];
+ mockCurrentChatConfig = { skillActivateMode: 'manual' };
+
+ expect(generate().enabledToolIds).toEqual(['gmail-mcp']);
+ });
+
+ it('invokes a connector that is on directly in custom mode, which has no activator either', () => {
+ mockCurrentAgentAutoPlugins = ['gmail-mcp'];
+ mockCurrentChatConfig = { toolMode: 'custom' };
+
+ expect(generate().enabledToolIds).toEqual(['gmail-mcp']);
+ });
+
+ it('reads the switches of the agent that is executing, not the active one', () => {
+ // The active (parent) agent has the connector off; the sub-agent turned it on.
+ const runAgent = { plugins: [{ identifier: 'gmail-mcp', mode: 'auto' as const }] };
+ const generateFor = (explicit: boolean) =>
+ createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }, undefined, undefined, {
+ runAgent,
+ }).generateToolsDetailed({
+ context: explicit ? { isExplicitActivation: true } : undefined,
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ toolIds: ['gmail-mcp'],
+ });
+
+ expect(generateFor(false).enabledToolIds).toEqual([]);
+ expect(generateFor(true).enabledToolIds).toEqual(['gmail-mcp']);
+ });
+
+ it('hides a connector the active agent has on from an executing agent that has it off', () => {
+ mockCurrentAgentAutoPlugins = ['gmail-mcp'];
+
+ const result = createAgentToolsEngine(
+ { model: 'gpt-4', provider: 'openai' },
+ undefined,
+ undefined,
+ { runAgent: { plugins: [] } },
+ ).generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ toolIds: ['gmail-mcp'],
+ });
+
+ expect(result.enabledToolIds).toEqual([]);
+ });
+
+ it('invokes a connector this turn mentions even when the agent has it off', () => {
+ expect(generate({ pluginIds: ['gmail-mcp'] }).enabledToolIds).toEqual(['gmail-mcp']);
+ });
+ });
+
describe('Migration functions', () => {
describe('getEnabledTools', () => {
it('should return empty array when no tool IDs provided', () => {
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 01154a7d741..76d3dc2b785 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -12,8 +12,12 @@ import {
} from '@lobechat/context-engine';
import { assembleManifestPool, resolveToolRules } from '@lobechat/mecha';
import {
+ type AgentPluginEntry,
type BuiltinToolResolveContext,
type ChatCompletionTool,
+ getActivePluginIds,
+ getDisabledPluginIds,
+ type LobeAgentChatConfig,
type ToolManifest,
type WorkingModel,
} from '@lobechat/types';
@@ -41,6 +45,11 @@ import { settingsSelectors } from '@/store/user/selectors';
import { getSearchConfig } from '../getSearchConfig';
import { isCanUseFC } from '../isCanUseFC';
import { buildClientConnectorManifests } from './buildClientConnectorManifests';
+import {
+ type AgentConnectorActivation,
+ applyAgentConnectorActivation,
+ resolveAgentConnectorActivation,
+} from './connectorActivation';
/**
* Tools engine configuration options
@@ -152,12 +161,25 @@ export const createAgentToolsEngine = (
* `readAttachment` so the preview can be paged, as the server's tool discovery does.
*/
hasOversizedFiles?: boolean;
+ /** Resolved for the executing agent, which can differ from the agent open in the UI. */
+ runAgent?: {
+ chatConfig?: LobeAgentChatConfig;
+ connectors?: AgentConnectorActivation;
+ enabledPluginIds?: string[];
+ plugins?: AgentPluginEntry[];
+ };
} = {},
) => {
const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);
const agentState = getAgentStoreState();
const activeAgentId = agentState.activeAgentId || '';
- const chatConfig = agentChatConfigSelectors.currentChatConfig(agentState);
+ const agent = options.runAgent ?? {
+ chatConfig: agentChatConfigSelectors.currentChatConfig(agentState),
+ plugins: agentSelectors.currentAgentConfig(agentState)?.plugins,
+ };
+ const chatConfig = agent.chatConfig ?? {};
+ const connectors =
+ options.runAgent?.connectors ?? resolveAgentConnectorActivation(agent, pluginIds);
// The rules — mode, per-tool enablement and defaults — are shared with the
// server runtime through `@lobechat/mecha`; the browser only assembles its
@@ -166,13 +188,16 @@ export const createAgentToolsEngine = (
const resolved = resolveToolRules({
agent: {
chatConfig,
- // `currentAgentPlugins` already resolves to pinned-only identifiers.
- plugins: agentSelectors.currentAgentPlugins(agentState),
+ plugins: applyAgentConnectorActivation(
+ options.runAgent?.enabledPluginIds ?? getActivePluginIds(agent.plugins),
+ connectors,
+ ),
},
// Feature-flagged tools (e.g. builtin-dashboard) leave the pool while their
// flag is off for this user.
disabledPluginIds: [
- ...agentSelectors.currentAgentDisabledPlugins(agentState),
+ ...getDisabledPluginIds(agent.plugins),
+ ...connectors.offIds,
...getFeatureDisabledToolIds(getServerConfigStoreState()?.featureFlags),
// This engine serves runs the browser executes; server-only tools have nothing to run here.
...serverOnlyToolIds,
@@ -203,6 +228,10 @@ export const createAgentToolsEngine = (
manifestContext,
enableChecker: createEnableChecker({
allowExplicitActivation: resolved.allowExplicitActivation,
+ explicitActivationIds:
+ resolved.toolMode === 'custom'
+ ? new Set(connectors.connectorIds.filter(connectors.activation.isAllowed))
+ : undefined,
platformFilter: ({ pluginId }) => {
const toolStoreState = getToolStoreState();
const installedPlugin = pluginSelectors.getInstalledPluginById(pluginId)(toolStoreState);
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index 3a48fccaccb..23bea64d8c6 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -1,5 +1,5 @@
import { isDesktop } from '@lobechat/const';
-import { getActivePluginIds, type LobeAgentConfig } from '@lobechat/types';
+import { getOptedInPluginIds, type LobeAgentConfig } from '@lobechat/types';
import {
ActionIcon,
confirmModal,
@@ -203,9 +203,10 @@ const Header = memo<HeaderProps>(({ active = 'profile' }) => {
const profileMarkdown = buildAgentProfileMarkdown({
description: meta?.description,
model: config?.model,
- // Pinned identifiers only — a disabled plugin shouldn't be advertised
- // as "enabled" in the exported markdown.
- plugins: getActivePluginIds(config?.plugins),
+ // Everything turned on — a disabled plugin shouldn't be advertised
+ // as "enabled" in the exported markdown, while a connector is on
+ // through an `auto` entry rather than a pin.
+ plugins: getOptedInPluginIds(config?.plugins),
provider: config?.provider,
systemRole: editorMarkdown ?? systemRole,
t,
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index c573f68d678..d0811538ad3 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -28,6 +28,7 @@ import { ModelProvider } from 'model-bank/modelProvider';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { getSearchConfig } from '@/helpers/getSearchConfig';
+import { resolveAgentConnectorActivation } from '@/helpers/toolEngineering/connectorActivation';
import { oneShotRelay } from '@/services/llmRelay';
import { getAgentStoreState } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
@@ -231,7 +232,15 @@ class ChatService {
// `agentConfig.plugins` is the raw (pre-filter) field — `plugins` below
// is already pinned-only (resolved upstream in agentConfigResolver).
autoSkillIds: getAutoPluginIds(agentConfig.plugins),
- disabledPluginIds: getDisabledPluginIds(agentConfig.plugins),
+ // 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),
+ ...resolveAgentConnectorActivation(
+ { chatConfig, plugins: agentConfig.plugins },
+ enabledToolIds,
+ ).offIds,
+ ],
// The stored mode passes through: a model without function calling is
// not demoted to chat mode here, matching the server runtime.
enableAgentMode: modelParams.enableAgentMode,
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 141f96dcaf8..c805425fe44 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -245,9 +245,15 @@ export const contextEngineering = async ({
let toolDiscoveryConfig: ToolDiscoveryConfig | undefined;
if (isLobeToolsEnabled) {
const toolState = getToolStoreState();
+ // Disabled tools and connectors the agent has off are in neither set: the
+ // engine dropped their manifests, so listing them would only invite an
+ // activation that cannot succeed.
+ const disabledIdSet = new Set(disabledPluginIds ?? []);
const availableTools = toolSelectors
.availableToolsForDiscovery(toolState)
- .filter((tool) => !enabledToolSet.has(tool.identifier));
+ .filter(
+ (tool) => !enabledToolSet.has(tool.identifier) && !disabledIdSet.has(tool.identifier),
+ );
if (availableTools.length > 0) {
toolDiscoveryConfig = { availableTools };
@@ -282,6 +288,7 @@ export const contextEngineering = async ({
},
agentId,
disabledPluginIds,
+ discoverableTools: toolDiscoveryConfig?.availableTools,
// The Profile panel edits `activeAgentId` / `activeGroupId`, not the
// builder agent that is answering.
editingAgentId: tools?.includes(AgentBuilderIdentifier)
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts
index 21cce23ef81..7ad92d6e1f4 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts
@@ -1,8 +1,9 @@
import { act } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as toolEngineering from '@/helpers/toolEngineering';
import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
+import { useAgentStore } from '@/store/agent';
import { useToolStore } from '@/store/tool';
import { useChatStore } from '../../../../store';
@@ -25,6 +26,15 @@ const discoverableTool = {
type: 'builtin',
} as any;
+const initialAgentState = useAgentStore.getState();
+const initialToolState = useToolStore.getState();
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ useAgentStore.setState(initialAgentState);
+ useToolStore.setState(initialToolState);
+});
+
describe('internal_createAgentState manifest map', () => {
beforeEach(() => {
resetTestEnvironment();
@@ -56,3 +66,73 @@ describe('internal_createAgentState manifest map', () => {
expect(state.operationToolSet?.enabledToolIds).not.toContain('test-discoverable');
});
});
+
+describe('connectors on the executing client agent', () => {
+ const ids = ['target-connector', 'parent-connector'];
+ beforeEach(() => {
+ resetTestEnvironment();
+ useAgentStore.setState({
+ activeAgentId: 'parent',
+ agentMap: {
+ parent: createMockAgentConfig({
+ plugins: ['parent-connector', { identifier: 'target-connector', mode: 'disabled' }],
+ }),
+ },
+ });
+ useToolStore.setState({
+ installedPlugins: ids.map((identifier) => ({
+ identifier,
+ manifest: {
+ api: [
+ { description: 'Read', name: 'read', parameters: { properties: {}, type: 'object' } },
+ ],
+ identifier,
+ meta: { title: identifier },
+ type: 'default',
+ },
+ type: 'plugin',
+ })),
+ });
+ });
+
+ const startTarget = (toolMode: 'agent' | 'custom', pinned: string[] = []) => {
+ const chatConfig = createMockChatConfig({ toolMode });
+ const agentConfig = createMockAgentConfig({
+ chatConfig,
+ plugins: [...pinned, { identifier: ids[0], mode: 'auto' }],
+ });
+ useAgentStore.setState((s) => ({ agentMap: { ...s.agentMap, target: agentConfig } }));
+ return useChatStore.getState().internal_createAgentState({
+ agentId: 'parent',
+ messages: [createMockMessage()],
+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,
+ subAgentId: 'target',
+ });
+ };
+
+ it.each(['agent', 'custom'] as const)(
+ 'activates only the target’s connector in %s mode',
+ (mode) => {
+ const run = startTarget(mode, mode === 'custom' ? ['lobe-activator'] : []);
+ expect(run.agentConfig.enabledToolIds).toContain('lobe-activator');
+ expect(run.agentConfig.enabledToolIds).not.toContain(ids[0]);
+ const activated = run.toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: run.agentConfig.agentConfig.model,
+ provider: run.agentConfig.agentConfig.provider!,
+ skipDefaultTools: true,
+ toolIds: ids,
+ });
+ expect(activated.tools?.map((tool) => tool.function.name)).toEqual([
+ 'target-connector____read',
+ ]);
+ },
+ );
+
+ it('offers the target’s connector up front in custom mode without an activator', () => {
+ const run = startTarget('custom');
+ expect(run.agentConfig.tools?.map((tool) => tool.function.name)).toEqual([
+ 'target-connector____read',
+ ]);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 89e9010f3a0..c71bc56b04d 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -1298,7 +1298,7 @@ describe('StreamingExecutor actions', () => {
expect.any(Object),
undefined,
expect.objectContaining({ executionEnv: 'local' }),
- { hasOversizedFiles: false },
+ expect.objectContaining({ hasOversizedFiles: false }),
);
const localSystem = state.operationToolSet?.manifestMap['lobe-local-system'];
const readFile = localSystem?.api.find((api: LobeChatPluginApi) => api.name === 'readFile');
@@ -1473,85 +1473,29 @@ describe('StreamingExecutor actions', () => {
);
});
- it('should use excludeDefaultToolIds (not skipDefaultTools) in manual mode for builtin agents', () => {
- 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({ skillActivateMode: 'manual' }),
- 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,
- });
-
- expect(generateToolsDetailed).toHaveBeenCalledWith(
- expect.objectContaining({
- // Must NOT use skipDefaultTools for builtin agents in manual mode
- skipDefaultTools: undefined,
- // Must use excludeDefaultToolIds to only exclude discovery tools
- excludeDefaultToolIds: expect.arrayContaining(['lobe-activator', 'lobe-skill-store']),
- }),
- );
- });
-
- it('should use excludeDefaultToolIds in manual mode for regular agents', () => {
- 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({ skillActivateMode: 'manual' }),
- isBuiltinAgent: false,
- 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,
- });
-
- expect(generateToolsDetailed).toHaveBeenCalledWith(
- expect.objectContaining({
- skipDefaultTools: undefined,
- excludeDefaultToolIds: expect.arrayContaining(['lobe-activator', 'lobe-skill-store']),
- }),
- );
- });
+ it.each([true, false])(
+ 'keeps manual-mode tools callable while omitting the activator (builtin: %s)',
+ (isBuiltinAgent) => {
+ const chatConfig = createMockChatConfig({ skillActivateMode: 'manual' });
+ const plugins = ['lobe-skill-store'];
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig({ plugins }),
+ chatConfig,
+ isBuiltinAgent,
+ plugins,
+ });
+ useAiInfraStore.setState({ isInitAiProviderRuntimeState: false });
+ const userMessage = createUserMessage();
+ const { agentConfig } = useChatStore.getState().internal_createAgentState({
+ agentId: TEST_IDS.SESSION_ID,
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ });
+ expect(agentConfig.enabledToolIds).toContain('lobe-skill-store');
+ expect(agentConfig.enabledToolIds).toContain('lobe-skills');
+ expect(agentConfig.enabledToolIds).not.toContain('lobe-activator');
+ },
+ );
it('should not set excludeDefaultToolIds in auto mode', () => {
act(() => {
@@ -1740,7 +1684,7 @@ describe('StreamingExecutor actions', () => {
createState('x'.repeat(FILE_PREVIEW_CHARS + 1));
- expect(spy.mock.calls.at(-1)?.[3]).toEqual({ hasOversizedFiles: true });
+ expect(spy.mock.calls.at(-1)?.[3]).toMatchObject({ hasOversizedFiles: true });
});
it('does not enable readAttachment for short attachments', () => {
@@ -1748,7 +1692,7 @@ describe('StreamingExecutor actions', () => {
createState('short note');
- expect(spy.mock.calls.at(-1)?.[3]).toEqual({ hasOversizedFiles: false });
+ expect(spy.mock.calls.at(-1)?.[3]).toMatchObject({ hasOversizedFiles: false });
});
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index fed9a5f2597..4cacef8df26 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -35,6 +35,10 @@ import {
import debug from 'debug';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
+import {
+ applyAgentConnectorActivation,
+ resolveAgentConnectorActivation,
+} from '@/helpers/toolEngineering/connectorActivation';
import { aiAgentService } from '@/services/aiAgent';
import { isCanUseAudio, isCanUseVideo, isCanUseVision } from '@/services/chat/helper';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
@@ -216,10 +220,23 @@ export class StreamingExecutorActionImpl {
}
: resolvedAgentConfig;
- const { agentConfig: agentConfigData, plugins: pluginIds } = agentConfig;
+ const { agentConfig: agentConfigData, plugins: resolvedPluginIds } = agentConfig;
const selectedToolIds = initialContext?.initialContext?.selectedTools?.map(
(tool) => tool.identifier,
);
+ // Connectors are two-state: one the agent has on is found through the
+ // activator, so it leaves the invocation set here unless this turn mentions
+ // it. Manual mode has no activator and invokes it directly instead.
+ const runAgent = {
+ chatConfig: agentConfig.chatConfig,
+ enabledPluginIds: resolvedPluginIds,
+ plugins: agentConfigData?.plugins,
+ };
+ const connectors = resolveAgentConnectorActivation(runAgent, selectedToolIds);
+ const pluginIds =
+ disableTools || !resolvedPluginIds
+ ? resolvedPluginIds
+ : applyAgentConnectorActivation(resolvedPluginIds, connectors);
if (!agentConfigData || !agentConfigData.model) {
throw new Error(
@@ -274,11 +291,9 @@ export class StreamingExecutorActionImpl {
// sub-agent runs. Desktop client runs also need the local environment so
// local-system can advertise IPC-only capabilities such as direct image reads.
{ executionEnv: isDesktop ? 'local' : undefined, isSubAgent, scope },
- { hasOversizedFiles: hasPreviewableFiles(messages) },
+ { hasOversizedFiles: hasPreviewableFiles(messages), runAgent: { ...runAgent, connectors } },
);
- // When skillActivateMode is 'manual':
- // Exclude only discovery tools (activator, skill-store) so runtime-managed defaults
- // (skills, web-browsing, sandbox, memory, etc.) remain available for all agents.
+ // Manual mode omits the activator and keeps explicit pins and runtime tools.
const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';
const toolsDetailed = toolsEngine.generateToolsDetailed({
diff --git a/src/store/tool/slices/builtin/selectors.test.ts b/src/store/tool/slices/builtin/selectors.test.ts
index 505445f0bdf..c1fa911f1bc 100644
--- a/src/store/tool/slices/builtin/selectors.test.ts
+++ b/src/store/tool/slices/builtin/selectors.test.ts
@@ -113,63 +113,20 @@ describe('builtinToolSelectors', () => {
});
describe('fixedDisplayMetaList', () => {
- const fixedState = {
- ...initialState,
- builtinTools: [
- {
- hidden: true,
- identifier: 'lobe-agent',
- manifest: {
- api: [],
- identifier: 'lobe-agent',
- meta: { avatar: '🤖', title: 'Lobe Agent' },
- systemRole: '',
- },
- type: 'builtin',
- },
- {
- discoverable: false,
- hidden: true,
- identifier: 'lobe-activator',
- manifest: { api: [], identifier: 'lobe-activator', meta: {}, systemRole: '' },
- type: 'builtin',
- },
- {
- hidden: true,
- identifier: 'lobe-skill-store',
- manifest: { api: [], identifier: 'lobe-skill-store', meta: {}, systemRole: '' },
- type: 'builtin',
- },
- {
- hidden: true,
- identifier: 'tool-1',
- manifest: { api: [], identifier: 'tool-1', meta: { title: 'Tool 1' }, systemRole: '' },
- type: 'builtin',
- },
- ],
- uninstalledBuiltinTools: [],
- } as ToolStoreState;
-
- it('should surface app-fixed tools (e.g. lobe-agent) even though they are hidden', () => {
- const result = builtinToolSelectors.fixedDisplayMetaList()(fixedState);
-
- // Only fixed-display ids are returned; lobe-agent leads the list, unrelated tools excluded.
- expect(result.map((item) => item.identifier)).toContain('lobe-agent');
- expect(result.map((item) => item.identifier)).not.toContain('lobe-activator');
- expect(result.map((item) => item.identifier)).not.toContain('tool-1');
- expect(result[0].identifier).toBe('lobe-agent');
- });
-
- it('should drop manual-mode-excluded discovery tools in manual mode', () => {
- const result = builtinToolSelectors.fixedDisplayMetaList({ isManualMode: true })(fixedState);
- const ids = result.map((item) => item.identifier);
-
- // activator + skill-store are stripped from defaults in manual mode, so they aren't on.
- expect(ids).not.toContain('lobe-activator');
- expect(ids).not.toContain('lobe-skill-store');
- // lobe-agent stays on in manual mode.
- expect(ids).toContain('lobe-agent');
- });
+ 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 = {
@@ -279,12 +236,11 @@ describe('builtinToolSelectors', () => {
})(state);
expect(autoVisible.map((item) => item.identifier)).toEqual([
+ 'lobe-skill-store',
'lobe-agent-management',
'profile-tool',
]);
- expect(autoExcluded).toEqual(
- expect.arrayContaining(['lobe-web-browsing', 'lobe-verify', 'lobe-skill-store']),
- );
+ expect(autoExcluded).toEqual(expect.arrayContaining(['lobe-web-browsing', 'lobe-verify']));
expect(manualVisible.map((item) => item.identifier)).toEqual([
'lobe-skill-store',
'lobe-agent-management',
diff --git a/src/store/tool/slices/builtin/selectors.ts b/src/store/tool/slices/builtin/selectors.ts
index c7240e961f0..4dd91a9ecde 100644
--- a/src/store/tool/slices/builtin/selectors.ts
+++ b/src/store/tool/slices/builtin/selectors.ts
@@ -307,7 +307,7 @@ const ACTIVATION_MODE_CONTROLLED_TOOL_IDS = new Set(activationModeControlledTool
* 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` (activator, skill-store) are stripped from
+ * 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.
*/