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.

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

import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
import { ConnectorToolModel } from '@/database/models/connectorTool';
import { PluginModel } from '@/database/models/plugin';

import { connectorRouter } from '../connector';

const mocks = vi.hoisted(() => ({
  connectedAccountsDelete: vi.fn(),
  refreshSubscriptions: vi.fn(),
  removeSubscriptions: vi.fn(),
}));

// `vi.mock` is hoisted by vitest's transformer above all imports at runtime,
// so the relative import order doesn't matter functionally — the mocks below
// are still active when the router module is evaluated. They live below the
// imports to satisfy `import-x/first` without disabling the rule.
vi.mock('@/server/services/inboundWebhook/lifecycle', () => ({
  scheduleRefreshByConnector: mocks.refreshSubscriptions,
  removeByConnector: mocks.removeSubscriptions,
}));
vi.mock('@/database/models/connectorLink', () => ({
  ConnectorLinkModel: vi.fn(function () {
    return { listByConnectorIds: async () => [] };
  }),
}));

vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
vi.mock('@/libs/composio', () => ({
  getComposioClient: () => ({
    connectedAccounts: { delete: mocks.connectedAccountsDelete },
  }),
}));
vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
  KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
}));
vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
  const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
  // The real `wsCompatProcedure` validates a Better-Auth session; for unit
  // tests we skip auth and rely on the test ctx already carrying `userId`.
  return {
    requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware(async (opts: any) => opts.next()),
    wsCompatProcedure: mod.trpc.procedure,
  };
});
vi.mock('@/libs/trpc/lambda/middleware', () => ({
  serverDatabase: async (opts: any) =>
    opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
}));

const activeGmailAuthConfig = () => ({
  appSlug: 'GMAIL',
  authConfigId: 'ac-gmail',
  connectedAccountId: 'ca-gmail',
  status: 'ACTIVE',
});

