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.

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

import { registerTaskCommand } from './task';

const { mockCreateTask, mockGetTrpcClient, mockGetWorkspace, mockLogInfo, mockResolveWorkspaceId } =
  vi.hoisted(() => ({
    mockCreateTask: vi.fn(),
    mockGetTrpcClient: vi.fn(),
    mockGetWorkspace: vi.fn(),
    mockLogInfo: vi.fn(),
    mockResolveWorkspaceId: vi.fn(),
  }));

vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
vi.mock('../api/workspace', () => ({ resolveWorkspaceId: mockResolveWorkspaceId }));
vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));
vi.mock('../utils/logger', () => ({
  log: { debug: vi.fn(), error: vi.fn(), info: mockLogInfo, warn: vi.fn() },
}));

describe('task create', () => {
  let consoleSpy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    mockCreateTask.mockReset();
    mockGetWorkspace.mockReset();
    mockResolveWorkspaceId.mockReset();
    mockGetTrpcClient.mockResolvedValue({
      task: { create: { mutate: mockCreateTask } },
      workspace: { getById: { query: mockGetWorkspace } },
    });
    mockLogInfo.mockReset();
  });

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

  const run = async (...args: string[]) => {
    const program = new Command();
    program.exitOverride();
    registerTaskCommand(program);
    await program.parseAsync(['node', 'test', 'task', 'create', ...args]);
  };

  it('includes the personal task URL in JSON output', async () => {
    mockCreateTask.mockResolvedValue({
      data: { id: 'task_1', identifier: 'T-1', name: 'Personal task' },
      message: 'Task created',
      success: true,
    });

    await run('--instruction', 'Do the thing', '--json');

    expect(consoleSpy).toHaveBeenCalledWith(
      JSON.stringify(
        {
          id: 'task_1',
          identifier: 'T-1',
          name: 'Personal task',
          url: 'https://app.example.com/task/T-1/personal-task',
        },
        null,
        2,
      ),
    );
  });

  it('prints a clickable workspace task URL in human output', async () => {
    mockResolveWorkspaceId.mockReturnValue('ws-1');
    mockGetWorkspace.mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });
    mockCreateTask.mockResolvedValue({
      data: { id: 'task_2', identifier: 'T-321', name: 'Workspace task' },
      message: 'Task created',
      success: true,
    });

    await run('--instruction', 'Do the workspace thing');

    expect(mockLogInfo).toHaveBeenCalledWith(expect.stringContaining('T-321'));
    expect(consoleSpy).toHaveBeenCalledWith(
      expect.stringContaining('https://app.example.com/lobehub/task/T-321/workspace-task'),
    );
  });
});

describe('task edit', () => {
  const mockUpdate = vi.fn();
  const mockUpdateStatus = vi.fn();

  beforeEach(() => {
    mockUpdate.mockReset().mockResolvedValue({
      data: { id: 'task_1', identifier: 'T-1' },
      success: true,
    });
    mockUpdateStatus.mockReset().mockResolvedValue({
      data: { id: 'task_1', identifier: 'T-1' },
      success: true,
    });
    mockGetTrpcClient.mockResolvedValue({
      task: {
        update: { mutate: mockUpdate },
        updateStatus: { mutate: mockUpdateStatus },
      },
    });
    mockLogInfo.mockReset();
  });

  const run = async (...args: string[]) => {
    const program = new Command();
    program.exitOverride();
    registerTaskCommand(program);
    await program.parseAsync(['node', 'test', 'task', 'edit', ...args]);
  };

  // --status used to early-return, silently dropping --agent and every other
  // field passed in the same invocation.
  it('applies --agent and --status together in one invocation', async () => {
    await run('task_1', '--agent', 'agt_new', '--status', 'backlog');

    expect(mockUpdate).toHaveBeenCalledWith(
      expect.objectContaining({ assigneeAgentId: 'agt_new', id: 'task_1', status: 'backlog' }),
    );
    expect(mockUpdateStatus).not.toHaveBeenCalled();
    expect(mockLogInfo).toHaveBeenCalledWith(expect.stringContaining('backlog'));
  });

  it('keeps the status-only path on the lifecycle API alone', async () => {
    await run('task_1', '--status', 'paused');

    expect(mockUpdateStatus).toHaveBeenCalledWith({ id: 'task_1', status: 'paused' });
    expect(mockUpdate).not.toHaveBeenCalled();
  });

  it('keeps field-only edits off the lifecycle API', async () => {
    await run('task_1', '--agent', 'agt_new');

    expect(mockUpdate).toHaveBeenCalledWith(
      expect.objectContaining({ assigneeAgentId: 'agt_new', id: 'task_1' }),
    );
    expect(mockUpdateStatus).not.toHaveBeenCalled();
  });
});

