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.

13.5 KB
Raw Blame
import { type ToolManifest } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';

import { type ToolStoreState } from '../initialState';
import { initialState } from '../initialState';
import { toolSelectors } from './tool';

// The conversation's server listing (`connector.listForRun`)
const runListing = vi.hoisted(() => ({ rows: undefined as unknown[] | undefined }));
vi.mock('@/services/runConnectors', () => ({
  getAllRunConnectors: () => runListing.rows ?? [],
  getRunConnectors: () => runListing.rows,
}));

// Mock builtin skill for testing
const mockBuiltinSkill = {
  avatar: '🧪',
  content: '# Test Skill',
  description: 'A test skill',
  identifier: 'test-skill',
  name: 'Test Skill',
  source: 'builtin' as const,
};

const mockState = {
  ...initialState,
  builtinSkills: [mockBuiltinSkill],
  installedPlugins: [
    {
      identifier: 'plugin-1',
      manifest: {
        identifier: 'plugin-1',
        api: [{ name: 'api-1' }],
        author: 'Test Author',
        createdAt: '2024-01-01',
        homepage: 'https://example.com/plugin-1',
        meta: { title: 'Plugin 1', description: 'Plugin 1 description' },
      } as ToolManifest,
      runtimeType: 'standalone',
      type: 'plugin',
    },
    {
      identifier: 'plugin-2',
      manifest: {
        identifier: 'plugin-2',
        api: [{ name: 'api-2' }],
        author: 'Another Author',
        homepage: 'https://example.com/plugin-2',
      } as ToolManifest,
      runtimeType: 'default',
      type: 'plugin',
    },
    {
      identifier: 'plugin-3',
      manifest: {
        identifier: 'plugin-3',
        api: [
          {
            name: 'api-3',
            url: 'bac',
            description: '123123',
            parameters: { type: 'object', properties: { a: { type: 'string' } } },
          },
        ],
      },
      type: 'customPlugin',
    },
  ],
  builtinTools: [
    {
      type: 'builtin',
      identifier: 'builtin-1',
      manifest: {
        identifier: 'builtin-1',
        api: [{ name: 'builtin-api-1' }],
        meta: { title: 'Builtin 1', description: 'Builtin 1 description' },
      } as ToolManifest,
    },
  ],
  pluginInstallLoading: {
    'plugin-1': false,
    'plugin-2': true,
  },
  pluginInstallErrors: {},
  uninstalledBuiltinTools: [],
} as ToolStoreState;