describe('connectorRouter.syncPluginTools — customPlugin guard', () => {
  let connectorModelMock: any;
  let connectorToolModelMock: any;
  let pluginModelMock: any;

  beforeEach(() => {
    vi.clearAllMocks();

    connectorModelMock = {
      create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
      createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
      findManageableByIdentifier: vi.fn().mockResolvedValue(null),
      findScopedByIdentifier: vi.fn().mockResolvedValue(null),
      isComposioAccountPrivateToTeammate: vi.fn().mockResolvedValue(false),
      queryByIdentifiers: vi.fn().mockResolvedValue([]),
      update: vi.fn(),
    };
    connectorToolModelMock = { upsertMany: vi.fn() };
    pluginModelMock = { findById: vi.fn() };

    vi.mocked(ConnectorModel).mockImplementation(function () {
      return connectorModelMock;
    });
    vi.mocked(ConnectorToolModel).mockImplementation(function () {
      return connectorToolModelMock;
    });
    vi.mocked(PluginModel).mockImplementation(function () {
      return pluginModelMock;
    });
  });

  const callerFor = (workspaceId?: string) =>
    connectorRouter.createCaller({
      serverDB: {},
      userId: 'user_test',
      workspaceId: workspaceId ?? null,
      ...(workspaceId && { workspaceRole: 'member' }),
    } as any);

  it('returns { connectorId: null } early for customPlugin rows that own an MCP endpoint', async () => {
    // This is the load-bearing guard: legacy custom MCP plugins MUST go through
    // the frontend `CustomConnectorModal` migration path, not this procedure —
    // otherwise we leak a half-baked marketplace connector row that the runtime
    // filter then discards, leaving the agent with no working tools.
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'customPlugin',
      manifest: { meta: { title: 'Legacy MCP' } },
      customParams: { mcp: { type: 'http', url: 'http://10.9.16.224:9100/mcp' } },
    });

    const result = await callerFor().syncPluginTools({ identifier: 'dockpit' });

    expect(result).toEqual({ connectorId: null, toolCount: 0 });
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
    expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
  });

  it('still bootstraps a connector row for marketplace plugins (the original happy path)', async () => {
    // Same plugin row shape but type='plugin' — the marketplace case the
    // procedure was originally written for. The customPlugin guard must NOT
    // affect this branch.
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      manifest: {
        api: [
          {
            description: 'Search the web',
            humanIntervention: 'never',
            name: 'web_search',
            parameters: { properties: { q: { type: 'string' } }, type: 'object' },
          },
        ],
        meta: { avatar: '🔎', description: 'Web search', title: 'WebSearch' },
      },
    });

    const result = await callerFor().syncPluginTools({ identifier: 'web-search' });

    expect(result.connectorId).toBe('conn-new');
    expect(result.toolCount).toBe(1);
    expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledTimes(1);
    expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(
      'conn-new',
      expect.arrayContaining([expect.objectContaining({ toolName: 'web_search' })]),
    );
  });

  /** @example A removed Composio provider cannot be projected back into connector storage. */
  it('does not bootstrap legacy GitHub Composio plugin rows', async () => {
    // ROOT CAUSE:
    //
    // GitHub was removed from the Composio catalog, but an existing plugin row could still reach
    // syncPluginTools and recreate a connector carrying its obsolete Composio account metadata.
    //
    // Before: opening the legacy plugin detail created a GitHub Composio connector projection.
    // We fixed this by requiring every Composio plugin projection to remain in the live catalog.
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      customParams: {
        composio: {
          appSlug: 'GITHUB',
          authConfigId: 'ac-github',
          connectedAccountId: 'ca-github',
          status: 'ACTIVE',
        },
      },
      manifest: { api: [], meta: { title: 'GitHub' } },
    });

    const result = await callerFor().syncPluginTools({ identifier: 'github' });

    expect(result).toEqual({ connectorId: null, toolCount: 0 });
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
    expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
  });

  it('copies Composio account metadata when bootstrapping its connector projection', async () => {
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      customParams: {
        composio: activeGmailAuthConfig(),
      },
      manifest: { api: [], meta: { title: 'Gmail' } },
    });

    await callerFor().syncPluginTools({ identifier: 'gmail' });

    expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
      expect.objectContaining({
        metadata: expect.objectContaining({
          composio: expect.objectContaining({ connectedAccountId: 'ca-gmail' }),
        }),
      }),
    );
  });

  it('preserves Composio account metadata when refreshing an existing connector', async () => {
    // ROOT CAUSE:
    //
    // Opening connector details automatically calls syncPluginTools. The old
    // update replaced metadata with display fields only, erasing the account id
    // needed for execution and remote revocation.
    connectorModelMock.findManageableByIdentifier.mockResolvedValueOnce({
      id: 'conn-existing',
      metadata: {
        composio: activeGmailAuthConfig(),
        mountedByAgentId: 'agent-1',
      },
      userId: 'user_test',
    });
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      customParams: {
        composio: activeGmailAuthConfig(),
      },
      manifest: { api: [], meta: { description: 'Gmail tools', title: 'Gmail' } },
    });

    await callerFor().syncPluginTools({ identifier: 'gmail' });

    expect(connectorModelMock.update).toHaveBeenCalledWith('conn-existing', {
      metadata: expect.objectContaining({
        composio: expect.objectContaining({ connectedAccountId: 'ca-gmail' }),
        description: 'Gmail tools',
        mountedByAgentId: 'agent-1',
      }),
    });
  });

  // A marketplace MCP reinstalled on the connector path keeps its plugin row and
  // that row's old manifest; opening Settings must not sync it over the tools
  // the reinstall synced from the server
  it.each([
    ['an HTTP', { mcpConnectionType: 'http', mcpServerUrl: 'https://mcp.example.com' }],
    ['a cloud', { mcpConnectionType: 'cloud', mcpServerUrl: null }],
    ['a stdio', { mcpConnectionType: 'stdio', mcpServerUrl: null }],
  ])('leaves %s connector installed for the identifier as it is', async (_, endpoint) => {
    connectorModelMock.queryByIdentifiers.mockResolvedValue([
      {
        id: 'conn-installed',
        metadata: { description: 'Synced from the server' },
        sourceType: 'marketplace',
        userId: 'user_test',
        ...endpoint,
      },
    ]);
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      manifest: {
        api: [{ description: 'Old search', name: 'search', parameters: {} }],
        meta: { description: 'Old manifest', title: 'Search MCP' },
      },
    });

    const result = await callerFor().syncPluginTools({ identifier: 'search-mcp' });

    expect(result).toEqual({ connectorId: 'conn-installed', toolCount: 0 });
    expect(connectorModelMock.update).not.toHaveBeenCalled();
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
    expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
  });

  it("leaves the caller's private installed connector as it is", async () => {
    // The shared-only lookup misses a private row, which upsertConnectorEntry
    // then refreshes in place: the plugin row's old manifest would go back
    // over the tools the install synced from the server.
    connectorModelMock.findScopedByIdentifier.mockResolvedValue({
      id: 'conn-private-installed',
      mcpConnectionType: 'http',
      mcpServerUrl: 'https://mcp.example.com',
      sourceType: 'marketplace',
      userId: 'user_test',
      visibility: 'private',
    });
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      manifest: {
        api: [{ description: 'Old search', name: 'search', parameters: {} }],
        meta: { description: 'Old manifest', title: 'Search MCP' },
      },
    });

    const result = await callerFor('ws-1').syncPluginTools({ identifier: 'search-mcp' });

    expect(connectorModelMock.findScopedByIdentifier).toHaveBeenCalledWith(
      'search-mcp',
      undefined,
      undefined,
      'private',
    );
    expect(result).toEqual({ connectorId: 'conn-private-installed', toolCount: 0 });
    expect(connectorModelMock.update).not.toHaveBeenCalled();
    expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
  });

  it('refreshes a connector switched to private in place, not through a new shared twin', async () => {
    // Regression: the lookup saw shared rows only, so refreshing a private
    // Composio connector created an enabled shared row carrying the same
    // account from the plugin projection, offering it to every workspace agent.
    connectorModelMock.findManageableByIdentifier.mockResolvedValueOnce({
      agentId: null,
      id: 'conn-private',
      metadata: { composio: activeGmailAuthConfig() },
      userId: 'user_test',
      visibility: 'private',
    });
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      customParams: { composio: activeGmailAuthConfig() },
      manifest: { api: [{ name: 'send' }], meta: { title: 'Gmail' } },
    });

    const result = await callerFor('ws-1').syncPluginTools({ identifier: 'gmail' });

    expect(connectorModelMock.findManageableByIdentifier).toHaveBeenCalledWith(
      'gmail',
      undefined,
      'ca-gmail',
    );
    expect(result).toEqual({ connectorId: 'conn-private', toolCount: 1 });
    expect(connectorModelMock.create).not.toHaveBeenCalled();
    expect(connectorModelMock.update).toHaveBeenCalledWith('conn-private', {
      metadata: expect.objectContaining({ composio: activeGmailAuthConfig() }),
    });
  });

  it("never projects a teammate's private Composio account onto a shared row", async () => {
    // The plugin projection is workspace-wide, so a teammate still reads the
    // account of a connector its owner made private.
    connectorModelMock.isComposioAccountPrivateToTeammate.mockResolvedValue(true);
    pluginModelMock.findById.mockResolvedValue({
      type: 'plugin',
      customParams: { composio: activeGmailAuthConfig() },
      manifest: { api: [{ name: 'send' }], meta: { description: 'Gmail tools', title: 'Gmail' } },
    });

    // No row of theirs: nothing is created
    expect(await callerFor('ws-1').syncPluginTools({ identifier: 'gmail' })).toEqual({
      connectorId: null,
      toolCount: 0,
    });
    expect(connectorModelMock.create).not.toHaveBeenCalled();
    expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();

    // Their own shared row keeps its account; only the display fields refresh
    connectorModelMock.findManageableByIdentifier.mockResolvedValueOnce({
      agentId: null,
      id: 'conn-shared',
      metadata: { composio: { ...activeGmailAuthConfig(), connectedAccountId: 'ca-shared' } },
      userId: 'user_test',
      visibility: 'public',
    });
    await callerFor('ws-1').syncPluginTools({ identifier: 'gmail' });

    expect(connectorModelMock.update).toHaveBeenCalledWith('conn-shared', {
      metadata: {
        composio: expect.objectContaining({ connectedAccountId: 'ca-shared' }),
        description: 'Gmail tools',
      },
    });
  });

  it('also defers when plugin has type=customPlugin AND has a manifest (no half-baked row written)', async () => {
    // Some legacy customPlugin rows DO have a manifest (cached from a successful
    // tools/list call earlier). The guard must not fall through just because a
    // manifest exists — the discriminator is `type === 'customPlugin'` + mcp.
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'customPlugin',
      manifest: { api: [{ name: 'cached_tool' }], meta: { title: 'X' } },
      customParams: { mcp: { type: 'stdio', command: '/bin/x' } },
    });

    const result = await callerFor().syncPluginTools({ identifier: 'x' });

    expect(result).toEqual({ connectorId: null, toolCount: 0 });
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
  });

  it('throws NOT_FOUND when the plugin row does not exist (unchanged behavior)', async () => {
    pluginModelMock.findById.mockResolvedValueOnce(null);
    await expect(callerFor().syncPluginTools({ identifier: 'nope' })).rejects.toMatchObject({
      code: 'NOT_FOUND',
    });
  });

  it('defers (not NOT_FOUND) for customPlugin+mcp rows whose manifest is NULL', async () => {
    // This is the exact #15674 victim profile: legacy custom MCP whose
    // `tools/list` never succeeded after the v2.2.3 break, so `manifest` is
    // NULL on the row. The customPlugin migration guard MUST run before the
    // manifest check, otherwise the user gets a NOT_FOUND, the SkillDetail
    // fallback never renders, and the migration modal never surfaces.
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'customPlugin',
      manifest: null,
      customParams: { mcp: { type: 'http', url: 'http://10.9.16.224:9100/mcp' } },
    });

    const result = await callerFor().syncPluginTools({ identifier: 'dockpit' });

    expect(result).toEqual({ connectorId: null, toolCount: 0 });
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
  });

  it('still throws NOT_FOUND for non-customPlugin rows with no manifest', async () => {
    // Marketplace rows are expected to always carry a manifest. If a plugin
    // row exists but its manifest is missing AND it isn't a customPlugin with
    // an MCP blob to migrate, we can't bootstrap a connector from it — the
    // NOT_FOUND signal stays as it was for that genuinely broken case.
    pluginModelMock.findById.mockResolvedValueOnce({
      type: 'plugin',
      manifest: null,
    });
    await expect(
      callerFor().syncPluginTools({ identifier: 'broken-marketplace' }),
    ).rejects.toMatchObject({ code: 'NOT_FOUND' });
  });
});

