Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

8.9 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest';

const mockCallCoreRpc = vi.fn();

vi.mock('../coreRpcClient', () => ({
  callCoreRpc: (...args: unknown[]) => mockCallCoreRpc(...args),
}));

describe('threadApi', () => {
  beforeEach(() => {
    mockCallCoreRpc.mockReset();
  });

  it('loads threads from the threads RPC store', async () => {
    mockCallCoreRpc.mockResolvedValueOnce({
      data: {
        threads: [
          {
            id: 'default-thread',
            title: 'Conversation',
            chatId: null,
            isActive: true,
            messageCount: 2,
            lastMessageAt: '2026-04-10T12:01:00Z',
            createdAt: '2026-04-10T12:00:00Z',
          },
        ],
        count: 1,
      },
    });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.getThreads();

    expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.threads_list' });
    expect(result.count).toBe(1);
    expect(result.threads[0].id).toBe('default-thread');
  });

  it('appends a message via threads RPC', async () => {
    const message = {
      id: 'm1',
      content: 'hello',
      type: 'text',
      extraMetadata: {},
      sender: 'user' as const,
      createdAt: '2026-04-10T12:01:00Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: message });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.appendMessage('default-thread', message);

    expect(mockCallCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.threads_message_append',
      params: { thread_id: 'default-thread', message },
    });
    expect(result).toEqual(message);
  });

  it('searches message text across threads', async () => {
    const hit = {
      threadId: 't1',
      messageId: 'm1',
      role: 'user',
      snippet: '…the quarterly plan…',
      createdAt: '2026-04-10T12:00:00Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: { hits: [hit] } });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.searchMessages('plan', 10);

    expect(mockCallCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.threads_search',
      params: { query: 'plan', limit: 10 },
    });
    expect(result).toEqual([hit]);
  });

  it('folds the legacy `assistant` sender onto `agent` when listing messages (#5933)', async () => {
    mockCallCoreRpc.mockResolvedValueOnce({
      data: {
        messages: [
          {
            id: 'user:1',
            content: 'hi',
            type: 'text',
            extraMetadata: {},
            sender: 'user',
            createdAt: '2026-04-10T12:01:00Z',
          },
          {
            // Written by a legacy core writer before it switched its closing
            // message to the `agent` vocabulary.
            id: 'assistant:legacy',
            content: 'done',
            type: 'text',
            extraMetadata: { scope: 'autonomous_task_result' },
            sender: 'assistant',
            createdAt: '2026-04-10T12:02:00Z',
          },
        ],
        count: 2,
      },
    });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.getThreadMessages('default-thread');

    expect(result.count).toBe(2);
    expect(result.messages.map(m => m.sender)).toEqual(['user', 'agent']);
    // Everything else on the row is untouched.
    expect(result.messages[1]).toMatchObject({ id: 'assistant:legacy', content: 'done' });
  });

  it('folds the legacy `assistant` sender onto `agent` on append and update results', async () => {
    const stored = {
      id: 'agent:run-1',
      content: 'done',
      type: 'text',
      extraMetadata: {},
      sender: 'assistant',
      createdAt: '2026-04-10T12:02:00Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: stored });
    mockCallCoreRpc.mockResolvedValueOnce({ data: stored });

    const { threadApi } = await import('./threadApi');
    const appended = await threadApi.appendMessage('default-thread', {
      ...stored,
      sender: 'agent',
    });
    const updated = await threadApi.updateMessage('default-thread', 'agent:run-1', {});

    expect(appended.sender).toBe('agent');
    expect(updated.sender).toBe('agent');
  });

  it('generates a thread title via threads RPC', async () => {
    const thread = {
      id: 'default-thread',
      title: 'Invoice follow-up',
      chatId: null,
      isActive: true,
      messageCount: 2,
      lastMessageAt: '2026-04-10T12:01:00Z',
      createdAt: '2026-04-10T12:00:00Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: thread });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.generateTitleIfNeeded(
      'default-thread',
      'I can draft the invoice follow-up note for you.'
    );

    expect(mockCallCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.threads_generate_title',
      params: {
        thread_id: 'default-thread',
        assistant_message: 'I can draft the invoice follow-up note for you.',
      },
    });
    expect(result).toEqual(thread);
  });

  it('updates a thread title via threads RPC', async () => {
    const thread = {
      id: 'thread-1',
      title: 'Invoice follow-up',
      chatId: null,
      isActive: true,
      messageCount: 3,
      lastMessageAt: '2026-05-01T09:00:00Z',
      createdAt: '2026-05-01T08:00:00Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: thread });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.updateTitle('thread-1', 'Invoice follow-up');

    expect(mockCallCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.threads_update_title',
      params: { thread_id: 'thread-1', title: 'Invoice follow-up' },
    });
    expect(result).toEqual(thread);
  });

  it('loads durable run ledger rows and events through run_ledger RPCs', async () => {
    const run = {
      id: 'sub-1',
      kind: 'worker_thread',
      parentRunId: 'req-1',
      parentThreadId: 'thread-1',
      agentId: 'researcher',
      status: 'awaiting_user',
      workerThreadId: 'worker-1',
      checkpoint: { resumeTool: 'continue_subagent' },
      metadata: {},
      startedAt: '2026-06-04T12:00:00Z',
      updatedAt: '2026-06-04T12:00:10Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: { runs: [run], count: 1 } });

    const { threadApi } = await import('./threadApi');
    await expect(threadApi.listRuns({ parentThreadId: 'thread-1' })).resolves.toEqual([run]);
    expect(mockCallCoreRpc).toHaveBeenCalledWith({
      method: 'openhuman.run_ledger_list',
      params: { parentThreadId: 'thread-1' },
    });

    mockCallCoreRpc.mockResolvedValueOnce({ data: { runs: [], count: 0 } });
    await expect(threadApi.listRuns()).resolves.toEqual([]);
    expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
      method: 'openhuman.run_ledger_list',
      params: {},
    });

    mockCallCoreRpc.mockResolvedValueOnce({ data: { run } });
    await expect(threadApi.getRun('sub-1')).resolves.toEqual(run);
    expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
      method: 'openhuman.run_ledger_get',
      params: { id: 'sub-1' },
    });

    const event = {
      runId: 'sub-1',
      sequence: 1,
      eventType: 'subagent_awaiting_user',
      payload: { question: 'Which file?' },
      timestamp: '2026-06-04T12:00:10Z',
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: { events: [event], count: 1 } });
    await expect(threadApi.listRunEvents('sub-1', { afterSequence: 0 })).resolves.toEqual([event]);
    expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
      method: 'openhuman.run_ledger_events',
      params: { runId: 'sub-1', afterSequence: 0 },
    });
  });

  it('fetches the derived transcript page with pagination controls', async () => {
    const pageData = {
      threadId: 'thread-1',
      items: [{ kind: 'turnBoundary', requestId: 'req-1' }],
      total: 1,
      hasMore: false,
      hasTranscript: true,
    };
    mockCallCoreRpc.mockResolvedValueOnce({ data: pageData });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.getDerivedTranscript('thread-1', { cursor: '10', limit: 50 });

    expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
      method: 'openhuman.threads_transcript_get',
      params: { thread_id: 'thread-1', cursor: '10', limit: 50 },
    });
    expect(result).toEqual(pageData);
  });

  it('fetches the derived transcript with default (undefined) pagination when omitted', async () => {
    mockCallCoreRpc.mockResolvedValueOnce({
      data: { threadId: 'thread-1', items: [], total: 0, hasMore: false, hasTranscript: false },
    });

    const { threadApi } = await import('./threadApi');
    const result = await threadApi.getDerivedTranscript('thread-1');

    expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
      method: 'openhuman.threads_transcript_get',
      params: { thread_id: 'thread-1', cursor: undefined, limit: undefined },
    });
    expect(result.hasTranscript).toBe(false);
  });
});