describe('toolSelectors', () => {
  describe('getToolManifestLoadingStatus', () => {
    it('should return "loading" if the plugin manifest is being loaded', () => {
      const result = toolSelectors.getManifestLoadingStatus('plugin-2')(mockState);
      expect(result).toBe('loading');
    });

    it('should return "error" if the plugin manifest is not found', () => {
      const result = toolSelectors.getManifestLoadingStatus('non-existing-plugin')(mockState);
      expect(result).toBe('error');
    });

    it('should return "success" if the plugin manifest is loaded', () => {
      const result = toolSelectors.getManifestLoadingStatus('plugin-1')(mockState);
      expect(result).toBe('success');
    });

    it('should return "error" when a refresh failed even if an old manifest remains', () => {
      const state = {
        ...mockState,
        pluginInstallErrors: {
          'plugin-1': { cause: 'Connection refused', message: 'fetchError' },
        },
      } as unknown as ToolStoreState;

      expect(toolSelectors.getManifestLoadingStatus('plugin-1')(state)).toBe('error');
      expect(toolSelectors.getPluginInstallError('plugin-1')(state)).toEqual({
        cause: 'Connection refused',
        message: 'fetchError',
      });
    });
  });

  describe('metaList and getMetaById', () => {
    it('should return the correct list of tool metadata', () => {
      const result = toolSelectors.metaList(mockState);
      expect(result).toEqual([
        {
          author: 'LobeHub',
          identifier: 'test-skill',
          meta: { avatar: '🧪', description: 'A test skill', title: 'Test Skill' },
          type: 'builtin',
        },
        {
          type: 'builtin',
          author: 'LobeHub',
          identifier: 'builtin-1',
          meta: { title: 'Builtin 1', description: 'Builtin 1 description' },
        },
        {
          author: 'Test Author',
          createdAt: '2024-01-01',
          description: 'Plugin 1 description',
          homepage: 'https://example.com/plugin-1',
          identifier: 'plugin-1',
          meta: { title: 'Plugin 1', description: 'Plugin 1 description' },
          runtimeType: 'standalone',
          title: 'Plugin 1',
          type: 'plugin',
        },
        {
          author: 'Another Author',
          createdAt: undefined,
          homepage: 'https://example.com/plugin-2',
          identifier: 'plugin-2',
          meta: undefined,
          runtimeType: 'default',
          type: 'plugin',
        },
        {
          author: undefined,
          createdAt: undefined,
          homepage: undefined,
          identifier: 'plugin-3',
          meta: undefined,
          runtimeType: undefined,
          type: 'customPlugin',
        },
      ]);
    });

    it('should return the correct metadata by identifier', () => {
      const result = toolSelectors.getMetaById('plugin-1')(mockState);
      expect(result).toEqual({ title: 'Plugin 1', description: 'Plugin 1 description' });
    });

    it('should return undefined for non-existent identifier', () => {
      const result = toolSelectors.getMetaById('non-existent')(mockState);
      expect(result).toBeUndefined();
    });
  });

  describe('getManifestById and getManifestLoadingStatus', () => {
    it('should return the correct manifest by identifier', () => {
      const result = toolSelectors.getManifestById('plugin-1')(mockState);
      expect(result).toEqual({
        identifier: 'plugin-1',
        api: [{ name: 'api-1' }],
        author: 'Test Author',
        createdAt: '2024-01-01',
        homepage: 'https://example.com/plugin-1',
        meta: { title: 'Plugin 1', description: 'Plugin 1 description' },
      });
    });

    it('should return undefined for non-existent identifier', () => {
      const result = toolSelectors.getManifestById('non-existent')(mockState);
      expect(result).toBeUndefined();
    });

    it('should return the correct loading status for a plugin', () => {
      expect(toolSelectors.getManifestLoadingStatus('plugin-1')(mockState)).toBe('success');
      expect(toolSelectors.getManifestLoadingStatus('plugin-2')(mockState)).toBe('loading');
      expect(toolSelectors.getManifestLoadingStatus('non-existent')(mockState)).toBe('error');
    });
  });

  describe('isToolHasUI', () => {
    it('should return false if the tool has no UI', () => {
      expect(toolSelectors.isToolHasUI('plugin-1')(mockState)).toBe(false);
    });

    it('should return true if the tool has UI', () => {
      expect(toolSelectors.isToolHasUI('builtin-1')(mockState)).toBe(true);
    });

    it('should return false if the tool does not exist', () => {
      expect(toolSelectors.isToolHasUI('non-existent')(mockState)).toBe(false);
    });
  });
});

