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.

πŸ› fix(connector): unlink remote accounts on delete (#18270)

Neko249aa03c061c
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
index 089471df633..8a047d2a297 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
@@ -8,6 +8,10 @@ import { PluginModel } from '@/database/models/plugin';
import { connectorRouter } from '../connector';
+const mocks = vi.hoisted(() => ({
+ connectedAccountsDelete: 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
@@ -16,6 +20,11 @@ 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 () => ({}) },
}));
@@ -109,6 +118,76 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
);
});
+ it('copies Composio account metadata when bootstrapping its connector projection', async () => {
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'plugin',
+ customParams: {
+ composio: {
+ appSlug: 'GITHUB',
+ authConfigId: 'ac-github',
+ connectedAccountId: 'ca-github',
+ status: 'ACTIVE',
+ },
+ },
+ manifest: { api: [], meta: { title: 'GitHub' } },
+ });
+
+ await callerFor().syncPluginTools({ identifier: 'github' });
+
+ expect(connectorModelMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ composio: expect.objectContaining({ connectedAccountId: 'ca-github' }),
+ }),
+ }),
+ );
+ });
+
+ 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.queryByIdentifiers.mockResolvedValueOnce([
+ {
+ id: 'conn-existing',
+ metadata: {
+ composio: {
+ appSlug: 'GITHUB',
+ authConfigId: 'ac-github',
+ connectedAccountId: 'ca-github',
+ status: 'ACTIVE',
+ },
+ mountedByAgentId: 'agent-1',
+ },
+ userId: 'user_test',
+ },
+ ]);
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'plugin',
+ customParams: {
+ composio: {
+ appSlug: 'GITHUB',
+ authConfigId: 'ac-github',
+ connectedAccountId: 'ca-github',
+ status: 'ACTIVE',
+ },
+ },
+ manifest: { api: [], meta: { description: 'GitHub tools', title: 'GitHub' } },
+ });
+
+ await callerFor().syncPluginTools({ identifier: 'github' });
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith('conn-existing', {
+ metadata: expect.objectContaining({
+ composio: expect.objectContaining({ connectedAccountId: 'ca-github' }),
+ description: 'GitHub tools',
+ mountedByAgentId: 'agent-1',
+ }),
+ });
+ });
+
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
@@ -266,6 +345,7 @@ describe('connectorRouter.delete β€” agent connector unpins from the owning agen
// 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';
@@ -279,9 +359,11 @@ describe('connectorRouter.delete β€” agent connector unpins from the owning agen
getAgentConfigById: vi.fn(),
update: vi.fn().mockResolvedValue(undefined),
};
+ pluginModelMock = { delete: vi.fn().mockResolvedValue(undefined) };
+ mocks.connectedAccountsDelete.mockResolvedValue(undefined);
vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);
vi.mocked(ConnectorToolModel).mockImplementation(() => ({}) as any);
- vi.mocked(PluginModel).mockImplementation(() => ({}) as any);
+ vi.mocked(PluginModel).mockImplementation(() => pluginModelMock);
vi.mocked(AgentModel).mockImplementation(() => agentModelMock);
});
@@ -324,6 +406,66 @@ describe('connectorRouter.delete β€” agent connector unpins from the owning agen
expect(agentModelMock.update).not.toHaveBeenCalled();
});
+ it('revokes the remote account and removes the legacy plugin for a personal 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.delete).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(() => 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.delete).toHaveBeenCalledWith('gmail');
+ expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);
+ warn.mockRestore();
+ });
+
+ 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.delete).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);
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index 0b3ca7fbf43..dbbff2201aa 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -10,7 +10,7 @@ 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 type { OIDCConfig } from '@/database/schemas';
+import type { ConnectorMetadata, OIDCConfig } from '@/database/schemas';
import {
ConnectorMcpConnectionType,
ConnectorSourceType,
@@ -18,6 +18,7 @@ import {
ConnectorToolPermission,
} from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
+import { getComposioClient } from '@/libs/composio';
import { inferCrudType } from '@/libs/mcp/utils';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -664,6 +665,24 @@ export const connectorRouter = router({
// Missing row β†’ keep the delete idempotent, nothing to authorize.
if (!target) return;
assertWorkspaceRowManageable(ctx, target.userId, 'connector');
+
+ const connectedAccountId = target.metadata?.composio?.connectedAccountId;
+ if (connectedAccountId) {
+ try {
+ await getComposioClient().connectedAccounts.delete(connectedAccountId);
+ } catch (error) {
+ // Keep deletion recoverable when the remote account is already gone or
+ // Composio is temporarily unavailable. This matches deleteConnection:
+ // the local connector must not become impossible to remove.
+ console.warn('[Composio] Failed to delete remote connection:', error);
+ }
+
+ // Personal Composio connections still carry the legacy plugin projection.
+ // Agent-scoped connections never create one, so do not remove a base
+ // plugin that may belong to a separate personal connection.
+ if (!target.agentId) await ctx.pluginModel.delete(target.identifier);
+ }
+
await ctx.connectorModel.delete(input.id);
// Agent-owned connector: also unpin its tool from the owning agent's
@@ -955,6 +974,7 @@ export const connectorRouter = router({
const { connectorId, writable } = await upsertConnectorEntry(ctx, {
avatar: plugin.manifest.meta?.avatar,
+ composio: plugin.customParams?.composio,
description: plugin.manifest.meta?.description,
identifier: input.identifier,
name: plugin.manifest.meta?.title || input.identifier,
@@ -996,15 +1016,17 @@ async function upsertConnectorEntry(
},
params: {
avatar?: string;
+ composio?: ConnectorMetadata['composio'];
description?: string;
identifier: string;
name: string;
sourceType: string;
},
): Promise<{ connectorId: string; writable: boolean }> {
- const metadata: Record<string, unknown> = {};
+ const metadata: ConnectorMetadata = {};
if (params.description) metadata.description = params.description;
if (params.avatar) metadata.avatar = params.avatar;
+ if (params.composio) metadata.composio = params.composio;
// Viewers keep browse access: they resolve existing rows read-only below,
// but must never create or rewrite connector state. These bootstrap
@@ -1027,8 +1049,9 @@ async function upsertConnectorEntry(
const row = existing[0];
const writable = canWrite && (!isWorkspaceNonOwner(ctx) || row.userId === ctx.userId);
if (writable) {
- // Update metadata with latest description/avatar from manifest
- await ctx.connectorModel.update(row.id, { metadata });
+ // Preserve runtime-owned metadata (especially Composio account identity)
+ // while refreshing display fields from the latest plugin manifest.
+ await ctx.connectorModel.update(row.id, { metadata: { ...row.metadata, ...metadata } });
}
return { connectorId: row.id, writable };
}