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.0 KB
Raw Blame
// @vitest-environment node
import { TRPCError } from '@trpc/server';
import type { SQL } from 'drizzle-orm';
import { PgDialect } from 'drizzle-orm/pg-core';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { BriefModel } from '@/database/models/brief';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';

import { TaskRunnerService } from './index';
import { runScheduleTick } from './scheduleTick';

const mockSelectTask = vi.fn();
const mockWhereTask = vi.fn((_condition: SQL) => ({
  limit: () => mockSelectTask(),
}));

vi.mock('@/database/server', () => ({
  getServerDB: vi.fn().mockResolvedValue({
    select: () => ({
      from: () => ({
        where: mockWhereTask,
      }),
    }),
  }),
}));

vi.mock('@/database/models/task', () => ({
  TaskModel: vi.fn(),
}));

vi.mock('@/database/models/taskTopic', () => ({
  TaskTopicModel: vi.fn(),
}));

vi.mock('@/database/models/brief', () => ({
  BriefModel: vi.fn(),
}));

vi.mock('./index', () => ({
  TaskRunnerService: vi.fn(),
}));

describe('runScheduleTick', () => {
  const taskId = 'task-1';
  const userId = 'user-1';

  const mockTaskModel = {
    updateStatus: vi.fn(),
  };
  const mockTaskTopicModel = {
    countByTask: vi.fn(),
  };
  const mockBriefModel = {
    hasUnresolvedUrgentByTask: vi.fn().mockResolvedValue(false),
  };
  const mockRunner = {
    runTask: vi.fn(),
  };

  const baseTask = (overrides: Partial<Record<string, unknown>> = {}) => ({
    automationMode: 'schedule',
    config: {},
    context: { scheduler: { scheduleStartedAt: new Date('2026-05-01T00:00:00Z').toISOString() } },
    id: taskId,
    identifier: 'T-1',
    schedulePattern: '*/5 * * * *',
    status: 'scheduled',
    ...overrides,
  });

  beforeEach(() => {
    vi.clearAllMocks();
    mockSelectTask.mockResolvedValue([]);
    mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(false);
    (TaskModel as any).mockImplementation(function () {
      return mockTaskModel;
    });
    (TaskTopicModel as any).mockImplementation(function () {
      return mockTaskTopicModel;
    });
    (BriefModel as any).mockImplementation(function () {
      return mockBriefModel;
    });
    (TaskRunnerService as any).mockImplementation(function () {
      return mockRunner;
    });
  });

  it('skips not-found tasks', async () => {
    mockSelectTask.mockResolvedValue([]);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'not-found' });
    expect(mockRunner.runTask).not.toHaveBeenCalled();
  });

  it('excludes trashed tasks from the queued tick lookup', async () => {
    const outcome = await runScheduleTick(taskId, userId);

    const condition = mockWhereTask.mock.calls[0][0];
    expect(new PgDialect().sqlToQuery(condition).sql).toContain('"tasks"."is_deleted" IS NOT TRUE');
    expect(outcome).toEqual({ ran: false, reason: 'not-found' });
  });

  it('skips when automationMode has been changed away from schedule', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ automationMode: 'heartbeat' })]);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'mode-changed' });
    expect(mockRunner.runTask).not.toHaveBeenCalled();
  });

  it('skips an archived task without running it', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ archivedAt: new Date() })]);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'archived' });
    expect(mockRunner.runTask).not.toHaveBeenCalled();
  });

  it('skips terminal / paused tasks before checking maxExecutions', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ status: 'paused' })]);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'paused' });
    expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();
  });

  it('runs the task when no maxExecutions is configured', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ config: {} })]);
    mockRunner.runTask.mockResolvedValue(undefined);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });
    expect(mockBriefModel.hasUnresolvedUrgentByTask).toHaveBeenCalledWith(taskId, {
      excludeTypes: ['error'],
    });
    expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();
    expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId, trigger: 'schedule' });
  });

  it('runs the task when the run count is still under maxExecutions', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ config: { schedule: { maxExecutions: 10 } } })]);
    mockTaskTopicModel.countByTask.mockResolvedValue(7);
    mockRunner.runTask.mockResolvedValue(undefined);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });
    // Quota counts only scheduled ticks, not ad-hoc manual runs.
    expect(mockTaskTopicModel.countByTask).toHaveBeenCalledWith(taskId, {
      since: new Date('2026-05-01T00:00:00Z'),
      triggers: ['schedule'],
    });
    expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId, trigger: 'schedule' });
    expect(mockTaskModel.updateStatus).not.toHaveBeenCalled();
  });

  it('marks the task completed and skips when the run count has reached maxExecutions', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ config: { schedule: { maxExecutions: 10 } } })]);
    mockTaskTopicModel.countByTask.mockResolvedValue(10);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'max-executions-reached' });
    expect(mockRunner.runTask).not.toHaveBeenCalled();
    expect(mockTaskModel.updateStatus).toHaveBeenCalledWith(taskId, 'completed', {
      completedAt: expect.any(Date),
    });
  });

  it('falls back to running when maxExecutions is set but scheduleStartedAt is missing', async () => {
    // Pre-existing scheduled tasks (created before this PR) won't have a
    // scheduleStartedAt stamp. They should still tick normally; the cap will
    // start enforcing once the user pauses + restarts.
    mockSelectTask.mockResolvedValue([
      baseTask({ config: { schedule: { maxExecutions: 10 } }, context: {} }),
    ]);
    mockRunner.runTask.mockResolvedValue(undefined);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });
    expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();
    expect(mockRunner.runTask).toHaveBeenCalled();
  });

  it('returns in-flight when runTask raises a CONFLICT', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ config: {} })]);
    mockRunner.runTask.mockRejectedValue(new TRPCError({ code: 'CONFLICT', message: 'busy' }));

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'in-flight' });
  });

  it('skips when a human is waiting on an urgent brief', async () => {
    mockSelectTask.mockResolvedValue([baseTask({ config: {} })]);
    mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(true);

    const outcome = await runScheduleTick(taskId, userId);

    expect(outcome).toEqual({ ran: false, reason: 'human-waiting' });
    expect(mockBriefModel.hasUnresolvedUrgentByTask).toHaveBeenCalledWith(taskId, {
      excludeTypes: ['error'],
    });
    expect(mockRunner.runTask).not.toHaveBeenCalled();
  });

  describe('delayed delivery', () => {
    const task = {
      automationMode: 'schedule',
      schedulePattern: '15 9 * * *',
      scheduleTimezone: 'UTC',
      status: 'scheduled',
    };

    it('skips an occurrence the schedule no longer includes', async () => {
      mockSelectTask.mockResolvedValue([task]);

      await expect(
        runScheduleTick(taskId, userId, { occurrence: '2026-09-21T09:17:00.000Z' }),
      ).resolves.toEqual({ ran: false, reason: 'schedule-changed' });
      expect(mockRunner.runTask).not.toHaveBeenCalled();
    });
  });
});