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.

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

import { ChannelService } from './ChannelService';

const {
  agentEnvironment,
  create,
  getAgent,
  findDevice,
  notify,
  querySystemInfo,
  statPath,
  update,
  wake,
} = vi.hoisted(() => ({
  agentEnvironment: vi.fn(),
  create: vi.fn(),
  findDevice: vi.fn(),
  getAgent: vi.fn(),
  notify: vi.fn(),
  querySystemInfo: vi.fn(),
  statPath: vi.fn(),
  update: vi.fn(),
  wake: vi.fn(),
}));
vi.mock('@/database/repositories/channel', async (original) => ({
  ...(await original<object>()),
  ChannelRepository: class {
    agentEnvironment = agentEnvironment;
    create = create;
    updateAgentEnvironment = update;
  },
}));
vi.mock('@/database/models/device', () => ({
  DeviceModel: class {
    findPersonalByDeviceId = findDevice;
  },
}));
vi.mock('@/server/services/agent', () => ({
  AgentService: class {
    getAgentConfigById = getAgent;
  },
}));
vi.mock('@/server/services/deviceGateway', () => ({
  deviceGateway: { queryDeviceSystemInfo: querySystemInfo, statPath },
}));
vi.mock('@/server/services/file', () => ({ FileService: class {} }));
vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
vi.mock('./notify', () => ({ notifyChannel: notify }));
vi.mock('./deviceGrantCard', () => ({
  announceDeviceGrants: vi.fn(),
  refreshDeviceGrantCard: vi.fn(),
}));
vi.mock('./queue', () => ({ wakeChannel: wake }));

describe('changing an Agent member’s channel environment', () => {
  beforeEach(() => {
    vi.resetAllMocks();
    agentEnvironment.mockResolvedValue({
      agentId: 'agent-1',
      deviceId: 'mac',
      workingDirectory: '/a',
    });
    getAgent.mockResolvedValue({ agencyConfig: { heterogeneousProvider: { type: 'codex' } } });
    findDevice.mockResolvedValue({ deviceId: 'mac', platform: 'darwin', userId: 'owner' });
    statPath.mockResolvedValue({ canonicalPath: '/real/b', isDirectory: true });
    update.mockResolvedValue({ id: 'member-1' });
  });
  const service = () => new ChannelService({} as never, 'owner');

  describe.each(['create', 'update'] as const)('%s directory validation', (action) => {
    it.each([
      {
        message: 'Could not reach the device to verify the working directory',
        name: 'unreachable device',
        result: undefined,
      },
      {
        message: 'The working directory does not exist or is not a directory',
        name: 'missing directory',
        result: { exists: false, isDirectory: false },
      },
      {
        message: 'The working directory does not exist or is not a directory',
        name: 'file instead of a directory',
        result: { exists: true, isDirectory: false },
      },
      {
        message: 'The device connector must be upgraded to verify the working directory',
        name: 'legacy connector with an existing directory',
        result: { exists: true, isDirectory: true, repoType: 'github' },
      },
    ])('reports $name without saving the environment', async ({ message, result }) => {
      statPath.mockResolvedValue(result);
      const input = { agentId: 'agent-1', deviceId: 'mac', workingDirectory: '/b' };

      const save =
        action === 'create'
          ? service().create({ agents: [input], title: 'c' })
          : service().updateAgentEnvironment('channel', 'member-1', input);

      await expect(save).rejects.toMatchObject({ code: 'BAD_REQUEST', message });
      expect(create).not.toHaveBeenCalled();
      expect(update).not.toHaveBeenCalled();
      expect(wake).not.toHaveBeenCalled();
      expect(notify).not.toHaveBeenCalled();
    });
  });

  it('validates the new directory on the device and stores its canonical path', async () => {
    await service().updateAgentEnvironment('channel', 'member-1', {
      deviceId: 'mac',
      workingDirectory: '/b',
    });

    expect(getAgent).toHaveBeenCalledWith('agent-1');
    expect(update).toHaveBeenCalledWith('channel', 'member-1', {
      deviceId: 'mac',
      deviceOwnerId: 'owner',
      workingDirectory: '/real/b',
    });
    expect(wake).toHaveBeenCalledWith('channel');
    expect(notify).toHaveBeenCalledWith(expect.anything(), 'channel');
  });

  // A Channel binds no device by default, so clearing one returns a coding Agent to its own
  // settings instead of being refused.
  it("clears a coding Agent's device so it runs where its own settings say", async () => {
    await expect(
      service().updateAgentEnvironment('channel', 'member-1', {}),
    ).resolves.toBeDefined();

    expect(update).toHaveBeenCalledWith('channel', 'member-1', {});
    expect(wake).toHaveBeenCalledWith('channel');
    expect(notify).toHaveBeenCalledWith(expect.anything(), 'channel');
  });

  it.each(['hermes', 'openclaw'])('refuses a device for a remote %s Agent', async (type) => {
    getAgent.mockResolvedValue({ agencyConfig: { heterogeneousProvider: { type } } });
    await expect(
      service().updateAgentEnvironment('channel', 'member-1', { deviceId: 'mac' }),
    ).rejects.toMatchObject({
      code: 'BAD_REQUEST',
      message: 'A remote Agent runs on its own host, not a device',
    });

    expect(findDevice).not.toHaveBeenCalled();
    expect(update).not.toHaveBeenCalled();
  });

  it('seats a remote Agent with no device', async () => {
    getAgent.mockResolvedValue({ agencyConfig: { heterogeneousProvider: { type: 'hermes' } } });
    await service().updateAgentEnvironment('channel', 'member-1', {});

    expect(update).toHaveBeenCalledWith('channel', 'member-1', {});
  });

  it('still refuses a directory without a device', async () => {
    await expect(
      service().updateAgentEnvironment('channel', 'member-1', { workingDirectory: '/repo' }),
    ).rejects.toMatchObject({ code: 'BAD_REQUEST' });

    expect(update).not.toHaveBeenCalled();
  });

  it('creates a member in the device home folder when the Agent has no directory there', async () => {
    querySystemInfo.mockResolvedValue({ homePath: '/Users/me' });
    statPath.mockResolvedValue({ canonicalPath: '/Users/me', isDirectory: true });
    create.mockResolvedValue({
      channel: { id: 'chn_1', metadata: null, projectId: null, title: 'c' },
    });

    await service().create({ agents: [{ agentId: 'agent-1', deviceId: 'mac' }], title: 'c' });

    expect(querySystemInfo).toHaveBeenCalledWith('owner', 'mac', undefined);
    expect(statPath).toHaveBeenCalledWith(expect.objectContaining({ path: '/Users/me' }));
    expect(create).toHaveBeenCalledWith({
      agents: [
        {
          agentId: 'agent-1',
          config: { deviceId: 'mac', deviceOwnerId: 'owner', workingDirectory: '/Users/me' },
        },
      ],
      projectId: undefined,
      title: 'c',
      userIds: [],
    });
  });

  it('still asks for a directory when the device cannot report its home folder', async () => {
    querySystemInfo.mockResolvedValue(undefined);

    await expect(
      service().create({ agents: [{ agentId: 'agent-1', deviceId: 'mac' }], title: 'c' }),
    ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
    expect(create).not.toHaveBeenCalled();
  });
});