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.

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

import { INBOX_SESSION_ID } from '@/const/session';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { AgentService } from '@/server/services/agent';
import type * as AgentReferenceModule from '@/server/services/agent/resolveReference';
import {
  InboxNotProvisionedError,
  resolveAgentReference,
} from '@/server/services/agent/resolveReference';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
import {
  assertCanEditResource,
  assertCanPerformResourceAction,
  canPerformResourceAction,
  getResourceMeta,
} from '@/server/services/resourcePermission';
import {
  hasWorkspaceScopedPermission,
  isWorkspacePrimaryOwner,
} from '@/server/services/workspacePermission';
import { KnowledgeType } from '@/types/knowledgeBase';

import { agentRouter } from '../agent';

vi.mock('@/server/services/agent/resolveReference', async (importOriginal) => ({
  ...(await importOriginal<typeof AgentReferenceModule>()),
  resolveAgentReference: vi.fn(),
}));

vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
vi.mock('../_helpers/workspaceAgentGuard', () => ({
  getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),
}));

const publishResourceEventMock = vi.mocked(publishResourceEvent);

vi.mock('@/database/models/user', () => ({
  UserModel: {
    findById: vi.fn(),
  },
}));

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

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

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

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

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

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

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

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

vi.mock('@/server/services/agent', () => ({
  AgentService: vi.fn(),
}));

vi.mock('@/server/services/workspacePermission', () => ({
  getWorkspaceScopedPermissionMatches: vi.fn(),
  hasWorkspaceScopedPermission: vi.fn(),
  isWorkspacePrimaryOwner: vi.fn(),
}));

// The serverDatabase middleware replaces ctx.serverDB with this. The chain is
// awaitable-empty so the restricted-KB lookups resolve to "no restrictions".
vi.mock('@/database/core/db-adaptor', () => ({
  getServerDB: vi.fn(function () {
    return {
      select: vi.fn(function () {
        return {
          from: vi.fn(function () {
            const whereResult = () => Promise.resolve([]);
            return {
              innerJoin: vi.fn(function () {
                return { where: vi.fn(whereResult) };
              }),
              where: vi.fn(whereResult),
            };
          }),
        };
      }),
    };
  }),
}));

vi.mock('@/server/services/resourcePermission', () => ({
  assertCanEditResource: vi.fn(),
  assertCanPerformResourceAction: vi.fn(),
  buildResourcePermissionState: vi.fn(function (params: any) {
    return {
      ...params,
      generalAccess: params.accessLevel === 'edit' ? 'editor' : 'viewer',
    };
  }),
  canPerformResourceAction: vi.fn(),
  getResourceMeta: vi.fn(),
  // `resourceConfigGuard` classifies collaborative builtins to exempt them from the
  // parent-group cap; without this export the guard throws before any assertion.
  isCollaborativeBuiltinAgent: vi.fn(function () {
    return false;
  }),
}));

