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.

39.1 KB
Raw Blame
import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import { WebhookManifest } from '@lobechat/builtin-tool-webhook';
import type * as ConstModule from '@lobechat/const';
import { type ToolManifest } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createAgentToolsEngine, createToolsEngine, getEnabledTools } from './index';

const desktopEnv = vi.hoisted(() => ({ enabled: false }));
vi.mock('@lobechat/const', async (importOriginal) => ({
  ...(await importOriginal<typeof ConstModule>()),
  get isDesktop() {
    return desktopEnv.enabled;
  },
}));
afterEach(() => {
  desktopEnv.enabled = false;
});

vi.mock(import('@/store/tool/slices/builtin/projection'), async (importOriginal) => ({
  ...(await importOriginal()),
  runtimeUninstalledBuiltinTools: () => [],
}));

// Mock the store and helper dependencies
let mockConnectors: any[] = [];
// No conversation listing here: the local lists stand in (see index.runConnectors.test.ts)
vi.mock('@/services/runConnectors', () => ({ getRunConnectors: () => undefined }));

vi.mock('@/store/tool', () => ({
  getToolStoreState: () => ({
    connectors: mockConnectors,
    // The rows behind `installedPluginManifestList`: an installed plugin is a
    // connector, so the agent's on/off switch applies to it.
    get installedPlugins() {
      return mockInstalledPluginManifestList().map((manifest) => ({
        identifier: manifest.identifier,
      }));
    },
    builtinTools: [
      { identifier: AuvManifest.identifier, manifest: AuvManifest, type: 'builtin' as const },
      {
        identifier: DashboardManifest.identifier,
        manifest: DashboardManifest,
        type: 'builtin' as const,
      },
      {
        identifier: AttachmentsManifest.identifier,
        manifest: AttachmentsManifest,
        type: 'builtin' as const,
      },
      {
        identifier: WebhookManifest.identifier,
        manifest: WebhookManifest,
        type: 'builtin' as const,
      },
      {
        identifier: 'search',
        manifest: {
          api: [
            {
              description: 'Search the web',
              name: 'search',
              parameters: {
                properties: {
                  query: { description: 'Search query', type: 'string' },
                },
                required: ['query'],
                type: 'object',
              },
            },
          ],
          identifier: 'search',
          meta: {
            title: 'Web Search',
            description: 'Search tool',
            avatar: '🔍',
          },
          type: 'builtin',
        } as unknown as ToolManifest,
        type: 'builtin' as const,
      },
      {
        identifier: 'lobe-web-browsing',
        manifest: {
          api: [
            {
              description:
                'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',
              name: 'search',
              parameters: {
                properties: {
                  query: { description: 'The search query', type: 'string' },
                },
                required: ['query'],
                type: 'object',
              },
            },
          ],
          identifier: 'lobe-web-browsing',
          meta: {
            title: 'Web Browsing',
            avatar: '🌐',
          },
          type: 'builtin',
        } as unknown as ToolManifest,
        type: 'builtin' as const,
      },
      {
        identifier: 'lobe-agent',
        manifest: {
          api: [
            {
              description: 'Analyze visual media',
              name: 'analyzeMedia',
              parameters: {
                properties: {
                  question: { type: 'string' },
                  refs: {
                    items: { type: 'string' },
                    type: 'array',
                  },
                  urls: {
                    items: { type: 'string' },
                    type: 'array',
                  },
                },
                required: ['question'],
                type: 'object',
              },
            },
          ],
          identifier: 'lobe-agent',
          meta: {
            title: 'Lobe Agent',
            avatar: 'V',
          },
          type: 'builtin',
        } as unknown as ToolManifest,
        type: 'builtin' as const,
      },
      {
        identifier: 'lobe-image-generation',
        manifest: {
          api: [
            {
              description: 'Generate image',
              name: 'generateImage',
              parameters: {
                properties: {
                  prompt: { type: 'string' },
                },
                required: ['prompt'],
                type: 'object',
              },
            },
          ],
          identifier: 'lobe-image-generation',
          meta: {
            title: 'Image Generation',
            avatar: 'I',
          },
          type: 'builtin',
        } as unknown as ToolManifest,
        type: 'builtin' as const,
      },
      {
        identifier: 'lobe-video-generation',
        manifest: {
          api: [
            {
              description: 'Generate video',
              name: 'generateVideo',
              parameters: {
                properties: {
                  prompt: { type: 'string' },
                },
                required: ['prompt'],
                type: 'object',
              },
            },
          ],
          identifier: 'lobe-video-generation',
          meta: {
            avatar: 'V',
            title: 'Video Generation',
          },
          type: 'builtin',
        } as unknown as ToolManifest,
        type: 'builtin' as const,
      },
    ],
  }),
}));

