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.

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

import { hasServerRuntime } from '..';
import { groupAgentBuilderRuntime } from '../groupAgentBuilder';

const {
  mockAddAgentsToGroup,
  mockBatchCreate,
  mockAssertCanPerformResourceAction,
  mockBuilderInstallPlugin,
  mockBuilderUpdateConfig,
  mockFindById,
  mockGetAccessLevel,
  mockGetAgentConfigById,
  mockGetGroupAgentsWithMeta,
  mockGetResourceConfigAccess,
  mockQueryAgents,
  mockRemoveAgentsFromGroup,
  mockSetAccessLevel,
  mockUpdateAgent,
  mockUpdateGroup,
} = vi.hoisted(() => ({
  mockAddAgentsToGroup: vi.fn(),
  mockBatchCreate: vi.fn(),
  mockAssertCanPerformResourceAction: vi.fn(),
  mockBuilderInstallPlugin: vi.fn(),
  mockBuilderUpdateConfig: vi.fn(),
  mockFindById: vi.fn(),
  mockGetAccessLevel: vi.fn(),
  mockGetAgentConfigById: vi.fn(),
  mockGetGroupAgentsWithMeta: vi.fn(),
  mockGetResourceConfigAccess: vi.fn(),
  mockQueryAgents: vi.fn(),
  mockRemoveAgentsFromGroup: vi.fn(),
  mockSetAccessLevel: vi.fn(),
  mockUpdateAgent: vi.fn(),
  mockUpdateGroup: vi.fn(),
}));

vi.mock('@/database/models/agent', () => ({
  AgentModel: vi.fn(function () {
    return {
      batchCreate: mockBatchCreate,
      getAgentConfigById: mockGetAgentConfigById,
      queryAgents: mockQueryAgents,
      update: mockUpdateAgent,
      updateConfig: vi.fn(),
    };
  }),
}));

vi.mock('@/database/models/chatGroup', () => ({
  ChatGroupModel: vi.fn(function () {
    return {
      addAgentsToGroup: mockAddAgentsToGroup,
      findById: mockFindById,
      getGroupAgentsWithMeta: mockGetGroupAgentsWithMeta,
      removeAgentsFromGroup: mockRemoveAgentsFromGroup,
      update: mockUpdateGroup,
    };
  }),
}));

vi.mock('@/database/models/resourcePermission', () => ({
  ResourcePermissionModel: vi.fn(function () {
    return {
      getAccessLevel: mockGetAccessLevel,
      setAccessLevel: mockSetAccessLevel,
    };
  }),
}));

vi.mock('@/database/repositories/agentGroup', () => ({
  AgentGroupRepository: vi.fn(function () {
    return { createGroupWithSupervisor: vi.fn() };
  }),
}));

vi.mock('@/server/services/agentGroup', () => ({
  AgentGroupService: vi.fn(function () {
    return { normalizeGroupConfig: (config: unknown) => config };
  }),
}));

vi.mock('@/server/services/resourcePermission', () => ({
  assertCanPerformResourceAction: mockAssertCanPerformResourceAction,
}));

vi.mock('@/server/routers/lambda/_helpers/resourceConfigGuard', () => ({
  getResourceConfigAccess: mockGetResourceConfigAccess,
}));

vi.mock('../agentBuilder', () => ({
  agentBuilderRuntime: {
    factory: () => ({
      installPlugin: mockBuilderInstallPlugin,
      updateConfig: mockBuilderUpdateConfig,
    }),
    identifier: 'lobe-agent-builder',
  },
}));

const createRuntime = (workspaceId?: string) =>
  groupAgentBuilderRuntime.factory({
    serverDB: {} as never,
    toolManifestMap: {},
    userId: 'user-1',
    workspaceId,
  });

const groupCtx = { editingGroupId: 'cg_1' } as never;