describe('agentRouter', () => {
  const userId = 'testUserId';
  let mockCtx: any;
  let agentModelMock: any;
  let taskModelMock: any;
  let chatGroupModelMock: any;
  let sessionModelMock: any;
  let fileModelMock: any;
  let knowledgeBaseModelMock: any;
  let agentServiceMock: any;
  let resourcePermissionModelMock: any;
  let workspaceUserSettingsModelMock: any;

  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(resolveAgentReference).mockImplementation(async (id) => {
      if (id === INBOX_SESSION_ID)
        throw new TRPCError({ cause: new InboxNotProvisionedError(), code: 'NOT_FOUND' });
      return { agentId: id, sessionId: null };
    });
    vi.mocked(assertCanPerformResourceAction).mockResolvedValue();
    vi.mocked(isWorkspacePrimaryOwner).mockResolvedValue(false);
    vi.mocked(getResourceMeta).mockResolvedValue({
      userId: 'creator-1',
      visibility: 'public',
      workspaceId: 'ws-1',
    });
    resourcePermissionModelMock = {
      getAccessLevel: vi.fn().mockResolvedValue(undefined),
      getEffectiveAccessLevel: vi.fn().mockResolvedValue('use'),
      removeAll: vi.fn(),
      setAccessLevel: vi.fn(),
    };
    vi.mocked(ResourcePermissionModel).mockImplementation(function () {
      return resourcePermissionModelMock;
    });
    workspaceUserSettingsModelMock = {
      getPreference: vi.fn().mockResolvedValue({}),
      updatePreference: vi.fn(),
    };
    vi.mocked(WorkspaceUserSettingsModel).mockImplementation(function () {
      return workspaceUserSettingsModelMock;
    });

    agentModelMock = {
      createAgentFiles: vi.fn(),
      createAgentKnowledgeBase: vi.fn(),
      deleteAgentFile: vi.fn(),
      deleteAgentKnowledgeBase: vi.fn(),
      duplicate: vi.fn(),
      existsOwnedById: vi.fn().mockResolvedValue(false),
      findBySessionId: vi.fn(),
      getAgentAssignedKnowledge: vi.fn(),
      getAgentVisibility: vi.fn().mockResolvedValue(null),
      getAgentVisibilityMeta: vi.fn().mockResolvedValue(null),
      publishToWorkspace: vi.fn(),
      resolveIdBySlug: vi.fn().mockResolvedValue(null),
      toggleFile: vi.fn(),
      toggleKnowledgeBase: vi.fn(),
      update: vi.fn(),
    };
    vi.mocked(AgentModel).mockImplementation(function () {
      return agentModelMock;
    });

    taskModelMock = {
      countTasksBlockingAgentDemotion: vi.fn().mockResolvedValue(0),
    };
    vi.mocked(TaskModel).mockImplementation(function () {
      return taskModelMock;
    });

    chatGroupModelMock = {
      countGroupsBlockingAgentDemotion: vi.fn().mockResolvedValue(0),
    };
    vi.mocked(ChatGroupModel).mockImplementation(function () {
      return chatGroupModelMock;
    });

    sessionModelMock = {
      findByIdOrSlug: vi.fn(),
    };
    vi.mocked(SessionModel).mockImplementation(function () {
      return sessionModelMock;
    });

    fileModelMock = {
      query: vi.fn(),
    };
    vi.mocked(FileModel).mockImplementation(function () {
      return fileModelMock;
    });

    knowledgeBaseModelMock = {
      query: vi.fn(),
    };
    vi.mocked(KnowledgeBaseModel).mockImplementation(function () {
      return knowledgeBaseModelMock;
    });

    agentServiceMock = {
      createInbox: vi.fn(),
    };
    vi.mocked(AgentService).mockImplementation(function () {
      return agentServiceMock;
    });

    mockCtx = {
      userId,
      agentModel: agentModelMock,
      agentService: agentServiceMock,
      fileModel: fileModelMock,
      knowledgeBaseModel: knowledgeBaseModelMock,
      sessionModel: sessionModelMock,
    };
  });

  describe('getAgentConfig', () => {
    it('should return default config if user not found when getting inbox config', async () => {
      vi.mocked(UserModel.findById).mockResolvedValue(undefined);
      sessionModelMock.findByIdOrSlug.mockResolvedValue(undefined);

      const caller = agentRouter.createCaller(mockCtx);
      const result = await caller.getAgentConfig({ sessionId: INBOX_SESSION_ID });

      expect(result).toEqual(DEFAULT_AGENT_CONFIG);
    });

    it('provisions the builtin inbox when no legacy inbox exists', async () => {
      const mockUser = { id: userId };
      const mockSession = { id: 'inboxSessionId' };

      vi.mocked(UserModel.findById).mockResolvedValue(mockUser as any);
      sessionModelMock.findByIdOrSlug
        .mockResolvedValueOnce(undefined)
        .mockResolvedValueOnce(mockSession);
      agentServiceMock.getBuiltinAgent = vi.fn().mockResolvedValue(DEFAULT_AGENT_CONFIG);

      const caller = agentRouter.createCaller(mockCtx);
      const result = await caller.getAgentConfig({ sessionId: INBOX_SESSION_ID });

      expect(agentServiceMock.getBuiltinAgent).toHaveBeenCalledWith(INBOX_SESSION_ID);
      expect(agentServiceMock.createInbox).not.toHaveBeenCalled();
      expect(result).toEqual(DEFAULT_AGENT_CONFIG);
    });

    it('should find agent by session id if session exists', async () => {
      const mockSession = { id: 'session1' };
      sessionModelMock.findByIdOrSlug.mockResolvedValue(mockSession);
      agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(DEFAULT_AGENT_CONFIG);

      const caller = agentRouter.createCaller(mockCtx);
      const result = await caller.getAgentConfig({ sessionId: 'session1' });

      expect(resolveAgentReference).toHaveBeenCalledWith(
        'session1',
        expect.anything(),
        userId,
        undefined,
      );
      expect(result).toEqual(DEFAULT_AGENT_CONFIG);
    });
  });

  describe('configuration read guard', () => {
    const fullConfig = {
      avatar: 'avatar.png',
      id: 'agent-1',
      model: 'private-model',
      openingMessage: 'Hello',
      plugins: ['private-tool'],
      systemRole: 'private prompt',
      title: 'Public title',
      userId: 'creator-1',
      visibility: 'public',
      workspaceId: 'ws-1',
    };

    it('returns null from getAgentConfigById for an agent outside the caller scope', async () => {
      // Another member's private agent is filtered out by the scoped lookup.
      vi.mocked(resolveAgentReference).mockRejectedValueOnce(
        new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' }),
      );
      agentServiceMock.getAgentConfigById = vi.fn();

      const caller = agentRouter.createCaller({ ...mockCtx, serverDB: {}, workspaceId: 'ws-1' });

      await expect(caller.getAgentConfigById({ agentId: 'agt_private' })).resolves.toBeNull();
      expect(agentServiceMock.getAgentConfigById).not.toHaveBeenCalled();
    });

    it('redacts getAgentConfigById for a member who can view but not edit', async () => {
      agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(fullConfig);
      vi.mocked(canPerformResourceAction).mockResolvedValueOnce(false).mockResolvedValueOnce(true);

      const caller = agentRouter.createCaller({
        ...mockCtx,
        serverDB: {},
        workspaceId: 'ws-1',
      });
      const result = await caller.getAgentConfigById({ agentId: 'agent-1' });

      expect(result).toEqual({
        avatar: 'avatar.png',
        id: 'agent-1',
        // The model identity is part of the safe profile surface: use-only
        // members see (and under `member` policy, switch) the model in chat.
        model: 'private-model',
        openingMessage: 'Hello',
        title: 'Public title',
        userId: 'creator-1',
        visibility: 'public',
        workspaceId: 'ws-1',
      });
      expect(result).not.toHaveProperty('systemRole');
      expect(result).not.toHaveProperty('plugins');
    });

    it('returns the full config to a member who can edit', async () => {
      agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(fullConfig);
      vi.mocked(canPerformResourceAction).mockResolvedValueOnce(true);

      const caller = agentRouter.createCaller({
        ...mockCtx,
        serverDB: {},
        workspaceId: 'ws-1',
      });

      await expect(caller.getAgentConfigById({ agentId: 'agent-1' })).resolves.toEqual(fullConfig);
    });
  });

  describe('getKnowledgeBasesAndFiles', () => {
    it('should return combined knowledge bases and files', async () => {
      const mockFiles = [
        { id: 'file1', name: 'File 1', fileType: 'text' },
        { id: 'file2', name: 'File 2', fileType: 'pdf' },
      ];

      const mockKnowledgeBases = [
        { id: 'kb1', name: 'KB 1', description: 'desc 1', avatar: 'avatar1' },
        { id: 'kb2', name: 'KB 2', description: 'desc 2', avatar: 'avatar2' },
      ];

      const mockKnowledge = {
        files: [{ id: 'file1', enabled: true }],
        knowledgeBases: [{ id: 'kb1', enabled: true }],
      };

      fileModelMock.query.mockResolvedValue(mockFiles);
      knowledgeBaseModelMock.query.mockResolvedValue(mockKnowledgeBases);
      agentModelMock.getAgentAssignedKnowledge.mockResolvedValue(mockKnowledge);

      const caller = agentRouter.createCaller(mockCtx);
      const result = await caller.getKnowledgeBasesAndFiles({ agentId: 'agent1' });

      expect(result).toEqual([
        {
          enabled: true,
          fileType: 'text',
          id: 'file1',
          name: 'File 1',
          ownerUserId: undefined,
          type: KnowledgeType.File,
          visibility: undefined,
        },
        {
          enabled: false,
          fileType: 'pdf',
          id: 'file2',
          name: 'File 2',
          ownerUserId: undefined,
          type: KnowledgeType.File,
          visibility: undefined,
        },
        {
          avatar: 'avatar1',
          description: 'desc 1',
          enabled: true,
          id: 'kb1',
          memberRestricted: false,
          name: 'KB 1',
          ownerUserId: undefined,
          type: KnowledgeType.KnowledgeBase,
          visibility: undefined,
        },
        {
          avatar: 'avatar2',
          description: 'desc 2',
          enabled: false,
          id: 'kb2',
          memberRestricted: false,
          name: 'KB 2',
          ownerUserId: undefined,
          type: KnowledgeType.KnowledgeBase,
          visibility: undefined,
        },
      ]);
    });

    // Regression: `visibility` is workspace-scoped — buildWorkspaceWhere ignores
    // the column in personal mode while it still defaults to 'public', so
    // forcing the public scope there filtered personal rows by a value that
    // carries no meaning.
    it('sends no visibility scope in personal mode, even for a public agent', async () => {
      agentModelMock.getAgentVisibility.mockResolvedValue('public');
      fileModelMock.query.mockResolvedValue([]);
      knowledgeBaseModelMock.query.mockResolvedValue([]);
      agentModelMock.getAgentAssignedKnowledge.mockResolvedValue({ files: [], knowledgeBases: [] });

      const caller = agentRouter.createCaller(mockCtx);
      await caller.getKnowledgeBasesAndFiles({ agentId: 'agent1', visibility: 'private' });

      expect(fileModelMock.query).toHaveBeenCalledWith(
        expect.objectContaining({ visibility: undefined }),
      );
      expect(knowledgeBaseModelMock.query).toHaveBeenCalledWith(
        expect.objectContaining({ visibility: undefined }),
      );
    });

    it('forces the workspace scope for a public agent inside a workspace', async () => {
      agentModelMock.getAgentVisibility.mockResolvedValue('public');
      fileModelMock.query.mockResolvedValue([]);
      knowledgeBaseModelMock.query.mockResolvedValue([]);
      agentModelMock.getAgentAssignedKnowledge.mockResolvedValue({ files: [], knowledgeBases: [] });

      const caller = agentRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
      await caller.getKnowledgeBasesAndFiles({ agentId: 'agent1', visibility: 'private' });

      expect(fileModelMock.query).toHaveBeenCalledWith(
        expect.objectContaining({ visibility: 'public' }),
      );
    });
  });

  describe('createAgentFiles', () => {
    it('should create agent files', async () => {
      const mockInput = {
        agentId: 'agent1',
        fileIds: ['file1', 'file2'],
        enabled: true,
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.createAgentFiles(mockInput);

      expect(agentModelMock.createAgentFiles).toHaveBeenCalledWith(
        mockInput.agentId,
        mockInput.fileIds,
        mockInput.enabled,
      );
    });
  });

  describe('deleteAgentFile', () => {
    it('should delete agent file', async () => {
      const mockInput = {
        agentId: 'agent1',
        fileId: 'file1',
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.deleteAgentFile(mockInput);

      expect(agentModelMock.deleteAgentFile).toHaveBeenCalledWith(
        mockInput.agentId,
        mockInput.fileId,
      );
    });
  });

  describe('toggleFile', () => {
    it('should toggle file', async () => {
      const mockInput = {
        agentId: 'agent1',
        fileId: 'file1',
        enabled: true,
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.toggleFile(mockInput);

      expect(agentModelMock.toggleFile).toHaveBeenCalledWith(
        mockInput.agentId,
        mockInput.fileId,
        mockInput.enabled,
      );
    });
  });

  describe('createAgentKnowledgeBase', () => {
    it('should create agent knowledge base', async () => {
      const mockInput = {
        agentId: 'agent1',
        knowledgeBaseId: 'kb1',
        enabled: true,
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.createAgentKnowledgeBase(mockInput);

      expect(agentModelMock.createAgentKnowledgeBase).toHaveBeenCalledWith(
        mockInput.agentId,
        mockInput.knowledgeBaseId,
        mockInput.enabled,
      );
    });
  });

  describe('deleteAgentKnowledgeBase', () => {
    it('should delete agent knowledge base', async () => {
      const mockInput = {
        agentId: 'agent1',
        knowledgeBaseId: 'kb1',
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.deleteAgentKnowledgeBase(mockInput);

      expect(agentModelMock.deleteAgentKnowledgeBase).toHaveBeenCalledWith(
        mockInput.agentId,
        mockInput.knowledgeBaseId,
      );
    });
  });

  describe('toggleKnowledgeBase', () => {
    it('should toggle knowledge base', async () => {
      const mockInput = {
        agentId: 'agent1',
        knowledgeBaseId: 'kb1',
        enabled: true,
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.toggleKnowledgeBase(mockInput);

      expect(agentModelMock.toggleKnowledgeBase).toHaveBeenCalledWith(
        mockInput.agentId,
        mockInput.knowledgeBaseId,
        mockInput.enabled,
      );
    });
  });

  describe('updateAgentPinned', () => {
    it('should pin an agent', async () => {
      const mockInput = {
        id: 'agent1',
        pinned: true,
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.updateAgentPinned(mockInput);

      expect(agentModelMock.update).toHaveBeenCalledWith(mockInput.id, { pinned: true });
    });

    it('should unpin an agent', async () => {
      const mockInput = {
        id: 'agent1',
        pinned: false,
      };

      const caller = agentRouter.createCaller(mockCtx);
      await caller.updateAgentPinned(mockInput);

      expect(agentModelMock.update).toHaveBeenCalledWith(mockInput.id, { pinned: false });
    });
  });

  describe('duplicateAgent', () => {
    it('allows a Workspace member to duplicate a public Agent without edit access', async () => {
      agentModelMock.duplicate.mockResolvedValue({ agentId: 'copied-agent' });

      const caller = agentRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
      const result = await caller.duplicateAgent({ agentId: 'public-agent' });

      expect(result).toEqual({ agentId: 'copied-agent' });
      expect(assertCanEditResource).not.toHaveBeenCalled();
      expect(agentModelMock.duplicate).toHaveBeenCalledWith('public-agent', undefined);
      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'copied-agent',
        DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
        userId,
      );
      // Folder placement is shared state, carried by AgentModel.duplicate's
      // `sessionGroupId` copy — no per-member bookkeeping on top.
      expect(workspaceUserSettingsModelMock.updatePreference).not.toHaveBeenCalled();
    });
  });

  describe('publishAgentToWorkspace', () => {
    const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });

    it('writes general access only after the private agent is actually published', async () => {
      agentModelMock.publishToWorkspace.mockResolvedValue({
        id: 'agent-1',
        visibility: 'public',
      });

      const caller = agentRouter.createCaller(wsCtx());
      await caller.publishAgentToWorkspace({ accessLevel: 'view', id: 'agent-1' });

      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'agent-1',
        'view',
        userId,
      );
    });

    it('keeps a level the creator set while the agent was still private', async () => {
      agentModelMock.publishToWorkspace.mockResolvedValue({
        id: 'agent-1',
        visibility: 'public',
      });
      resourcePermissionModelMock.getAccessLevel.mockResolvedValue('edit');

      const caller = agentRouter.createCaller(wsCtx());
      await caller.publishAgentToWorkspace({ id: 'agent-1' });

      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'agent-1',
        'edit',
        userId,
      );
    });

    it('falls back to the default when nothing was configured before publishing', async () => {
      agentModelMock.publishToWorkspace.mockResolvedValue({
        id: 'agent-1',
        visibility: 'public',
      });

      const caller = agentRouter.createCaller(wsCtx());
      await caller.publishAgentToWorkspace({ id: 'agent-1' });

      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'agent-1',
        DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
        userId,
      );
    });

    it('does not write general access when the guarded publish updates no row', async () => {
      agentModelMock.publishToWorkspace.mockRejectedValue(
        new Error('Agent not found, already published, or access denied'),
      );

      const caller = agentRouter.createCaller(wsCtx());

      await expect(caller.publishAgentToWorkspace({ id: 'agent-1' })).rejects.toThrow(
        'Agent not found, already published, or access denied',
      );
      expect(resourcePermissionModelMock.setAccessLevel).not.toHaveBeenCalled();
    });
  });

  describe('setAgentVisibility', () => {
    const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });

    beforeEach(() => {
      agentModelMock.getAgentVisibilityMeta = vi.fn().mockResolvedValue({
        slug: null,
        userId,
        visibility: 'public',
      });
      agentModelMock.setVisibility = vi.fn().mockResolvedValue({ id: 'agent-1' });
    });

    it('rejects demotion while workspace tasks still depend on the agent', async () => {
      taskModelMock.countTasksBlockingAgentDemotion.mockResolvedValue(2);

      const caller = agentRouter.createCaller(wsCtx());

      await expect(
        caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' }),
      ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
      // Compared against the agent owner (meta.userId), not just the caller.
      expect(taskModelMock.countTasksBlockingAgentDemotion).toHaveBeenCalledWith('agent-1', userId);
      expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
    });

    it('allows demotion when no task depends on the agent', async () => {
      taskModelMock.countTasksBlockingAgentDemotion.mockResolvedValue(0);

      const caller = agentRouter.createCaller(wsCtx());
      const result = await caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' });

      expect(result).toEqual({
        accessLevel: 'edit',
        canManage: true,
        creatorId: userId,
        generalAccess: 'editor',
        visibility: 'private',
      });
      expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'private');
    });

    it('rejects demotion while the agent supervises group chats visible to others ', async () => {
      chatGroupModelMock.countGroupsBlockingAgentDemotion.mockResolvedValue(1);

      const caller = agentRouter.createCaller(wsCtx());

      await expect(
        caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' }),
      ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
      // Compared against the agent owner (meta.userId), not just the caller.
      expect(chatGroupModelMock.countGroupsBlockingAgentDemotion).toHaveBeenCalledWith(
        'agent-1',
        userId,
      );
      expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
    });

    it('rejects demotion of another member agent even for a workspace owner ', async () => {
      agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
        slug: null,
        userId: 'other-member',
        visibility: 'public',
      });
      vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
        new TRPCError({ code: 'FORBIDDEN' }),
      );

      const caller = agentRouter.createCaller(wsCtx());

      await expect(
        caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' }),
      ).rejects.toMatchObject({ code: 'FORBIDDEN' });
      // Creator-only: rejected before the owner-permission lookup even runs.
      expect(hasWorkspaceScopedPermission).not.toHaveBeenCalled();
      expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
    });

    it('rejects promotion when resource permission denies access to another member agent', async () => {
      agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
        slug: null,
        userId: 'other-member',
        visibility: 'private',
      });
      vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
        new TRPCError({ code: 'FORBIDDEN' }),
      );

      const caller = agentRouter.createCaller(wsCtx());
      await expect(
        caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' }),
      ).rejects.toMatchObject({ code: 'FORBIDDEN' });
      expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
    });

    it('does not run the public-task guard on promotion', async () => {
      agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
        slug: null,
        userId,
        visibility: 'private',
      });

      const caller = agentRouter.createCaller(wsCtx());
      await caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' });

      expect(taskModelMock.countTasksBlockingAgentDemotion).not.toHaveBeenCalled();
      expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'agent-1',
        DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
        userId,
      );
    });

    it('keeps a pre-publish level when promoting through setAgentVisibility', async () => {
      agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
        slug: null,
        userId,
        visibility: 'private',
      });
      resourcePermissionModelMock.getAccessLevel.mockResolvedValue('edit');

      const caller = agentRouter.createCaller(wsCtx());
      await caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' });

      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'agent-1',
        'edit',
        userId,
      );
    });

    it('stores explicit view access when publishing an agent', async () => {
      agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
        slug: null,
        userId,
        visibility: 'private',
      });

      const caller = agentRouter.createCaller(wsCtx());
      await caller.setAgentVisibility({
        accessLevel: 'view',
        id: 'agent-1',
        visibility: 'public',
      });

      expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
      expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
        'agent',
        'agent-1',
        'view',
        userId,
      );
    });
  });

  describe('edit lock', () => {
    const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });

    describe('updateAgentConfig write guard', () => {
      it('accepts explicit device replacement ids outside the persisted config', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ success: true });
        const value = {
          agencyConfig: { workingDirByDevice: { 'device-a': { path: '/new-project' } } },
        };
        const result = await agentRouter.createCaller(mockCtx).updateAgentConfig({
          agentId: 'agent-1',
          replaceWorkingDirDeviceIds: ['device-a'],
          value,
        });
        expect(result).toEqual({ success: true });
        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', value, [
          'device-a',
        ]);
      });

      it('rejects the update when general access is use-only for the caller', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        const { TRPCError } = await import('@trpc/server');
        vi.mocked(assertCanEditResource).mockRejectedValueOnce(
          new TRPCError({
            code: 'FORBIDDEN',
            message: 'This resource is use-only for workspace members',
          }),
        );

        const caller = agentRouter.createCaller(wsCtx());

        await expect(
          caller.updateAgentConfig({ agentId: 'agent-1', value: { systemRole: 'x' } }),
        ).rejects.toMatchObject({ code: 'FORBIDDEN' });
        expect(assertCanEditResource).toHaveBeenCalledWith(
          expect.objectContaining({
            resourceId: 'agent-1',
            resourceType: 'agent',
            workspaceId: 'ws-1',
          }),
        );
        expect(agentServiceMock.updateAgentConfig).not.toHaveBeenCalled();
      });

      it('rejects the update when another member holds the lock', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue('other-user');

        const caller = agentRouter.createCaller(wsCtx());

        await expect(
          caller.updateAgentConfig({ agentId: 'agent-1', value: { systemRole: 'x' } }),
        ).rejects.toMatchObject({ code: 'CONFLICT' });
        expect(agentServiceMock.updateAgentConfig).not.toHaveBeenCalled();
      });

      it.each(['executionTargetSelectionPolicy', 'modelSelectionPolicy'] as const)(
        'strips %s from workspace admin updates',
        async (policyKey) => {
          agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
          vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);

          const caller = agentRouter.createCaller(wsCtx());
          await caller.updateAgentConfig({
            agentId: 'agent-1',
            value: { agencyConfig: { boundDeviceId: 'device-1', [policyKey]: 'fixed' } },
          });

          expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
            'agent-1',
            {
              agencyConfig: { boundDeviceId: 'device-1' },
            },
            undefined,
          );
        },
      );

      it('drops a team pin even when the policy strip rebuilds the patch', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);

        await agentRouter.createCaller(wsCtx()).updateAgentConfig({
          agentId: 'agent-1',
          value: {
            agencyConfig: { boundDeviceId: 'device-1', modelSelectionPolicy: 'fixed' },
            pinned: true,
          },
        });

        // `pinned` is the owner/admin team pin; only `updateAgentPinned` writes it.
        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
          'agent-1',
          { agencyConfig: { boundDeviceId: 'device-1' } },
          undefined,
        );
      });

      it('strips fully merged stale policies before a collaborator update', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);

        const caller = agentRouter.createCaller(wsCtx());
        await caller.updateAgentConfig({
          agentId: 'agent-1',
          value: {
            agencyConfig: {
              boundDeviceId: 'device-1',
              executionTargetSelectionPolicy: 'member',
              modelSelectionPolicy: 'member',
            },
          },
        });

        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
          'agent-1',
          {
            agencyConfig: { boundDeviceId: 'device-1' },
          },
          undefined,
        );
      });

      it('preserves policy updates from the agent creator', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        agentModelMock.existsOwnedById.mockResolvedValueOnce(true);
        vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);

        const value = { agencyConfig: { modelSelectionPolicy: 'fixed' as const } };
        const caller = agentRouter.createCaller(wsCtx());
        await caller.updateAgentConfig({ agentId: 'agent-1', value });

        expect(isWorkspacePrimaryOwner).not.toHaveBeenCalled();
        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
          'agent-1',
          value,
          undefined,
        );
      });

      it('preserves policy updates from the workspace primary owner', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        vi.mocked(isWorkspacePrimaryOwner).mockResolvedValueOnce(true);
        vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);

        const value = { agencyConfig: { executionTargetSelectionPolicy: 'fixed' as const } };
        const caller = agentRouter.createCaller(wsCtx());
        await caller.updateAgentConfig({ agentId: 'agent-1', value });

        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
          'agent-1',
          value,
          undefined,
        );
      });

      it('allows the update when no other member holds the lock', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
          new TRPCError({ code: 'FORBIDDEN', message: 'Unexpected manage check' }),
        );
        vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);

        const caller = agentRouter.createCaller(wsCtx());
        await caller.updateAgentConfig({ agentId: 'agent-1', value: { systemRole: 'x' } });

        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
          'agent-1',
          {
            systemRole: 'x',
          },
          undefined,
        );
      });

      it('does not check the lock for personal (non-workspace) agents', async () => {
        agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
        const guardSpy = vi.spyOn(EditLockService.prototype, 'getBlockingHolder');

        const caller = agentRouter.createCaller(mockCtx);
        await caller.updateAgentConfig({ agentId: 'agent-1', value: { systemRole: 'x' } });

        expect(guardSpy).not.toHaveBeenCalled();
        expect(agentServiceMock.updateAgentConfig).toHaveBeenCalled();
      });
    });

    describe('acquireAgentLock', () => {
      it('returns unlocked without touching the lock service for personal agents', async () => {
        const acquireSpy = vi.spyOn(EditLockService.prototype, 'acquire');

        const caller = agentRouter.createCaller(mockCtx);
        const result = await caller.acquireAgentLock({ agentId: 'agent-1' });

        expect(result).toEqual({ expiresAt: null, holderId: null, lockedByOther: false });
        expect(acquireSpy).not.toHaveBeenCalled();
      });

      it('broadcasts lock.changed on a holder edge (first claim)', async () => {
        vi.spyOn(EditLockService.prototype, 'getActiveHolder').mockResolvedValue(undefined);
        vi.spyOn(EditLockService.prototype, 'acquire').mockResolvedValue({
          expiresAt: new Date(),
          holderId: userId,
          lockedByOther: false,
          ownerId: null,
        });

        const caller = agentRouter.createCaller(wsCtx());
        await caller.acquireAgentLock({ agentId: 'agent-1' });

        expect(publishResourceEventMock).toHaveBeenCalledWith(
          { id: 'agent-1', type: 'agent' },
          expect.objectContaining({ data: { holderId: userId }, type: 'lock.changed' }),
        );
      });

      it('does NOT broadcast on a steady-state heartbeat (same holder)', async () => {
        vi.spyOn(EditLockService.prototype, 'getActiveHolder').mockResolvedValue(userId);
        vi.spyOn(EditLockService.prototype, 'acquire').mockResolvedValue({
          expiresAt: new Date(),
          holderId: userId,
          lockedByOther: false,
          ownerId: null,
        });

        const caller = agentRouter.createCaller(wsCtx());
        await caller.acquireAgentLock({ agentId: 'agent-1' });

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

    describe('getAgentLock', () => {
      it('reports another member as the holder', async () => {
        vi.spyOn(EditLockService.prototype, 'getActiveHolder').mockResolvedValue('other-user');

        const caller = agentRouter.createCaller(wsCtx());
        const result = await caller.getAgentLock({ agentId: 'agent-1' });

        expect(result).toEqual({ expiresAt: null, holderId: 'other-user', lockedByOther: true });
      });
    });

    describe('releaseAgentLock', () => {
      it('broadcasts unlocked only when it actually freed the lock', async () => {
        vi.spyOn(EditLockService.prototype, 'release').mockResolvedValue(true);

        const caller = agentRouter.createCaller(wsCtx());
        await caller.releaseAgentLock({ agentId: 'agent-1' });

        expect(publishResourceEventMock).toHaveBeenCalledWith(
          { id: 'agent-1', type: 'agent' },
          expect.objectContaining({ data: { holderId: null }, type: 'lock.changed' }),
        );
      });

      it('does NOT broadcast when the lease expired / was taken over', async () => {
        vi.spyOn(EditLockService.prototype, 'release').mockResolvedValue(false);

        const caller = agentRouter.createCaller(wsCtx());
        await caller.releaseAgentLock({ agentId: 'agent-1' });

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

  describe('resolveAgentRoute (released-client compatibility)', () => {
    it('treats an id-shaped param as an own agent without touching the database', async () => {
      const caller = agentRouter.createCaller(mockCtx);
      const result = await caller.resolveAgentRoute({ slugOrId: 'agt_abc123' });

      expect(result).toEqual({ agentId: 'agt_abc123', kind: 'own' });
      expect(agentModelMock.resolveIdBySlug).not.toHaveBeenCalled();
    });

    it('resolves an own agent slug to its id', async () => {
      agentModelMock.resolveIdBySlug.mockResolvedValue('agt_from_slug');

      const caller = agentRouter.createCaller(mockCtx);
      const result = await caller.resolveAgentRoute({ slugOrId: 'my-bot' });

      expect(result).toEqual({ agentId: 'agt_from_slug', kind: 'own' });
    });

    // The lookup is ownership-scoped, so a stranger's slug is indistinguishable
    // from a missing one and this resolver cannot become a slug oracle.
    it('reports not found when no agent of the caller claims the slug', async () => {
      agentModelMock.resolveIdBySlug.mockResolvedValue(null);

      const caller = agentRouter.createCaller(mockCtx);

      expect(await caller.resolveAgentRoute({ slugOrId: 'nope' })).toEqual({ kind: 'notFound' });
    });
  });
});