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.

11.6 KB
Raw Blame
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { ChannelCoordinator } from './ChannelCoordinator';

const { executions, executeToolCall, interruptTask } = vi.hoisted(() => ({
  interruptTask: vi.fn().mockResolvedValue({ success: true }),
  executions: {
    input: vi.fn(),
    deliverAnswerToAsker: vi.fn(),
    fail: vi.fn(),
    deliverReplyMentions: vi
      .fn()
      .mockResolvedValue({ mentions: [], woke: false, workspaceId: null }),
    publish: vi.fn(),
    releaseWriter: vi.fn(),
    retireReservation: vi.fn().mockResolvedValue(false),
    revokeExpiredLease: vi.fn(),
  },
  executeToolCall: vi.fn(),
}));
const { findTopic, generateTopicTitle, updateTopic } = vi.hoisted(() => ({
  findTopic: vi.fn(),
  generateTopicTitle: vi.fn(),
  updateTopic: vi.fn(),
}));
vi.mock('@/database/models/topic', () => ({
  TopicModel: class {
    findById = findTopic;
    update = updateTopic;
  },
}));
vi.mock('@/server/services/systemAgent', () => ({
  SystemAgentService: class {
    generateTopicTitle = generateTopicTitle;
  },
}));
vi.mock('@/database/repositories/channel', () => ({
  ChannelExecutionRepository: class {
    constructor() {
      return executions;
    }
  },
}));
vi.mock('@/server/services/aiAgent', () => ({
  AiAgentService: class {
    interruptTask = interruptTask;
  },
}));
vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { executeToolCall } }));
vi.mock('@/server/globalConfig', () => ({ getServerDefaultAgentConfig: vi.fn() }));
vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
  getScopedOnlineDevices: vi.fn(),
}));
vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: vi.fn() }));
vi.mock('./ChannelRoutingService', () => ({ ChannelRoutingService: vi.fn() }));
vi.mock('./attachments', () => ({ resolveChannelAttachments: vi.fn() }));
vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
vi.mock('./queue', () => ({ registerLocalChannelAdvance: vi.fn(), wakeChannel: vi.fn() }));
const { reportChannelReplyFailure } = vi.hoisted(() => ({
  reportChannelReplyFailure: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('./replyError', () => ({ reportChannelReplyFailure }));

describe('Channel completion physical writer confirmation', () => {
  beforeEach(() => vi.clearAllMocks());

  const coordinator = (
    publicationRevoked = false,
    runtime = 'codex',
    leaseOwner: string | null = null,
    status = 'done',
    topicId: string | null = null,
    deviceId: string | null = 'device',
  ) => {
    const job = {
      channelId: 'channel',
      draft: 'Final reply',
      id: 'job',
      leaseOwner,
      manifest: {},
      operationId: 'op',
      publicationRevoked,
      topicId,
      writerHeld: true,
    };
    const operation = { id: 'op', status, userId: 'user', workspaceId: null };
    const rows = [
      {
        ...job,
        job,
        operation,
        config: deviceId ? { runtime, deviceId, deviceOwnerId: 'owner' } : { runtime },
      },
    ];
    const query = Object.assign(Promise.resolve(rows), {
      from: vi.fn(),
      innerJoin: vi.fn(),
      leftJoin: vi.fn(),
      where: vi.fn(),
      limit: vi.fn(),
    });
    for (const method of ['from', 'innerJoin', 'leftJoin', 'where', 'limit'] as const)
      query[method].mockReturnValue(query);
    return new ChannelCoordinator({ select: () => query } as never);
  };

  it.each([false, true])(
    'keeps the directory held without physical confirmation (revoked: %s)',
    async (revoked) => {
      executeToolCall.mockResolvedValue({ success: true, state: { exited: false } });
      await coordinator(revoked).complete('channel', 'job', 'op');
      expect(executions.releaseWriter).not.toHaveBeenCalled();
      expect(executeToolCall).toHaveBeenCalled();
      expect(executions.publish).toHaveBeenCalledTimes(revoked ? 0 : 1);
    },
  );

  it.each(['abandoned', 'error', 'interrupted'])(
    'fails a run that ended %s and explains it in the reply slot',
    async (status) => {
      executeToolCall.mockResolvedValue({ success: true, state: { exited: false } });
      await coordinator(false, 'codex', null, status).complete('channel', 'job', 'op');

      expect(executions.fail).toHaveBeenCalledWith('channel', 'job', expect.any(Object));
      expect(reportChannelReplyFailure).toHaveBeenCalledWith(expect.anything(), 'channel', 'job');
      expect(executions.publish).not.toHaveBeenCalled();
    },
  );

  it('names an untitled topic from the request and the published reply', async () => {
    executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
    executions.input.mockResolvedValue([{ content: 'What can you do?' }]);
    findTopic.mockResolvedValue({ title: null });
    generateTopicTitle.mockResolvedValue('Assistant abilities');

    await coordinator(false, 'codex', null, 'done', 'topic').complete('channel', 'job', 'op');

    await vi.waitFor(() =>
      expect(updateTopic).toHaveBeenCalledWith('topic', { title: 'Assistant abilities' }),
    );
    expect(generateTopicTitle).toHaveBeenCalledWith({
      lastAssistantContent: 'Final reply',
      topicId: 'topic',
      userPrompt: 'What can you do?',
    });
  });

  it('keeps the title of a topic that already has one', async () => {
    executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
    findTopic.mockResolvedValue({ title: 'Existing' });

    await coordinator(false, 'codex', null, 'done', 'topic').complete('channel', 'job', 'op');

    await vi.waitFor(() => expect(findTopic).toHaveBeenCalledWith('topic'));
    await Promise.resolve();
    expect(generateTopicTitle).not.toHaveBeenCalled();
    expect(updateTopic).not.toHaveBeenCalled();
  });

  // With no device picked in the Channel the run went through the ordinary pipeline, so its
  // writer used to stay held after the reply and every later request waited as member_busy.
  it('releases an external writer with no Channel device once the ordinary run stops', async () => {
    await coordinator(false, 'codex', null, 'done', null, null).complete('channel', 'job', 'op');
    expect(interruptTask).toHaveBeenCalledWith({ operationId: 'op', topicId: undefined });
    expect(executeToolCall).not.toHaveBeenCalled();
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });

  it('keeps an unbound external writer while its run can neither stop nor has ended', async () => {
    interruptTask.mockResolvedValueOnce({ success: false });
    await coordinator(true, 'codex', null, 'running', null, null).complete('channel', 'job', 'op');
    expect(executions.releaseWriter).not.toHaveBeenCalled();
  });

  // An unbound coding Agent may still have run on a device through its own settings; a failed
  // operation does not prove its CLI exited, so the writer waits for confirmed cancellation.
  it('keeps an unbound external writer while its device cancellation is unconfirmed', async () => {
    interruptTask.mockResolvedValueOnce({ deviceCancellationConfirmed: false, success: false });
    await coordinator(true, 'codex', null, 'error', null, null).complete('channel', 'job', 'op');
    expect(executions.releaseWriter).not.toHaveBeenCalled();
  });

  it('releases an ended unbound external writer that left no device process behind', async () => {
    interruptTask.mockResolvedValueOnce({ success: false });
    await coordinator(true, 'codex', null, 'error', null, null).complete('channel', 'job', 'op');
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });

  it('releases a completed writer only after the device confirms termination', async () => {
    executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
    await coordinator().complete('channel', 'job', 'op');
    expect(executeToolCall).toHaveBeenCalled();
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });

  it.each([false, true])(
    'does not release a Native writer on runtime interruption alone (revoked: %s)',
    async (revoked) => {
      executeToolCall.mockResolvedValue({ success: true, state: { exited: false } });
      await coordinator(revoked, 'native').complete('channel', 'job', 'op');
      expect(executions.releaseWriter).not.toHaveBeenCalled();
    },
  );

  it('releases a Native writer only after its device tools and processes have drained', async () => {
    executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
    await coordinator(true, 'native').complete('channel', 'job', 'op');
    expect(executeToolCall).toHaveBeenCalled();
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });

  // A worker that crashed after starting the run never reached finishDispatch.
  it('revokes an expired dispatch lease, then releases only after confirmed termination', async () => {
    executions.revokeExpiredLease.mockResolvedValue('revoked');
    executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
    await coordinator(false, 'codex', 'crashed-worker').complete('channel', 'job', 'op');
    expect(executions.revokeExpiredLease).toHaveBeenCalledWith('channel', 'job');
    expect(executeToolCall).toHaveBeenCalled();
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });

  it('keeps the writer held after revoking an expired lease without confirmed termination', async () => {
    executions.revokeExpiredLease.mockResolvedValue('revoked');
    executeToolCall.mockResolvedValue({ success: true, state: { exited: false } });
    await coordinator(false, 'native', 'crashed-worker').complete('channel', 'job', 'op');
    expect(executions.releaseWriter).not.toHaveBeenCalled();
  });

  it('does not stop a writer while a live dispatcher still holds its lease', async () => {
    executions.revokeExpiredLease.mockResolvedValue('live');
    await coordinator(false, 'codex', 'live-worker').complete('channel', 'job', 'op');
    expect(executeToolCall).not.toHaveBeenCalled();
    expect(executions.releaseWriter).not.toHaveBeenCalled();
  });

  // A worker passed its lease check and started the operation, then stalled past the lease.
  // A stop revokes the lease; the Desktop finds no process because the late start has not
  // arrived yet. Releasing now would let another writer into the directory before it does.
  it('keeps the writer when a revoked dispatcher may still start the run late', async () => {
    executions.revokeExpiredLease.mockResolvedValue('revoked');
    executeToolCall.mockResolvedValue({
      success: true,
      state: { exited: true, reason: 'not_found' },
    });
    await coordinator(true, 'codex', 'stalled-worker', 'running').stopWriters([
      { channelId: 'channel', id: 'job', operationId: 'op' },
    ]);
    expect(executeToolCall).toHaveBeenCalled();
    expect(executions.releaseWriter).not.toHaveBeenCalled();
  });

  it('releases a revoked dispatch once the device itself reported the run done', async () => {
    executions.revokeExpiredLease.mockResolvedValue('revoked');
    executeToolCall.mockResolvedValue({
      success: true,
      state: { exited: true, reason: 'not_found' },
    });
    await coordinator(false, 'codex', 'crashed-worker').complete('channel', 'job', 'op');
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });

  it('trusts a missing process after the dispatch settled normally', async () => {
    executeToolCall.mockResolvedValue({
      success: true,
      state: { exited: true, reason: 'not_found' },
    });
    await coordinator(true, 'codex', null, 'running').stopWriters([
      { channelId: 'channel', id: 'job', operationId: 'op' },
    ]);
    expect(executions.revokeExpiredLease).not.toHaveBeenCalled();
    expect(executions.releaseWriter).toHaveBeenCalledWith('channel', 'job');
  });
});