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.

17.3 KB
Raw Blame
import { BOT_CREDENTIAL_MASK } from '@lobechat/const';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { log } from '../utils/logger';
import { registerBotCommand } from './bot';

const { mockTrpcClient } = vi.hoisted(() => ({
  mockTrpcClient: {
    agentBotProvider: {
      connectBot: { mutate: vi.fn() },
      create: { mutate: vi.fn() },
      delete: { mutate: vi.fn() },
      getByAgentId: { query: vi.fn() },
      list: { query: vi.fn() },
      listPlatforms: { query: vi.fn() },
      testConnection: { mutate: vi.fn() },
      update: { mutate: vi.fn() },
    },
  },
}));

const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
  getTrpcClient: vi.fn(),
}));

vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
describe('bot command', () => {
  let exitSpy: ReturnType<typeof vi.spyOn>;
  let consoleSpy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    exitSpy = vi.spyOn(process, 'exit').mockImplementation((code) => {
      throw new Error(`process.exit ${code}`);
    });
    consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
    for (const method of Object.values(mockTrpcClient.agentBotProvider)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    mockTrpcClient.agentBotProvider.listPlatforms.query.mockResolvedValue([
      {
        id: 'discord',
        schema: [
          {
            key: 'credentials',
            properties: [
              { key: 'botToken', required: true },
              { key: 'publicKey', required: true },
            ],
          },
        ],
      },
      {
        id: 'telegram',
        schema: [
          {
            key: 'credentials',
            properties: [
              { key: 'botToken', required: true },
              { key: 'secretToken', required: false },
            ],
          },
        ],
      },
    ]);
  });

  afterEach(() => {
    exitSpy.mockRestore();
    consoleSpy.mockRestore();
  });

  function createProgram() {
    const program = new Command();
    program.exitOverride();
    registerBotCommand(program);
    return program;
  }

  describe('list', () => {
    it('should list all bot integrations', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
        {
          agentId: 'agent1',
          applicationId: 'app123',
          enabled: true,
          id: 'b1',
          platform: 'discord',
        },
      ]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'list']);

      expect(mockTrpcClient.agentBotProvider.list.query).toHaveBeenCalledWith({});
      expect(consoleSpy).toHaveBeenCalledTimes(2); // header + 1 row
      expect(consoleSpy.mock.calls[0][0]).toContain('ID');
    });

    it('should filter by agent', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'list', '--agent', 'agent1']);

      expect(mockTrpcClient.agentBotProvider.list.query).toHaveBeenCalledWith({
        agentId: 'agent1',
      });
    });

    it('should filter by platform', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'list', '--platform', 'discord']);

      expect(mockTrpcClient.agentBotProvider.list.query).toHaveBeenCalledWith({
        platform: 'discord',
      });
    });

    it('should output JSON', async () => {
      const items = [{ id: 'b1', platform: 'discord' }];
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue(items);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'list', '--json']);

      expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(items, null, 2));
    });

    it('should show message when no bots found', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'list']);

      expect(consoleSpy).toHaveBeenCalledWith('No bot integrations found.');
    });
  });

  describe('view', () => {
    it('should display bot details', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
        { agentId: 'agent1', id: 'b1', platform: 'discord' },
      ]);
      mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
        {
          applicationId: 'app123',
          credentials: { botToken: 'tok_12345678' },
          enabled: true,
          id: 'b1',
          platform: 'discord',
        },
      ]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'view', 'b1']);

      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('discord'));
      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('app123'));
    });

    it('should error when bot not found', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);

      const program = createProgram();
      await expect(
        program.parseAsync(['node', 'test', 'bot', 'view', 'nonexistent']),
      ).rejects.toThrow('process.exit 1');

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });
  });

  describe('add', () => {
    it('should add a discord bot', async () => {
      mockTrpcClient.agentBotProvider.create.mutate.mockResolvedValue({ id: 'new-bot' });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'bot',
        'add',
        '--agent',
        'agent1',
        '--platform',
        'discord',
        '--app-id',
        'app123',
        '--bot-token',
        'tok123',
        '--public-key',
        'pk123',
      ]);

      expect(mockTrpcClient.agentBotProvider.create.mutate).toHaveBeenCalledWith({
        agentId: 'agent1',
        applicationId: 'app123',
        credentials: { botToken: 'tok123', publicKey: 'pk123' },
        platform: 'discord',
      });
      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Added'));
    });

    it('should add a telegram bot', async () => {
      mockTrpcClient.agentBotProvider.create.mutate.mockResolvedValue({ id: 'new-bot' });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'bot',
        'add',
        '--agent',
        'agent1',
        '--platform',
        'telegram',
        '--app-id',
        'tg123',
        '--bot-token',
        'tok123',
      ]);

      expect(mockTrpcClient.agentBotProvider.create.mutate).toHaveBeenCalledWith({
        agentId: 'agent1',
        applicationId: 'tg123',
        credentials: { botToken: 'tok123' },
        platform: 'telegram',
      });
    });

    it('should reject invalid platform', async () => {
      const program = createProgram();
      await expect(
        program.parseAsync([
          'node',
          'test',
          'bot',
          'add',
          '--agent',
          'agent1',
          '--platform',
          'invalid',
          '--app-id',
          'x',
          '--bot-token',
          'x',
        ]),
      ).rejects.toThrow('process.exit 1');

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Invalid platform'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should reject missing required credentials', async () => {
      const program = createProgram();
      await expect(
        program.parseAsync([
          'node',
          'test',
          'bot',
          'add',
          '--agent',
          'agent1',
          '--platform',
          'discord',
          '--app-id',
          'app123',
          '--bot-token',
          'tok123',
          // missing --public-key
        ]),
      ).rejects.toThrow('process.exit 1');

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Missing required'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });
  });

  describe('update', () => {
    const mockExistingBot = (credentials: Record<string, string>) => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
        { agentId: 'agent1', id: 'b1', platform: 'discord' },
      ]);
      mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
        { agentId: 'agent1', credentials, id: 'b1', platform: 'discord', settings: {} },
      ]);
    };

    it('preserves the existing public key when updating the token', async () => {
      mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });
      mockTrpcClient.agentBotProvider.update.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'update', 'b1', '--bot-token', 'new-token']);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
        credentials: { botToken: 'new-token', publicKey: 'public-key' },
        id: 'b1',
      });
    });

    it('preserves the existing token mask when updating the public key', async () => {
      mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'old-public-key' });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'bot',
        'update',
        'b1',
        '--public-key',
        'new-public-key',
      ]);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
        credentials: { botToken: BOT_CREDENTIAL_MASK, publicKey: 'new-public-key' },
        id: 'b1',
      });
    });

    it('does not send credentials for a settings-only update', async () => {
      mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'update', 'b1', '--dm-policy', 'open']);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
        id: 'b1',
        settings: { dmPolicy: 'open' },
      });
    });

    it('turns the processing message off without touching other settings', async () => {
      mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'bot',
        'update',
        'b1',
        '--processing-message',
        'off',
      ]);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
        id: 'b1',
        settings: { processingMessage: false },
      });
    });

    it('does not carry credentials from the old platform when changing platform', async () => {
      mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'discord-public-key' });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'bot',
        'update',
        'b1',
        '--platform',
        'telegram',
        '--bot-token',
        'telegram-token',
      ]);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith({
        credentials: { botToken: 'telegram-token' },
        id: 'b1',
        platform: 'telegram',
      });
    });

    it('should error when no changes specified', async () => {
      mockExistingBot({ botToken: BOT_CREDENTIAL_MASK, publicKey: 'public-key' });
      const program = createProgram();
      await expect(program.parseAsync(['node', 'test', 'bot', 'update', 'b1'])).rejects.toThrow(
        'process.exit 1',
      );

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No changes'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });
  });

  describe('remove', () => {
    it('should remove with --yes', async () => {
      mockTrpcClient.agentBotProvider.delete.mutate.mockResolvedValue([{ id: 'b1' }]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'remove', 'b1', '--yes']);

      expect(mockTrpcClient.agentBotProvider.delete.mutate).toHaveBeenCalledWith({ id: 'b1' });
    });

    it('fails loudly when the server removed nothing', async () => {
      // A delete that matched no row used to print the same checkmark as a real
      // one, which is what made an unreachable binding look deleted.
      mockTrpcClient.agentBotProvider.delete.mutate.mockResolvedValue([]);
      const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'remove', 'b1', '--yes']);

      expect(errorSpy.mock.calls.flat().join(' ')).toContain('Nothing removed');
      expect(process.exitCode).toBe(1);

      process.exitCode = 0;
      errorSpy.mockRestore();
    });
  });

  describe('enable / disable', () => {
    it('should enable a bot', async () => {
      mockTrpcClient.agentBotProvider.update.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'enable', 'b1']);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ enabled: true, id: 'b1' }),
      );
    });

    it('should disable a bot', async () => {
      mockTrpcClient.agentBotProvider.update.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'disable', 'b1']);

      expect(mockTrpcClient.agentBotProvider.update.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ enabled: false, id: 'b1' }),
      );
    });
  });

  describe('connect', () => {
    it('should connect a bot', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
        { agentId: 'agent1', id: 'b1', platform: 'discord' },
      ]);
      mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
        { applicationId: 'app123', id: 'b1', platform: 'discord' },
      ]);
      mockTrpcClient.agentBotProvider.connectBot.mutate.mockResolvedValue({ status: 'connected' });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'bot', 'connect', 'b1']);

      expect(mockTrpcClient.agentBotProvider.connectBot.mutate).toHaveBeenCalledWith({
        applicationId: 'app123',
        platform: 'discord',
      });
      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Connected'));
    });

    it('should error when bot not found', async () => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([]);

      const program = createProgram();
      await expect(
        program.parseAsync(['node', 'test', 'bot', 'connect', 'nonexistent']),
      ).rejects.toThrow('process.exit 1');

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });
  });

  describe('watch-keywords', () => {
    const withKeywords = (watchKeywords: unknown[]) => {
      mockTrpcClient.agentBotProvider.list.query.mockResolvedValue([
        { agentId: 'agent1', id: 'b1', platform: 'discord' },
      ]);
      mockTrpcClient.agentBotProvider.getByAgentId.query.mockResolvedValue([
        { id: 'b1', platform: 'discord', settings: { dmPolicy: 'open', watchKeywords } },
      ]);
    };
    const savedKeywords = () =>
      mockTrpcClient.agentBotProvider.update.mutate.mock.calls[0][0].settings.watchKeywords;

    it('adds a keyword as one of the bot names with --as-name', async () => {
      withKeywords([{ keyword: 'bug' }]);

      await createProgram().parseAsync([
        'node',
        'test',
        'bot',
        'watch-keywords',
        'add',
        'b1',
        'Canis',
        '--as-name',
      ]);

      expect(savedKeywords()).toEqual([
        { instruction: undefined, keyword: 'bug' },
        { asName: true, keyword: 'canis' },
      ]);
    });

    it('keeps the name mark on existing entries when another keyword is added', async () => {
      withKeywords([{ asName: true, keyword: 'canis' }]);

      await createProgram().parseAsync([
        'node',
        'test',
        'bot',
        'watch-keywords',
        'add',
        'b1',
        'bug',
      ]);

      expect(savedKeywords()).toEqual([
        { asName: true, instruction: undefined, keyword: 'canis' },
        { keyword: 'bug' },
      ]);
    });

    it('marks an existing keyword as a name when re-added with --as-name', async () => {
      withKeywords([{ instruction: 'look', keyword: 'canis' }]);

      await createProgram().parseAsync([
        'node',
        'test',
        'bot',
        'watch-keywords',
        'add',
        'b1',
        'canis',
        '--as-name',
      ]);

      expect(savedKeywords()).toEqual([{ asName: true, instruction: 'look', keyword: 'canis' }]);
    });

    it('shows which keywords are bot names in the list', async () => {
      withKeywords([{ asName: true, keyword: 'canis' }, { keyword: 'bug' }]);

      await createProgram().parseAsync(['node', 'test', 'bot', 'watch-keywords', 'list', 'b1']);

      const printed = consoleSpy.mock.calls.map((call) => String(call[0]));
      expect(printed[0]).toContain('BOT NAME');
      expect(printed.find((line) => line.includes('canis'))).toContain('yes');
    });
  });
});