// Marketplace and custom MCP installs land only in `user_connectors` now: chat
// must discover and activate them the way it did their plugin rows
describe('MCP connectors in tool discovery', () => {
  const connectorTool = (toolName: string) => ({
    crudType: 'read',
    description: `${toolName} tool`,
    displayName: null,
    id: toolName,
    inputSchema: { properties: {}, type: 'object' },
    permission: 'auto',
    toolName,
    userConnectorId: 'c',
  });
  const marketplace = (identifier: string, patch: Record<string, unknown> = {}) => ({
    id: identifier,
    identifier,
    isEnabled: true,
    mcpConnectionType: 'http',
    mcpServerUrl: `https://${identifier}.example.com/mcp`,
    metadata: { marketplaceInstalled: true },
    name: `${identifier} name`,
    sourceType: 'marketplace',
    status: 'connected',
    tools: [connectorTool('search')],
    ...patch,
  });
  const state = (connectors: unknown[]) =>
    ({ ...mockState, connectors }) as unknown as ToolStoreState;

  it('lists a finished marketplace install and a custom connector', () => {
    const s = state([
      marketplace('notes-mcp'),
      marketplace('my-custom', { metadata: {}, sourceType: 'custom' }),
    ]);

    const ids = toolSelectors.availableToolsForDiscovery(s).map((tool) => tool.identifier);

    expect(ids).toEqual(expect.arrayContaining(['notes-mcp', 'my-custom']));
    expect(toolSelectors.availableToolsForDiscovery(s)).toContainEqual({
      description: 'notes-mcp name connector with 1 tools',
      identifier: 'notes-mcp',
      name: 'notes-mcp name',
    });
  });

  it('leaves out unfinished installs, stdio servers off desktop, and plugin-served ids', () => {
    const s = state([
      marketplace('pending-mcp', { metadata: {}, status: 'disconnected' }),
      marketplace('local-mcp', { mcpConnectionType: 'stdio', mcpServerUrl: null }),
      // A plugin row still serves this identifier: one entry, the plugin's
      marketplace('plugin-1'),
    ]);

    const ids = toolSelectors.availableToolsForDiscovery(s).map((tool) => tool.identifier);

    expect(ids).not.toContain('pending-mcp');
    expect(ids).not.toContain('local-mcp');
    expect(ids.filter((id) => id === 'plugin-1')).toHaveLength(1);
  });

  it("offers a private row's tool set in place of a same-identifier legacy plugin", () => {
    // Regression: the plugin's bare entry hid the private row's suffixed tool
    // set, but the run's pool replaces the plugin with that tool set, so the
    // advertised bare name had nothing to activate.
    const s = state([
      marketplace('plugin-1', {
        id: '3f9a1c2e-mine',
        metadata: {},
        sourceType: 'custom',
        visibility: 'private',
      }),
    ]);
    runListing.rows = [s.connectors[0]];
    const ids = toolSelectors
      .availableToolsForDiscovery(s, { agentId: 'agt-private', topicId: 'tpc-own' })
      .map((tool) => tool.identifier);
    runListing.rows = undefined;

    expect(ids).toContain('plugin-1-3f9a1c2e');
    expect(ids).not.toContain('plugin-1');
  });

  it('lists a private row beside the shared one of its connector, each under its prefix', () => {
    // Regression: discovery matched manifests against base identifiers, so a
    // private row's `identifier-<suffix>` tool set never matched and could not
    // be discovered or activated.
    const s = state([
      marketplace('notes-mcp', { id: 'c-shared', metadata: {}, sourceType: 'custom' }),
      marketplace('notes-mcp', {
        id: '3f9a1c2e-mine',
        metadata: {},
        sourceType: 'custom',
        visibility: 'private',
      }),
    ]);

    const shared = s.connectors[0];
    const mine = s.connectors[1];
    // The conversation's server listing names the rows it may run
    runListing.rows = [mine, shared];
    const run = { agentId: 'agt-private', topicId: 'tpc-own' };

    expect(toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier)).toEqual(
      expect.arrayContaining(['notes-mcp', 'notes-mcp-3f9a1c2e']),
    );
  });

  it("offers no private row a conversation's listing leaves out, nor any without a listing", () => {
    // Regression: discovery merged every listed conversation's rows, so a
    // public agent's chat advertised a private agent's connectors.
    const s = state([
      marketplace('notes-mcp', { id: 'c-shared', metadata: {}, sourceType: 'custom' }),
      marketplace('notes-mcp', {
        id: '3f9a1c2e-mine',
        metadata: {},
        sourceType: 'custom',
        visibility: 'private',
      }),
    ]);
    runListing.rows = [s.connectors[0]];
    const ids = (run = {}) =>
      toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier);

    expect(ids({ agentId: 'agt-public', topicId: 'tpc-1' })).not.toContain('notes-mcp-3f9a1c2e');
    runListing.rows = undefined;
    expect(ids()).toContain('notes-mcp');
    expect(ids()).not.toContain('notes-mcp-3f9a1c2e');
  });

  it('offers no Composio app whose only connection the conversation may not use', () => {
    // Regression: a shared Composio connection switched to private kept its
    // projection, so a workspace agent's chat advertised tools it cannot run.
    const gmail = {
      identifier: 'gmail',
      label: 'Gmail',
      status: 'active',
      tools: [{ name: 'GMAIL_SEND', inputSchema: {} }],
    };
    const s = {
      ...state([]),
      composioServers: [gmail],
      connectors: [
        {
          id: 'c-gmail',
          identifier: 'gmail',
          metadata: { composio: { connectedAccountId: 'ca-1' } },
          visibility: 'private',
        },
      ],
    } as unknown as ToolStoreState;
    const ids = (run = {}) =>
      toolSelectors.availableToolsForDiscovery(s, run).map((tool) => tool.identifier);

    runListing.rows = [];
    expect(ids({ agentId: 'agt-public', topicId: 'tpc-1' })).not.toContain('gmail');
    runListing.rows = undefined;
    expect(ids()).not.toContain('gmail');
    // The owner's private agent's own conversation lists it
    runListing.rows = [s.connectors[0]];
    expect(ids({ agentId: 'agt-private', topicId: 'tpc-own' })).toContain('gmail');
    runListing.rows = undefined;
  });

  it("reads a connector-only identifier's manifest from its connector", () => {
    const s = state([marketplace('notes-mcp'), marketplace('plugin-1')]);

    expect(toolSelectors.getManifestById('notes-mcp')(s)).toMatchObject({
      api: [expect.objectContaining({ name: 'search' })],
      identifier: 'notes-mcp',
      type: 'mcp',
    });
    // A plugin row keeps serving its identifier
    expect(toolSelectors.getManifestById('plugin-1')(s)?.api).toEqual([{ name: 'api-1' }]);
  });
});