describe('connectorRouter.create — sourceType handling on existing rows', () => {
  // Companion to the syncPluginTools guard above. The legacy customPlugin →
  // connector migration relies on `connector.create` being idempotent on
  // (user_id, identifier); the existing-row branch must also accept the
  // `sourceType` from the input so a half-baked `marketplace` connector row
  // (left behind by the pre-guard `syncPluginTools` code path) gets promoted
  // to `custom`. Without the promotion the row stays invisible to the custom-
  // connector list selectors and the migrated MCP disappears from the UI.

  let connectorModelMock: any;
  let pluginModelMock: any;
  let connectorToolModelMock: any;

  beforeEach(() => {
    vi.clearAllMocks();
    connectorModelMock = {
      createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
      findScopedByIdentifier: vi.fn().mockResolvedValue(null),
      queryByIdentifiers: vi.fn().mockResolvedValue([]),
      update: vi.fn().mockResolvedValue(true),
    };
    connectorToolModelMock = { upsertMany: vi.fn() };
    pluginModelMock = { findById: vi.fn() };
    vi.mocked(ConnectorModel).mockImplementation(function () {
      return connectorModelMock;
    });
    vi.mocked(ConnectorToolModel).mockImplementation(function () {
      return connectorToolModelMock;
    });
    vi.mocked(PluginModel).mockImplementation(function () {
      return pluginModelMock;
    });
  });

  const caller = () =>
    connectorRouter.createCaller({
      serverDB: {},
      userId: 'user_test',
      workspaceId: null,
    } as any);

  const baseCustomInput = {
    identifier: 'legacy-mcp',
    isEnabled: true,
    mcpConnectionType: 'http' as const,
    mcpServerUrl: 'https://mcp.example.com',
    name: 'Legacy MCP',
    sourceType: 'custom' as const,
  };

  it('promotes an existing marketplace row to custom when the input asks for it', async () => {
    // Pre-existing half-baked row from the old syncPluginTools code path.
    connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce({
      id: 'conn-existing',
      identifier: 'legacy-mcp',
      sourceType: 'marketplace',
    });

    const result = await caller().create(baseCustomInput);

    expect(result).toEqual({ id: 'conn-existing', isNew: false });
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
    expect(connectorModelMock.update).toHaveBeenCalledTimes(1);
    expect(connectorModelMock.update).toHaveBeenCalledWith(
      'conn-existing',
      expect.objectContaining({ sourceType: 'custom' }),
    );
  });

  it('keeps sourceType consistent when the input and existing row agree', async () => {
    // A normal re-save / re-authorize of an already-custom connector — the
    // update still includes sourceType, but the value stays the same. This
    // documents that the promotion path is safe for the no-op case.
    connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce({
      id: 'conn-existing',
      identifier: 'legacy-mcp',
      sourceType: 'custom',
    });

    await caller().create(baseCustomInput);

    expect(connectorModelMock.update).toHaveBeenCalledWith(
      'conn-existing',
      expect.objectContaining({ sourceType: 'custom' }),
    );
  });

  it('still creates a fresh row when no existing identifier matches', async () => {
    connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce(null);

    const result = await caller().create(baseCustomInput);

    expect(result).toEqual({ id: 'conn-new', isNew: true });
    expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
      expect.objectContaining({ identifier: 'legacy-mcp', sourceType: 'custom' }),
    );
    expect(connectorModelMock.update).not.toHaveBeenCalled();
  });

  it('re-adds over a base row another writer claimed after the lookup, adding none', async () => {
    // An Agent Builder install claimed the identifier between this lookup and
    // the insert: the add takes the claimed row, as if the lookup had found it.
    connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce(null);
    connectorModelMock.createUnlessIdentifierHeld.mockResolvedValueOnce({
      holder: { agentId: null, id: 'conn-claimed', identifier: 'legacy-mcp', userId: 'user_test' },
    });

    const result = await caller().create(baseCustomInput);

    expect(result).toEqual({ id: 'conn-claimed', isNew: false });
    expect(connectorModelMock.create).toBeUndefined();
    expect(connectorModelMock.update).toHaveBeenCalledWith(
      'conn-claimed',
      expect.objectContaining({ mcpServerUrl: 'https://mcp.example.com', sourceType: 'custom' }),
    );
  });

  it('re-adds over the row that replaced the one it read, not over the deleted one', async () => {
    // An Agent Builder install took over the stale unfinished row this add read
    // (deleting it) before the update: the add lands on the install's new row.
    const stale = {
      agentId: null,
      id: 'conn-stale',
      identifier: 'legacy-mcp',
      userId: 'user_test',
    };
    connectorModelMock.findScopedByIdentifier
      .mockResolvedValueOnce(stale)
      .mockResolvedValueOnce({ ...stale, id: 'conn-replacement' });
    connectorModelMock.update.mockResolvedValueOnce(false);

    const result = await caller().create(baseCustomInput);

    expect(result).toEqual({ id: 'conn-replacement', isNew: false });
    expect(connectorModelMock.update).toHaveBeenLastCalledWith(
      'conn-replacement',
      expect.objectContaining({ mcpServerUrl: 'https://mcp.example.com' }),
    );
    expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
  });

  it('reports a conflict instead of a deleted id when the retry misses too', async () => {
    connectorModelMock.findScopedByIdentifier.mockResolvedValue({
      agentId: null,
      id: 'conn-gone',
      identifier: 'legacy-mcp',
      userId: 'user_test',
    });
    connectorModelMock.update.mockResolvedValue(false);

    await expect(caller().create(baseCustomInput)).rejects.toMatchObject({ code: 'CONFLICT' });
    expect(connectorModelMock.update).toHaveBeenCalledTimes(2);
  });

  it('moves an agent connector to the base scope only through the identifier lock', async () => {
    const AGENT_ROW_ID = '9f1f6f30-0000-4000-8000-000000000003';
    connectorModelMock.findById = vi.fn().mockResolvedValue({
      agentId: 'agent-1',
      id: AGENT_ROW_ID,
      identifier: 'legacy-mcp',
      userId: 'user_test',
    });
    connectorModelMock.moveToBaseUnlessIdentifierHeld = vi
      .fn()
      .mockResolvedValueOnce({ moved: true })
      .mockResolvedValueOnce({ holder: { id: 'conn-base' } });

    await expect(caller().unbindAgent({ connectorId: AGENT_ROW_ID })).resolves.toEqual({
      id: AGENT_ROW_ID,
    });
    await expect(caller().unbindAgent({ connectorId: AGENT_ROW_ID })).rejects.toMatchObject({
      code: 'CONFLICT',
    });
    expect(connectorModelMock.moveToBaseUnlessIdentifierHeld).toHaveBeenCalledWith(
      AGENT_ROW_ID,
      'legacy-mcp',
    );
    expect(connectorModelMock.update).not.toHaveBeenCalled();
  });
});