let mockGetInstalledPluginById: (id: string) => () => any = () => () => undefined;
let mockInstalledPluginManifestList: () => ToolManifest[] = () => [];

vi.mock('@/store/tool/selectors', () => ({
  pluginSelectors: {
    getInstalledPluginById: (id: string) => mockGetInstalledPluginById(id),
    installedPluginManifestList: () => mockInstalledPluginManifestList(),
  },
  composioStoreSelectors: {
    composioAsLobeTools: () => [],
  },
  lobehubSkillStoreSelectors: {
    lobehubSkillAsLobeTools: () => [],
  },
}));

let mockServerConfig: { toolNameMaxLength?: number } = {};
let mockFeatureFlags: { enableDashboard?: boolean; enableWebhook?: boolean } = {};

vi.mock('@/store/serverConfig', () => ({
  getServerConfigStoreState: () => ({
    featureFlags: mockFeatureFlags,
    serverConfig: mockServerConfig,
  }),
  // Connector manifests ask whether MCP Apps are on (`buildClientConnectorManifests`)
  serverConfigSelectors: { enableMcpApps: () => false },
}));

let mockIsCanUseFC = true;

vi.mock('../isCanUseFC', () => ({
  isCanUseFC: () => mockIsCanUseFC,
}));

let mockCurrentAgentPlugins: string[] = [];
let mockCurrentAgentDisabledPlugins: string[] = [];
/** Explicit `auto` entries: what turns a connector on without pinning it. */
let mockCurrentAgentAutoPlugins: string[] = [];
let mockCurrentChatConfig: {
  enableAgentMode?: boolean;
  memory?: { enabled?: boolean };
  skillActivateMode?: 'auto' | 'manual';
  toolMode?: 'agent' | 'chat' | 'custom';
} = {};
let mockImageOutputSupport = false;

vi.mock('@/store/agent', () => ({
  getAgentStoreState: () => ({}),
}));

let mockCurrentAgentVisibility: 'private' | 'public' | undefined;

vi.mock('@/store/agent/selectors', () => ({
  agentSelectors: {
    currentAgentConfig: () => ({
      plugins: [
        ...mockCurrentAgentPlugins,
        ...mockCurrentAgentAutoPlugins.map((identifier) => ({ identifier, mode: 'auto' })),
        ...mockCurrentAgentDisabledPlugins.map((identifier) => ({ identifier, mode: 'disabled' })),
      ],
    }),
    currentAgentDisabledPlugins: () => mockCurrentAgentDisabledPlugins,
    currentAgentPlugins: () => mockCurrentAgentPlugins,
    currentAgentVisibility: () => mockCurrentAgentVisibility,
    hasEnabledKnowledgeBases: () => false,
  },
  agentChatConfigSelectors: {
    currentChatConfig: () => mockCurrentChatConfig,
    isMemoryToolEnabled: () => false,
  },
  chatConfigByIdSelectors: {
    // A local target only resolves on the desktop; elsewhere the run has no
    // execution environment.
    getExecutionTargetById: () => () => (desktopEnv.enabled ? 'local' : 'none'),
  },
}));

vi.mock('@/store/aiInfra', () => ({
  aiModelSelectors: {
    isModelSupportImageOutput: () => () => mockImageOutputSupport,
  },
  getAiInfraStoreState: () => ({}),
}));

vi.mock('@/store/user', () => ({
  useUserStore: { getState: () => ({}) },
}));

vi.mock('@/store/user/selectors', () => ({
  settingsSelectors: {
    memoryEnabled: () => false,
  },
}));

let mockUseApplicationBuiltinSearchTool = true;

vi.mock('@/helpers/getSearchConfig', () => ({
  getSearchConfig: () => ({
    get useApplicationBuiltinSearchTool() {
      return mockUseApplicationBuiltinSearchTool;
    },
  }),
}));

