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.

16.3 KB
Raw Blame
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { registerMessageCommand } from './message';

const { mockTrpcClient } = vi.hoisted(() => ({
  mockTrpcClient: {
    message: {
      count: { query: vi.fn() },
      countByTopic: { query: vi.fn() },
      getHeatmaps: { query: vi.fn() },
      getMessages: { query: vi.fn() },
      listAll: { query: vi.fn() },
      removeMessage: { mutate: vi.fn() },
      removeMessages: { mutate: vi.fn() },
      searchByKeyword: { query: vi.fn() },
      searchMessages: { query: vi.fn() },
      topicStats: { query: vi.fn() },
    },
  },
}));

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

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

  beforeEach(() => {
    exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
    consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
    for (const method of Object.values(mockTrpcClient.message)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
  });

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

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

  describe('list', () => {
    it('should use listAll with a default page size of 50 when no filters', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([
        { content: 'Hello', createdAt: new Date().toISOString(), id: 'm1', role: 'user' },
      ]);

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

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ pageSize: 50 }),
      );
      expect(mockTrpcClient.message.getMessages.query).not.toHaveBeenCalled();
      expect(consoleSpy).toHaveBeenCalledTimes(2);
    });

    it('should push topic-id filter to listAll', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'list', '--topic-id', 't1']);

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ topicId: 't1' }),
      );
      expect(mockTrpcClient.message.getMessages.query).not.toHaveBeenCalled();
    });

    it('should push role and date range filters to listAll', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'message',
        'list',
        '--role',
        'user',
        '--start',
        '2026-08-31',
        '--end',
        '2026-09-01',
      ]);

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ endDate: '2026-09-01', role: 'user', startDate: '2026-08-31' }),
      );
    });

    it('should treat --user as --role user on the server side', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([]);

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

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ role: 'user' }),
      );
    });

    it('should keep first page on the backend default offset for filtered queries', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'message',
        'list',
        '--topic-id',
        't1',
        '-L',
        '200',
      ]);

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ pageSize: 200, topicId: 't1' }),
      );
    });

    it('should convert page 2 to current 1 for filtered queries', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'message',
        'list',
        '--topic-id',
        't1',
        '--page',
        '2',
      ]);

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ current: 1, topicId: 't1' }),
      );
    });

    it('should support the short page flag for filtered queries', async () => {
      mockTrpcClient.message.listAll.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'list', '--topic-id', 't1', '-P', '2']);

      expect(mockTrpcClient.message.listAll.query).toHaveBeenCalledWith(
        expect.objectContaining({ current: 1, topicId: 't1' }),
      );
    });
  });

  describe('search', () => {
    it('searches through the filtered endpoint with default paging', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({ hasMore: false, items: [] });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'hello']);

      expect(mockTrpcClient.message.searchByKeyword.query).toHaveBeenCalledWith({
        keywords: 'hello',
        limit: 20,
        offset: 0,
      });
      expect(mockTrpcClient.message.searchMessages.query).not.toHaveBeenCalled();
    });

    it('passes the time window, roles, scope and match options', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({ hasMore: false, items: [] });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'message',
        'search',
        'STAMP',
        '--since',
        '2026-10-12',
        '--until',
        '2026-10-18',
        '--role',
        'user, assistant',
        '--topic-id',
        'tpc_1',
        '--agent-id',
        'agt_1',
        '--exact',
        '--include-system',
        '-L',
        '5',
        '-P',
        '3',
      ]);

      expect(mockTrpcClient.message.searchByKeyword.query).toHaveBeenCalledWith({
        agentId: 'agt_1',
        endDate: new Date(2026, 9, 18, 23, 59, 59, 999),
        exact: true,
        includeAutomatedPrompts: true,
        keywords: 'STAMP',
        limit: 5,
        offset: 10,
        roles: ['user', 'assistant'],
        startDate: new Date(2026, 9, 12, 0, 0, 0, 0),
        topicId: 'tpc_1',
      });
    });

    it('prints time, topic and snippet, and hints at the next page', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
        hasMore: true,
        items: [
          {
            createdAt: new Date(2026, 9, 15, 9, 5),
            id: 'msg_1',
            role: 'user',
            snippet: 'turning on STAMP mode',
            topicId: 'tpc_1',
            topicTitle: 'Weekly report',
          },
        ],
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'STAMP']);

      const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
      expect(output).toContain('2026-10-15 09:05');
      expect(output).toContain('Weekly report');
      expect(output).toContain('turning on STAMP mode');
      expect(output).toContain('-P 2');
    });

    it('warns when the provider pool cut off lower-ranked matches', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
        hasMore: false,
        items: [{ createdAt: new Date(2026, 9, 15), id: 'msg_1', role: 'user', snippet: 'x' }],
        truncated: true,
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'x']);

      const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
      expect(output).toContain('Only the most relevant matches were considered');
    });

    it('keeps the truncation caveat when filtering empties the page', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
        hasMore: false,
        items: [],
        truncated: true,
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--exact']);

      const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
      expect(output).toContain('No messages found.');
      expect(output).toContain('Only the most relevant matches were considered');
    });

    it('keeps the truncation caveat on stderr for --json output', async () => {
      const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
      mockTrpcClient.message.searchByKeyword.query.mockResolvedValue({
        hasMore: false,
        items: [{ contentLength: 1, createdAt: new Date(2026, 9, 15), id: 'msg_1', role: 'user' }],
        truncated: true,
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--json']);

      // stdout stays a bare array so scripts keep parsing it
      const stdout = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
      expect(() => JSON.parse(stdout)).not.toThrow();
      expect(JSON.parse(stdout)).toHaveLength(1);

      const stderr = errorSpy.mock.calls.map((call) => call.join(' ')).join('\n');
      expect(stderr).toContain('Only the most relevant matches were considered');

      errorSpy.mockRestore();
    });

    it('rejects an impossible calendar date instead of shifting the window', async () => {
      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--until', '2026-02-31']);

      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.message.searchByKeyword.query).not.toHaveBeenCalled();
    });

    it('rejects an invalid time instead of searching everything', async () => {
      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'x', '--since', 'last week']);

      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.message.searchByKeyword.query).not.toHaveBeenCalled();
    });

    it('falls back to the legacy endpoint on an older server when no filters are used', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockRejectedValue(
        Object.assign(new Error('No "query"-procedure on path "message.searchByKeyword"'), {
          data: { code: 'NOT_FOUND' },
        }),
      );
      mockTrpcClient.message.searchMessages.query.mockResolvedValue([
        { content: 'hello there', id: 'msg_legacy', role: 'user' },
      ]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'hello']);

      expect(mockTrpcClient.message.searchMessages.query).toHaveBeenCalledWith({
        keywords: 'hello',
      });
      const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
      expect(output).toContain('msg_legacy');
    });

    it('refuses to drop filters silently on an older server', async () => {
      mockTrpcClient.message.searchByKeyword.query.mockRejectedValue(
        Object.assign(new Error('No "query"-procedure on path "message.searchByKeyword"'), {
          data: { code: 'NOT_FOUND' },
        }),
      );

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'search', 'hello', '--since', '7d']);

      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.message.searchMessages.query).not.toHaveBeenCalled();
    });
  });

  describe('delete', () => {
    it('should delete single message', async () => {
      mockTrpcClient.message.removeMessage.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'delete', 'm1', '--yes']);

      expect(mockTrpcClient.message.removeMessage.mutate).toHaveBeenCalledWith({ id: 'm1' });
    });

    it('should batch delete messages', async () => {
      mockTrpcClient.message.removeMessages.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'delete', 'm1', 'm2', '--yes']);

      expect(mockTrpcClient.message.removeMessages.mutate).toHaveBeenCalledWith({
        ids: ['m1', 'm2'],
      });
    });
  });

  describe('count', () => {
    it('should count messages', async () => {
      mockTrpcClient.message.count.query.mockResolvedValue(42);

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

      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('42'));
    });

    it('should output JSON', async () => {
      mockTrpcClient.message.count.query.mockResolvedValue(42);

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

      expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify({ count: 42 }));
    });

    it('should forward topic / agent / role filters', async () => {
      mockTrpcClient.message.count.query.mockResolvedValue(3);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'message',
        'count',
        '--topic-id',
        't1',
        '--agent-id',
        'a1',
        '--role',
        'user',
      ]);

      expect(mockTrpcClient.message.count.query).toHaveBeenCalledWith({
        agentId: 'a1',
        role: 'user',
        topicId: 't1',
      });
    });

    it('should group by topic', async () => {
      mockTrpcClient.message.countByTopic.query.mockResolvedValue([
        { count: 7, topicId: 't1' },
        { count: 2, topicId: 't2' },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'message',
        'count',
        '--group-by',
        'topic',
        '--agent-id',
        'a1',
        '--json',
      ]);

      expect(mockTrpcClient.message.countByTopic.query).toHaveBeenCalledWith({ agentId: 'a1' });
      expect(mockTrpcClient.message.count.query).not.toHaveBeenCalled();
      expect(consoleSpy).toHaveBeenCalledWith(
        JSON.stringify([
          { count: 7, topicId: 't1' },
          { count: 2, topicId: 't2' },
        ]),
      );
    });

    it('should reject an unsupported --group-by', async () => {
      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'count', '--group-by', 'agent']);

      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.message.countByTopic.query).not.toHaveBeenCalled();
    });
  });

  describe('stats', () => {
    const sampleStats = {
      histogram: [
        { topics: 1, userCount: 1 },
        { topics: 1, userCount: 5 },
      ],
      max: 5,
      mean: 3,
      median: 3,
      min: 1,
      oneshot: 1,
      oneshotRatio: 0.5,
      p90: 5,
      p99: 5,
      topics: 2,
      totalMessages: 6,
    };

    it('should default to user-role distribution', async () => {
      mockTrpcClient.message.topicStats.query.mockResolvedValue(sampleStats);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'stats', '--agent-id', 'a1']);

      expect(mockTrpcClient.message.topicStats.query).toHaveBeenCalledWith({
        agentId: 'a1',
        role: 'user',
      });
    });

    it('should support --all-roles', async () => {
      mockTrpcClient.message.topicStats.query.mockResolvedValue(sampleStats);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'message', 'stats', '--all-roles']);

      expect(mockTrpcClient.message.topicStats.query).toHaveBeenCalledWith({});
    });

    it('should output JSON', async () => {
      mockTrpcClient.message.topicStats.query.mockResolvedValue(sampleStats);

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

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