describe('task usage', () => {
  const mockUsage = vi.fn();

  beforeEach(() => {
    mockUsage.mockReset().mockResolvedValue({
      data: {
        byTask: [],
        runs: 2,
        taskId: 'task_1',
        taskIdentifier: 'T-1',
        totalCost: 0.125,
        totalInputTokens: 1200,
        totalOutputTokens: 300,
        totalTokens: 1500,
      },
      success: true,
    });
    mockGetTrpcClient.mockResolvedValue({ task: { usage: { query: mockUsage } } });
  });

  it('prints the task aggregate as JSON', async () => {
    const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    const program = new Command();
    program.exitOverride();
    registerTaskCommand(program);

    await program.parseAsync(['node', 'test', 'task', 'usage', 'T-1', '--json']);

    expect(mockUsage).toHaveBeenCalledWith({ id: 'T-1' });
    expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"totalCost": 0.125'));
    consoleSpy.mockRestore();
  });
});

describe('task list', () => {
  const mockList = vi.fn();
  let consoleSpy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    mockList.mockReset();
    mockResolveWorkspaceId.mockReset();
    mockGetWorkspace.mockReset();
    mockGetTrpcClient.mockResolvedValue({
      task: { list: { query: mockList } },
      workspace: { getById: { query: mockGetWorkspace } },
    });
  });

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

  it('links every task to its workspace page in JSON output', async () => {
    mockResolveWorkspaceId.mockReturnValue('ws-1');
    mockGetWorkspace.mockResolvedValue({ id: 'ws-1', slug: 'lobehub' });
    mockList.mockResolvedValue({
      data: [{ id: 'task_1', identifier: 'T-1031', name: 'Weekly digest', status: 'backlog' }],
    });

    const program = new Command();
    program.exitOverride();
    registerTaskCommand(program);
    await program.parseAsync(['node', 'test', 'task', 'list', '--json']);

    expect(JSON.parse(String(consoleSpy.mock.calls.at(-1)?.[0]))).toEqual([
      {
        id: 'task_1',
        identifier: 'T-1031',
        name: 'Weekly digest',
        status: 'backlog',
        url: 'https://app.example.com/lobehub/task/T-1031/weekly-digest',
      },
    ]);
  });

  it('still lists tasks when the workspace lookup behind the link fails', async () => {
    mockResolveWorkspaceId.mockReturnValue('ws-1');
    mockGetWorkspace.mockRejectedValue(new Error('forbidden'));
    mockList.mockResolvedValue({ data: [{ id: 'task_1', identifier: 'T-1', name: 'A' }] });

    const program = new Command();
    program.exitOverride();
    registerTaskCommand(program);
    await program.parseAsync(['node', 'test', 'task', 'list', '--json']);

    expect(JSON.parse(String(consoleSpy.mock.calls.at(-1)?.[0]))).toEqual([
      { id: 'task_1', identifier: 'T-1', name: 'A' },
    ]);
  });
});

describe('task topic list', () => {
  it('links each topic through the agent that owns it', async () => {
    const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    mockResolveWorkspaceId.mockReturnValue(undefined);
    mockGetTrpcClient.mockResolvedValue({
      task: {
        getTopics: {
          query: vi.fn().mockResolvedValue({ data: [{ agentId: 'agt_1', id: 'tpc_1', seq: 1 }] }),
        },
      },
    });

    const program = new Command();
    program.exitOverride();
    registerTaskCommand(program);
    await program.parseAsync(['node', 'test', 'task', 'topic', 'list', 'T-1', '--json']);

    expect(JSON.parse(String(consoleSpy.mock.calls.at(-1)?.[0]))).toEqual([
      { agentId: 'agt_1', id: 'tpc_1', seq: 1, url: 'https://app.example.com/agent/agt_1/tpc_1' },
    ]);
    consoleSpy.mockRestore();
  });
});