describe('connectorRouter.delete — agent connector unpins from the owning agent ', () => {
  // Deleting an agent-owned connector must also remove its tool from that
  // agent's `plugins`, so the unified settings delete matches the agent-profile
  // delete (row + pin) and never leaves a dangling pin. Done server-side so the
  // unified page needs no access to an arbitrary agent's config.
  let connectorModelMock: any;
  let agentModelMock: any;
  let pluginModelMock: any;

  const DELETE_ID = '11111111-1111-4111-8111-111111111111';

  beforeEach(() => {
    vi.clearAllMocks();
    connectorModelMock = {
      delete: vi.fn().mockResolvedValue(undefined),
      findById: vi.fn(),
      // The Composio rows below run their own account and no other row does.
      queryComposioAccountHolders: vi
        .fn()
        .mockResolvedValue([
          { agentId: null, id: 'c-composio', userId: 'user_test', visibility: 'public' },
        ]),
    };
    agentModelMock = {
      getAgentConfigById: vi.fn(),
      update: vi.fn().mockResolvedValue(undefined),
    };
    pluginModelMock = {
      deleteComposioMirrors: vi.fn().mockResolvedValue(undefined),
      deleteComposioProjectionKeepingPrivate: vi.fn().mockResolvedValue(undefined),
    };
    mocks.connectedAccountsDelete.mockResolvedValue(undefined);
    mocks.removeSubscriptions.mockResolvedValue(undefined);
    vi.mocked(ConnectorModel).mockImplementation(function () {
      return connectorModelMock;
    });
    vi.mocked(ConnectorToolModel).mockImplementation(function () {
      return {} as any;
    });
    vi.mocked(PluginModel).mockImplementation(function () {
      return pluginModelMock;
    });
    vi.mocked(AgentModel).mockImplementation(function () {
      return agentModelMock;
    });
  });

  const caller = () =>
    connectorRouter.createCaller({
      serverDB: {},
      userId: 'user_test',
      workspaceId: null,
    } as any);

  it('deletes the row and strips the identifier from the owning agent plugins', async () => {
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: 'agent-1',
      id: 'c1',
      identifier: 'gmail',
      userId: 'user_test',
    });
    agentModelMock.getAgentConfigById.mockResolvedValueOnce({ plugins: ['gmail', 'notion'] });

    await caller().delete({ id: DELETE_ID });

    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
    expect(agentModelMock.getAgentConfigById).toHaveBeenCalledWith('agent-1');
    // 'gmail' removed, 'notion' preserved.
    expect(agentModelMock.update).toHaveBeenCalledWith('agent-1', { plugins: ['notion'] });
  });

  it('waits for remote subscription cleanup before deleting the connector foreign key', async () => {
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: null,
      id: DELETE_ID,
      identifier: 'linear',
      userId: 'user_test',
    });
    let finishCleanup!: () => void;
    mocks.removeSubscriptions.mockReturnValueOnce(
      new Promise<void>((resolve) => {
        finishCleanup = resolve;
      }),
    );
    const deleting = caller().delete({ id: DELETE_ID });
    await vi.waitFor(() =>
      expect(mocks.removeSubscriptions).toHaveBeenCalledWith(
        {},
        { userId: 'user_test', workspaceId: undefined },
        DELETE_ID,
      ),
    );
    expect(connectorModelMock.delete).not.toHaveBeenCalled();

    finishCleanup();
    await deleting;
    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
    expect(mocks.removeSubscriptions.mock.invocationCallOrder[0]).toBeLessThan(
      connectorModelMock.delete.mock.invocationCallOrder[0],
    );
  });

  it('leaves the agent config untouched for a base (non-agent) connector', async () => {
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: null,
      id: 'c2',
      identifier: 'notion',
      userId: 'user_test',
    });

    await caller().delete({ id: DELETE_ID });

    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
    expect(agentModelMock.getAgentConfigById).not.toHaveBeenCalled();
    expect(agentModelMock.update).not.toHaveBeenCalled();
  });

  it('revokes the remote account and removes a legacy GitHub Composio connector', async () => {
    // ROOT CAUSE:
    //
    // The connector settings page called connector.delete, which previously
    // removed only user_connectors while leaving the Composio account active.
    // We now identify Composio rows from metadata and revoke the same account
    // before deleting both local projections.
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: null,
      id: 'c-composio',
      identifier: 'github',
      metadata: { composio: { connectedAccountId: 'ca-github' } },
      userId: 'user_test',
    });

    await caller().delete({ id: DELETE_ID });

    expect(mocks.connectedAccountsDelete).toHaveBeenCalledWith('ca-github');
    expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).toHaveBeenCalledWith('github');
    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
  });

  it('still deletes local projections when remote Composio revocation fails', async () => {
    const warn = vi.spyOn(console, 'warn').mockImplementation(function () {
      return undefined;
    });
    mocks.connectedAccountsDelete.mockRejectedValueOnce(new Error('Composio unavailable'));
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: null,
      id: 'c-composio',
      identifier: 'gmail',
      metadata: { composio: { connectedAccountId: 'ca-gmail' } },
      userId: 'user_test',
    });

    await caller().delete({ id: DELETE_ID });

    expect(warn).toHaveBeenCalledWith(
      '[Composio] Failed to delete remote connection:',
      expect.any(Error),
    );
    expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).toHaveBeenCalledWith('gmail');
    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
    warn.mockRestore();
  });

  it('keeps a teammate’s private account when a row of the caller’s merely names it', async () => {
    // A connector's metadata is client-written, so a member's own row can name
    // the account of a teammate's private connector. Deleting the row must not
    // delete that remote account or the projection rows mirroring it.
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: null,
      id: 'c-forged',
      identifier: 'gmail',
      metadata: { composio: { connectedAccountId: 'ca-mate' } },
      userId: 'user_test',
      visibility: 'private',
    });
    connectorModelMock.queryComposioAccountHolders.mockResolvedValueOnce([
      { agentId: null, id: 'c-forged', userId: 'user_test', visibility: 'private' },
      { agentId: null, id: 'c-mate', userId: 'another-user', visibility: 'private' },
    ]);

    await connectorRouter
      .createCaller({
        serverDB: {},
        userId: 'user_test',
        workspaceId: 'ws-1',
        workspaceRole: 'member',
      } as any)
      .delete({ id: DELETE_ID });

    expect(connectorModelMock.queryComposioAccountHolders).toHaveBeenCalledWith('ca-mate');
    expect(mocks.connectedAccountsDelete).not.toHaveBeenCalled();
    expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
    expect(pluginModelMock.deleteComposioMirrors).not.toHaveBeenCalled();
    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
  });

  it('does not call Composio or delete a plugin for an ordinary connector', async () => {
    connectorModelMock.findById.mockResolvedValueOnce({
      agentId: null,
      id: 'c-custom',
      identifier: 'my-mcp',
      metadata: {},
      userId: 'user_test',
    });

    await caller().delete({ id: DELETE_ID });

    expect(mocks.connectedAccountsDelete).not.toHaveBeenCalled();
    expect(pluginModelMock.deleteComposioProjectionKeepingPrivate).not.toHaveBeenCalled();
    expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
  });

  it('is a no-op on the agent when the connector row is already gone', async () => {
    connectorModelMock.findById.mockResolvedValueOnce(null);

    await caller().delete({ id: DELETE_ID });

    expect(connectorModelMock.delete).not.toHaveBeenCalled();
    expect(agentModelMock.update).not.toHaveBeenCalled();
    expect(mocks.removeSubscriptions).not.toHaveBeenCalled();
  });
});