describe('toolEngineering', () => {
  afterEach(() => {
    mockGetInstalledPluginById = () => () => undefined;
    mockInstalledPluginManifestList = () => [];
    mockUseApplicationBuiltinSearchTool = true;
    mockCurrentAgentPlugins = [];
    mockCurrentAgentDisabledPlugins = [];
    mockCurrentAgentAutoPlugins = [];
    mockIsCanUseFC = true;
    mockCurrentChatConfig = {};
    mockImageOutputSupport = false;
    mockServerConfig = {};
    mockFeatureFlags = {};
    mockConnectors = [];
    mockCurrentAgentVisibility = undefined;
  });

  describe('feature-flagged tools', () => {
    const generate = (explicit = false) =>
      createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }).generateToolsDetailed({
        context: { isExplicitActivation: explicit },
        toolIds: [DashboardManifest.identifier],
        model: 'gpt-4',
        provider: 'openai',
      });

    it('never offers builtin-dashboard while the dashboard flag is off, even when pinned', () => {
      mockCurrentAgentPlugins = [DashboardManifest.identifier];
      mockFeatureFlags = { enableDashboard: false };
      expect(generate().enabledToolIds).not.toContain(DashboardManifest.identifier);
    });

    it('offers the previously pinned dashboard only after activation once the flag is on', () => {
      mockCurrentAgentPlugins = [DashboardManifest.identifier];
      mockFeatureFlags = { enableDashboard: true };
      expect(generate().enabledToolIds).not.toContain(DashboardManifest.identifier);
      expect(generate(true).enabledToolIds).toContain(DashboardManifest.identifier);
    });
  });

  describe('server-only tools', () => {
    it('never offers the webhook tools to a run the browser executes, even pinned and flagged on', () => {
      mockCurrentAgentPlugins = [WebhookManifest.identifier];
      mockFeatureFlags = { enableWebhook: true };
      const result = createAgentToolsEngine({
        model: 'gpt-4',
        provider: 'openai',
      }).generateToolsDetailed({
        model: 'gpt-4',
        provider: 'openai',
        toolIds: [WebhookManifest.identifier],
      });
      expect(result.enabledToolIds).not.toContain(WebhookManifest.identifier);
    });
  });

  // `TOOL_NAME_MAX_LENGTH` is a server env, but this path generates tool names in
  // the browser — the value has to arrive via the server config for `0` to
  // actually turn the MD5 compression off here.
  describe('tool name compression', () => {
    const longNamedPlugin = {
      api: [
        {
          description: 'Search documents',
          name: 'searchDocumentsInWorkspace',
          parameters: { properties: {}, required: [], type: 'object' },
        },
      ],
      identifier: 'my-notion-mcp-connector-with-a-long-identifier',
      meta: { avatar: '📓', title: 'Notion' },
      type: 'default',
    } as unknown as ToolManifest;

    const generateLongToolName = () => {
      mockInstalledPluginManifestList = () => [longNamedPlugin];
      const toolsEngine = createToolsEngine();

      return toolsEngine.generateTools({
        model: 'gpt-4',
        provider: 'openai',
        toolIds: [longNamedPlugin.identifier],
      })![0].function.name;
    };

    it('should compress names past the default 64 chars', () => {
      expect(generateLongToolName()).toContain('MD5HASH_');
    });

    it('should keep the full name when the server config sets 0', () => {
      mockServerConfig = { toolNameMaxLength: 0 };

      expect(generateLongToolName()).toBe(
        'my-notion-mcp-connector-with-a-long-identifier____searchDocumentsInWorkspace',
      );
    });

    it('should honour a custom threshold from the server config', () => {
      mockServerConfig = { toolNameMaxLength: 200 };

      expect(generateLongToolName()).not.toContain('MD5HASH_');
    });
  });

  describe('createToolsEngine', () => {
    it('should generate tools array for enabled plugins', () => {
      const toolsEngine = createToolsEngine();
      const result = toolsEngine.generateTools({
        toolIds: ['search'],
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result).toBeDefined();
      expect(result).toHaveLength(1);
      expect(result![0]).toMatchObject({
        function: {
          description: 'Search the web',
          name: 'search____search',
          parameters: {
            properties: {
              query: { description: 'Search query', type: 'string' },
            },
            required: ['query'],
            type: 'object',
          },
        },
        type: 'function',
      });
    });

    it('should return undefined when no plugins match', () => {
      const toolsEngine = createToolsEngine();
      const result = toolsEngine.generateTools({
        toolIds: ['non-existent'],
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result).toBeUndefined();
    });

    it('should return detailed result with correct field names', () => {
      const toolsEngine = createToolsEngine();
      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['search'],
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result).toHaveProperty('enabledToolIds');
      expect(result).toHaveProperty('filteredTools');
      expect(result).toHaveProperty('tools');
      expect(result.enabledToolIds).toEqual(['search']);
      expect(result.filteredTools).toEqual([]);
      expect(result.tools).toHaveLength(1);
    });
  });

  describe('createChatToolsEngine', () => {
    it('should not auto-enable image generation in chat mode', () => {
      mockCurrentChatConfig = { enableAgentMode: false };
      mockImageOutputSupport = false;

      const toolsEngine = createAgentToolsEngine({
        model: 'claude-sonnet',
        provider: 'anthropic',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: [],
        model: 'claude-sonnet',
        provider: 'anthropic',
      });

      expect(result.enabledToolIds).not.toContain('lobe-image-generation');
    });

    it('should enable image generation in chat mode when the tool is pinned', () => {
      mockCurrentChatConfig = { enableAgentMode: false };
      mockCurrentAgentPlugins = ['lobe-image-generation'];
      mockImageOutputSupport = false;

      const toolsEngine = createAgentToolsEngine({
        model: 'claude-sonnet',
        provider: 'anthropic',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['lobe-image-generation'],
        model: 'claude-sonnet',
        provider: 'anthropic',
      });

      expect(result.enabledToolIds).toContain('lobe-image-generation');
    });

    it('should not enable image generation in chat mode when model has native image output', () => {
      mockCurrentChatConfig = { enableAgentMode: false };
      mockCurrentAgentPlugins = ['lobe-image-generation'];
      mockImageOutputSupport = true;

      const toolsEngine = createAgentToolsEngine({
        model: 'gpt-image-chat',
        provider: 'openai',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['lobe-image-generation'],
        model: 'gpt-image-chat',
        provider: 'openai',
      });

      expect(result.enabledToolIds).not.toContain('lobe-image-generation');
    });

    it('should not enable image generation in chat mode when model cannot call tools', () => {
      mockCurrentChatConfig = { enableAgentMode: false };
      mockCurrentAgentPlugins = ['lobe-image-generation'];
      mockIsCanUseFC = false;

      const toolsEngine = createAgentToolsEngine({
        model: 'plain-text-model',
        provider: 'test',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['lobe-image-generation'],
        model: 'plain-text-model',
        provider: 'test',
      });

      expect(result.enabledToolIds).not.toContain('lobe-image-generation');
    });

    it('should enable video generation in chat mode when the tool is pinned', () => {
      mockCurrentChatConfig = { enableAgentMode: false };
      mockCurrentAgentPlugins = ['lobe-video-generation'];

      const toolsEngine = createAgentToolsEngine({
        model: 'claude-sonnet',
        provider: 'anthropic',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['lobe-video-generation'],
        model: 'claude-sonnet',
        provider: 'anthropic',
      });

      expect(result.enabledToolIds).toContain('lobe-video-generation');
    });

    it('should not enable video generation in chat mode when model cannot call tools', () => {
      mockCurrentChatConfig = { enableAgentMode: false };
      mockIsCanUseFC = false;

      const toolsEngine = createAgentToolsEngine({
        model: 'plain-text-model',
        provider: 'test',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: [],
        model: 'plain-text-model',
        provider: 'test',
      });

      expect(result.enabledToolIds).not.toContain('lobe-video-generation');
    });

    it('should include web browsing tool as default when no tools are provided', () => {
      const toolsEngine = createAgentToolsEngine({
        model: 'gpt-4',
        provider: 'openai',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: [], // No explicitly enabled tools
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result.enabledToolIds).toContain('lobe-web-browsing');
    });

    it('should include web browsing tool alongside user-provided tools', () => {
      mockCurrentAgentPlugins = ['search'];

      const toolsEngine = createAgentToolsEngine({
        model: 'gpt-4',
        provider: 'openai',
      });

      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['search'], // User explicitly enables search tool
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result.enabledToolIds).toEqual(['search', 'lobe-web-browsing']);
    });

    it('should enable lobe-agent when it is injected into runtime plugin ids', () => {
      const toolsEngine = createAgentToolsEngine({ model: 'deepseek-chat', provider: 'deepseek' }, [
        'lobe-agent',
      ]);

      const result = toolsEngine.generateToolsDetailed({
        model: 'deepseek-chat',
        provider: 'deepseek',
        toolIds: [],
      });

      expect(result.enabledToolIds).toContain('lobe-agent');
    });

    it.each([true, false])('enables lobe-attachments only with oversized files (%s)', (flag) => {
      const toolsEngine = createAgentToolsEngine(
        { model: 'deepseek-chat', provider: 'deepseek' },
        undefined,
        undefined,
        { hasOversizedFiles: flag },
      );

      const result = toolsEngine.generateToolsDetailed({
        model: 'deepseek-chat',
        provider: 'deepseek',
        toolIds: [],
      });

      expect(result.enabledToolIds.includes('lobe-attachments')).toBe(flag);
    });

    it('makes Lobe Agent callable after discovery and honors an explicit disable', () => {
      const model = { model: 'deepseek-chat', provider: 'deepseek' };
      const activation = {
        ...model,
        context: { isExplicitActivation: true },
        skipDefaultTools: true,
        toolIds: ['lobe-agent'],
      };
      const engine = createAgentToolsEngine(model);

      expect(engine.generateToolsDetailed({ ...model, toolIds: [] }).enabledToolIds).not.toContain(
        'lobe-agent',
      );
      expect(engine.generateToolsDetailed(activation).enabledToolIds).toEqual(['lobe-agent']);

      mockCurrentAgentDisabledPlugins = ['lobe-agent'];
      expect(
        createAgentToolsEngine(model).generateToolsDetailed(activation).enabledToolIds,
      ).toEqual([]);
    });

    it('should keep agent-mode defaults and mark every tool incompatible when the model cannot call functions', () => {
      mockIsCanUseFC = false;

      const toolsEngine = createAgentToolsEngine({
        model: 'gemini-3.1-flash-lite-image',
        provider: 'lobehub',
      });

      const result = toolsEngine.generateToolsDetailed({
        model: 'gemini-3.1-flash-lite-image',
        provider: 'lobehub',
        toolIds: [],
      });

      // The stored mode is not demoted to chat mode for a non-FC model (same
      // rule as the server runtime); the engine reports the incompatibility
      // per tool instead.
      expect(result.enabledToolIds).toEqual([]);
      expect(result.filteredTools).toContainEqual({
        id: 'lobe-agent',
        reason: 'incompatible',
      });
      expect(result.filteredTools).toContainEqual({
        id: 'lobe-web-browsing',
        reason: 'incompatible',
      });
    });

    it('should not enable image generation by default in agent mode', () => {
      const toolsEngine = createAgentToolsEngine({
        model: 'gpt-4',
        provider: 'openai',
      });

      const result = toolsEngine.generateToolsDetailed({
        model: 'gpt-4',
        provider: 'openai',
        toolIds: [],
      });

      expect(result.enabledToolIds).not.toContain('lobe-image-generation');
    });

    it('should allow opted-in image generation explicit activation in agent mode', () => {
      mockCurrentAgentAutoPlugins = ['lobe-image-generation'];
      const toolsEngine = createAgentToolsEngine({
        model: 'gpt-4',
        provider: 'openai',
      });

      const result = toolsEngine.generateToolsDetailed({
        context: { isExplicitActivation: true },
        model: 'gpt-4',
        provider: 'openai',
        skipDefaultTools: true,
        toolIds: ['lobe-image-generation'],
      });

      expect(result.enabledToolIds).toContain('lobe-image-generation');
    });
  });

  describe('isExplicitActivation bypass', () => {
    it('should disable web browsing when useApplicationBuiltinSearchTool is false', () => {
      mockUseApplicationBuiltinSearchTool = false;

      const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['lobe-web-browsing'],
        model: 'gpt-4',
        provider: 'openai',
        skipDefaultTools: true,
      });

      expect(result.enabledToolIds).not.toContain('lobe-web-browsing');
      expect(result.filteredTools).toContainEqual({
        id: 'lobe-web-browsing',
        reason: 'not_found',
      });
    });

    it('keeps web browsing unavailable to explicit activation when application search is off', () => {
      mockUseApplicationBuiltinSearchTool = false;

      const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
      const result = toolsEngine.generateToolsDetailed({
        context: { isExplicitActivation: true },
        toolIds: ['lobe-web-browsing'],
        model: 'gpt-4',
        provider: 'openai',
        skipDefaultTools: true,
      });

      expect(result.enabledToolIds).not.toContain('lobe-web-browsing');
      expect(result.tools).toBeUndefined();
    });

    it('only allows explicit activation of manifests present in the run', () => {
      mockUseApplicationBuiltinSearchTool = false;
      mockInstalledPluginManifestList = () => [
        {
          api: [
            {
              description: 'Run stdio tool',
              name: 'run',
              parameters: { properties: {}, required: [], type: 'object' },
            },
          ],
          identifier: 'stdio-mcp-plugin',
          meta: { title: 'Stdio MCP', avatar: '🔧' },
          type: 'default',
        } as unknown as ToolManifest,
      ];
      mockGetInstalledPluginById = (id: string) => () =>
        id === 'stdio-mcp-plugin'
          ? { customParams: { mcp: { type: 'stdio' } }, identifier: id }
          : undefined;
      mockCurrentAgentPlugins = ['stdio-mcp-plugin'];

      const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
      const result = toolsEngine.generateToolsDetailed({
        context: { isExplicitActivation: true },
        toolIds: ['stdio-mcp-plugin', 'lobe-web-browsing'],
        model: 'gpt-4',
        provider: 'openai',
        skipDefaultTools: true,
      });

      expect(result.enabledToolIds).toEqual(['stdio-mcp-plugin']);
    });

    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', () => {
    const stdioMcpManifest = {
      api: [
        {
          description: 'Run stdio tool',
          name: 'run',
          parameters: { properties: {}, required: [], type: 'object' },
        },
      ],
      identifier: 'stdio-mcp-plugin',
      meta: { title: 'Stdio MCP', avatar: '🔧' },
      type: 'default',
    } as unknown as ToolManifest;

    const httpMcpManifest = {
      api: [
        {
          description: 'Run http tool',
          name: 'run',
          parameters: { properties: {}, required: [], type: 'object' },
        },
      ],
      identifier: 'http-mcp-plugin',
      meta: { title: 'HTTP MCP', avatar: '🌐' },
      type: 'default',
    } as unknown as ToolManifest;

    it('should filter stdio MCP tools in non-desktop environment', () => {
      mockInstalledPluginManifestList = () => [stdioMcpManifest];
      mockGetInstalledPluginById = (id: string) => () =>
        id === 'stdio-mcp-plugin'
          ? { customParams: { mcp: { type: 'stdio' } }, identifier: id }
          : undefined;
      mockCurrentAgentPlugins = ['stdio-mcp-plugin'];

      const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
      const result = toolsEngine.generateToolsDetailed({
        toolIds: ['stdio-mcp-plugin'],
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result.enabledToolIds).not.toContain('stdio-mcp-plugin');
    });

    it('should NOT filter http MCP tools in non-desktop environment', () => {
      mockInstalledPluginManifestList = () => [httpMcpManifest];
      mockGetInstalledPluginById = (id: string) => () =>
        id === 'http-mcp-plugin'
          ? { customParams: { mcp: { type: 'http' } }, identifier: id }
          : undefined;
      mockCurrentAgentAutoPlugins = ['http-mcp-plugin'];

      const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
      const result = toolsEngine.generateToolsDetailed({
        // A connector that is on is found through the activator.
        context: { isExplicitActivation: true },
        toolIds: ['http-mcp-plugin'],
        model: 'gpt-4',
        provider: 'openai',
      });

      expect(result.enabledToolIds).toContain('http-mcp-plugin');
    });
  });

  describe('private (私人) workspace connectors', () => {
    const connector = (identifier: string, visibility: 'private' | 'public') => ({
      credentials: null,
      id: `${identifier}-id`,
      identifier,
      isEnabled: true,
      mcpConnectionType: 'http',
      mcpServerUrl: `https://${identifier}.example.com/mcp`,
      metadata: null,
      name: identifier,
      sourceType: 'custom',
      status: 'connected',
      tools: [
        {
          crudType: 'read',
          description: 'Search',
          displayName: 'Search',
          id: `${identifier}-search`,
          inputSchema: { properties: {}, type: 'object' },
          permission: 'auto',
          toolName: 'search',
          userConnectorId: `${identifier}-id`,
        },
      ],
      visibility,
    });

    const enabledConnectorIds = (manifestContext?: { isSubAgent?: boolean; scope?: string }) => {
      mockConnectors = [connector('ws-linear', 'public'), connector('my-notion', 'private')];
      mockCurrentAgentPlugins = ['ws-linear', 'my-notion'];
      return (
        createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }, undefined, manifestContext)
          // A connector that is on reaches the model through the activator
          .generateToolsDetailed({
            context: { isExplicitActivation: true },
            model: 'gpt-4',
            provider: 'openai',
            toolIds: ['ws-linear', 'my-notion'],
          })
          .enabledToolIds.filter((id) => id.startsWith('ws-linear') || id.startsWith('my-notion'))
          .sort()
      );
    };

    it('keeps them away from a workspace agent', () => {
      mockCurrentAgentVisibility = 'public';

      expect(enabledConnectorIds()).toEqual(['ws-linear']);
    });

    it("offers them in a private agent's own conversation", () => {
      mockCurrentAgentVisibility = 'private';

      // A private row is a tool set of its own, under its row-suffixed prefix
      expect(enabledConnectorIds({ scope: 'main' })).toEqual(['my-notion-mynotion', 'ws-linear']);
    });

    it.each([
      { scope: 'group' },
      { scope: 'group_agent' },
      { isSubAgent: true, scope: 'sub_agent' },
    ])('keeps them out of a private agent run in %o', (manifestContext) => {
      mockCurrentAgentVisibility = 'private';

      expect(enabledConnectorIds(manifestContext)).toEqual(['ws-linear']);
    });

    describe('a private and a shared row of one identifier', () => {
      // The owner's private connection and the workspace's shared one of the
      // same identifier, each with its own tool list
      const withTool = (visibility: 'private' | 'public', toolName: string) => {
        const row = connector('team-docs', visibility);
        return {
          ...row,
          id: `team-docs-${visibility}`,
          tools: [{ ...row.tools[0], id: `${visibility}-tool`, toolName }],
        };
      };
      const privateRow = withTool('private', 'search_mine');
      const sharedRow = withTool('public', 'search_team');

      const toolNames = (rows: unknown[], manifestContext?: { scope?: string }) => {
        mockConnectors = rows;
        mockCurrentAgentPlugins = ['team-docs'];
        return createAgentToolsEngine(
          { model: 'gpt-4', provider: 'openai' },
          undefined,
          manifestContext,
        )
          .generateToolsDetailed({
            context: { isExplicitActivation: true },
            model: 'gpt-4',
            provider: 'openai',
            toolIds: ['team-docs'],
          })
          .tools?.map((tool) => tool.function.name);
      };

      it('offers the private agent both rows, each under its own prefix, in either list order', () => {
        // Regression: both rows reached the identifier-keyed manifest map and
        // the last one won, so the model could get one row's schema while the
        // server ran the other. Each row is now its own tool set.
        mockCurrentAgentVisibility = 'private';

        for (const rows of [
          [privateRow, sharedRow],
          [sharedRow, privateRow],
        ]) {
          expect(
            toolNames(rows, { scope: 'main' })?.filter((name) => name.includes('search')),
          ).toEqual(
            expect.arrayContaining([
              'team-docs____search_team____mcp',
              'team-docs-teamdocs____search_mine____mcp',
            ]),
          );
        }
      });

      it("builds a workspace agent's manifest from the shared row", () => {
        mockCurrentAgentVisibility = 'public';

        const names = toolNames([privateRow, sharedRow]);
        expect(names?.some((name) => name.includes('search_team'))).toBe(true);
        expect(names?.some((name) => name.includes('search_mine'))).toBe(false);
      });
    });
  });

  describe('connector discovery', () => {
    const connectorManifest = {
      api: [
        {
          description: 'Run the tool',
          name: 'run',
          parameters: { properties: {}, required: [], type: 'object' },
        },
      ],
      identifier: 'gmail-mcp',
      meta: { title: 'Gmail MCP' },
      type: 'default',
    } as unknown as ToolManifest;

    const generate = (
      options: { explicit?: boolean; pluginIds?: string[]; toolIds?: string[] } = {},
    ) =>
      createAgentToolsEngine(
        { model: 'gpt-4', provider: 'openai' },
        options.pluginIds,
      ).generateToolsDetailed({
        context: options.explicit ? { isExplicitActivation: true } : undefined,
        model: 'gpt-4',
        provider: 'openai',
        skipDefaultTools: true,
        toolIds: options.toolIds ?? ['gmail-mcp'],
      });

    beforeEach(() => {
      mockInstalledPluginManifestList = () => [connectorManifest];
    });

    it('offers an unconfigured connector only after activation', () => {
      expect(generate().enabledToolIds).toEqual([]);
      expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);
    });

    it('leaves a connector that is on to the activator instead of invoking it up front', () => {
      mockCurrentAgentAutoPlugins = ['gmail-mcp'];

      expect(generate().enabledToolIds).toEqual([]);
      expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);
    });

    it('reads a connector pinned before the two-state switch as on, not invoked up front', () => {
      mockCurrentAgentPlugins = ['gmail-mcp'];

      expect(generate().enabledToolIds).toEqual([]);
      expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);
    });

    it('defers an enabled connector despite a legacy manual preference', () => {
      mockCurrentAgentAutoPlugins = ['gmail-mcp'];
      mockCurrentChatConfig = { skillActivateMode: 'manual' };

      expect(generate().enabledToolIds).toEqual([]);
      expect(generate({ explicit: true }).enabledToolIds).toEqual(['gmail-mcp']);
    });

    it('invokes a connector that is on directly in custom mode, which has no activator either', () => {
      mockCurrentAgentAutoPlugins = ['gmail-mcp'];
      mockCurrentChatConfig = { toolMode: 'custom' };

      expect(generate().enabledToolIds).toEqual(['gmail-mcp']);
    });

    it('reads the switches of the agent that is executing, not the active one', () => {
      // The active (parent) agent has the connector off; the sub-agent turned it on.
      const runAgent = { plugins: [{ identifier: 'gmail-mcp', mode: 'auto' as const }] };
      const generateFor = (explicit: boolean) =>
        createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }, undefined, undefined, {
          runAgent,
        }).generateToolsDetailed({
          context: explicit ? { isExplicitActivation: true } : undefined,
          model: 'gpt-4',
          provider: 'openai',
          skipDefaultTools: true,
          toolIds: ['gmail-mcp'],
        });

      expect(generateFor(false).enabledToolIds).toEqual([]);
      expect(generateFor(true).enabledToolIds).toEqual(['gmail-mcp']);
    });

    it('hides a connector the active agent has on from an executing agent that has it off', () => {
      mockCurrentAgentAutoPlugins = ['gmail-mcp'];

      const result = createAgentToolsEngine(
        { model: 'gpt-4', provider: 'openai' },
        undefined,
        undefined,
        { runAgent: { plugins: [{ identifier: 'gmail-mcp', mode: 'disabled' }] } },
      ).generateToolsDetailed({
        context: { isExplicitActivation: true },
        model: 'gpt-4',
        provider: 'openai',
        skipDefaultTools: true,
        toolIds: ['gmail-mcp'],
      });

      expect(result.enabledToolIds).toEqual([]);
    });

    it('invokes a connector this turn mentions even when the agent has it off', () => {
      expect(generate({ pluginIds: ['gmail-mcp'] }).enabledToolIds).toEqual(['gmail-mcp']);
    });
  });

  describe('Migration functions', () => {
    describe('getEnabledTools', () => {
      it('should return empty array when no tool IDs provided', () => {
        const result = getEnabledTools([], 'gpt-4', 'openai');
        expect(result).toEqual([]);
      });

      it('should return tools for valid tool IDs', () => {
        const result = getEnabledTools(['search'], 'gpt-4', 'openai');
        expect(result).toHaveLength(1);
        expect(result[0]).toHaveProperty('type', 'function');
        expect(result[0].function).toHaveProperty('name', 'search____search');
      });

      it('should use provided model and provider', () => {
        const result = getEnabledTools(['search'], 'gpt-3.5-turbo', 'anthropic');
        expect(result).toBeDefined();
        expect(Array.isArray(result)).toBe(true);
      });

      it('should return empty array for non-existent tools', () => {
        const result = getEnabledTools(['non-existent-tool'], 'gpt-4', 'openai');
        expect(result).toEqual([]);
      });
    });
  });
});

// https://github.com/lobehub/lobehub/pull/19051
describe('Computer Use activation', () => {
  it('loads the native API only after activation in standalone Electron', () => {
    desktopEnv.enabled = true;
    mockCurrentAgentAutoPlugins = [AuvManifest.identifier];
    const engine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
    expect(
      engine.generateToolsDetailed({ model: 'gpt-4', provider: 'openai', toolIds: [] })
        .enabledToolIds,
    ).not.toContain(AuvManifest.identifier);
    expect(
      engine.generateToolsDetailed({
        model: 'gpt-4',
        provider: 'openai',
        toolIds: [AuvManifest.identifier],
        context: { isExplicitActivation: true },
      }).enabledToolIds,
    ).toContain(AuvManifest.identifier);
  });
  it('does not let explicit activation bypass the Web platform restriction', () => {
    desktopEnv.enabled = false;
    mockCurrentAgentAutoPlugins = [AuvManifest.identifier];
    const engine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
    expect(
      engine.generateToolsDetailed({
        model: 'gpt-4',
        provider: 'openai',
        toolIds: [AuvManifest.identifier],
        context: { isExplicitActivation: true },
      }).enabledToolIds,
    ).not.toContain(AuvManifest.identifier);
  });
});