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(agent): three-state (pinned/auto/disabled) plugin config (#16924)

LiJian1b21f5877aaf
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index f67d6b8a402..c3f4a8e067d 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -14,8 +14,10 @@ import {
import {
type ComposioServiceSummary,
type CredSummary,
+ excludeDisabledComposioServices,
generateComposioServicesList,
generateCredsList,
+ resolveAvailableComposioServices,
} from '@lobechat/builtin-tool-creds';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { builtinTools } from '@lobechat/builtin-tools';
@@ -62,7 +64,13 @@ import {
CONTEXT_ENGINEERING_SPAN_NAME,
tracer as agentRuntimeTracer,
} from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload, type MessageToolCall, type UIChatMessage } from '@lobechat/types';
+import {
+ type ChatToolPayload,
+ getActivePluginIds,
+ getDisabledPluginIds,
+ type MessageToolCall,
+ type UIChatMessage,
+} from '@lobechat/types';
import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';
import { type ExtendParamsType, ModelProvider } from 'model-bank';
@@ -646,12 +654,25 @@ export const callLlm =
)
.map((p) => p.identifier),
);
- const connected: ComposioServiceSummary[] = COMPOSIO_APP_TYPES.filter((t) =>
- connectedIds.has(t.identifier),
- ).map((t) => ({ identifier: t.identifier, name: t.label }));
- const available: ComposioServiceSummary[] = COMPOSIO_APP_TYPES.filter(
- (t) => !connectedIds.has(t.identifier),
+ // Disabled services are dropped from both lists — not surfaced as
+ // "connected, use directly" (this agent shouldn't use it) nor as
+ // "available to connect" (the account-level OAuth connection, if
+ // any, is untouched; this agent just isn't meant to see it).
+ let disabledIdSet = new Set<string>();
+ if (agentId) {
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const agentConfig = await agentModel.getAgentConfigById(agentId);
+ disabledIdSet = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));
+ }
+ const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(
+ COMPOSIO_APP_TYPES.filter((t) => connectedIds.has(t.identifier)),
+ disabledIdSet,
).map((t) => ({ identifier: t.identifier, name: t.label }));
+ const available = resolveAvailableComposioServices(
+ COMPOSIO_APP_TYPES,
+ connectedIds,
+ disabledIdSet,
+ );
composioServicesListStr = generateComposioServicesList(connected, available);
log(
'Fetched Composio services for {{COMPOSIO_SERVICES_LIST}}: connected=%d, available=%d',
@@ -688,9 +709,9 @@ export const callLlm =
// search API — can't see installable builtin/Composio tools or their
// enabled/connected status, so the model may pick invalid ids or
// claim a supported tool is unavailable.
- const enabledPlugins: string[] = Array.isArray(editingConfig.plugins)
- ? (editingConfig.plugins as string[])
- : [];
+ const enabledPlugins: string[] = getActivePluginIds(
+ Array.isArray(editingConfig.plugins) ? editingConfig.plugins : undefined,
+ );
const composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((t) => t.identifier));
const officialTools: OfficialToolItem[] = [];
@@ -747,7 +768,7 @@ export const callLlm =
openingMessage: editingConfig.openingMessage ?? undefined,
openingQuestions: editingConfig.openingQuestions ?? undefined,
params: editingConfig.params ?? undefined,
- plugins: editingConfig.plugins ?? undefined,
+ plugins: enabledPlugins,
provider: editingConfig.provider ?? undefined,
systemRole: editingConfig.systemRole ?? undefined,
},
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index ceb79cd3d88..5cf1ecd4e7d 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -88,6 +88,11 @@ export const agentRouter = router({
.mutation(async ({ input, ctx }) => {
const agent = await ctx.agentModel.create({
...input.config,
+ // The DB-layer AgentItem (packages/database/src/schemas/agent.ts) is
+ // intentionally still typed `plugins?: string[]` — the JSONB column
+ // itself isn't widened, only the domain-level `@lobechat/types`
+ // shapes. Bridges the tri-state object shape through.
+ plugins: input.config?.plugins as unknown as string[] | undefined,
sessionGroupId: input.groupId,
// Router-level `visibility` wins over any nested config value so the
// sidebar's "Create in Private" entry can't be overridden by a stale
diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.ts
index 0e9a35effca..a18307c26be 100644
--- a/apps/server/src/routers/lambda/agentGroup.ts
+++ b/apps/server/src/routers/lambda/agentGroup.ts
@@ -1,4 +1,4 @@
-import { InsertChatGroupSchema } from '@lobechat/types';
+import { AgentPluginEntrySchema, InsertChatGroupSchema } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -35,7 +35,7 @@ const agentMemberInputSchema = z
model: z.string().nullish(),
params: z.any().nullish(),
pinned: z.boolean().nullish(),
- plugins: z.array(z.string()).nullish(),
+ plugins: z.array(AgentPluginEntrySchema).nullish(),
provider: z.string().nullish(),
sessionGroupId: z.string().nullish(),
slug: z.string().nullish(),
@@ -93,7 +93,10 @@ export const agentGroupRouter = router({
// Batch create virtual agents
const agentConfigs = input.agents.map((agent) => ({
...agent,
- plugins: agent.plugins as string[] | undefined,
+ // `agentModel.batchCreate`'s config type is still `plugins?: string[]`
+ // (widening deferred to the tri-state rollout's final phase); the
+ // zod schema above already allows the tri-state object shape through.
+ plugins: agent.plugins as unknown as string[] | undefined,
tags: agent.tags as string[] | undefined,
virtual: true,
}));
@@ -160,7 +163,7 @@ export const agentGroupRouter = router({
description: z.string().nullish(),
model: z.string().nullish(),
params: z.any().nullish(),
- plugins: z.array(z.string()).nullish(),
+ plugins: z.array(AgentPluginEntrySchema).nullish(),
provider: z.string().nullish(),
systemRole: z.string().nullish(),
tags: z.array(z.string()).nullish(),
@@ -173,7 +176,9 @@ export const agentGroupRouter = router({
// 1. Batch create virtual member agents
const memberConfigs = input.members.map((member) => ({
...member,
- plugins: member.plugins as string[] | undefined,
+ // See the `batchCreateAgentsInGroup` cast above for why this bridges
+ // to `string[]` instead of failing type-check.
+ plugins: member.plugins as unknown as string[] | undefined,
tags: member.tags as string[] | undefined,
virtual: true,
}));
diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.ts
index b2b0791e6d4..51b4f70d4e7 100644
--- a/apps/server/src/services/agent/index.ts
+++ b/apps/server/src/services/agent/index.ts
@@ -223,7 +223,12 @@ export class AgentService {
value: PartialDeep<AgentItem>,
): Promise<UpdateAgentResult> {
// 1. Execute update
- await this.agentModel.updateConfig(agentId, value);
+ // `AgentItem` here is the `@lobechat/types` domain shape (plugins:
+ // AgentPluginEntry[]); `agentModel.updateConfig` takes the DB-layer
+ // AgentItem, whose `plugins` column type is intentionally left as
+ // `string[]` (only the domain types are widened for the tri-state
+ // rollout, not the JSONB column's compile-time annotation).
+ await this.agentModel.updateConfig(agentId, value as any);
// 2. Query and return updated data (with default config merged)
const agent = await this.getAgentConfigById(agentId);
diff --git a/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts b/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts
index 9db813ab17d..9e42ac6e618 100644
--- a/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts
+++ b/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts
@@ -1,4 +1,9 @@
-import type { SkillItem, SkillListItem, SkillResourceMeta } from '@lobechat/types';
+import {
+ getActivePluginIds,
+ type SkillItem,
+ type SkillListItem,
+ type SkillResourceMeta,
+} from '@lobechat/types';
import type { AgentModel } from '@/database/models/agent';
import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
@@ -35,7 +40,7 @@ export class ProviderSkillsInstalledActive implements SkillMountProvider {
private async getEnabledIdentifiers(agentId: string) {
const agent = await this.deps.agentModel.getAgentConfigById(agentId);
- return new Set(agent?.plugins ?? []);
+ return new Set(getActivePluginIds(agent?.plugins ?? undefined));
}
private async findSkillByIdentifier(
diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.ts
index a1b90802a77..97c40dc9361 100644
--- a/apps/server/src/services/agentEvalRun/index.ts
+++ b/apps/server/src/services/agentEvalRun/index.ts
@@ -11,7 +11,7 @@ import type {
EvalThreadResult,
RubricType,
} from '@lobechat/types';
-import { RequestTrigger } from '@lobechat/types';
+import { getActivePluginIds, RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import {
@@ -1529,13 +1529,7 @@ export class AgentEvalRunService {
rubricScores: meta.rubricScores as any,
score: meta.score as number | undefined,
status: meta.status as
- | 'error'
- | 'external'
- | 'failed'
- | 'passed'
- | 'running'
- | 'timeout'
- | undefined,
+ 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout' | undefined,
steps: meta.steps as number | undefined,
threadId: t.id,
tokens: meta.tokens as number | undefined,
@@ -2206,7 +2200,10 @@ export class AgentEvalRunService {
fewShots: agentConfig.fewShots,
model: agentConfig.model,
params: agentConfig.params as Record<string, unknown>,
- plugins: agentConfig.plugins,
+ // Pinned identifiers only — this snapshot is a display-only DTO
+ // (EvalRunAgentSnapshot.plugins stays string[]), and a disabled entry
+ // isn't part of what actually ran.
+ plugins: getActivePluginIds(agentConfig.plugins),
provider: agentConfig.provider,
systemRole: agentConfig.systemRole,
title: agentConfig.title,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
new file mode 100644
index 00000000000..f5df9c5ccf7
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
@@ -0,0 +1,254 @@
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockConnectorQueryByIdentifiers,
+ mockConnectorToolQueryAll,
+ mockCreateOperation,
+ mockCreateServerAgentToolsEngine,
+ mockGetAgentConfig,
+ mockGetComposioManifests,
+ mockGetLobehubSkillManifests,
+ mockMessageCreate,
+ mockPluginQuery,
+} = vi.hoisted(() => ({
+ mockConnectorQueryByIdentifiers: vi.fn().mockResolvedValue([]),
+ mockConnectorToolQueryAll: vi.fn().mockResolvedValue([]),
+ mockCreateOperation: vi.fn(),
+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ mockGetAgentConfig: vi.fn(),
+ mockGetComposioManifests: vi.fn().mockResolvedValue([]),
+ mockGetLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ mockMessageCreate: vi.fn(),
+ mockPluginQuery: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: {
+ initWithEnvKey: vi.fn().mockResolvedValue({ decrypt: vi.fn(), encrypt: vi.fn() }),
+ },
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: mockMessageCreate,
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ })),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(() => ({ getAgentConfig: mockGetAgentConfig })),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(() => ({ query: mockPluginQuery })),
+}));
+
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn().mockImplementation(() => ({
+ queryByIdentifiers: mockConnectorQueryByIdentifiers,
+ })),
+}));
+
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(() => ({
+ queryAllByConnectorIds: mockConnectorToolQueryAll,
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ queryByConnectorIds: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ })),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({ createOperation: mockCreateOperation })),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(() => ({
+ getLobehubSkillManifests: mockGetLobehubSkillManifests,
+ })),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(() => ({
+ getComposioManifests: mockGetComposioManifests,
+ })),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ uploadFromUrl: vi.fn() })),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ { abilities: { functionCall: true }, id: 'gpt-4', providerId: 'openai' },
+ ],
+ };
+});
+
+const pluginManifest = (identifier: string) => ({
+ customParams: {},
+ identifier,
+ manifest: { api: [{ description: 'x', name: 'x', parameters: {} }], identifier },
+});
+
+const toolManifest = (identifier: string) => ({
+ api: [{ description: 'x', name: 'x', parameters: {} }],
+ identifier,
+ meta: { description: 'x', title: identifier },
+});
+
+const installedPluginsArg = () =>
+ mockCreateServerAgentToolsEngine.mock.calls[0][0].installedPlugins as any[];
+
+const agentConfigPluginsArg = () =>
+ mockCreateServerAgentToolsEngine.mock.calls[0][1].agentConfig.plugins as string[];
+
+const toolManifestMapArg = () =>
+ mockCreateOperation.mock.calls[0][0].toolSet.manifestMap as Record<string, unknown>;
+
+describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disabled)', () => {
+ let service: AiAgentService;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockPluginQuery.mockResolvedValue([
+ pluginManifest('plugin-a'),
+ pluginManifest('plugin-b'),
+ pluginManifest('plugin-c'),
+ ]);
+ 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 () => {
+ 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' }],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+
+ 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).not.toContain('plugin-b');
+ });
+
+ it('only feeds pinned identifiers into the engine agentConfig.plugins, excluding disabled', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [
+ { identifier: 'plugin-a', mode: 'pinned' },
+ { identifier: 'plugin-b', mode: 'disabled' },
+ ],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+
+ expect(agentConfigPluginsArg()).toEqual(['plugin-a']);
+ });
+
+ it('behaves identically to a pure string array when no entry is disabled', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: ['plugin-a'],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+
+ 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']);
+ });
+
+ it('excludes a disabled composio/lobehub-skill manifest from the activator-discovery toolManifestMap', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: [
+ { identifier: 'composio-disabled', mode: 'disabled' },
+ { identifier: 'skill-disabled', mode: 'disabled' },
+ ],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+ mockGetComposioManifests.mockResolvedValue([toolManifest('composio-disabled')]);
+ mockGetLobehubSkillManifests.mockResolvedValue([toolManifest('skill-disabled')]);
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+
+ // 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
+ // used to re-add them here from the raw (unfiltered) manifest arrays.
+ expect(toolManifestMapArg()).not.toHaveProperty('composio-disabled');
+ expect(toolManifestMapArg()).not.toHaveProperty('skill-disabled');
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index a98a1f35eb8..9befbfafdd7 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -47,6 +47,8 @@ import type {
} from '@lobechat/types';
import {
buildHeteroExecArgs,
+ getActivePluginIds,
+ getDisabledPluginIds,
getWorkingDirEffectivePath,
RequestTrigger,
ThreadStatus,
@@ -1068,6 +1070,20 @@ export class AiAgentService {
agentConfig.provider,
);
+ // Capture disabled identifiers before collapsing to pinned-only ids below
+ // — everything from here on (builtin runtime merge, page/task/sub-agent
+ // injection, the `agentPlugins` build further down) expects a plain
+ // pinned-id string[], matching pre-tri-state behavior. Operating on a
+ // local `string[]` (rather than repeatedly re-reading/writing
+ // `agentConfig.plugins`, whose declared type is the wider
+ // `AgentPluginEntry[]`) keeps this whole block free of per-line casts;
+ // `agentConfig.plugins` is written back once, at the end.
+ // `disabledPluginIds` is consumed later to filter the auto-discovery
+ // candidate pool (installedPlugins) so disabled plugins can't be
+ // rediscovered/activated by the auto activator.
+ const disabledPluginIds = getDisabledPluginIds(agentConfig.plugins);
+ let activePluginIds: string[] = getActivePluginIds(agentConfig.plugins);
+
// 2. Merge builtin agent runtime config (systemRole, plugins)
// The DB only stores persist config. Runtime config (e.g. inbox systemRole) is generated dynamically.
const agentSlug = agentConfig.slug;
@@ -1083,7 +1099,7 @@ export class AiAgentService {
const runtimeConfig = getAgentRuntimeConfig(agentSlug, {
model: agentConfig.model,
- plugins: agentConfig.plugins ?? [],
+ plugins: activePluginIds,
userLocale,
});
if (runtimeConfig) {
@@ -1094,7 +1110,7 @@ export class AiAgentService {
}
// Runtime plugins merged (runtime plugins take priority if provided)
if (runtimeConfig.plugins && runtimeConfig.plugins.length > 0) {
- agentConfig.plugins = runtimeConfig.plugins;
+ activePluginIds = runtimeConfig.plugins;
log('execAgent: merged builtin agent runtime plugins for slug=%s', agentSlug);
}
if (runtimeConfig.agencyConfig) {
@@ -1108,13 +1124,13 @@ export class AiAgentService {
}
if (appContext?.scope !== 'page') {
- agentConfig.plugins = agentConfig.plugins?.filter((id) => id !== PageAgentIdentifier);
+ activePluginIds = activePluginIds.filter((id) => id !== PageAgentIdentifier);
}
if (appContext?.scope === 'page' && agentSlug !== BUILTIN_AGENT_SLUGS.pageAgent) {
const pageAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.pageAgent, {
model: agentConfig.model,
- plugins: agentConfig.plugins ?? [],
+ plugins: activePluginIds,
});
const pageAgentSystemRole = pageAgentRuntime?.systemRole || '';
@@ -1124,9 +1140,9 @@ export class AiAgentService {
: pageAgentSystemRole;
}
- agentConfig.plugins = agentConfig.plugins?.includes(PageAgentIdentifier)
- ? agentConfig.plugins
- : [PageAgentIdentifier, ...(agentConfig.plugins ?? [])];
+ activePluginIds = activePluginIds.includes(PageAgentIdentifier)
+ ? activePluginIds
+ : [PageAgentIdentifier, ...activePluginIds];
agentConfig.chatConfig = {
...agentConfig.chatConfig,
enableHistoryCount: false,
@@ -1137,7 +1153,7 @@ export class AiAgentService {
if (appContext?.scope === 'task' && agentSlug !== BUILTIN_AGENT_SLUGS.taskAgent) {
const taskAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.taskAgent, {
model: agentConfig.model,
- plugins: agentConfig.plugins ?? [],
+ plugins: activePluginIds,
});
const taskAgentSystemRole = taskAgentRuntime?.systemRole || '';
@@ -1147,16 +1163,18 @@ export class AiAgentService {
: taskAgentSystemRole;
}
- agentConfig.plugins = agentConfig.plugins?.includes(TaskIdentifier)
- ? agentConfig.plugins
- : [TaskIdentifier, ...(agentConfig.plugins ?? [])];
+ activePluginIds = activePluginIds.includes(TaskIdentifier)
+ ? activePluginIds
+ : [TaskIdentifier, ...activePluginIds];
log('execAgent: injected task-agent runtime for task scope');
}
if (appContext?.isSubAgent) {
- agentConfig.plugins = agentConfig.plugins?.filter((id) => id !== LobeAgentIdentifier);
+ activePluginIds = activePluginIds.filter((id) => id !== LobeAgentIdentifier);
}
+ agentConfig.plugins = activePluginIds;
+
await throwIfExecutionAborted('agent configuration');
// 2.5. Append additional instructions to agent's systemRole
@@ -2164,7 +2182,7 @@ export class AiAgentService {
// connector) is both queried for manifests and enabled by the tools engine.
let agentPlugins: string[] = [
...new Set([
- ...(agentConfig?.plugins ?? []),
+ ...getActivePluginIds(agentConfig?.plugins),
...(additionalPluginIds || []),
...(selectedToolIds || []),
...(hasMentionedAgents ? ['lobe-agent-management'] : []),
@@ -2251,9 +2269,20 @@ export class AiAgentService {
if (params.disableTools) {
log('execAgent: tools disabled by disableTools flag, skipping all tool discovery');
} else {
- // 5a. Get installed plugins from database
- const installedPlugins = await this.pluginModel.query();
- log('execAgent: got %d installed plugins', installedPlugins.length);
+ // 5a. Get installed plugins from database. Disabled identifiers are
+ // excluded from this candidate pool entirely — not just from the pinned
+ // `rules` allowlist — because `createEnableChecker`'s explicit-activation
+ // bypass (auto activator) short-circuits before rules are consulted, so a
+ // present-but-rule-disabled manifest could still be auto-activated.
+ const disabledPluginIdSet = new Set(disabledPluginIds);
+ const installedPlugins = (await this.pluginModel.query()).filter(
+ (p) => !disabledPluginIdSet.has(p.identifier),
+ );
+ log(
+ 'execAgent: got %d installed plugins (%d disabled excluded)',
+ installedPlugins.length,
+ disabledPluginIdSet.size,
+ );
// 5a-1. Resolve connectors — connector identifier takes priority over plugin.
// Credentials (OAuth tokens) are encrypted at rest, so decrypt them with a
@@ -2568,11 +2597,24 @@ export class AiAgentService {
operationAgentGroup = buildBotConversationGroupContext(resolvedAgentId, agentConfig);
}
+ // Skills/Composio/connector identifiers share the same `plugins`
+ // identifier space as installed plugins, so a disabled entry must be
+ // excluded from their manifests too — otherwise the disabled tool stays
+ // discoverable/activatable via these additionalManifests even though
+ // `installedPlugins` above already dropped it.
+ const dropDisabledManifests = <T extends { identifier: string }>(manifests: T[]): T[] =>
+ disabledPluginIdSet.size === 0
+ ? manifests
+ : manifests.filter((m) => !disabledPluginIdSet.has(m.identifier));
+ const activeLobehubSkillManifests = dropDisabledManifests(lobehubSkillManifests);
+ const activeComposioManifests = dropDisabledManifests(composioManifests);
+ const activeConnectorManifests = dropDisabledManifests(connectorManifests);
+
const toolsEngine = createServerAgentToolsEngine(toolsContext, {
additionalManifests: [
- ...lobehubSkillManifests,
- ...composioManifests,
- ...connectorManifests,
+ ...activeLobehubSkillManifests,
+ ...activeComposioManifests,
+ ...activeConnectorManifests,
],
agentConfig: {
chatConfig: agentConfig.chatConfig ?? undefined,
@@ -2619,10 +2661,10 @@ export class AiAgentService {
...(disableLocalSystem ? [] : [LocalSystemManifest.identifier]),
RemoteDeviceManifest.identifier,
// Include LobeHub Skills and Composio tools so they are passed to generateToolsDetailed
- ...lobehubSkillManifests.map((m) => m.identifier),
- ...composioManifests.map((m) => m.identifier),
+ ...activeLobehubSkillManifests.map((m) => m.identifier),
+ ...activeComposioManifests.map((m) => m.identifier),
// Connector manifests are also injected as additionalManifests
- ...connectorManifests.map((m) => m.identifier),
+ ...activeConnectorManifests.map((m) => m.identifier),
]),
];
log('execAgent: agent configured plugins: %O', pluginIds);
@@ -2727,25 +2769,30 @@ export class AiAgentService {
toolManifestMap[LocalSystemManifest.identifier] = LocalSystemManifest as LobeToolManifest;
}
- // Include lobehub skill and composio manifests for activator discovery
- for (const manifest of lobehubSkillManifests) {
+ // Include lobehub skill and composio manifests for activator discovery.
+ // Uses the disabled-filtered `active*Manifests` (not the raw
+ // lobehubSkillManifests/composioManifests) — otherwise a disabled
+ // skill/composio integration would be re-ingested here and shown to
+ // the model as discoverable in <available_tools>, even though it was
+ // correctly excluded from the actual invocation pool above.
+ for (const manifest of activeLobehubSkillManifests) {
if (!isManifestIngestAllowed(manifest.identifier)) continue;
if (!toolManifestMap[manifest.identifier]) {
toolManifestMap[manifest.identifier] = manifest;
}
}
- for (const manifest of composioManifests) {
+ for (const manifest of activeComposioManifests) {
if (!isManifestIngestAllowed(manifest.identifier)) continue;
if (!toolManifestMap[manifest.identifier]) {
toolManifestMap[manifest.identifier] = manifest;
}
}
- for (const manifest of lobehubSkillManifests) {
+ for (const manifest of activeLobehubSkillManifests) {
if (!isManifestIngestAllowed(manifest.identifier)) continue;
toolSourceMap[manifest.identifier] = 'lobehubSkill';
}
- for (const manifest of composioManifests) {
+ for (const manifest of activeComposioManifests) {
if (!isManifestIngestAllowed(manifest.identifier)) continue;
toolSourceMap[manifest.identifier] = 'composio';
}
@@ -3401,9 +3448,17 @@ export class AiAgentService {
// Agent-skills carry the `agent-skills:` prefix in their `name`, so they
// can only collide with each other — but we still dedupe by name to keep
// a single shape for the SkillEngine input.
+ //
+ // Disabled skills are dropped here, not just rule-gated later: this
+ // `skills` array is the sole candidate pool SkillEngine/SkillResolver
+ // build `<available_skills>` from AND the pool `activateSkill` resolves
+ // against, so a disabled identifier absent here is neither listed nor
+ // activatable — mirrors the tool-manifest treatment above (installedPlugins/
+ // additionalManifests), which this array had never received.
const seenNames = new Set<string>();
const skills = [...projectMetas, ...dbMetas, ...agentSkillMetas, ...builtinMetas].filter(
(skill) => {
+ if (disabledPluginIds.includes(skill.identifier)) return false;
if (seenNames.has(skill.name)) return false;
seenNames.add(skill.name);
return true;
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
new file mode 100644
index 00000000000..e87aa7cf5a9
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ findAll: vi.fn(),
+ findById: vi.fn(),
+ findByName: vi.fn(),
+ getAgentConfigById: vi.fn(),
+}));
+
+vi.mock('@lobechat/builtin-skills', () => ({
+ builtinSkills: [],
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(() => ({
+ getAgentConfigById: mocks.getAgentConfigById,
+ })),
+}));
+
+vi.mock('@/database/models/agentSkill', () => ({
+ AgentSkillModel: vi.fn(() => ({
+ findAll: mocks.findAll,
+ findById: mocks.findById,
+ findByName: mocks.findByName,
+ })),
+}));
+
+vi.mock('@/helpers/skillFilters', () => ({
+ filterBuiltinSkills: vi.fn((skills: unknown) => skills),
+}));
+
+vi.mock('@/server/services/agentSignal/procedure', () => ({
+ emitToolOutcomeSafely: vi.fn().mockResolvedValue(undefined),
+ resolveToolOutcomeScope: vi.fn(() => ({ scope: 'agent', scopeKey: 'agent-1' })),
+}));
+
+vi.mock('@/server/services/agentSignal/store/adapters/redis/policyStateStore', () => ({
+ redisPolicyStateStore: {},
+}));
+
+describe('activatorRuntime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getAgentConfigById.mockResolvedValue({ plugins: [] });
+ mocks.findAll.mockResolvedValue({ data: [], total: 0 });
+ mocks.findById.mockResolvedValue(undefined);
+ mocks.findByName.mockResolvedValue(undefined);
+ });
+
+ describe('activateSkill — disabled skill enforcement', () => {
+ // First dynamic `import('../activator')` in the file pays the real
+ // transform cost for this module — default 5s timeout is marginal for
+ // that cold cost alone, independent of test logic.
+ it('refuses to activate a DB skill the agent has disabled, even though it exists', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({
+ plugins: [{ identifier: 'user-skill-identifier', mode: 'disabled' }],
+ });
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill'
+ ? {
+ content: '# User skill',
+ id: 'user-skill-id',
+ identifier: 'user-skill-identifier',
+ name: 'user-skill',
+ }
+ : undefined,
+ );
+
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateSkill({ name: 'user-skill' });
+
+ expect(result.success).toBe(false);
+ }, 20_000);
+
+ it('still activates the skill when it is not disabled', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({ plugins: [] });
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill'
+ ? {
+ content: '# User skill',
+ id: 'user-skill-id',
+ identifier: 'user-skill-identifier',
+ name: 'user-skill',
+ }
+ : undefined,
+ );
+
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateSkill({ name: 'user-skill' });
+
+ expect(result.success).toBe(true);
+ });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
new file mode 100644
index 00000000000..7cf856552bb
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentBuilderRuntime } from '../agentBuilder';
+
+const { mockGetAgentConfigById, mockUpdateConfig, mockFindById, mockCreatePlugin } = vi.hoisted(
+ () => ({
+ mockCreatePlugin: vi.fn(),
+ mockFindById: vi.fn(),
+ mockGetAgentConfigById: vi.fn(),
+ mockUpdateConfig: vi.fn(),
+ }),
+);
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(() => ({
+ getAgentConfigById: mockGetAgentConfigById,
+ updateConfig: mockUpdateConfig,
+ })),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn(() => ({
+ create: mockCreatePlugin,
+ findById: mockFindById,
+ })),
+}));
+
+vi.mock('@/database/repositories/aiInfra', () => ({
+ AiInfraRepos: vi.fn(() => ({})),
+}));
+
+vi.mock('@/server/services/discover', () => ({
+ DiscoverService: vi.fn(() => ({})),
+}));
+
+const createRuntime = () =>
+ agentBuilderRuntime.factory({
+ editingAgentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+describe('agentBuilderRuntime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('updateConfig - togglePlugin', () => {
+ it('appends a new pinned entry when enabling an absent identifier', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['plugin-a'] });
+
+ const runtime = createRuntime();
+ const result = await runtime.updateConfig(
+ { togglePlugin: { enabled: true, pluginId: 'plugin-b' } },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],
+ });
+ });
+
+ it('flips an existing disabled object entry back to pinned in place, without duplicating it', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }],
+ });
+
+ const runtime = createRuntime();
+ const result = await runtime.updateConfig(
+ { togglePlugin: { enabled: true, pluginId: 'plugin-b' } },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],
+ });
+ });
+
+ it('disabling (enabled: false) reverts the entry to auto, removing it from the array', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: ['plugin-a', 'plugin-b'],
+ });
+
+ const runtime = createRuntime();
+ const result = await runtime.updateConfig(
+ { togglePlugin: { enabled: false, pluginId: 'plugin-b' } },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', { plugins: ['plugin-a'] });
+ });
+ });
+
+ describe('installPlugin', () => {
+ it('flips an existing disabled builtin-tool entry back to pinned, without duplicating it', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: [{ identifier: 'lobe-web-browsing', mode: 'disabled' }],
+ });
+
+ const runtime = createRuntime();
+ const result = await runtime.installPlugin(
+ { identifier: 'lobe-web-browsing', source: 'official' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: [{ identifier: 'lobe-web-browsing', mode: 'pinned' }],
+ });
+ });
+
+ it('is a no-op write when the builtin-tool identifier is already pinned', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: ['lobe-web-browsing'],
+ });
+
+ const runtime = createRuntime();
+ const result = await runtime.installPlugin(
+ { identifier: 'lobe-web-browsing', source: 'official' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ });
+
+ it('flips an existing disabled market-plugin entry back to pinned, without duplicating it', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: [{ identifier: 'market-plugin', mode: 'disabled' }],
+ });
+ mockFindById.mockResolvedValue({ identifier: 'market-plugin', manifest: { api: [] } });
+
+ const runtime = createRuntime();
+ const result = await runtime.installPlugin(
+ { identifier: 'market-plugin', source: 'market' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: [{ identifier: 'market-plugin', mode: 'pinned' }],
+ });
+ });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
index 770d3046954..c08c4c1b06b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
@@ -5,21 +5,38 @@ import { PluginModel } from '@/database/models/plugin';
import { agentManagementRuntime } from '../agentManagement';
-const { mockCountAgents, mockGetAssistantList, mockQueryAgents } = vi.hoisted(() => ({
+const {
+ mockCountAgents,
+ mockGetAssistantList,
+ mockQueryAgents,
+ mockGetAgentConfigById,
+ mockUpdateConfig,
+ mockFindById,
+ mockCreatePlugin,
+} = vi.hoisted(() => ({
mockCountAgents: vi.fn(),
+ mockCreatePlugin: vi.fn(),
+ mockFindById: vi.fn(),
+ mockGetAgentConfigById: vi.fn(),
mockGetAssistantList: vi.fn(),
mockQueryAgents: vi.fn(),
+ mockUpdateConfig: vi.fn(),
}));
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn(() => ({
countAgents: mockCountAgents,
+ getAgentConfigById: mockGetAgentConfigById,
queryAgents: mockQueryAgents,
+ updateConfig: mockUpdateConfig,
})),
}));
vi.mock('@/database/models/plugin', () => ({
- PluginModel: vi.fn(() => ({})),
+ PluginModel: vi.fn(() => ({
+ create: mockCreatePlugin,
+ findById: mockFindById,
+ })),
}));
vi.mock('@/server/services/discover', () => ({
@@ -354,4 +371,50 @@ describe('agentManagementRuntime', () => {
expect(result.content).toContain('Failed to search agents');
});
});
+
+ describe('installPlugin', () => {
+ it('appends a new pinned entry when the identifier is absent', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['plugin-a'] });
+ mockFindById.mockResolvedValue(undefined);
+
+ const runtime = createRuntime();
+ const result = await runtime.installPlugin({ agentId: 'agent-1', identifier: 'plugin-b' });
+
+ expect(result.success).toBe(true);
+ expect(mockCreatePlugin).toHaveBeenCalledWith({ identifier: 'plugin-b', type: 'plugin' });
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],
+ });
+ });
+
+ it('flips an existing disabled object entry back to pinned in place, without duplicating it', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }],
+ });
+ mockFindById.mockResolvedValue({ identifier: 'plugin-b' });
+
+ const runtime = createRuntime();
+ const result = await runtime.installPlugin({ agentId: 'agent-1', identifier: 'plugin-b' });
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],
+ });
+ });
+
+ it('is a no-op write when the identifier is already pinned', async () => {
+ mockGetAgentConfigById.mockResolvedValue({
+ id: 'agent-1',
+ plugins: ['plugin-a', 'plugin-b'],
+ });
+ mockFindById.mockResolvedValue({ identifier: 'plugin-b' });
+
+ const runtime = createRuntime();
+ const result = await runtime.installPlugin({ agentId: 'agent-1', identifier: 'plugin-b' });
+
+ expect(result.success).toBe(true);
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index ed05e86c847..ad50390ba31 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -26,6 +26,7 @@ const mocks = vi.hoisted(() => {
findAll: vi.fn(),
findById: vi.fn(),
findByName: vi.fn(),
+ getAgentConfigById: vi.fn(),
getAgentSkills: vi.fn(),
getUserSettings: vi.fn(),
marketService: {},
@@ -39,6 +40,12 @@ vi.mock('@lobechat/builtin-skills', () => ({
builtinSkills: [],
}));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(() => ({
+ getAgentConfigById: mocks.getAgentConfigById,
+ })),
+}));
+
vi.mock('@/database/models/agentSkill', () => ({
AgentSkillModel: vi.fn(() => ({
findAll: mocks.findAll,
@@ -111,6 +118,7 @@ describe('skillsRuntime', () => {
mocks.fileService.getFullFileUrl.mockResolvedValue('https://files.example.com/user-skill.zip');
mocks.findAll.mockResolvedValue({ data: [], total: 0 });
mocks.findById.mockResolvedValue(undefined);
+ mocks.getAgentConfigById.mockResolvedValue(undefined);
mocks.findByName.mockImplementation(async (name: string) => {
if (name === 'user-skill') {
return {
@@ -135,6 +143,9 @@ describe('skillsRuntime', () => {
});
});
+ // First dynamic `import('../skills')` in the file pays the real transform
+ // cost for this (now larger) module — default 5s timeout is marginal for
+ // that cold cost alone, independent of test logic.
it('executes scripts through the sandbox service and only attaches persisted skill zips', async () => {
const { skillsRuntime } = await import('../skills');
const runtime = await skillsRuntime.factory({
@@ -167,7 +178,7 @@ describe('skillsRuntime', () => {
},
}),
);
- });
+ }, 20_000);
it('tags sandbox exec results with executionEnv for plugin-state observability', async () => {
const { skillsRuntime } = await import('../skills');
@@ -187,6 +198,59 @@ describe('skillsRuntime', () => {
expect(result.state).toMatchObject({ executionEnv: 'sandbox' });
});
+ describe('disabled skill enforcement', () => {
+ it('refuses to activate a DB skill the agent has disabled, even though it exists', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({
+ plugins: [{ identifier: 'user-skill-identifier', mode: 'disabled' }],
+ });
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill'
+ ? { id: 'user-skill-id', identifier: 'user-skill-identifier', name: 'user-skill' }
+ : undefined,
+ );
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateSkill({ name: 'user-skill' });
+
+ expect(result.success).toBe(false);
+ });
+
+ it('still activates the skill when it is not disabled', async () => {
+ mocks.getAgentConfigById.mockResolvedValue({ plugins: [] });
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill'
+ ? {
+ content: '# User skill',
+ id: 'user-skill-id',
+ identifier: 'user-skill-identifier',
+ name: 'user-skill',
+ }
+ : undefined,
+ );
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateSkill({ name: 'user-skill' });
+
+ expect(result.success).toBe(true);
+ });
+ });
+
// Regression guard for the server/gateway migration: when the execution plan
// routed a device (activeDeviceId present), execScript must run ON the device
// — prepare the skill archives via the prepareSkillDirectory RPC and execute
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index 848698c08a4..956fd47ae87 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -6,7 +6,9 @@ import {
type ToolManifestInfo,
} from '@lobechat/builtin-tool-activator/executionRuntime';
import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';
+import { getDisabledPluginIds } from '@lobechat/types';
+import { AgentModel } from '@/database/models/agent';
import { AgentSkillModel } from '@/database/models/agentSkill';
import { filterBuiltinSkills } from '@/helpers/skillFilters';
import {
@@ -68,17 +70,38 @@ export const activatorRuntime: ServerRuntimeRegistration = {
let skillsRuntime: SkillsExecutionRuntime | undefined;
if (context.serverDB && context.userId) {
const skillModel = new AgentSkillModel(context.serverDB, context.userId, context.workspaceId);
+
+ // `activateSkill` resolves independently of `operationSkillSet`/
+ // `<available_skills>` (built once, earlier, in aiAgent/index.ts) — it
+ // queries builtins/DB directly by name. Without this guard, a skill
+ // the agent has explicitly disabled would no longer be *listed*, but a
+ // model that already knows its name (prior turn, or a guess) could
+ // still activate and use it. Re-derive the disabled set here so this
+ // independent resolution path enforces the same tri-state.
+ let disabledSkillIds = new Set<string>();
+ if (context.agentId) {
+ const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);
+ const agentConfig = await agentModel.getAgentConfigById(context.agentId);
+ disabledSkillIds = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));
+ }
+
skillsRuntime = new SkillsExecutionRuntime({
// Same device gate as the skills runtime: device-only skills are
// activatable in device-capable runs (matching <available_skills>),
// with `activeDeviceId` as the fallback for callers without a plan.
builtinSkills: filterBuiltinSkills(builtinSkills, {
canExecuteOnDevice: context.deviceCapable ?? !!context.activeDeviceId,
- }),
+ }).filter((skill) => !disabledSkillIds.has(skill.identifier)),
service: {
findAll: () => skillModel.findAll(),
- findById: (id) => skillModel.findById(id),
- findByName: (name) => skillModel.findByName(name),
+ findById: async (id) => {
+ const skill = await skillModel.findById(id);
+ return skill && disabledSkillIds.has(skill.identifier) ? undefined : skill;
+ },
+ findByName: async (name) => {
+ const skill = await skillModel.findByName(name);
+ return skill && disabledSkillIds.has(skill.identifier) ? undefined : skill;
+ },
readResource: async () => {
throw new Error('readResource not available in tools runtime');
},
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
index bb70586d34a..eb3e2f3845e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
@@ -9,6 +9,7 @@ import {
import { builtinTools } from '@lobechat/builtin-tools';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { modelsResultsPrompt } from '@lobechat/prompts';
+import { getPluginMode, upsertPluginMode } from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
import { PluginModel } from '@/database/models/plugin';
@@ -195,16 +196,17 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
if (params.togglePlugin) {
const { pluginId, enabled } = params.togglePlugin;
- const currentPlugins = (agent.plugins as string[] | null) || [];
- const isEnabled = currentPlugins.includes(pluginId);
+ const isEnabled = getPluginMode(agent.plugins ?? undefined, pluginId) === 'pinned';
const shouldEnable = enabled !== undefined ? enabled : !isEnabled;
- const newPlugins =
- shouldEnable && !isEnabled
- ? [...currentPlugins, pluginId]
- : !shouldEnable && isEnabled
- ? currentPlugins.filter((id: string) => id !== pluginId)
- : currentPlugins;
+ // upsertPluginMode preserves an already-matching entry as-is and
+ // flips a disabled entry back to pinned in place, instead of
+ // blindly pushing a duplicate bare-string identifier.
+ const newPlugins = upsertPluginMode(
+ agent.plugins ?? undefined,
+ pluginId,
+ shouldEnable ? 'pinned' : 'auto',
+ );
finalConfig = { ...finalConfig, plugins: newPlugins };
updatedParts.push(`plugin ${pluginId} ${shouldEnable ? 'enabled' : 'disabled'}`);
@@ -296,10 +298,13 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
const agent = await agentModel.getAgentConfigById(agentId);
if (!agent) return { content: `Agent "${agentId}" not found.`, success: false };
- const currentPlugins = (agent.plugins as string[] | null) || [];
- if (!currentPlugins.includes(identifier)) {
+ if (getPluginMode(agent.plugins ?? undefined, identifier) !== 'pinned') {
await agentModel.updateConfig(agentId, {
- plugins: [...currentPlugins, identifier],
+ plugins: upsertPluginMode(
+ agent.plugins ?? undefined,
+ identifier,
+ 'pinned',
+ ) as unknown as string[],
});
}
return {
@@ -345,10 +350,13 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
}
}
- const currentPlugins = (agent.plugins as string[] | null) || [];
- if (!currentPlugins.includes(identifier)) {
+ if (getPluginMode(agent.plugins ?? undefined, identifier) !== 'pinned') {
await agentModel.updateConfig(agentId, {
- plugins: [...currentPlugins, identifier],
+ plugins: upsertPluginMode(
+ agent.plugins ?? undefined,
+ identifier,
+ 'pinned',
+ ) as unknown as string[],
});
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
index 2dbb4a10649..b9d89938eae 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
@@ -11,7 +11,12 @@ import {
type UpdatePromptParams,
} from '@lobechat/builtin-tool-agent-management';
import { searchAgentsResultsPrompt } from '@lobechat/prompts';
-import type { HeterogeneousProviderConfig } from '@lobechat/types';
+import {
+ getPluginMode,
+ type HeterogeneousProviderConfig,
+ parsePluginEntry,
+ upsertPluginMode,
+} from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
import { PluginModel } from '@/database/models/plugin';
@@ -177,12 +182,23 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
return { content: `Agent "${params.agentId}" not found.`, success: false };
}
+ // Normalize to identifier strings (annotated with mode when not
+ // pinned) — `agent.plugins` is the raw AgentPluginEntry[] (string |
+ // {identifier, mode}), but both the LLM-facing summary and the
+ // GetAgentDetailState.config.plugins contract expect string[].
+ // Passing object-shaped entries through to the client would break
+ // GetAgentDetailRender's <Tag key={plugin}>{plugin}</Tag>.
+ const pluginSummaries = agent.plugins?.map((entry) => {
+ const { identifier, mode } = parsePluginEntry(entry);
+ return mode === 'pinned' ? identifier : `${identifier} (${mode})`;
+ });
+
const detail = {
config: {
model: agent.model,
openingMessage: agent.openingMessage,
openingQuestions: agent.openingQuestions,
- plugins: agent.plugins,
+ plugins: pluginSummaries,
provider: agent.provider,
systemRole: agent.systemRole,
},
@@ -200,8 +216,9 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
if (detail.meta.description) parts.push(detail.meta.description);
if (detail.config.model)
parts.push(`Model: ${detail.config.provider || ''}/${detail.config.model}`);
- if (detail.config.plugins?.length)
+ if (detail.config.plugins?.length) {
parts.push(`Plugins: ${detail.config.plugins.join(', ')}`);
+ }
if (detail.config.systemRole) parts.push(`System Prompt: ${detail.config.systemRole}`);
return {
@@ -229,10 +246,16 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
await pluginModel.create({ identifier, type: 'plugin' });
}
- const currentPlugins = (agent.plugins as string[] | null) || [];
- if (!currentPlugins.includes(identifier)) {
+ // upsertPluginMode preserves an already-pinned entry (string or
+ // object) as-is and flips a disabled entry back to pinned in place,
+ // instead of blindly pushing a duplicate bare-string identifier.
+ if (getPluginMode(agent.plugins ?? undefined, identifier) !== 'pinned') {
await agentModel.updateConfig(agentId, {
- plugins: [...currentPlugins, identifier],
+ plugins: upsertPluginMode(
+ agent.plugins ?? undefined,
+ identifier,
+ 'pinned',
+ ) as unknown as string[],
});
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index c9063733d26..6bdbb59b494 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -14,9 +14,16 @@ import {
type SkillRuntimeService,
SkillsExecutionRuntime,
} from '@lobechat/builtin-tool-skills/executionRuntime';
-import type { BuiltinSkill, SkillItem, SkillListItem, SkillResourceContent } from '@lobechat/types';
+import {
+ type BuiltinSkill,
+ getDisabledPluginIds,
+ type SkillItem,
+ type SkillListItem,
+ type SkillResourceContent,
+} from '@lobechat/types';
import debug from 'debug';
+import { AgentModel } from '@/database/models/agent';
import { AgentSkillModel } from '@/database/models/agentSkill';
import { FileModel } from '@/database/models/file';
import { UserModel } from '@/database/models/user';
@@ -98,9 +105,17 @@ class SkillServerRuntimeService implements SkillRuntimeService {
private topicId?: string;
private userId: string;
private device?: SkillDeviceExecution;
+ private disabledSkillIds: Set<string>;
constructor(options: {
device?: SkillDeviceExecution;
+ /**
+ * Identifiers the agent has explicitly disabled (`agents.plugins` tri-state)
+ * — findById/findByName resolve to `undefined` for these, so a disabled
+ * DB/market skill can't be activated even by a model that already knows
+ * its name, independent of whatever's listed in `<available_skills>`.
+ */
+ disabledSkillIds?: Set<string>;
fileModel: FileModel;
fileService: FileService;
marketService: MarketService;
@@ -119,18 +134,21 @@ class SkillServerRuntimeService implements SkillRuntimeService {
this.topicId = options.topicId;
this.userId = options.userId;
this.device = options.device;
+ this.disabledSkillIds = options.disabledSkillIds ?? new Set();
}
findAll = (): Promise<{ data: SkillListItem[]; total: number }> => {
return this.skillModel.findAll();
};
- findById = (id: string): Promise<SkillItem | undefined> => {
- return this.skillModel.findById(id);
+ findById = async (id: string): Promise<SkillItem | undefined> => {
+ const skill = await this.skillModel.findById(id);
+ return skill && this.disabledSkillIds.has(skill.identifier) ? undefined : skill;
};
- findByName = (name: string): Promise<SkillItem | undefined> => {
- return this.skillModel.findByName(name);
+ findByName = async (name: string): Promise<SkillItem | undefined> => {
+ const skill = await this.skillModel.findByName(name);
+ return skill && this.disabledSkillIds.has(skill.identifier) ? undefined : skill;
};
readResource = async (id: string, path: string): Promise<SkillResourceContent> => {
@@ -585,6 +603,18 @@ export const skillsRuntime: ServerRuntimeRegistration = {
log('Failed to fetch market accessToken for user %s: %O', context.userId, error);
}
+ // Independent of `<available_skills>` (built once, earlier, in
+ // aiAgent/index.ts) — this runtime resolves skills fresh by name/id, so a
+ // model that already knows a disabled skill's name (prior turn, or a
+ // guess) could otherwise still activate/run it. Re-derive the disabled
+ // set here so this path enforces the same tri-state.
+ let disabledSkillIds = new Set<string>();
+ if (context.agentId) {
+ const agentModel = new AgentModel(context.serverDB, context.userId, context.workspaceId);
+ const agentConfig = await agentModel.getAgentConfigById(context.agentId);
+ disabledSkillIds = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));
+ }
+
const skillModel = new AgentSkillModel(context.serverDB, context.userId, context.workspaceId);
const resourceService = new SkillResourceService(
context.serverDB,
@@ -621,6 +651,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {
const service = new SkillServerRuntimeService({
device,
+ disabledSkillIds,
fileModel,
fileService,
marketService,
@@ -645,14 +676,16 @@ export const skillsRuntime: ServerRuntimeRegistration = {
? await new AgentDocumentsService(context.serverDB, context.userId, context.workspaceId)
.getAgentSkills(context.agentId)
.then((skills) =>
- skills.map((skill) => ({
- content: skill.content,
- description: skill.description,
- identifier: skill.identifier,
- name: skill.name,
- source: 'builtin' as const,
- ...(skill.title && { title: skill.title }),
- })),
+ skills
+ .filter((skill) => !disabledSkillIds.has(skill.identifier))
+ .map((skill) => ({
+ content: skill.content,
+ description: skill.description,
+ identifier: skill.identifier,
+ name: skill.name,
+ source: 'builtin' as const,
+ ...(skill.title && { title: skill.title }),
+ })),
)
.catch((error) => {
log('failed to load agent skills for agent %s: %O', context.agentId, error);
@@ -733,7 +766,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {
// execution plan.
...filterBuiltinSkills(builtinSkills, {
canExecuteOnDevice: context.deviceCapable ?? !!activeDeviceId,
- }),
+ }).filter((skill) => !disabledSkillIds.has(skill.identifier)),
...agentSkillBuiltins,
],
deviceFileAccess,
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 01825c2fc97..616a9329207 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1042,6 +1042,8 @@
"tab.usage": "Usage",
"tools.activation.auto": "Auto",
"tools.activation.auto.desc": "Smart",
+ "tools.activation.disabled": "Disabled",
+ "tools.activation.disabled.desc": "Turned Off",
"tools.activation.fixed.hint": "Always on — managed by the app and can’t be turned off",
"tools.activation.pinned": "Pinned",
"tools.activation.pinned.desc": "Always On",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 2fb6101e9b0..a746ea00006 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1042,6 +1042,8 @@
"tab.usage": "用量",
"tools.activation.auto": "自动",
"tools.activation.auto.desc": "智能调用",
+ "tools.activation.disabled": "已禁用",
+ "tools.activation.disabled.desc": "不会启用",
"tools.activation.fixed.hint": "由应用强制开启,始终可用,无法关闭",
"tools.activation.pinned": "固定启用",
"tools.activation.pinned.desc": "始终注入",
diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
index 31b8a2e598c..9177c9b8acf 100644
--- a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
@@ -20,7 +20,13 @@ import {
modelsResultsPrompt,
searchAgentsResultsPrompt,
} from '@lobechat/prompts';
-import type { BuiltinToolResult, HeterogeneousProviderConfig } from '@lobechat/types';
+import {
+ type BuiltinToolResult,
+ getPluginMode,
+ type HeterogeneousProviderConfig,
+ parsePluginEntry,
+ upsertPluginMode,
+} from '@lobechat/types';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors/selectors';
@@ -173,18 +179,17 @@ export class AgentManagerRuntime {
// Handle togglePlugin - merge into config.plugins
if (params.togglePlugin) {
const { pluginId, enabled } = params.togglePlugin;
- const currentPlugins = previousConfig?.plugins || [];
- const isCurrentlyEnabled = currentPlugins.includes(pluginId);
+ const isCurrentlyEnabled = getPluginMode(previousConfig?.plugins, pluginId) === 'pinned';
const shouldEnable = enabled !== undefined ? enabled : !isCurrentlyEnabled;
- let newPlugins: string[];
- if (shouldEnable && !isCurrentlyEnabled) {
- newPlugins = [...currentPlugins, pluginId];
- } else if (!shouldEnable && isCurrentlyEnabled) {
- newPlugins = currentPlugins.filter((id) => id !== pluginId);
- } else {
- newPlugins = currentPlugins;
- }
+ // upsertPluginMode preserves an already-matching entry as-is and
+ // flips a disabled entry back to pinned in place, instead of
+ // blindly pushing a duplicate bare-string identifier.
+ const newPlugins = upsertPluginMode(
+ previousConfig?.plugins,
+ pluginId,
+ shouldEnable ? 'pinned' : 'auto',
+ );
finalConfig = { ...finalConfig, plugins: newPlugins };
@@ -314,12 +319,23 @@ export class AgentManagerRuntime {
// orchestrator can reason about what the external agent can actually do.
const runtime = describeHeterogeneousAgent(config.agencyConfig);
+ // Normalize to identifier strings (annotated with mode when not
+ // pinned) — `config.plugins` is the raw AgentPluginEntry[] (string |
+ // {identifier, mode}), but both the LLM-facing summary and the
+ // GetAgentDetailState.config.plugins contract expect string[]. Passing
+ // object-shaped entries through would break GetAgentDetailRender's
+ // <Tag key={plugin}>{plugin}</Tag>.
+ const pluginSummaries = config.plugins?.map((entry) => {
+ const { identifier, mode } = parsePluginEntry(entry);
+ return mode === 'pinned' ? identifier : `${identifier} (${mode})`;
+ });
+
const detail = {
config: {
model: config.model,
openingMessage: config.openingMessage,
openingQuestions: config.openingQuestions,
- plugins: config.plugins,
+ plugins: pluginSummaries,
provider: config.provider,
...(runtime && { runtime }),
systemRole: config.systemRole,
@@ -338,7 +354,9 @@ export class AgentManagerRuntime {
if (detail.meta.description) parts.push(detail.meta.description);
if (detail.config.model)
parts.push(`Model: ${detail.config.provider || ''}/${detail.config.model}`);
- if (detail.config.plugins?.length) parts.push(`Plugins: ${detail.config.plugins.join(', ')}`);
+ if (detail.config.plugins?.length) {
+ parts.push(`Plugins: ${detail.config.plugins.join(', ')}`);
+ }
parts.push(...renderHeteroRuntimeLines(runtime));
if (detail.config.systemRole) {
parts.push(`System Prompt: ${detail.config.systemRole}`);
@@ -505,21 +523,19 @@ export class AgentManagerRuntime {
const providers: AvailableProvider[] = filteredList.map((provider) => ({
id: provider.id,
- models: provider.children.map(
- (model): AvailableModel => ({
- abilities: model.abilities
- ? {
- files: model.abilities.files,
- functionCall: model.abilities.functionCall,
- reasoning: model.abilities.reasoning,
- vision: model.abilities.vision,
- }
- : undefined,
- description: model.description,
- id: model.id,
- name: model.displayName || model.id,
- }),
- ),
+ models: provider.children.map((model): AvailableModel => ({
+ abilities: model.abilities
+ ? {
+ files: model.abilities.files,
+ functionCall: model.abilities.functionCall,
+ reasoning: model.abilities.reasoning,
+ vision: model.abilities.vision,
+ }
+ : undefined,
+ description: model.description,
+ id: model.id,
+ name: model.displayName || model.id,
+ })),
name: provider.name,
}));
@@ -1035,11 +1051,14 @@ export class AgentManagerRuntime {
private async enablePluginForAgent(agentId: string, pluginId: string): Promise<void> {
await this.ensureAgentLoaded(agentId);
const agentState = getAgentStoreState();
- const currentPlugins = agentSelectors.getAgentConfigById(agentId)(agentState)?.plugins || [];
+ const currentPlugins = agentSelectors.getAgentConfigById(agentId)(agentState)?.plugins;
- if (!currentPlugins.includes(pluginId)) {
+ // upsertPluginMode preserves an already-matching entry as-is and flips a
+ // disabled entry back to pinned in place, instead of blindly pushing a
+ // duplicate bare-string identifier.
+ if (getPluginMode(currentPlugins, pluginId) !== 'pinned') {
await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
- plugins: [...currentPlugins, pluginId],
+ plugins: upsertPluginMode(currentPlugins, pluginId, 'pinned'),
});
}
}
diff --git a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
index 95e86afe547..f7ad218ab86 100644
--- a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
+++ b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
@@ -1,8 +1,24 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getAgentStoreState } from '@/store/agent';
+
import { AgentManagerRuntime } from '../AgentManagerRuntime';
import type { IAgentService, IDiscoverService } from '../types';
+/**
+ * The `@/store/agent` mock below recreates a fresh object (with fresh
+ * `vi.fn()`s) on every `getAgentStoreState()` call, so a write made through
+ * one call's `optimisticUpdateAgentConfig` isn't visible on another call's
+ * returned object. This finds whichever of this test's calls actually wrote.
+ */
+const getLastOptimisticConfigUpdateCall = () => {
+ for (const result of [...vi.mocked(getAgentStoreState).mock.results].reverse()) {
+ const calls = (result.value.optimisticUpdateAgentConfig as ReturnType<typeof vi.fn>).mock.calls;
+ if (calls.length > 0) return calls.at(-1);
+ }
+ return undefined;
+};
+
// Create mock services
const mockAgentService: IAgentService = {
countAgents: vi.fn(),
@@ -202,6 +218,35 @@ describe('AgentManagerRuntime', () => {
expect(result.success).toBe(true);
expect(result.content).toBe('No fields to update.');
});
+
+ it('flips an existing disabled object entry back to pinned, without duplicating it', async () => {
+ const originalPlugins = mockAgentConfig.plugins;
+ mockAgentConfig.plugins = [
+ 'plugin-1',
+ { identifier: 'plugin-2', mode: 'disabled' } as any,
+ ] as any;
+
+ try {
+ // Also pass `config.model` so the code populates `state.config.newValues`
+ // (it's otherwise omitted when only `togglePlugin` is set), letting this
+ // test inspect the actual computed plugins array.
+ const result = await runtime.updateAgentConfig('agent-id', {
+ config: { model: 'gpt-4o' },
+ togglePlugin: { pluginId: 'plugin-2', enabled: true },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({
+ config: {
+ newValues: {
+ plugins: ['plugin-1', { identifier: 'plugin-2', mode: 'pinned' }],
+ },
+ },
+ });
+ } finally {
+ mockAgentConfig.plugins = originalPlugins;
+ }
+ });
});
describe('deleteAgent', () => {
@@ -682,6 +727,28 @@ describe('AgentManagerRuntime', () => {
expect(result.content).toContain('not found');
});
+ it('flips an existing disabled object entry back to pinned, without duplicating it', async () => {
+ const originalPlugins = mockAgentConfig.plugins;
+ mockAgentConfig.plugins = [
+ { identifier: 'lobe-web-browsing', mode: 'disabled' } as any,
+ ] as any;
+
+ try {
+ const result = await runtime.installPlugin('agent-id', {
+ identifier: 'lobe-web-browsing',
+ source: 'official',
+ });
+
+ expect(result.success).toBe(true);
+ expect(getLastOptimisticConfigUpdateCall()).toEqual([
+ 'agent-id',
+ { plugins: [{ identifier: 'lobe-web-browsing', mode: 'pinned' }] },
+ ]);
+ } finally {
+ mockAgentConfig.plugins = originalPlugins;
+ }
+ });
+
it('should install market plugin', async () => {
const result = await runtime.installPlugin('agent-id', {
identifier: 'market-plugin',
diff --git a/packages/builtin-tool-creds/src/helpers.test.ts b/packages/builtin-tool-creds/src/helpers.test.ts
index 9c70c818fad..030e15cdf99 100644
--- a/packages/builtin-tool-creds/src/helpers.test.ts
+++ b/packages/builtin-tool-creds/src/helpers.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { generateCredsList } from './helpers';
+import {
+ excludeDisabledComposioServices,
+ generateCredsList,
+ resolveAvailableComposioServices,
+} from './helpers';
describe('generateCredsList', () => {
it("tags a member-shared credential with who shared it, never as the workspace's own", () => {
@@ -42,3 +46,60 @@ describe('generateCredsList', () => {
expect(result).not.toContain('[workspace credential]');
});
});
+
+describe('excludeDisabledComposioServices', () => {
+ it('drops a service the agent has disabled from the list', () => {
+ const result = excludeDisabledComposioServices(
+ [
+ { identifier: 'gmail', name: 'Gmail' },
+ { identifier: 'slack', name: 'Slack' },
+ ],
+ new Set(['gmail']),
+ );
+
+ expect(result).toEqual([{ identifier: 'slack', name: 'Slack' }]);
+ });
+
+ it('keeps every service unchanged when nothing is disabled', () => {
+ const services = [{ identifier: 'gmail', name: 'Gmail' }];
+
+ expect(excludeDisabledComposioServices(services, new Set())).toEqual(services);
+ });
+});
+
+describe('resolveAvailableComposioServices', () => {
+ const appTypes = [
+ { identifier: 'gmail', label: 'Gmail' },
+ { identifier: 'slack', label: 'Slack' },
+ { identifier: 'jira', label: 'Jira' },
+ ];
+
+ it('excludes an already-connected app type from the available list', () => {
+ const result = resolveAvailableComposioServices(appTypes, new Set(['gmail']), new Set());
+
+ expect(result).toEqual([
+ { identifier: 'slack', name: 'Slack' },
+ { identifier: 'jira', name: 'Jira' },
+ ]);
+ });
+
+ it('excludes a disabled app type even though it is not connected', () => {
+ const result = resolveAvailableComposioServices(appTypes, new Set(), new Set(['slack']));
+
+ expect(result.map((s) => s.identifier)).not.toContain('slack');
+ expect(result.map((s) => s.identifier)).toEqual(['gmail', 'jira']);
+ });
+
+ it('a disabled app type never resurfaces as "available" even though it is not connected', () => {
+ // Regression: mirrors the real bug (composio_integrations still listed a
+ // disabled service as "available to connect" because only the connected
+ // list was filtered, not the available one).
+ const result = resolveAvailableComposioServices(
+ appTypes,
+ new Set(['gmail']),
+ new Set(['slack']),
+ );
+
+ expect(result).toEqual([{ identifier: 'jira', name: 'Jira' }]);
+ });
+});
diff --git a/packages/builtin-tool-creds/src/helpers.ts b/packages/builtin-tool-creds/src/helpers.ts
index 4fe8130e904..5ca9da47855 100644
--- a/packages/builtin-tool-creds/src/helpers.ts
+++ b/packages/builtin-tool-creds/src/helpers.ts
@@ -113,6 +113,37 @@ export interface ComposioServiceSummary {
name: string;
}
+export interface ComposioAppTypeLike {
+ identifier: string;
+ label: string;
+}
+
+/**
+ * Drops services the agent has disabled (tri-state `agents.plugins`) from a
+ * Composio service list. Shared by both the client (contextEngineering.ts)
+ * and server (callLlm.ts) prompt-building paths so a disabled integration
+ * never surfaces as "connected — use tools directly" in either one.
+ */
+export const excludeDisabledComposioServices = <T extends { identifier: string }>(
+ services: T[],
+ disabledIds: Set<string>,
+): T[] => services.filter((s) => !disabledIds.has(s.identifier));
+
+/**
+ * Builds the "available to connect" list: every known Composio app type
+ * that's neither already connected nor disabled for this agent. The client
+ * and server paths compute this identically off the static
+ * `COMPOSIO_APP_TYPES` catalog, so it's extracted once here.
+ */
+export const resolveAvailableComposioServices = (
+ appTypes: ComposioAppTypeLike[],
+ connectedIds: Set<string>,
+ disabledIds: Set<string>,
+): ComposioServiceSummary[] =>
+ appTypes
+ .filter((t) => !connectedIds.has(t.identifier) && !disabledIds.has(t.identifier))
+ .map((t) => ({ identifier: t.identifier, name: t.label }));
+
/**
* Generate the Composio services list string for injection into the prompt
*/
diff --git a/packages/builtin-tool-creds/src/index.ts b/packages/builtin-tool-creds/src/index.ts
index 56f107c04ce..958a58afc60 100644
--- a/packages/builtin-tool-creds/src/index.ts
+++ b/packages/builtin-tool-creds/src/index.ts
@@ -1,13 +1,16 @@
export { CredsExecutionRuntime, type ICredsService } from './ExecutionRuntime';
export {
checkCredsSatisfied,
+ type ComposioAppTypeLike,
type ComposioServiceSummary,
type CredRequirement,
type CredSummary,
+ excludeDisabledComposioServices,
generateComposioServicesList,
generateCredsList,
groupCredsByType,
injectCredsContext,
+ resolveAvailableComposioServices,
type UserCredsContext,
} from './helpers';
export { CredsIdentifier, CredsManifest } from './manifest';
diff --git a/packages/context-engine/src/engine/skills/SkillResolver.ts b/packages/context-engine/src/engine/skills/SkillResolver.ts
index 3b645954bfe..7c9f94c60f6 100644
--- a/packages/context-engine/src/engine/skills/SkillResolver.ts
+++ b/packages/context-engine/src/engine/skills/SkillResolver.ts
@@ -50,13 +50,24 @@ export class SkillResolver {
const isOperationActivated = enabledPluginIds.has(skill.identifier);
const stepActivation = stepActivatedMap.get(skill.identifier);
const isStepActivated = !!stepActivation;
+ // Step delta content overrides original content if provided
+ const resolvedContent = stepActivation?.content || skill.content;
- if (isOperationActivated || isStepActivated) {
+ // Being pinned (isOperationActivated) alone must NOT force `activated:
+ // true` when there's no real content to inject — e.g. a ZIP-bundled
+ // skill whose content is deliberately withheld until `activateSkill`
+ // mounts its bundle (see resolveClientSkills / aiAgent's skills build).
+ // Force-activating it anyway would make it vanish from BOTH the
+ // injected content (no content to show) and SkillContextProvider's
+ // <available_skills> list (which only lists non-activated skills) —
+ // making a pinned-but-unmounted skill invisible to the model entirely.
+ // Falling through here keeps it listed as available so the model can
+ // still discover and activate it.
+ if ((isOperationActivated || isStepActivated) && resolvedContent) {
return {
...skill,
activated: true,
- // Step delta content overrides original content if provided
- content: stepActivation?.content || skill.content,
+ content: resolvedContent,
};
}
diff --git a/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts b/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts
index 9faf74e1b8c..4c6be15a48e 100644
--- a/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts
+++ b/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts
@@ -98,7 +98,11 @@ describe('SkillResolver', () => {
const resolved = resolver.resolve(operationSkillSet, delta, accumulated);
- expect(resolved.enabledSkills.filter((s) => s.activated)).toHaveLength(3);
+ // `lobehub-cli` has no content anywhere (neither its own base definition
+ // nor the accumulated activation) — see the dedicated content-guard
+ // tests below for why it's correctly excluded here rather than being
+ // force-activated with nothing to show.
+ expect(resolved.enabledSkills.filter((s) => s.activated)).toHaveLength(2);
});
it('should let step delta content override original content', () => {
@@ -134,4 +138,53 @@ describe('SkillResolver', () => {
const artifacts = resolved.enabledSkills.find((s) => s.identifier === 'artifacts');
expect(artifacts?.content).toBe('from-delta');
});
+
+ describe('content guard — a pinned/activated skill with no content must not vanish', () => {
+ // Regression test: a ZIP-bundled skill deliberately has no pre-fetched
+ // `content` (resolveClientSkills / aiAgent's skills build withhold it
+ // until `activateSkill` mounts the bundle). Before this fix, being pinned
+ // alone forced `activated: true` with `content: undefined` — and
+ // SkillContextProvider's `activated && content` / `!activated` filters
+ // both reject that combination, making the skill invisible in the
+ // injected prompt entirely (neither auto-injected nor listed as
+ // available for the model to discover and activate).
+ const bundledSkill = {
+ description: 'A skill whose content requires activation to mount',
+ identifier: 'pptx',
+ name: 'PPTX',
+ // no `content` — mirrors a ZIP-bundled skill pre-activation
+ };
+
+ it('does not mark a pinned skill activated when it has no content', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: ['pptx'],
+ skills: [bundledSkill],
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, emptyDelta);
+
+ const pptx = resolved.enabledSkills.find((s) => s.identifier === 'pptx');
+ // Falls through as a plain (non-activated) entry — visible to
+ // SkillContextProvider's `!activated` (available) bucket instead of
+ // vanishing.
+ expect(pptx?.activated).toBeUndefined();
+ expect(pptx?.content).toBeUndefined();
+ });
+
+ it('activates it once a step delta supplies real content (post-activateSkill)', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: ['pptx'],
+ skills: [bundledSkill],
+ };
+ const delta: StepSkillDelta = {
+ activatedSkills: [{ content: 'mounted skill content', identifier: 'pptx' }],
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, delta);
+
+ const pptx = resolved.enabledSkills.find((s) => s.identifier === 'pptx');
+ expect(pptx?.activated).toBe(true);
+ expect(pptx?.content).toBe('mounted skill content');
+ });
+ });
});
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 056bd0ac3e9..e5811561994 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -312,7 +312,12 @@ export class SessionModel {
if (item) return;
return await this.create({
- config: merge(DEFAULT_AGENT_CONFIG, defaultAgentConfig),
+ // `merge` returns the `@lobechat/types` LobeAgentConfig shape
+ // (plugins: AgentPluginEntry[]); `create`'s `config` is the DB-layer
+ // NewAgent, whose `plugins` column type is intentionally left as
+ // `string[]` (only the domain types are widened for the tri-state
+ // rollout, not the JSONB column's compile-time annotation).
+ config: merge(DEFAULT_AGENT_CONFIG, defaultAgentConfig) as Partial<NewAgent>,
slug: INBOX_SESSION_ID,
type: 'agent',
});
@@ -533,8 +538,7 @@ export class SessionModel {
type,
...res
}: SessionItem & { agentsToSessions?: { agent: AgentItem }[] }):
- | LobeAgentSession
- | LobeGroupSession => {
+ LobeAgentSession | LobeGroupSession => {
const meta = {
avatar: avatar ?? undefined,
backgroundColor: backgroundColor ?? undefined,
diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.ts
index dbf7162ca84..693acc35522 100644
--- a/packages/database/src/repositories/agentGroup/index.ts
+++ b/packages/database/src/repositories/agentGroup/index.ts
@@ -1,5 +1,5 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
-import type { AgentGroupDetail, AgentGroupMember } from '@lobechat/types';
+import type { AgentGroupDetail, AgentGroupMember, AgentPluginEntry } from '@lobechat/types';
import { cleanObject } from '@lobechat/utils';
import { and, eq, inArray, not } from 'drizzle-orm';
@@ -41,7 +41,7 @@ export interface SupervisorAgentConfig {
description?: string;
model?: string;
params?: any;
- plugins?: string[];
+ plugins?: AgentPluginEntry[];
provider?: string;
systemRole?: string;
tags?: string[];
@@ -427,7 +427,11 @@ export class AgentGroupRepository {
description: supervisorConfig?.description,
model: supervisorConfig?.model,
params: supervisorConfig?.params,
- plugins: supervisorConfig?.plugins,
+ // The `plugins` column is still typed `string[]` at the schema layer
+ // (widening deferred to the tri-state rollout's final phase) but
+ // legitimately holds mixed AgentPluginEntry[] at runtime — JSONB has
+ // no schema enforcement.
+ plugins: supervisorConfig?.plugins as unknown as string[] | undefined,
provider: supervisorConfig?.provider,
systemRole: supervisorConfig?.systemRole,
tags: supervisorConfig?.tags,
diff --git a/packages/database/src/repositories/dataImporter/deprecated/index.ts b/packages/database/src/repositories/dataImporter/deprecated/index.ts
index 0af03556a15..e1b25b89cfb 100644
--- a/packages/database/src/repositories/dataImporter/deprecated/index.ts
+++ b/packages/database/src/repositories/dataImporter/deprecated/index.ts
@@ -144,6 +144,14 @@ export class DeprecatedDataImporterRepos {
.values(
shouldInsertSessionAgents.map(({ config, meta }) => ({
...config,
+ // `config` is the `@lobechat/types` LobeAgentConfig shape
+ // (plugins: AgentPluginEntry[]); the `agents` table's
+ // `plugins` column is intentionally left typed `string[]`
+ // (only the domain types are widened for the tri-state
+ // rollout, not the JSONB column's compile-time annotation).
+ // Legacy import payloads only ever contain bare strings
+ // anyway.
+ plugins: config.plugins as unknown as string[] | undefined,
...meta,
userId: this.userId,
workspaceId: this.workspaceId ?? null,
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 121959f5e48..1aeccbd19b1 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -3035,6 +3035,8 @@ When I am ___, I need ___
'tools.search': 'Search skills...',
'tools.activation.auto': 'Auto',
'tools.activation.auto.desc': 'Smart',
+ 'tools.activation.disabled': 'Disabled',
+ 'tools.activation.disabled.desc': 'Turned Off',
'tools.activation.fixed.hint': 'Always on — managed by the app and can’t be turned off',
'tools.activation.pinned': 'Pinned',
'tools.activation.pinned.desc': 'Always On',
diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.ts
index 741bd726a29..72b57eafa69 100644
--- a/packages/types/src/agent/index.ts
+++ b/packages/types/src/agent/index.ts
@@ -3,4 +3,5 @@ export * from './agentConfig';
export * from './chatConfig';
export * from './document';
export * from './item';
+export * from './pluginConfig';
export * from './tts';
diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.ts
index 903f5329b37..d2125501c11 100644
--- a/packages/types/src/agent/item.ts
+++ b/packages/types/src/agent/item.ts
@@ -6,6 +6,7 @@ import type { KnowledgeBaseItem } from '../knowledgeBase';
import type { FewShots } from '../llm';
import type { LobeAgentAgencyConfig } from './agencyConfig';
import { AgentChatConfigSchema, type LobeAgentChatConfig } from './chatConfig';
+import { type AgentPluginEntry, AgentPluginEntrySchema } from './pluginConfig';
import type { LobeAgentTTSConfig } from './tts';
/**
@@ -64,9 +65,13 @@ export interface LobeAgentConfig {
*/
params: LLMParams;
/**
- * Enabled plugins
+ * Enabled plugins. Each entry is either a legacy bare identifier string
+ * (implicit pinned) or a tri-state `{ identifier, mode }` object — see
+ * `AgentPluginEntry` / `parsePluginEntry`. Prefer the read helpers
+ * (`getActivePluginIds`, `getPinnedPluginIds`, `getDisabledPluginIds`,
+ * `getPluginMode`) over reading this field directly.
*/
- plugins?: string[];
+ plugins?: AgentPluginEntry[];
/**
* Model provider
@@ -114,7 +119,7 @@ export const CreateAgentSchema = z.object({
openingMessage: z.string().nullish(),
openingQuestions: z.array(z.string()).optional(),
params: z.record(z.unknown()).optional(),
- plugins: z.array(z.string()).optional(),
+ plugins: z.array(AgentPluginEntrySchema).optional(),
provider: z.string().nullish(),
sessionGroupId: z.string().nullish(),
systemRole: z.string().nullish(),
@@ -150,7 +155,7 @@ export interface AgentItem {
openingMessage?: string | null;
openingQuestions?: string[];
params?: any;
- plugins?: string[];
+ plugins?: AgentPluginEntry[];
provider?: string | null;
/** Session group ID for direct grouping */
sessionGroupId?: string | null;
diff --git a/packages/types/src/agent/pluginConfig.test.ts b/packages/types/src/agent/pluginConfig.test.ts
new file mode 100644
index 00000000000..a451a09d865
--- /dev/null
+++ b/packages/types/src/agent/pluginConfig.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getActivePluginIds,
+ getDisabledPluginIds,
+ getPinnedPluginIds,
+ getPluginMode,
+ parsePluginEntry,
+ upsertPluginMode,
+} from './pluginConfig';
+
+describe('parsePluginEntry', () => {
+ it('resolves a legacy string entry as pinned', () => {
+ expect(parsePluginEntry('web-search')).toEqual({ identifier: 'web-search', mode: 'pinned' });
+ });
+
+ it('resolves an object entry with no mode as pinned', () => {
+ expect(parsePluginEntry({ identifier: 'web-search' })).toEqual({
+ identifier: 'web-search',
+ mode: 'pinned',
+ });
+ });
+
+ it('resolves an object entry with an explicit mode', () => {
+ expect(parsePluginEntry({ identifier: 'web-search', mode: 'auto' })).toEqual({
+ identifier: 'web-search',
+ mode: 'auto',
+ });
+ expect(parsePluginEntry({ identifier: 'web-search', mode: 'disabled' })).toEqual({
+ identifier: 'web-search',
+ mode: 'disabled',
+ });
+ expect(parsePluginEntry({ identifier: 'web-search', mode: 'pinned' })).toEqual({
+ identifier: 'web-search',
+ mode: 'pinned',
+ });
+ });
+});
+
+describe('getPluginMode', () => {
+ it('returns auto when plugins is undefined', () => {
+ expect(getPluginMode(undefined, 'web-search')).toBe('auto');
+ });
+
+ it('returns auto when the identifier is not present', () => {
+ expect(getPluginMode(['a', 'b'], 'web-search')).toBe('auto');
+ });
+
+ it('returns pinned for a legacy string entry', () => {
+ expect(getPluginMode(['web-search'], 'web-search')).toBe('pinned');
+ });
+
+ it('returns the explicit mode for an object entry', () => {
+ expect(getPluginMode([{ identifier: 'web-search', mode: 'disabled' }], 'web-search')).toBe(
+ 'disabled',
+ );
+ });
+
+ it('resolves correctly within a mixed-shape array', () => {
+ const plugins = [
+ 'legacy-a',
+ { identifier: 'disabled-b', mode: 'disabled' as const },
+ { identifier: 'pinned-c', mode: 'pinned' as const },
+ ];
+
+ expect(getPluginMode(plugins, 'legacy-a')).toBe('pinned');
+ expect(getPluginMode(plugins, 'disabled-b')).toBe('disabled');
+ expect(getPluginMode(plugins, 'pinned-c')).toBe('pinned');
+ expect(getPluginMode(plugins, 'not-there')).toBe('auto');
+ });
+});
+
+describe('getPinnedPluginIds / getDisabledPluginIds / getActivePluginIds', () => {
+ const plugins = [
+ 'legacy-a',
+ { identifier: 'disabled-b', mode: 'disabled' as const },
+ { identifier: 'pinned-c', mode: 'pinned' as const },
+ { identifier: 'auto-d', mode: 'auto' as const },
+ ];
+
+ it('collects pinned identifiers, including legacy strings and mode-less objects', () => {
+ expect(getPinnedPluginIds(plugins)).toEqual(['legacy-a', 'pinned-c']);
+ });
+
+ it('collects disabled identifiers', () => {
+ expect(getDisabledPluginIds(plugins)).toEqual(['disabled-b']);
+ });
+
+ it('getActivePluginIds mirrors getPinnedPluginIds', () => {
+ expect(getActivePluginIds(plugins)).toEqual(getPinnedPluginIds(plugins));
+ });
+
+ it('returns an empty array for undefined input', () => {
+ expect(getPinnedPluginIds(undefined)).toEqual([]);
+ expect(getDisabledPluginIds(undefined)).toEqual([]);
+ expect(getActivePluginIds(undefined)).toEqual([]);
+ });
+});
+
+describe('upsertPluginMode', () => {
+ it('appends a new object entry when the identifier is absent', () => {
+ expect(upsertPluginMode(['a'], 'b', 'disabled')).toEqual([
+ 'a',
+ { identifier: 'b', mode: 'disabled' },
+ ]);
+ });
+
+ it('updates an existing object entry in place, preserving other fields', () => {
+ const plugins = [{ identifier: 'a', mode: 'pinned' as const, extra: 'keep-me' } as any];
+
+ expect(upsertPluginMode(plugins, 'a', 'disabled')).toEqual([
+ { identifier: 'a', mode: 'disabled', extra: 'keep-me' },
+ ]);
+ });
+
+ it('upgrades a touched legacy string entry to an object, leaving others as strings', () => {
+ const plugins = ['a', 'b', 'c'];
+
+ expect(upsertPluginMode(plugins, 'b', 'disabled')).toEqual([
+ 'a',
+ { identifier: 'b', mode: 'disabled' },
+ 'c',
+ ]);
+ });
+
+ it('never mutates the input array', () => {
+ const plugins = ['a', 'b'];
+ const result = upsertPluginMode(plugins, 'a', 'disabled');
+
+ expect(plugins).toEqual(['a', 'b']);
+ expect(result).not.toBe(plugins);
+ });
+
+ it('handles undefined input by creating a new array', () => {
+ expect(upsertPluginMode(undefined, 'a', 'pinned')).toEqual([
+ { identifier: 'a', mode: 'pinned' },
+ ]);
+ });
+
+ it('removes the entry (legacy string or object) when set to auto, instead of persisting it', () => {
+ expect(upsertPluginMode(['a', 'b'], 'a', 'auto')).toEqual(['b']);
+ expect(
+ upsertPluginMode([{ identifier: 'a', mode: 'disabled' as const }, 'b'], 'a', 'auto'),
+ ).toEqual(['b']);
+ });
+
+ it('is a no-op when setting auto on an identifier that is already absent', () => {
+ expect(upsertPluginMode(['a'], 'not-there', 'auto')).toEqual(['a']);
+ });
+});
diff --git a/packages/types/src/agent/pluginConfig.ts b/packages/types/src/agent/pluginConfig.ts
new file mode 100644
index 00000000000..d880ec7b567
--- /dev/null
+++ b/packages/types/src/agent/pluginConfig.ts
@@ -0,0 +1,121 @@
+import { z } from 'zod';
+
+/**
+ * Three-state per-agent plugin config.
+ *
+ * `agents.plugins` (JSONB) stays `AgentPluginEntry[]` at the DB layer — no
+ * schema migration. Legacy rows only ever contain bare identifier strings;
+ * new writes upgrade a touched entry to `AgentPluginConfigItem` in place and
+ * leave every other, untouched entry in its original shape (lazy per-item
+ * upgrade — mixed-shape arrays are a permanent, not transitional, state).
+ */
+export type AgentPluginMode = 'pinned' | 'auto' | 'disabled';
+
+export interface AgentPluginConfigItem {
+ identifier: string;
+ /**
+ * @default 'pinned' — absent on legacy string entries and on object
+ * entries written before this field existed.
+ */
+ mode?: AgentPluginMode;
+}
+
+export type AgentPluginEntry = string | AgentPluginConfigItem;
+
+export const AgentPluginModeSchema = z.enum(['pinned', 'auto', 'disabled']);
+
+/**
+ * Zod schema for a single `plugins[]` entry — for input validation on
+ * routers/procedures that accept a caller-supplied plugins array (e.g. group
+ * member creation). Accepts both the legacy bare string and the tri-state
+ * object shape, so a client can pre-seed a disabled/pinned entry instead of
+ * being rejected by a `z.array(z.string())` schema.
+ */
+export const AgentPluginEntrySchema: z.ZodType<AgentPluginEntry> = z.union([
+ z.string(),
+ z.object({ identifier: z.string(), mode: AgentPluginModeSchema.optional() }),
+]);
+
+/**
+ * Normalizes a single entry: legacy strings and mode-less objects both
+ * resolve to `'pinned'`, matching the pre-existing "present in the array ==
+ * pinned" behavior.
+ */
+export const parsePluginEntry = (
+ entry: AgentPluginEntry,
+): { identifier: string; mode: AgentPluginMode } =>
+ typeof entry === 'string'
+ ? { identifier: entry, mode: 'pinned' }
+ : { identifier: entry.identifier, mode: entry.mode ?? 'pinned' };
+
+/**
+ * Resolves an identifier's mode. An identifier absent from `plugins`
+ * altogether is `'auto'` — the implicit default for anything in the user's
+ * installed/connected pool that the agent hasn't explicitly pinned or
+ * disabled.
+ */
+export const getPluginMode = (
+ plugins: AgentPluginEntry[] | undefined,
+ identifier: string,
+): AgentPluginMode => {
+ const entry = plugins?.find((item) => parsePluginEntry(item).identifier === identifier);
+ return entry ? parsePluginEntry(entry).mode : 'auto';
+};
+
+const getPluginIdsByMode = (
+ plugins: AgentPluginEntry[] | undefined,
+ mode: AgentPluginMode,
+): string[] =>
+ (plugins ?? [])
+ .map((item) => parsePluginEntry(item))
+ .filter((item) => item.mode === mode)
+ .map((item) => item.identifier);
+
+export const getPinnedPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
+ getPluginIdsByMode(plugins, 'pinned');
+
+export const getDisabledPluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
+ getPluginIdsByMode(plugins, 'disabled');
+
+/**
+ * Pinned identifiers — the drop-in replacement for runtime boundaries that
+ * used to read `agentConfig?.plugins ?? []` directly as the enabled-tool
+ * list. Kept as a distinct name from `getPinnedPluginIds` so call sites read
+ * as "what should actually run" rather than "what's pinned".
+ */
+export const getActivePluginIds = (plugins: AgentPluginEntry[] | undefined): string[] =>
+ getPinnedPluginIds(plugins);
+
+/**
+ * Sets `identifier`'s mode, upgrading only that one entry. Every other entry
+ * — including untouched legacy strings — is returned unchanged.
+ *
+ * `'auto'` is the implicit default for an identifier absent from `plugins`
+ * altogether, so setting it explicitly removes any existing entry instead of
+ * persisting a redundant `{ identifier, mode: 'auto' }` record — this mirrors
+ * the pre-tri-state behavior where unpinning spliced the id out of the array.
+ */
+export const upsertPluginMode = (
+ plugins: AgentPluginEntry[] | undefined,
+ identifier: string,
+ mode: AgentPluginMode,
+): AgentPluginEntry[] => {
+ const list = plugins ? [...plugins] : [];
+ const index = list.findIndex((item) => parsePluginEntry(item).identifier === identifier);
+
+ if (mode === 'auto') {
+ if (index !== -1) list.splice(index, 1);
+ return list;
+ }
+
+ if (index === -1) {
+ list.push({ identifier, mode });
+ return list;
+ }
+
+ const existing = list[index];
+ list[index] =
+ typeof existing === 'string' ? { identifier: existing, mode } : { ...existing, mode };
+
+ return list;
+};
diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts
index 0fb2e120997..2f232e2ce51 100644
--- a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts
+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts
@@ -1,5 +1,5 @@
import { type BuilderSuggestionMode } from '@lobechat/prompts';
-import type { AgentGroupDetail } from '@lobechat/types';
+import { type AgentGroupDetail, type AgentPluginEntry, getActivePluginIds } from '@lobechat/types';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,7 +14,7 @@ interface AgentLike {
model?: string | null;
openingMessage?: string | null;
openingQuestions?: (string | undefined)[];
- plugins?: (string | undefined)[];
+ plugins?: AgentPluginEntry[];
provider?: string | null;
systemRole?: string | null;
title?: string | null;
@@ -26,7 +26,9 @@ const summarize = (value: string | null | undefined, fallback: string): string =
const buildAgentSummary = (agent?: AgentLike): string => {
if (!agent) return 'A new agent with default settings and no role configured yet.';
const role = agent.systemRole?.trim();
- const plugins = (agent.plugins ?? []).filter(Boolean) as string[];
+ // Pinned identifiers only — a disabled plugin isn't a "tool enabled" for
+ // the builder-suggestion summary's purposes.
+ const plugins = getActivePluginIds(agent.plugins);
const openingQuestions = agent.openingQuestions ?? [];
return [
`Name: ${summarize(agent.title, '(untitled)')}`,
diff --git a/src/features/AgentSetting/AgentConnectors/index.tsx b/src/features/AgentSetting/AgentConnectors/index.tsx
index 351acdcc24d..9a3d0ab6488 100644
--- a/src/features/AgentSetting/AgentConnectors/index.tsx
+++ b/src/features/AgentSetting/AgentConnectors/index.tsx
@@ -1,3 +1,4 @@
+import { getActivePluginIds } from '@lobechat/types';
import { Switch } from 'antd';
import { LinkIcon } from 'lucide-react';
import { memo, useEffect } from 'react';
@@ -12,7 +13,7 @@ const AgentConnectors = memo(() => {
const { t } = useTranslation('setting');
const [userEnabledPlugins, toggleAgentPlugin] = useStore((s) => [
- s.config.plugins ?? [],
+ getActivePluginIds(s.config.plugins),
s.toggleAgentPlugin,
]);
diff --git a/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx b/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx
index 9dc3b7d22b7..0d3c9800aa0 100644
--- a/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx
+++ b/src/features/AgentSetting/AgentPlugin/LocalPluginItem.tsx
@@ -1,3 +1,4 @@
+import { getActivePluginIds } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { Switch } from 'antd';
import { memo } from 'react';
@@ -10,7 +11,7 @@ const MarketList = memo<{ id: string }>(({ id }) => {
!!s.config.plugins,
s.disabled,
]);
- const plugins = useStore((s) => s.config.plugins || []);
+ const plugins = useStore((s) => getActivePluginIds(s.config.plugins));
return (
<Flexbox horizontal align={'center'} gap={8}>
diff --git a/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx b/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx
index f0c8d1ca74f..a1abe54d8bc 100644
--- a/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx
+++ b/src/features/AgentSetting/AgentPlugin/PluginAction/index.tsx
@@ -1,3 +1,4 @@
+import { getActivePluginIds } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { Switch } from 'antd';
import isEqual from 'fast-deep-equal';
@@ -10,7 +11,7 @@ import { useStore } from '../../store';
const PluginSwitch = memo<{ identifier: string }>(({ identifier }) => {
const pluginManifestLoading = useToolStore((s) => s.pluginInstallLoading, isEqual);
const [userEnabledPlugins, hasPlugin, disabled, toggleAgentPlugin] = useStore((s) => [
- s.config.plugins || [],
+ getActivePluginIds(s.config.plugins),
!!s.config.plugins,
s.disabled,
s.toggleAgentPlugin,
diff --git a/src/features/AgentSetting/AgentPlugin/index.tsx b/src/features/AgentSetting/AgentPlugin/index.tsx
index 5e5665b49fa..1432819c5a7 100644
--- a/src/features/AgentSetting/AgentPlugin/index.tsx
+++ b/src/features/AgentSetting/AgentPlugin/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import { getActivePluginIds } from '@lobechat/types';
import { type FormGroupItemType } from '@lobehub/ui';
import { Avatar, Button, Center, Empty, Flexbox, Form, Tag, Tooltip } from '@lobehub/ui';
import { Space, Switch } from 'antd';
@@ -35,7 +36,9 @@ const AgentPlugin = memo(() => {
}, []);
const [userEnabledPlugins, disabled, toggleAgentPlugin] = useStore((s) => [
- s.config.plugins || [],
+ // Pinned identifiers only — a disabled plugin is a distinct, valid
+ // config state, not a "deprecated" one, and shouldn't show up here.
+ getActivePluginIds(s.config.plugins),
s.disabled,
s.toggleAgentPlugin,
]);
diff --git a/src/features/AgentSetting/store/reducers/config.test.ts b/src/features/AgentSetting/store/reducers/config.test.ts
index 91ae31d33ba..7949e09e540 100644
--- a/src/features/AgentSetting/store/reducers/config.test.ts
+++ b/src/features/AgentSetting/store/reducers/config.test.ts
@@ -36,4 +36,58 @@ describe('configReducer', () => {
});
});
});
+
+ describe('togglePlugin', () => {
+ it('pins a new identifier when absent', () => {
+ const state = { ...DEFAULT_AGENT_CONFIG, plugins: ['plugin-a'] };
+
+ const nextState = configReducer(state, {
+ pluginId: 'plugin-b',
+ type: 'togglePlugin',
+ });
+
+ expect(nextState.plugins).toEqual(['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }]);
+ });
+
+ it('unpins (removes) an already-pinned legacy string entry', () => {
+ const state = { ...DEFAULT_AGENT_CONFIG, plugins: ['plugin-a', 'plugin-b'] };
+
+ const nextState = configReducer(state, {
+ pluginId: 'plugin-b',
+ type: 'togglePlugin',
+ });
+
+ expect(nextState.plugins).toEqual(['plugin-a']);
+ });
+
+ it('flips an existing disabled object entry back to pinned, without duplicating it', () => {
+ const state = {
+ ...DEFAULT_AGENT_CONFIG,
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }] as any,
+ };
+
+ const nextState = configReducer(state, {
+ pluginId: 'plugin-b',
+ state: true,
+ type: 'togglePlugin',
+ });
+
+ expect(nextState.plugins).toEqual(['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }]);
+ });
+
+ it('explicit state=false reverts the entry to auto, removing it from the array', () => {
+ const state = {
+ ...DEFAULT_AGENT_CONFIG,
+ plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'disabled' }] as any,
+ };
+
+ const nextState = configReducer(state, {
+ pluginId: 'plugin-b',
+ state: false,
+ type: 'togglePlugin',
+ });
+
+ expect(nextState.plugins).toEqual(['plugin-a']);
+ });
+ });
});
diff --git a/src/features/AgentSetting/store/reducers/config.ts b/src/features/AgentSetting/store/reducers/config.ts
index b0f8803c5e2..bda61bf5e30 100644
--- a/src/features/AgentSetting/store/reducers/config.ts
+++ b/src/features/AgentSetting/store/reducers/config.ts
@@ -1,3 +1,4 @@
+import { getPluginMode, upsertPluginMode } from '@lobechat/types';
import { produce } from 'immer';
import type { PartialDeep } from 'type-fest';
@@ -21,31 +22,13 @@ export const configReducer = (state: LobeAgentConfig, payload: ConfigDispatch):
case 'togglePlugin': {
return produce(state, (config) => {
const { pluginId: id, state } = payload;
- if (config.plugins === undefined) {
- config.plugins = [];
- }
+ const isPinned = getPluginMode(config.plugins, id) === 'pinned';
+ const shouldPin = typeof state === 'undefined' ? !isPinned : state;
- if (typeof state === 'undefined') {
- // @ts-ignore
- if (config.plugins.includes(id)) {
- // @ts-ignore
- config.plugins.splice(config.plugins.indexOf(id), 1);
-
- return;
- }
- // @ts-ignore
- config.plugins.push(id);
- return;
- }
-
- if (!state) {
- // @ts-ignore
- config.plugins = config?.plugins?.filter?.((pluginId) => pluginId !== id);
- // @ts-ignore
- } else if (!config?.plugins?.includes?.(id)) {
- // @ts-ignore
- config?.plugins?.push(id);
- }
+ // upsertPluginMode preserves an already-matching entry as-is and
+ // flips a disabled entry back to pinned in place, instead of
+ // blindly pushing a duplicate bare-string identifier.
+ config.plugins = upsertPluginMode(config.plugins, id, shouldPin ? 'pinned' : 'auto');
});
}
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 8a6c1d1c67c..e730ca18f80 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -4,6 +4,7 @@ import {
RECOMMENDED_SKILLS,
RecommendedSkillType,
} from '@lobechat/const';
+import { type AgentPluginMode, getDisabledPluginIds } from '@lobechat/types';
import type { ItemType } from '@lobehub/ui';
import { Avatar, Icon, Popover, SearchBar, stopPropagation, Tag, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
@@ -13,6 +14,7 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
import {
BadgeCheck,
+ Ban,
Check,
ChevronDown,
ChevronRight,
@@ -71,7 +73,7 @@ const officialTag = (
</Tooltip>
);
-type SkillPolicyMode = 'auto' | 'pinned';
+type SkillPolicyMode = AgentPluginMode;
interface SkillDeleteConfig {
displayName: string;
@@ -158,6 +160,9 @@ const styles = createStaticStyles(({ css }) => ({
iconDefault: css`
color: ${cssVar.colorTextTertiary};
`,
+ iconDisabled: css`
+ color: ${cssVar.colorError};
+ `,
iconPinned: css`
color: ${cssVar.colorInfo};
`,
@@ -338,6 +343,25 @@ const styles = createStaticStyles(({ css }) => ({
width: 100%;
min-width: 0;
`,
+ toolRowDisabled: css`
+ opacity: 0.5;
+ `,
+ disabledTag: css`
+ display: inline-flex;
+ flex: none;
+ gap: 3px;
+ align-items: center;
+
+ padding-block: 1px;
+ padding-inline: 4px;
+ border: 1px solid ${cssVar.colorErrorBorder};
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorError};
+
+ background: ${cssVar.colorErrorBg};
+ `,
toolTrailing: css`
display: inline-flex;
flex: none;
@@ -434,11 +458,22 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
pluginSelectors.getCustomPluginById(editingPluginId ?? ''),
isEqual,
);
- const [checked, togglePlugin] = useAgentStore((s) => [
+ const [checked, togglePlugin, setPluginMode] = useAgentStore((s) => [
+ // Pinned identifiers only (getAgentPluginsById already excludes disabled).
agentByIdSelectors.getAgentPluginsById(agentId)(s),
s.togglePlugin,
+ s.setPluginMode,
]);
const checkedSet = useMemo(() => new Set(checked), [checked]);
+ // Disabled identifiers, read from the raw (unfiltered) plugins config —
+ // needed to grey out an Auto-group item and to offer the third policy-menu
+ // option. Disabled items stay in the Auto group (no separate group), so
+ // `allPinnedItems`/`allAutoItems` below keep splitting on `checkedSet` alone.
+ const rawPlugins = useAgentStore(
+ (s) => agentByIdSelectors.getAgentConfigById(agentId)(s)?.plugins,
+ );
+ const disabledIds = useMemo(() => getDisabledPluginIds(rawPlugins), [rawPlugins]);
+ const disabledIdSet = useMemo(() => new Set(disabledIds), [disabledIds]);
// 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.
@@ -467,12 +502,16 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const updateSkillPolicy = useCallback(
async (id: string, mode: SkillPolicyMode) => {
if (!canEdit) return;
- const shouldPin = mode === 'pinned';
- if (checkedSet.has(id) === shouldPin) return;
-
- await togglePlugin(id, shouldPin);
+ const currentMode: SkillPolicyMode = checkedSet.has(id)
+ ? 'pinned'
+ : disabledIdSet.has(id)
+ ? 'disabled'
+ : 'auto';
+ if (currentMode === mode) return;
+
+ await setPluginMode(id, mode);
},
- [canEdit, checkedSet, togglePlugin],
+ [canEdit, checkedSet, disabledIdSet, setPluginMode],
);
const openSkillPolicyMenu = useCallback((id: string) => {
@@ -493,7 +532,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// meaningless but the user still needs a way to remove the entry.
deleteOnly = false,
) => {
- const mode: SkillPolicyMode = checkedSet.has(id) ? 'pinned' : 'auto';
+ const mode: SkillPolicyMode = checkedSet.has(id)
+ ? 'pinned'
+ : disabledIdSet.has(id)
+ ? 'disabled'
+ : 'auto';
const renderCheck = (value: SkillPolicyMode) =>
mode === value ? (
<span className={cx(styles.policyCheck)}>
@@ -545,6 +588,15 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
size={15}
/>,
)}
+ {!deleteOnly &&
+ renderPolicyItem(
+ 'disabled',
+ <Icon
+ className={cx(mode === 'disabled' ? styles.iconDisabled : styles.iconDefault)}
+ icon={Ban}
+ size={15}
+ />,
+ )}
{!deleteOnly && (configureConfig || deleteConfig) && (
<div className={cx(styles.deleteDivider)} />
)}
@@ -642,7 +694,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
</Popover>
);
},
- [canEdit, checkedSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],
+ [canEdit, checkedSet, disabledIdSet, openSkillPolicyMenu, policyOpenId, t, updateSkillPolicy],
);
const renderToolLabel = useCallback(
@@ -653,27 +705,39 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
badge?: ReactNode,
icon?: ReactNode,
extraTag?: ReactNode,
- ) => (
- <span
- className={cx(styles.toolRow)}
- onContextMenu={(event) => {
- event.preventDefault();
- event.stopPropagation();
- openSkillPolicyMenu(id);
- }}
- >
- <span className={cx(styles.toolLabel)}>
- {icon}
- <span className={cx(styles.toolLabelText)}>{label}</span>
- {extraTag}
- </span>
- <span className={cx(styles.toolTrailing)}>
- {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
- {action}
+ ) => {
+ // Disabled items stay in the Auto group (no separate group) — greyed out
+ // + relabeled in place, per the confirmed UI plan.
+ const isDisabled = disabledIdSet.has(id);
+
+ return (
+ <span
+ className={cx(styles.toolRow, isDisabled && styles.toolRowDisabled)}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openSkillPolicyMenu(id);
+ }}
+ >
+ <span className={cx(styles.toolLabel)}>
+ {icon}
+ <span className={cx(styles.toolLabelText)}>{label}</span>
+ {isDisabled && (
+ <span className={cx(styles.disabledTag)}>
+ <Icon icon={Ban} size={11} />
+ {t('tools.activation.disabled')}
+ </span>
+ )}
+ {extraTag}
+ </span>
+ <span className={cx(styles.toolTrailing)}>
+ {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
+ {action}
+ </span>
</span>
- </span>
- ),
- [openSkillPolicyMenu],
+ );
+ },
+ [openSkillPolicyMenu, disabledIdSet, t],
);
const createManagedSkillItem = useCallback(
@@ -843,7 +907,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// 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).
+ // 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
@@ -851,7 +916,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
(type) =>
installedComposioIds.has(type.identifier) ||
recommendedComposioIds.has(type.identifier) ||
- checkedSet.has(type.identifier),
+ checkedSet.has(type.identifier) ||
+ disabledIdSet.has(type.identifier),
).map((type) => {
const server = getServerByName(type.identifier);
const icon = (
@@ -903,7 +969,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
// 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)) {
+ if (server || checkedSet.has(type.identifier) || disabledIdSet.has(type.identifier)) {
return {
extra: renderPolicyMenu(
removableId,
@@ -953,6 +1019,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
renderPolicyMenu,
openSkillPolicyMenu,
checkedSet,
+ disabledIdSet,
],
);
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index a6cd20f3ea0..ce8ac2ace9e 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -1,6 +1,7 @@
'use client';
import { COMPOSIO_APP_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
+import { getActivePluginIds, parsePluginEntry, upsertPluginMode } from '@lobechat/types';
import { type ItemType } from '@lobehub/ui';
import { Avatar, Button, Flexbox, Icon } from '@lobehub/ui';
import { McpIcon, SkillsIcon } from '@lobehub/ui/icons';
@@ -76,8 +77,10 @@ const AgentTool = memo<AgentToolProps>(
const effectiveAgentId = agentId || activeAgentId || '';
const config = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId), isEqual);
- // Plugin state management
- const plugins = config?.plugins || [];
+ // 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);
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const updateAgentChatConfigById = useAgentStore((s) => s.updateAgentChatConfigById);
@@ -159,22 +162,18 @@ const AgentTool = memo<AgentToolProps>(
async (pluginId: string, state?: boolean) => {
if (!canEdit) return;
if (!effectiveAgentId) return;
- const currentPlugins = plugins;
- const hasPlugin = currentPlugins.includes(pluginId);
+ const hasPlugin = plugins.includes(pluginId);
const shouldEnable = state !== undefined ? state : !hasPlugin;
-
- let newPlugins: string[];
- if (shouldEnable && !hasPlugin) {
- newPlugins = [...currentPlugins, pluginId];
- } else if (!shouldEnable && hasPlugin) {
- newPlugins = currentPlugins.filter((id) => id !== pluginId);
- } else {
- return;
- }
-
- await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });
+ if (shouldEnable === hasPlugin) 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.
+ await updateAgentConfigById(effectiveAgentId, {
+ plugins: upsertPluginMode(config?.plugins, pluginId, shouldEnable ? 'pinned' : 'auto'),
+ });
},
- [canEdit, effectiveAgentId, plugins, updateAgentConfigById],
+ [canEdit, effectiveAgentId, plugins, config?.plugins, updateAgentConfigById],
);
// Check if a tool is enabled (handles web browsing specially)
@@ -740,7 +739,8 @@ const AgentTool = memo<AgentToolProps>(
useEffect(() => {
if (cleanupDoneRef.current) return;
if (validIdentifiers.size === 0) return;
- if (plugins.length === 0) return;
+ const rawPlugins = config?.plugins ?? [];
+ if (rawPlugins.length === 0) return;
// Don't prune until the connector store has loaded — connector identifiers
// are absent from validIdentifiers until fetchConnectors() resolves, so
// running cleanup before that would incorrectly mark enabled connectors as stale.
@@ -748,10 +748,16 @@ const AgentTool = memo<AgentToolProps>(
// Defer cleanup to avoid race with async data loading (SWR, Composio, etc.)
const timer = setTimeout(() => {
- const stalePlugins = plugins.filter((id) => !validIdentifiers.has(id));
-
- if (stalePlugins.length > 0 && effectiveAgentId) {
- const cleanedPlugins = plugins.filter((id) => validIdentifiers.has(id));
+ // Checked (and filtered) by identifier regardless of entry shape, so
+ // a stale disabled/pinned object entry is pruned exactly like a
+ // stale legacy string one — untouched valid entries keep their
+ // original shape (lazy per-item upgrade).
+ const isValid = (entry: (typeof rawPlugins)[number]) =>
+ validIdentifiers.has(parsePluginEntry(entry).identifier);
+ const hasStale = rawPlugins.some((entry) => !isValid(entry));
+
+ if (hasStale && effectiveAgentId) {
+ const cleanedPlugins = rawPlugins.filter(isValid);
updateAgentConfigById(effectiveAgentId, { plugins: cleanedPlugins });
}
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index 2b12e9ee411..c44a24f05f5 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -120,6 +120,7 @@ vi.mock('../isCanUseFC', () => ({
}));
let mockCurrentAgentPlugins: string[] = [];
+let mockCurrentAgentDisabledPlugins: string[] = [];
vi.mock('@/store/agent', () => ({
getAgentStoreState: () => ({}),
@@ -127,6 +128,7 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
+ currentAgentDisabledPlugins: () => mockCurrentAgentDisabledPlugins,
currentAgentPlugins: () => mockCurrentAgentPlugins,
hasEnabledKnowledgeBases: () => false,
},
@@ -164,6 +166,7 @@ describe('toolEngineering', () => {
mockInstalledPluginManifestList = () => [];
mockUseApplicationBuiltinSearchTool = true;
mockCurrentAgentPlugins = [];
+ mockCurrentAgentDisabledPlugins = [];
mockIsCanUseFC = true;
});
@@ -383,6 +386,33 @@ describe('toolEngineering', () => {
expect(result.enabledToolIds).toContain('stdio-mcp-plugin');
expect(result.enabledToolIds).toContain('lobe-web-browsing');
});
+
+ it('does NOT let isExplicitActivation enable a plugin the agent has disabled', () => {
+ mockInstalledPluginManifestList = () => [
+ {
+ api: [{ description: 'x', name: 'x', parameters: {} }],
+ identifier: 'disabled-plugin',
+ meta: { title: 'Disabled Plugin' },
+ type: 'default',
+ } as unknown as ToolManifest,
+ ];
+ mockCurrentAgentDisabledPlugins = ['disabled-plugin'];
+
+ const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
+ const result = toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ toolIds: ['disabled-plugin'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Unlike a merely rule-disabled tool, a disabled plugin's manifest is
+ // absent from the pool entirely, so explicit activation has nothing to
+ // resolve — it can't bypass a gate that was never reached.
+ expect(result.enabledToolIds).not.toContain('disabled-plugin');
+ expect(result.enabledToolIds).toEqual([]);
+ });
});
describe('stdio MCP filtering on web', () => {
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 5b24d1605c2..9450c06673d 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -44,6 +44,14 @@ export interface ToolsEngineConfig {
additionalManifests?: ToolManifest[];
/** Default tool IDs that will always be added to the end of the tools list */
defaultToolIds?: string[];
+ /**
+ * Identifiers the agent has explicitly disabled (`agents.plugins` tri-state).
+ * Dropped from the combined manifest pool entirely — not just the
+ * enableChecker rule map — because `allowExplicitActivation` lets the
+ * activator resolve/enable any manifest present in `manifestSchemas`
+ * regardless of the rules, bypassing a rule-only gate.
+ */
+ disabledPluginIds?: string[];
/** Custom enable checker for plugins */
enableChecker?: PluginEnableChecker;
/**
@@ -96,7 +104,13 @@ const dropInvalidManifests = (manifests: (ToolManifest | undefined)[], source: s
* Initialize ToolsEngine with current manifest schemas and configurable options
*/
export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine => {
- const { enableChecker, additionalManifests = [], defaultToolIds, manifestContext } = config;
+ const {
+ enableChecker,
+ additionalManifests = [],
+ defaultToolIds,
+ disabledPluginIds = [],
+ manifestContext,
+ } = config;
const toolStoreState = getToolStoreState();
@@ -159,7 +173,7 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
// Combine all manifests, dropping entries that would crash ToolsEngine.
// Each source is filtered separately so the warning pinpoints the origin.
- const allManifests = [
+ const combinedManifests = [
...dropInvalidManifests(pluginManifests, 'installedPlugins'),
...dropInvalidManifests(builtinManifests, 'builtinTools'),
...dropInvalidManifests(composioManifests, 'composio'),
@@ -168,6 +182,15 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
...dropInvalidManifests(additionalManifests, 'additionalManifests'),
];
+ // Disabled identifiers are dropped from the pool outright (not left for the
+ // enableChecker rules) — a plugin, skill, connector, or user-toggleable
+ // builtin tool the agent has explicitly disabled must not be discoverable/
+ // activatable at all, matching the server-side (aiAgent gateway) treatment.
+ const allManifests =
+ disabledPluginIds.length === 0
+ ? combinedManifests
+ : combinedManifests.filter((m) => !disabledPluginIds.includes(m.identifier));
+
return new ToolsEngine({
defaultToolIds,
enableChecker,
@@ -185,7 +208,10 @@ export const createAgentToolsEngine = (
) => {
const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);
const agentState = getAgentStoreState();
+ // `currentAgentPlugins` already resolves to pinned-only identifiers — disabled
+ // entries never reach the tools-engine whitelist.
const userPlugins = agentSelectors.currentAgentPlugins(agentState);
+ const disabledPluginIds = agentSelectors.currentAgentDisabledPlugins(agentState);
const isChatMode =
agentChatConfigSelectors.currentChatConfig(agentState).enableAgentMode === false ||
!isCanUseFC(workingModel.model, workingModel.provider);
@@ -224,6 +250,7 @@ export const createAgentToolsEngine = (
return createToolsEngine({
defaultToolIds: isChatMode ? chatModeAllowedToolIds : defaultToolIds,
+ disabledPluginIds,
manifestContext,
enableChecker: createEnableChecker({
allowExplicitActivation: !isChatMode,
diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
index 37aa17a0648..1876222e688 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
@@ -219,6 +219,7 @@ describe('Agent profile Header', () => {
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
mocks.agentState.isCurrentAgentHeterogeneous = false;
mocks.agentState.systemRole = 'You are helpful.';
+ mocks.agentState.config.plugins = ['lobe-web-browsing'];
mocks.profileState.editor = undefined;
});
@@ -245,6 +246,25 @@ describe('Agent profile Header', () => {
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:agent-profile');
});
+ it('excludes disabled entries from the exported markdown plugin list, in a mixed-shape array', async () => {
+ mocks.agentState.config.plugins = [
+ 'lobe-web-browsing',
+ { identifier: 'lobe-image-generation', mode: 'disabled' } as any,
+ ];
+
+ render(<Header />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }));
+
+ await waitFor(() => expect(URL.createObjectURL).toHaveBeenCalled());
+
+ const exportedBlob = getLatestExportedBlob();
+ const exportedMarkdown = await exportedBlob.text();
+
+ expect(exportedMarkdown).toContain('lobe-web-browsing');
+ expect(exportedMarkdown).not.toContain('lobe-image-generation');
+ });
+
it('should preserve an empty prompt from the mounted editor when exporting markdown', async () => {
mocks.profileState.editor = {
getDocument: vi.fn().mockReturnValue(''),
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index 90c161b4ab5..d3533b8033b 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -1,4 +1,5 @@
import { isDesktop } from '@lobechat/const';
+import { getActivePluginIds } from '@lobechat/types';
import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
@@ -132,7 +133,9 @@ const Header = memo(() => {
const profileMarkdown = buildAgentProfileMarkdown({
description: meta?.description,
model: config.model,
- plugins: config.plugins,
+ // Pinned identifiers only — a disabled plugin shouldn't be advertised
+ // as "enabled" in the exported markdown.
+ plugins: getActivePluginIds(config.plugins),
provider: config.provider,
systemRole: editorMarkdown ?? systemRole,
t,
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 37aed0023b2..5f72af9ef31 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -11,13 +11,15 @@ import { type FetchSSEOptions } from '@lobechat/fetch-sse';
import { fetchSSE, standardizeAnimationStyle } from '@lobechat/fetch-sse';
import type { ChatCompletionErrorPayload } from '@lobechat/model-runtime';
import { AgentRuntimeError, isResponsesAPIModel } from '@lobechat/model-runtime';
-import type {
- RuntimeInitialContext,
- RuntimeStepContext,
- TracePayload,
- UIChatMessage,
+import {
+ ChatErrorType,
+ getDisabledPluginIds,
+ type RuntimeInitialContext,
+ type RuntimeStepContext,
+ type TracePayload,
+ TraceTagMap,
+ type UIChatMessage,
} from '@lobechat/types';
-import { ChatErrorType, TraceTagMap } from '@lobechat/types';
import { merge } from 'es-toolkit/compat';
import { ModelProvider } from 'model-bank';
@@ -285,6 +287,9 @@ class ChatService {
agentBuilderContext,
agentDocuments,
agentId: targetAgentId,
+ // `agentConfig.plugins` is the raw (pre-filter) field — `plugins` below
+ // is already pinned-only (resolved upstream in agentConfigResolver).
+ disabledPluginIds: getDisabledPluginIds(agentConfig.plugins),
enableAgentMode,
// Use raw chatConfig values, not selectors with business logic that may force false
enableHistoryCount: chatConfig.enableHistoryCount,
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index 89958850e2c..dbabad1ba1c 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -117,6 +117,24 @@ describe('resolveAgentConfig', () => {
expect(result.plugins).toEqual([]);
});
+ it('should exclude disabled entries and resolve legacy strings as pinned, in a mixed-shape plugins array', () => {
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(
+ () =>
+ ({
+ ...mockAgentConfig,
+ plugins: [
+ 'plugin-a',
+ { identifier: 'plugin-b', mode: 'disabled' },
+ { identifier: 'plugin-c', mode: 'pinned' },
+ ],
+ }) as any,
+ );
+
+ const result = resolveAgentConfig({ agentId: 'test-agent' });
+
+ expect(result.plugins).toEqual(['plugin-a', 'plugin-c']);
+ });
+
it('should return agent config and chat config correctly', () => {
const result = resolveAgentConfig({ agentId: 'test-agent' });
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index b07633f49ac..a43a405a889 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -5,6 +5,7 @@ import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { type LobeToolManifest } from '@lobechat/context-engine';
import {
type ChatCompletionTool,
+ getActivePluginIds,
type LobeAgentChatConfig,
type LobeAgentConfig,
type MessageMapScope,
@@ -185,8 +186,8 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentStoreState);
const chatConfig = chatConfigByIdSelectors.getChatConfigById(agentId)(agentStoreState);
- // Base plugins from agent config
- const basePlugins = agentConfig?.plugins ?? [];
+ // Base plugins from agent config (pinned identifiers only — disabled entries excluded)
+ const basePlugins = getActivePluginIds(agentConfig?.plugins);
// Check if this is a builtin agent
// Priority: supervisor check (when in group scope) > agent store slug
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index e7d86cd5da5..7d54fd272f8 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -6,8 +6,10 @@ import {
type ComposioServiceSummary,
CredsIdentifier,
type CredSummary,
+ excludeDisabledComposioServices,
generateComposioServicesList,
generateCredsList,
+ resolveAvailableComposioServices,
} from '@lobechat/builtin-tool-creds';
import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
@@ -36,11 +38,12 @@ import type {
} from '@lobechat/context-engine';
import { MessagesEngine, resolveTopicReferences } from '@lobechat/context-engine';
import { historySummaryPrompt } from '@lobechat/prompts';
-import type {
- OpenAIChatMessage,
- RuntimeInitialContext,
- RuntimeStepContext,
- UIChatMessage,
+import {
+ getActivePluginIds,
+ type OpenAIChatMessage,
+ type RuntimeInitialContext,
+ type RuntimeStepContext,
+ type UIChatMessage,
} from '@lobechat/types';
import debug from 'debug';
@@ -87,6 +90,13 @@ interface ContextEngineeringContext {
agentDocuments?: AgentContextDocument[];
/** The agent ID that will respond (for group context injection) */
agentId?: string;
+ /**
+ * Identifiers the agent has explicitly disabled (`agents.plugins` tri-state).
+ * Excluded from the client skill candidate pool entirely — not just left
+ * out of `plugins` (pinned) — so a disabled skill is neither listed in
+ * `<available_skills>` nor resolvable by name via `activateSkill`.
+ */
+ disabledPluginIds?: string[];
/**
* Runtime-resolved agent mode. Callers may force chat mode for models without
* function calling while keeping the stored chatConfig unchanged.
@@ -141,6 +151,7 @@ export const contextEngineering = async ({
agentBuilderContext,
agentDocuments,
agentId,
+ disabledPluginIds,
enableAgentMode,
groupId,
initialContext,
@@ -228,12 +239,15 @@ export const contextEngineering = async ({
const supervisorAgentConfig = agentSelectors.getAgentConfigById(
activeGroupDetail.supervisorAgentId,
)(agentStoreState);
+ // Pinned identifiers only — GroupAgentBuilderContext.supervisorConfig.plugins
+ // is a display/prompt-formatting DTO (still `string[]`) that joins
+ // entries as plain text, and a disabled plugin isn't "enabled".
+ enabledPlugins = getActivePluginIds(supervisorAgentConfig.plugins);
supervisorConfig = {
model: supervisorAgentConfig.model,
- plugins: supervisorAgentConfig.plugins,
+ plugins: enabledPlugins,
provider: supervisorAgentConfig.provider,
};
- enabledPlugins = supervisorAgentConfig.plugins || [];
}
// Build official tools list (builtin tools + Composio tools)
@@ -398,14 +412,12 @@ export const contextEngineering = async ({
try {
const credsResult = await lambdaClient.market.creds.list.query();
const userCreds = (credsResult as any)?.data ?? [];
- credsList = userCreds.map(
- (cred: any): CredSummary => ({
- description: cred.description,
- key: cred.key,
- name: cred.name,
- type: cred.type,
- }),
- );
+ credsList = userCreds.map((cred: any): CredSummary => ({
+ description: cred.description,
+ key: cred.key,
+ name: cred.name,
+ type: cred.type,
+ }));
log('Creds context resolved: count=%d', credsList?.length ?? 0);
} catch (error) {
// Silently fail - creds context is optional
@@ -425,15 +437,23 @@ export const contextEngineering = async ({
try {
const toolState = getToolStoreState();
const allComposioServers = composioStoreSelectors.getServers(toolState);
+ const disabledIdSet = new Set(disabledPluginIds ?? []);
- const connected: ComposioServiceSummary[] = allComposioServers
- .filter((s) => s.status === ComposioServerStatus.ACTIVE)
- .map((s) => ({ identifier: s.identifier, name: s.label }));
+ // Disabled services are dropped from both lists — not surfaced as
+ // "connected, use directly" (this agent shouldn't use it) nor as
+ // "available to connect" (the user's account-level OAuth connection,
+ // if any, is untouched; this agent just isn't meant to see it).
+ const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(
+ allComposioServers.filter((s) => s.status === ComposioServerStatus.ACTIVE),
+ disabledIdSet,
+ ).map((s) => ({ identifier: s.identifier, name: s.label }));
const connectedIds = new Set(connected.map((s) => s.identifier));
- const available: ComposioServiceSummary[] = COMPOSIO_APP_TYPES.filter(
- (t) => !connectedIds.has(t.identifier),
- ).map((t) => ({ identifier: t.identifier, name: t.label }));
+ const available = resolveAvailableComposioServices(
+ COMPOSIO_APP_TYPES,
+ connectedIds,
+ disabledIdSet,
+ );
composioServicesList = generateComposioServicesList(connected, available);
log(
@@ -665,7 +685,7 @@ export const contextEngineering = async ({
// In manual mode: only expose user-selected skills (filtered by pluginIds).
let enabledSkills: OperationSkillSet['skills'] | undefined;
if (plugins) {
- const skillSet = await resolveClientSkills(plugins);
+ const skillSet = await resolveClientSkills(plugins, disabledPluginIds);
if (isInAutoSkillMode) {
enabledSkills = skillSet.skills;
} else {
diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.ts
index f4749a4ab77..87d116094eb 100644
--- a/src/services/chat/mecha/skillEngineering.test.ts
+++ b/src/services/chat/mecha/skillEngineering.test.ts
@@ -181,4 +181,52 @@ describe('resolveClientSkills', () => {
expect(skill?.content).toBeUndefined();
expect(skill?.activated).toBeFalsy();
});
+
+ describe('disabled skills', () => {
+ it('excludes a disabled DB skill entirely, not just from the pinned set', async () => {
+ setToolState({
+ agentSkills: [
+ { description: 'A user skill', id: 'db-1', identifier: 'my-skill', name: 'My Skill' },
+ ],
+ });
+
+ const result = await resolveClientSkills([], ['my-skill']);
+
+ // Not merely unpinned — absent from the candidate pool entirely, so it
+ // can't be listed in <available_skills> or resolved by activateSkill.
+ expect(findSkill(result.skills, 'my-skill')).toBeUndefined();
+ });
+
+ it('excludes a disabled builtin skill entirely', async () => {
+ setToolState({
+ builtinSkills: [
+ {
+ content: '<artifacts_guide>build UI</artifacts_guide>',
+ description: 'Generate interactive UI',
+ identifier: 'artifacts',
+ name: 'Artifacts',
+ source: 'builtin',
+ },
+ ],
+ });
+
+ const result = await resolveClientSkills([], ['artifacts']);
+
+ expect(findSkill(result.skills, 'artifacts')).toBeUndefined();
+ });
+
+ it('keeps a non-disabled skill even when other skills are disabled', async () => {
+ setToolState({
+ agentSkills: [
+ { description: '', id: 'db-1', identifier: 'disabled-skill', name: 'Disabled' },
+ { description: '', id: 'db-2', identifier: 'enabled-skill', name: 'Enabled' },
+ ],
+ });
+
+ const result = await resolveClientSkills([], ['disabled-skill']);
+
+ expect(findSkill(result.skills, 'disabled-skill')).toBeUndefined();
+ expect(findSkill(result.skills, 'enabled-skill')).toBeDefined();
+ });
+ });
});
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index 10c76110fd3..3c111cea41b 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -39,55 +39,66 @@ const buildDbSkillContent = (detail: SkillItem): string | undefined => {
* Uses isBuiltinSkillAvailableInCurrentEnv as the enableChecker to
* filter platform-specific skills (e.g., agent-browser on desktop only).
*/
-export const resolveClientSkills = async (pluginIds?: string[]): Promise<OperationSkillSet> => {
+export const resolveClientSkills = async (
+ pluginIds?: string[],
+ disabledIds?: string[],
+): Promise<OperationSkillSet> => {
const toolState = getToolStoreState();
const pinnedIds = new Set(pluginIds ?? []);
+ const disabledIdSet = new Set(disabledIds ?? []);
// Builtin skills keep their full content in the store, so it is always cheap
// to carry along. Pinned skills are marked `activated` so SkillContextProvider
// injects their content directly; non-pinned ones stay in <available_skills>.
- const builtinMetas = (toolState.builtinSkills || []).map((s) => ({
- activated: pinnedIds.has(s.identifier) && !!s.content,
- content: s.content,
- description: s.description,
- identifier: s.identifier,
- name: s.name,
- }));
+ // Disabled skills are dropped from the candidate pool entirely — not just
+ // left unpinned — so a disabled skill is neither listed nor resolvable by
+ // name via `activateSkill`.
+ const builtinMetas = (toolState.builtinSkills || [])
+ .filter((s) => !disabledIdSet.has(s.identifier))
+ .map((s) => ({
+ activated: pinnedIds.has(s.identifier) && !!s.content,
+ content: s.content,
+ description: s.description,
+ identifier: s.identifier,
+ name: s.name,
+ }));
const dbMetas = await Promise.all(
- (toolState.agentSkills || []).map(async (s) => {
- const meta = {
- description: s.description ?? '',
- identifier: s.identifier,
- name: s.name,
- };
+ (toolState.agentSkills || [])
+ .filter((s) => !disabledIdSet.has(s.identifier))
+ .map(async (s) => {
+ const meta = {
+ description: s.description ?? '',
+ identifier: s.identifier,
+ name: s.name,
+ };
- // Only pinned DB skills need full content for direct injection; the list
- // query (SkillListItem) does not carry content, so fetch it on demand.
- if (!pinnedIds.has(s.identifier)) return meta;
+ // Only pinned DB skills need full content for direct injection; the list
+ // query (SkillListItem) does not carry content, so fetch it on demand.
+ if (!pinnedIds.has(s.identifier)) return meta;
- // Skills bundled as a ZIP (scripts/resources) must be activated via the
- // activateSkill tool so the server mounts their bundle for execScript /
- // readReference — that runtime mount is keyed off stepContext.activatedSkills,
- // which operation-level pinning does not populate. Pre-injecting their
- // content would instruct the model to run scripts from an unmounted bundle,
- // so leave bundled skills in <available_skills> and let the model activate them.
- if (s.zipFileHash) return meta;
+ // Skills bundled as a ZIP (scripts/resources) must be activated via the
+ // activateSkill tool so the server mounts their bundle for execScript /
+ // readReference — that runtime mount is keyed off stepContext.activatedSkills,
+ // which operation-level pinning does not populate. Pre-injecting their
+ // content would instruct the model to run scripts from an unmounted bundle,
+ // so leave bundled skills in <available_skills> and let the model activate them.
+ if (s.zipFileHash) return meta;
- try {
- const detail =
- toolState.agentSkillDetailMap?.[s.id] ?? (await agentSkillService.getById(s.id));
- const content = detail && buildDbSkillContent(detail);
- // Mark activated only when content is available, otherwise the skill would
- // be excluded from both the activated and the <available_skills> lists.
- return content ? { ...meta, activated: true, content } : meta;
- } catch (error) {
- // A single skill's content fetch must never break the whole request;
- // degrade gracefully by listing the skill without injected content.
- log('Failed to load content for pinned skill %s: %O', s.identifier, error);
- return meta;
- }
- }),
+ try {
+ const detail =
+ toolState.agentSkillDetailMap?.[s.id] ?? (await agentSkillService.getById(s.id));
+ const content = detail && buildDbSkillContent(detail);
+ // Mark activated only when content is available, otherwise the skill would
+ // be excluded from both the activated and the <available_skills> lists.
+ return content ? { ...meta, activated: true, content } : meta;
+ } catch (error) {
+ // A single skill's content fetch must never break the whole request;
+ // degrade gracefully by listing the skill without injected content.
+ log('Failed to load content for pinned skill %s: %O', s.identifier, error);
+ return meta;
+ }
+ }),
);
const skillEngine = new SkillEngine({
diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.ts
index 2f6362d7a2f..656e76e811c 100644
--- a/src/store/agent/selectors/agentByIdSelectors.test.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts
@@ -57,11 +57,30 @@ describe('agentByIdSelectors', () => {
expect(context.config).toMatchObject({
chatConfig: undefined,
model: undefined,
- plugins: undefined,
+ // getActivePluginIds always normalizes to an array, even for a
+ // missing/undefined raw plugins field.
+ plugins: [],
provider: undefined,
systemRole: undefined,
});
});
+
+ it('excludes disabled entries from the builder context plugins, in a mixed-shape array', () => {
+ const state = createState({
+ agentMap: {
+ 'agent-1': {
+ model: 'gpt-4o',
+ plugins: ['search', { identifier: 'lobe-web-browsing', mode: 'disabled' }],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ } as any,
+ },
+ });
+
+ const context = agentByIdSelectors.getAgentBuilderContextById('agent-1')(state);
+
+ expect(context.config.plugins).toEqual(['search']);
+ });
});
describe('agent mode', () => {
diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.ts
index da33bf17d17..7e6b5820bba 100644
--- a/src/store/agent/selectors/agentByIdSelectors.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.ts
@@ -3,6 +3,7 @@ import { DEFAULT_MODEL, DEFAUTT_AGENT_TTS_CONFIG, isDesktop } from '@lobechat/co
import { type AgentBuilderContext } from '@lobechat/context-engine';
import {
type AgentMode,
+ getActivePluginIds,
getWorkingDirEffectivePath,
type LobeAgentAgencyConfig,
type LobeAgentTTSConfig,
@@ -30,10 +31,16 @@ const getAgentModelProviderById =
(s: AgentStoreState): string =>
agentSelectors.getAgentConfigById(agentId)(s)?.provider || DEFAULT_PROVIDER;
+/**
+ * Pinned plugin identifiers for the agent — disabled entries are excluded.
+ * Every current consumer (token estimation, share-image preview, auth alerts,
+ * the Skills panel) wants "what's actually configured/active", matching the
+ * pre-tri-state semantics where array-membership meant pinned.
+ */
const getAgentPluginsById =
(agentId: string) =>
(s: AgentStoreState): string[] =>
- agentSelectors.getAgentConfigById(agentId)(s)?.plugins || [];
+ getActivePluginIds(agentSelectors.getAgentConfigById(agentId)(s)?.plugins);
const getAgentSystemRoleById =
(agentId: string) =>
@@ -147,7 +154,9 @@ const getAgentBuilderContextById =
openingMessage: config?.openingMessage,
openingQuestions: config?.openingQuestions,
params: config?.params,
- plugins: config?.plugins,
+ // Pinned identifiers only — AgentBuilderContext.config.plugins is a
+ // display DTO (still string[]); a disabled plugin isn't "enabled".
+ plugins: getActivePluginIds(config?.plugins),
provider: config?.provider,
systemRole: config?.systemRole,
},
diff --git a/src/store/agent/selectors/selectors.test.ts b/src/store/agent/selectors/selectors.test.ts
index 5e0b15cdaff..9f282cc9272 100644
--- a/src/store/agent/selectors/selectors.test.ts
+++ b/src/store/agent/selectors/selectors.test.ts
@@ -224,6 +224,51 @@ describe('agentSelectors', () => {
expect(agentSelectors.currentAgentPlugins(state)).toEqual([]);
});
+
+ it('should exclude disabled entries in a mixed-shape plugins array', () => {
+ const state = createState({
+ activeAgentId: 'agent-1',
+ agentMap: {
+ 'agent-1': {
+ plugins: [
+ 'plugin-1',
+ { identifier: 'plugin-2', mode: 'disabled' },
+ { identifier: 'plugin-3', mode: 'pinned' },
+ ],
+ } as any,
+ },
+ });
+
+ expect(agentSelectors.currentAgentPlugins(state)).toEqual(['plugin-1', 'plugin-3']);
+ });
+ });
+
+ describe('currentAgentDisabledPlugins', () => {
+ it('returns only the disabled identifiers from a mixed-shape plugins array', () => {
+ const state = createState({
+ activeAgentId: 'agent-1',
+ agentMap: {
+ 'agent-1': {
+ plugins: [
+ 'plugin-1',
+ { identifier: 'plugin-2', mode: 'disabled' },
+ { identifier: 'plugin-3', mode: 'pinned' },
+ ],
+ } as any,
+ },
+ });
+
+ expect(agentSelectors.currentAgentDisabledPlugins(state)).toEqual(['plugin-2']);
+ });
+
+ it('returns an empty array when there are no plugins', () => {
+ const state = createState({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': {} },
+ });
+
+ expect(agentSelectors.currentAgentDisabledPlugins(state)).toEqual([]);
+ });
});
describe('currentAgentKnowledgeBases', () => {
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index ea3bdf34da3..6fdc8b72cb4 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -16,7 +16,12 @@ import {
type MetaData,
type RuntimeEnvConfig,
} from '@lobechat/types';
-import { getWorkingDirEffectivePath, KnowledgeType } from '@lobechat/types';
+import {
+ getActivePluginIds,
+ getDisabledPluginIds,
+ getWorkingDirEffectivePath,
+ KnowledgeType,
+} from '@lobechat/types';
import { DEFAULT_OPENING_QUESTIONS } from '@/features/AgentSetting/store/selectors';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
@@ -119,10 +124,29 @@ const currentAgentModelProvider = (s: AgentStoreState) => {
return config?.provider || DEFAULT_PROVIDER;
};
+/**
+ * Pinned plugin identifiers for the current agent — disabled entries are
+ * excluded. Matches the pre-tri-state semantics where array-membership meant
+ * pinned; consumers that need the disabled set use `getDisabledPluginIds`
+ * directly.
+ */
const currentAgentPlugins = (s: AgentStoreState) => {
const config = currentAgentConfig(s);
- return config?.plugins || [];
+ return getActivePluginIds(config?.plugins);
+};
+
+/**
+ * Disabled plugin identifiers for the current agent. Consumers that build a
+ * tool/skill candidate pool (not just the "always whitelisted" rule map)
+ * need this to actually drop a disabled entry from the pool — being absent
+ * from `currentAgentPlugins` alone doesn't stop it from being present (and
+ * explicit-activation-eligible) in an unfiltered manifest source.
+ */
+const currentAgentDisabledPlugins = (s: AgentStoreState) => {
+ const config = currentAgentConfig(s);
+
+ return getDisabledPluginIds(config?.plugins);
};
/**
@@ -312,6 +336,7 @@ export const agentSelectors = {
currentAgentRuntimeEnvConfig,
currentAgentMeta,
currentAgentMode,
+ currentAgentDisabledPlugins,
currentAgentModel,
currentAgentModelProvider,
currentAgentPlugins,
diff --git a/src/store/agent/slices/plugin/action.test.ts b/src/store/agent/slices/plugin/action.test.ts
index 56562b403d5..f36b9b02f57 100644
--- a/src/store/agent/slices/plugin/action.test.ts
+++ b/src/store/agent/slices/plugin/action.test.ts
@@ -64,7 +64,7 @@ describe('PluginSlice Actions', () => {
expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
'agent-1',
expect.objectContaining({
- plugins: ['plugin-1'],
+ plugins: [{ identifier: 'plugin-1', mode: 'pinned' }],
}),
expect.any(AbortSignal),
);
@@ -120,7 +120,7 @@ describe('PluginSlice Actions', () => {
expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
'agent-1',
expect.objectContaining({
- plugins: ['plugin-1'],
+ plugins: [{ identifier: 'plugin-1', mode: 'pinned' }],
}),
expect.any(AbortSignal),
);
@@ -173,11 +173,11 @@ describe('PluginSlice Actions', () => {
await result.current.togglePlugin('plugin-1', true);
});
- // Should still have only one plugin-1
+ // Should still have only one plugin-1 (upgraded in place to object shape)
expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
'agent-1',
expect.objectContaining({
- plugins: ['plugin-1'],
+ plugins: [{ identifier: 'plugin-1', mode: 'pinned' }],
}),
expect.any(AbortSignal),
);
@@ -205,7 +205,7 @@ describe('PluginSlice Actions', () => {
expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
'agent-1',
expect.objectContaining({
- plugins: ['plugin-1'],
+ plugins: [{ identifier: 'plugin-1', mode: 'pinned' }],
}),
expect.any(AbortSignal),
);
@@ -270,4 +270,97 @@ describe('PluginSlice Actions', () => {
);
});
});
+
+ describe('setPluginMode', () => {
+ it('disables a legacy string entry, upgrading only that entry', async () => {
+ const { result } = renderHook(() => useAgentStore());
+
+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({
+ agent: {} as any,
+ success: true,
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { plugins: ['plugin-1', 'plugin-2'] } as any },
+ });
+ });
+
+ await act(async () => {
+ await result.current.setPluginMode('plugin-1', 'disabled');
+ });
+
+ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ // untouched sibling entry stays a bare string (lazy per-item upgrade)
+ plugins: [{ identifier: 'plugin-1', mode: 'disabled' }, 'plugin-2'],
+ }),
+ expect.any(AbortSignal),
+ );
+ });
+
+ it('can switch a disabled entry back to pinned', async () => {
+ const { result } = renderHook(() => useAgentStore());
+
+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({
+ agent: {} as any,
+ success: true,
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ activeAgentId: 'agent-1',
+ agentMap: {
+ 'agent-1': { plugins: [{ identifier: 'plugin-1', mode: 'disabled' }] } as any,
+ },
+ });
+ });
+
+ await act(async () => {
+ await result.current.setPluginMode('plugin-1', 'pinned');
+ });
+
+ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ plugins: [{ identifier: 'plugin-1', mode: 'pinned' }],
+ }),
+ expect.any(AbortSignal),
+ );
+ });
+
+ it('setting mode to auto removes the entry entirely', async () => {
+ const { result } = renderHook(() => useAgentStore());
+
+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({
+ agent: {} as any,
+ success: true,
+ });
+
+ act(() => {
+ useAgentStore.setState({
+ activeAgentId: 'agent-1',
+ agentMap: {
+ 'agent-1': {
+ plugins: [{ identifier: 'plugin-1', mode: 'disabled' }, 'plugin-2'],
+ } as any,
+ },
+ });
+ });
+
+ await act(async () => {
+ await result.current.setPluginMode('plugin-1', 'auto');
+ });
+
+ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(
+ 'agent-1',
+ expect.objectContaining({
+ plugins: ['plugin-2'],
+ }),
+ expect.any(AbortSignal),
+ );
+ });
+ });
});
diff --git a/src/store/agent/slices/plugin/action.ts b/src/store/agent/slices/plugin/action.ts
index ddf3bcdce93..66c62fea316 100644
--- a/src/store/agent/slices/plugin/action.ts
+++ b/src/store/agent/slices/plugin/action.ts
@@ -1,3 +1,4 @@
+import { type AgentPluginMode, getPluginMode, upsertPluginMode } from '@lobechat/types';
import { produce } from 'immer';
import { type StoreSetter } from '@/store/types';
@@ -27,27 +28,40 @@ export class PluginSliceActionImpl {
await this.#get().togglePlugin(id, false);
};
+ /**
+ * Boolean pin/unpin toggle, kept for the many callers that only ever
+ * add-to-agent or remove-from-agent (no disabled concept). Internally
+ * upgrades to `upsertPluginMode` so the write path is unified with
+ * `setPluginMode`; callers that need the third (disabled) state should use
+ * `setPluginMode` directly instead.
+ */
togglePlugin = async (id: string, open?: boolean): Promise<void> => {
const originConfig = agentSelectors.currentAgentConfig(this.#get());
if (!originConfig) return;
+ const shouldOpen =
+ open !== undefined ? open : getPluginMode(originConfig.plugins, id) !== 'pinned';
+
+ await this.setPluginMode(id, shouldOpen ? 'pinned' : 'auto');
+ };
+
+ /**
+ * Sets one identifier's explicit mode (pinned / auto / disabled). Only the
+ * touched entry is upgraded to object shape — every other entry, including
+ * untouched legacy strings, is left exactly as-is (lazy per-item upgrade).
+ */
+ setPluginMode = async (id: string, mode: AgentPluginMode): Promise<void> => {
+ const originConfig = agentSelectors.currentAgentConfig(this.#get());
+ if (!originConfig) return;
+
const config = produce(originConfig, (draft) => {
- draft.plugins = produce(draft.plugins || [], (plugins) => {
- const index = plugins.indexOf(id);
- const shouldOpen = open !== undefined ? open : index === -1;
-
- if (shouldOpen) {
- // If open is true or id doesn't exist in plugins, add it
- if (index === -1) {
- plugins.push(id);
- }
- } else {
- // If open is false or id exists in plugins, remove it
- if (index !== -1) {
- plugins.splice(index, 1);
- }
- }
- });
+ // `LobeAgentConfig['plugins']` is still typed `string[]` — widening it is
+ // deferred to the final phase of the tri-state rollout so `.includes()`
+ // call sites keep getting compiler errors until manually migrated. The
+ // runtime value legitimately becomes mixed-shape here (JSONB has no
+ // schema enforcement), so this cast is the one deliberate boundary
+ // where that mismatch is intentional.
+ draft.plugins = upsertPluginMode(draft.plugins, id, mode) as unknown as string[];
});
await this.#get().updateAgentConfig(config);
diff --git a/src/store/user/slices/onboarding/action.test.ts b/src/store/user/slices/onboarding/action.test.ts
index 23680c2bc6d..2ec887b4277 100644
--- a/src/store/user/slices/onboarding/action.test.ts
+++ b/src/store/user/slices/onboarding/action.test.ts
@@ -1,9 +1,10 @@
-import { CURRENT_ONBOARDING_VERSION } from '@lobechat/const';
+import { CURRENT_ONBOARDING_VERSION, INBOX_SESSION_ID } from '@lobechat/const';
import { MAX_ONBOARDING_STEPS } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userService } from '@/services/user';
+import { useAgentStore } from '@/store/agent';
import { useUserStore } from '@/store/user';
import { initialOnboardingState } from './initialState';
@@ -339,4 +340,51 @@ describe('onboarding actions', () => {
consoleErrorSpy.mockRestore();
});
});
+
+ describe('toggleInboxAgentDefaultPlugin', () => {
+ const updateAgentConfigById = vi.fn();
+
+ beforeEach(() => {
+ updateAgentConfigById.mockClear();
+ act(() => {
+ useAgentStore.setState({
+ agentMap: { 'inbox-agent-id': { plugins: ['plugin-1'] } as any },
+ builtinAgentIdMap: { [INBOX_SESSION_ID]: 'inbox-agent-id' },
+ updateAgentConfigById,
+ } as any);
+ });
+ });
+
+ it('flips an existing disabled object entry back to pinned, without duplicating it', async () => {
+ act(() => {
+ useAgentStore.setState({
+ agentMap: {
+ 'inbox-agent-id': {
+ plugins: ['plugin-1', { identifier: 'plugin-2', mode: 'disabled' }],
+ } as any,
+ },
+ } as any);
+ });
+
+ const { result } = renderHook(() => useUserStore());
+
+ await act(async () => {
+ await result.current.toggleInboxAgentDefaultPlugin('plugin-2', true);
+ });
+
+ expect(updateAgentConfigById).toHaveBeenCalledWith('inbox-agent-id', {
+ plugins: ['plugin-1', { identifier: 'plugin-2', mode: 'pinned' }],
+ });
+ });
+
+ it('setting open=false reverts the entry to auto, removing it from the array', async () => {
+ const { result } = renderHook(() => useUserStore());
+
+ await act(async () => {
+ await result.current.toggleInboxAgentDefaultPlugin('plugin-1', false);
+ });
+
+ expect(updateAgentConfigById).toHaveBeenCalledWith('inbox-agent-id', { plugins: [] });
+ });
+ });
});
diff --git a/src/store/user/slices/onboarding/action.ts b/src/store/user/slices/onboarding/action.ts
index 5dec7b7728d..fe76556ddd6 100644
--- a/src/store/user/slices/onboarding/action.ts
+++ b/src/store/user/slices/onboarding/action.ts
@@ -1,5 +1,5 @@
import { CURRENT_ONBOARDING_VERSION, INBOX_SESSION_ID } from '@lobechat/const';
-import { MAX_ONBOARDING_STEPS } from '@lobechat/types';
+import { getPluginMode, MAX_ONBOARDING_STEPS, upsertPluginMode } from '@lobechat/types';
import { userService } from '@/services/user';
import { getAgentStoreState } from '@/store/agent';
@@ -138,27 +138,21 @@ export class OnboardingActionImpl {
toggleInboxAgentDefaultPlugin = async (id: string, open?: boolean): Promise<void> => {
const currentSettings = settingsSelectors.currentSettings(this.#get());
- const currentPlugins = currentSettings.defaultAgent?.config?.plugins || [];
-
- const index = currentPlugins.indexOf(id);
- const shouldOpen = open !== undefined ? open : index === -1;
+ const isDefaultPinned =
+ getPluginMode(currentSettings.defaultAgent?.config?.plugins, id) === 'pinned';
+ const shouldOpen = open !== undefined ? open : !isDefaultPinned;
const agentStore = getAgentStoreState();
const inboxAgentId = agentStore.builtinAgentIdMap[INBOX_SESSION_ID];
-
- // Calculate inbox agent's new plugins
- const inboxPlugins = inboxAgentId ? agentStore.agentMap[inboxAgentId]?.plugins || [] : [];
- const inboxIndex = inboxPlugins.indexOf(id);
- let newInboxPlugins: string[];
- if (shouldOpen) {
- newInboxPlugins = inboxIndex === -1 ? [...inboxPlugins, id] : inboxPlugins;
- } else {
- newInboxPlugins = inboxIndex !== -1 ? inboxPlugins.filter((p) => p !== id) : inboxPlugins;
- }
-
- if (inboxAgentId) {
- await agentStore.updateAgentConfigById(inboxAgentId, { plugins: newInboxPlugins });
- }
+ if (!inboxAgentId) return;
+
+ // upsertPluginMode preserves an already-matching entry as-is and flips a
+ // disabled entry back to pinned in place, instead of blindly pushing a
+ // duplicate bare-string identifier.
+ const inboxRawPlugins = agentStore.agentMap[inboxAgentId]?.plugins;
+ await agentStore.updateAgentConfigById(inboxAgentId, {
+ plugins: upsertPluginMode(inboxRawPlugins, id, shouldOpen ? 'pinned' : 'auto'),
+ });
};
updateDefaultModel = async (model: string, provider: string): Promise<void> => {