describe('groupAgentBuilderRuntime', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockFindById.mockResolvedValue({ id: 'cg_1', title: 'Launch Team', visibility: 'public' });
    mockGetGroupAgentsWithMeta.mockResolvedValue([
      { agentId: 'agt_sup', description: null, role: 'supervisor', title: 'Supervisor' },
    ]);
    mockGetResourceConfigAccess.mockResolvedValue('full');
    mockAssertCanPerformResourceAction.mockResolvedValue(undefined);
    mockQueryAgents.mockResolvedValue([]);
  });

  // The bug: gateway mode executes every builtin tool server-side, and a missing
  // registry entry makes `executeBuiltinTool` throw "is not implemented", so no
  // member ever reaches the group.
  it('is registered in the server runtime registry', () => {
    expect(hasServerRuntime('lobe-group-agent-builder')).toBe(true);
  });

  describe('createAgent', () => {
    it('creates a virtual agent and adds it to the edited group', async () => {
      mockBatchCreate.mockResolvedValue([{ id: 'agt_new', visibility: 'public' }]);

      const result = await createRuntime().createAgent(
        {
          systemRole: 'You drive launches.',
          title: 'Product Manager',
          tools: ['lobe-web-browsing'],
        },
        groupCtx,
      );

      expect(mockBatchCreate).toHaveBeenCalledWith([
        expect.objectContaining({
          plugins: ['lobe-web-browsing'],
          title: 'Product Manager',
          virtual: true,
          visibility: 'public',
        }),
      ]);
      expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_1', ['agt_new']);
      expect(result).toMatchObject({
        state: { agentId: 'agt_new', success: true, title: 'Product Manager' },
        success: true,
      });
    });

    it('inherits the group access level for workspace members', async () => {
      mockBatchCreate.mockResolvedValue([{ id: 'agt_new', visibility: 'public' }]);
      mockGetAccessLevel.mockResolvedValue('edit');

      await createRuntime('ws_1').createAgent({ systemRole: 'x', title: 'PM' }, groupCtx);

      expect(mockSetAccessLevel).toHaveBeenCalledWith('agent', 'agt_new', 'edit', 'user-1');
    });

    it('returns a structured error instead of throwing when no group is in context', async () => {
      const result = await createRuntime().createAgent(
        { systemRole: 'x', title: 'PM' },
        {} as never,
      );

      expect(result).toMatchObject({ error: { type: 'NoGroupContext' }, success: false });
      expect(mockBatchCreate).not.toHaveBeenCalled();
    });
  });

  describe('batchCreateAgents', () => {
    it('creates every agent and adds them all to the group in one roster write', async () => {
      mockBatchCreate.mockResolvedValue([
        { id: 'agt_a', visibility: 'public' },
        { id: 'agt_b', visibility: 'public' },
      ]);

      const result = await createRuntime().batchCreateAgents(
        {
          agents: [
            { systemRole: 'a', title: 'Marketing Lead' },
            { systemRole: 'b', title: 'Engineering Lead' },
          ],
        },
        groupCtx,
      );

      expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_1', ['agt_a', 'agt_b']);
      expect(result).toMatchObject({
        state: { failedCount: 0, successCount: 2 },
        success: true,
      });
    });
  });

  describe('searchAgent', () => {
    it('asks the query to exclude the inbox, which can never join a group', async () => {
      // The exclusion lives in the query: filtering the page here let a
      // recently updated inbox spend a `limit` slot and hide an addable agent,
      // so assert the contract instead of re-filtering a page that should no
      // longer carry the inbox in the first place.
      mockQueryAgents.mockResolvedValue([
        { description: null, id: 'agt_writer', isInbox: false, title: 'Writer' },
      ]);

      const result = await createRuntime().searchAgent({ query: '' }, groupCtx);

      expect(mockQueryAgents).toHaveBeenCalledWith({
        includeInbox: false,
        keyword: '',
        limit: 10,
      });
      expect(result.success).toBe(true);
      expect((result.state as any).agents.map((a: { id: string }) => a.id)).toEqual(['agt_writer']);
    });
  });

  describe('removeAgent', () => {
    it('refuses to remove the supervisor', async () => {
      const result = await createRuntime().removeAgent({ agentId: 'agt_sup' }, groupCtx);

      expect(result.success).toBe(false);
      expect(mockRemoveAgentsFromGroup).not.toHaveBeenCalled();
    });

    it('removes a participant', async () => {
      mockGetGroupAgentsWithMeta.mockResolvedValue([
        { agentId: 'agt_sup', role: 'supervisor', title: 'Supervisor' },
        { agentId: 'agt_a', role: 'participant', title: 'Marketing Lead' },
      ]);

      const result = await createRuntime().removeAgent({ agentId: 'agt_a' }, groupCtx);

      expect(mockRemoveAgentsFromGroup).toHaveBeenCalledWith('cg_1', ['agt_a']);
      expect(result).toMatchObject({ state: { agentId: 'agt_a', success: true }, success: true });
    });
  });

  describe('updateAgentPrompt', () => {
    it('rejects an agent that is not a member of the group', async () => {
      const result = await createRuntime().updateAgentPrompt(
        { agentId: 'agt_outsider', prompt: 'hi' },
        groupCtx,
      );

      expect(result).toMatchObject({ error: { type: 'AgentNotFound' }, success: false });
      expect(mockUpdateAgent).not.toHaveBeenCalled();
    });

    it('clears editorData so the profile editor does not revert the write', async () => {
      mockGetAgentConfigById.mockResolvedValue({ systemRole: 'old' });

      const result = await createRuntime().updateAgentPrompt(
        { agentId: 'agt_sup', prompt: 'new prompt' },
        groupCtx,
      );

      expect(mockUpdateAgent).toHaveBeenCalledWith('agt_sup', {
        editorData: null,
        systemRole: 'new prompt',
      });
      expect(result).toMatchObject({
        state: { newPrompt: 'new prompt', previousPrompt: 'old', success: true },
        success: true,
      });
    });
  });

  describe('updateConfig', () => {
    // The delegated `AgentBuilder.updateConfig` write is scoped by visibility
    // alone, so an unchecked caller-supplied id would let a group edit
    // reconfigure any workspace agent the caller can merely see.
    it('rejects a caller-supplied agent that is not on the roster', async () => {
      const result = await createRuntime('ws_1').updateConfig(
        { agentId: 'agt_outsider', model: 'gpt-5' },
        groupCtx,
      );

      expect(result).toMatchObject({ error: { type: 'AgentNotFound' }, success: false });
      expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();
    });

    it('refuses a caller-supplied agent when there is no group in context', async () => {
      const result = await createRuntime('ws_1').updateConfig(
        { agentId: 'agt_sup', model: 'gpt-5' },
        {} as never,
      );

      expect(result).toMatchObject({ success: false });
      expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();
    });

    it('delegates for a roster member, stamping it as the edited agent', async () => {
      await createRuntime('ws_1').updateConfig({ agentId: 'agt_sup', model: 'gpt-5' }, groupCtx);

      expect(mockBuilderUpdateConfig).toHaveBeenCalledWith(
        { model: 'gpt-5' },
        expect.objectContaining({ editingAgentId: 'agt_sup' }),
      );
    });

    it('falls back to the supervisor when no agentId is given', async () => {
      await createRuntime('ws_1').updateConfig({ model: 'gpt-5' }, groupCtx);

      expect(mockBuilderUpdateConfig).toHaveBeenCalledWith(
        { model: 'gpt-5' },
        expect.objectContaining({ editingAgentId: 'agt_sup' }),
      );
    });

    // G-01: group edit + member view must not reconfigure the linked member —
    // the same rule `updateAgentPrompt` and `agent.updateAgentConfig` enforce.
    it('rejects a roster member whose config the caller cannot edit', async () => {
      mockGetGroupAgentsWithMeta.mockResolvedValue([
        { agentId: 'agt_sup', role: 'supervisor' },
        { agentId: 'agt_alice', role: 'participant' },
      ]);
      mockGetResourceConfigAccess.mockImplementation(async (_ctx, _type, id) =>
        id === 'agt_alice' ? 'profile' : 'full',
      );

      const result = await createRuntime('ws_1').updateConfig(
        { agentId: 'agt_alice', model: 'gpt-4o-mini', provider: 'openai' },
        groupCtx,
      );

      expect(mockGetResourceConfigAccess).toHaveBeenCalledWith(
        expect.anything(),
        'agent',
        'agt_alice',
      );
      expect(result).toMatchObject({
        content: 'No permission to access the configuration of agent "agt_alice"',
        error: { type: 'Forbidden' },
        success: false,
      });
      expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();
    });

    // N-1: a group-edit denial reads like every other builder tool instead of
    // escaping as a raw TRPC FORBIDDEN error.
    it('returns a tool failure when the group is not editable', async () => {
      mockAssertCanPerformResourceAction.mockRejectedValue(
        new Error('You do not have permission to edit this resource'),
      );

      const result = await createRuntime('ws_1').updateConfig({ model: 'gpt-5' }, groupCtx);

      expect(result).toEqual({
        content: 'Failed to update agent config: You do not have permission to edit this resource',
        success: false,
      });
      expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();
    });
  });

  describe('installPlugin', () => {
    it('installs onto the supervisor when the caller has full config access', async () => {
      await createRuntime('ws_1').installPlugin(
        { identifier: 'lobe-web-browsing', source: 'official' },
        groupCtx,
      );

      expect(mockBuilderInstallPlugin).toHaveBeenCalledWith(
        { identifier: 'lobe-web-browsing', source: 'official' },
        expect.objectContaining({ editingAgentId: 'agt_sup' }),
      );
    });

    it('rejects when the caller cannot edit the supervisor config', async () => {
      mockGetResourceConfigAccess.mockResolvedValue('profile');

      const result = await createRuntime('ws_1').installPlugin(
        { identifier: 'lobe-web-browsing', source: 'official' },
        groupCtx,
      );

      expect(result).toMatchObject({ error: { type: 'Forbidden' }, success: false });
      expect(mockBuilderInstallPlugin).not.toHaveBeenCalled();
    });

    it('returns a tool failure when the group is not editable', async () => {
      mockAssertCanPerformResourceAction.mockRejectedValue(
        new Error('You do not have permission to edit this resource'),
      );

      const result = await createRuntime('ws_1').installPlugin(
        { identifier: 'lobe-web-browsing', source: 'official' },
        groupCtx,
      );

      expect(result).toEqual({
        content: 'Failed to install plugin: You do not have permission to edit this resource',
        success: false,
      });
      expect(mockBuilderInstallPlugin).not.toHaveBeenCalled();
    });
  });

  describe('updateGroupPrompt', () => {
    it('writes the shared prompt onto the edited group', async () => {
      mockFindById.mockResolvedValue({ content: 'old', id: 'cg_1', visibility: 'public' });

      const result = await createRuntime().updateGroupPrompt(
        { prompt: 'shared context' },
        groupCtx,
      );

      expect(mockUpdateGroup).toHaveBeenCalledWith('cg_1', {
        content: 'shared context',
        editorData: null,
      });
      expect(result).toMatchObject({
        state: { newPrompt: 'shared context', previousPrompt: 'old', success: true },
        success: true,
      });
    });
  });
  // An explicit `groupId` comes straight from the tool arguments, and the model
  // predicates admit any public workspace row. Prompts are edit-level config
  // (`resourceConfigGuard`), so a view/use member must not read them here.
  describe('config access on an explicitly targeted group', () => {
    const explicit = { agentId: 'agt_sup', groupId: 'cg_other' };

    beforeEach(() => {
      mockGetAgentConfigById.mockResolvedValue({ model: 'gpt-x', systemRole: 'secret prompt' });
    });

    it('returns the system prompt only with full config access', async () => {
      const result = await createRuntime('ws_1').getAgentInfo(explicit, groupCtx);

      expect(mockGetResourceConfigAccess).toHaveBeenCalledWith(
        expect.objectContaining({ userId: 'user-1', workspaceId: 'ws_1' }),
        'agent',
        'agt_sup',
      );
      expect(result.state).toMatchObject({ systemRole: 'secret prompt' });
    });

    it('omits the system prompt for view/use access', async () => {
      mockGetResourceConfigAccess.mockImplementation(async (_ctx, type) =>
        type === 'agent' ? 'profile' : 'full',
      );

      const result = await createRuntime('ws_1').getAgentInfo(explicit, groupCtx);

      expect(result.success).toBe(true);
      expect(result.content).not.toContain('secret prompt');
      expect(result.state).toMatchObject({ model: 'gpt-x', title: 'Supervisor' });
      expect((result.state as { systemRole?: string }).systemRole).toBeUndefined();
    });

    it('hides a group the caller has no access to', async () => {
      mockGetResourceConfigAccess.mockResolvedValue('none');

      const result = await createRuntime('ws_1').getAgentInfo(explicit, groupCtx);

      expect(result).toMatchObject({ error: { type: 'GroupNotFound' }, success: false });
      expect(mockGetGroupAgentsWithMeta).not.toHaveBeenCalled();
      expect(mockGetAgentConfigById).not.toHaveBeenCalled();
    });

    it('refuses to read or rewrite a member prompt without full config access', async () => {
      mockGetResourceConfigAccess.mockImplementation(async (_ctx, type) =>
        type === 'agent' ? 'profile' : 'full',
      );

      const result = await createRuntime('ws_1').updateAgentPrompt(
        { ...explicit, prompt: 'overwrite' },
        groupCtx,
      );

      expect(result).toMatchObject({ error: { type: 'Forbidden' }, success: false });
      expect(result.content).not.toContain('secret prompt');
      expect(mockGetAgentConfigById).not.toHaveBeenCalled();
      expect(mockUpdateAgent).not.toHaveBeenCalled();
    });
  });
});