describe('connectorRouter.listAgentBound — hides connectors of unseen agents ', () => {
  // `queryAllAgentScoped` filters only by `workspace_id`, so a member could
  // otherwise see connectors owned by another member's PRIVATE agent. Gate the
  // result on the visibility-aware agent set (`getAgentAvatarsByIds`).
  let connectorModelMock: any;
  let connectorToolModelMock: any;
  let agentModelMock: any;

  beforeEach(() => {
    vi.clearAllMocks();
    connectorModelMock = { queryAllAgentScoped: vi.fn() };
    connectorToolModelMock = { queryByConnector: vi.fn().mockResolvedValue([]) };
    agentModelMock = { getAgentAvatarsByIds: vi.fn() };
    vi.mocked(ConnectorModel).mockImplementation(function () {
      return connectorModelMock;
    });
    vi.mocked(ConnectorToolModel).mockImplementation(function () {
      return connectorToolModelMock;
    });
    vi.mocked(PluginModel).mockImplementation(function () {
      return {} as any;
    });
    vi.mocked(AgentModel).mockImplementation(function () {
      return agentModelMock;
    });
  });

  const caller = () =>
    connectorRouter.createCaller({
      serverDB: {},
      userId: 'user_test',
      workspaceId: 'ws-1',
    } as any);

  it('drops rows whose owning agent is not in the visible set', async () => {
    connectorModelMock.queryAllAgentScoped.mockResolvedValueOnce([
      {
        agentId: 'agent-visible',
        credentials: null,
        id: 'c-visible',
        identifier: 'gmail',
        oidcConfig: null,
      },
      {
        agentId: 'agent-private',
        credentials: null,
        id: 'c-private',
        identifier: 'notion',
        oidcConfig: null,
      },
    ]);
    // AgentModel.ownership() (visibility-aware) only returns the visible agent —
    // the other member's private agent is absent.
    agentModelMock.getAgentAvatarsByIds.mockResolvedValueOnce([
      { avatar: null, id: 'agent-visible', title: 'Visible Agent' },
    ]);

    const result = await caller().listAgentBound();

    expect(result.map((r: any) => r.id)).toEqual(['c-visible']);
    expect(result[0].agentTitle).toBe('Visible Agent');
  });
});