🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { composioToolsRouter } from './composio';
const mocks = vi.hoisted(() => ({
agentExistsById: vi.fn(),
connectorForRow: vi.fn(),
connectorPickLegacyMirrors: vi.fn(),
connectorResolveByIdentifiers: vi.fn(),
connectorToolQueryByConnector: vi.fn(),
isComposioNotFound: vi.fn(),
markComposioUnavailable: vi.fn(),
pluginQueryMirrors: vi.fn(),
processToolCallResult: vi.fn(),
toolsExecute: vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
// The cloud role gate, mirrored: the OSS stub lets every role through
vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
const rank: Record<string, number> = { admin: 2, member: 1, owner: 3, viewer: 0 };
return {
requireWorkspaceRoleWhenScoped: (minRole: string) =>
mod.trpc.middleware(async (opts: any) => {
const { workspaceId, workspaceRole } = opts.ctx;
if (workspaceId && (rank[workspaceRole] ?? -1) < rank[minRole]) {
const { TRPCError } = await import('@trpc/server');
throw new TRPCError({ code: 'FORBIDDEN', message: `Requires ${minRole}` });
}
return opts.next();
}),
wsCompatProcedure: mod.trpc.procedure,
};
});
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn().mockImplementation(function () {
return { existsById: mocks.agentExistsById };
}),
}));
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn().mockImplementation(function () {
const model: Record<string, unknown> = {
forRow: mocks.connectorForRow,
pickLegacyComposioMirrors: mocks.connectorPickLegacyMirrors,
markComposioConnectionUnavailable: mocks.markComposioUnavailable,
resolveByIdentifiers: mocks.connectorResolveByIdentifiers,
};
mocks.connectorForRow.mockReturnValue(model);
return model;
}),
}));
vi.mock('@/database/models/connectorTool', () => ({
ConnectorToolModel: vi.fn().mockImplementation(function () {
return { queryByConnector: mocks.connectorToolQueryByConnector };
}),
}));
vi.mock('@/database/models/plugin', () => ({
PluginModel: vi.fn().mockImplementation(function () {
return { queryComposioMirrors: mocks.pluginQueryMirrors };
}),
}));
vi.mock('@/libs/composio', () => ({
getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),
isComposioClientAvailable: () => true,
isComposioConnectedAccountNotFoundError: mocks.isComposioNotFound,
}));
vi.mock('@/server/services/mcp', () => ({
MCPService: { processToolCallResult: mocks.processToolCallResult },
}));
const caller = () => composioToolsRouter.createCaller({ userId: 'user-1' } as any);
const input = { identifier: 'gmail', toolArgs: { to: '[email protected]' }, toolSlug: 'GMAIL_SEND_EMAIL' };
beforeEach(() => {
vi.clearAllMocks();
mocks.agentExistsById.mockResolvedValue(true);
mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
// The resolved connector lists the tool the call names
mocks.connectorToolQueryByConnector.mockResolvedValue([
{ permission: 'auto', toolName: 'GMAIL_SEND_EMAIL' },
]);
mocks.connectorPickLegacyMirrors.mockImplementation(async (mirrors: unknown[]) => mirrors);
mocks.isComposioNotFound.mockImplementation(function (error: unknown) {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
error.code === 'CONNECTED_ACCOUNT_NOT_FOUND'
);
});
mocks.markComposioUnavailable.mockResolvedValue(false);
mocks.pluginQueryMirrors.mockResolvedValue([]);
mocks.toolsExecute.mockResolvedValue({ data: 'ok' });
mocks.processToolCallResult.mockResolvedValue({ content: 'ok', success: true });
});
describe('composioToolsRouter.executeAction', () => {
it('resolves connectedAccountId from connector metadata (new path)', async () => {
mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
await caller().executeAction(input);
expect(mocks.toolsExecute).toHaveBeenCalledWith(
'GMAIL_SEND_EMAIL',
expect.objectContaining({ connectedAccountId: 'ca-connector', userId: 'user-1' }),
);
// No conversation is named, so only the rows any run may use resolve.
expect(mocks.connectorResolveByIdentifiers).toHaveBeenCalledWith(['gmail'], {});
expect(mocks.pluginQueryMirrors).not.toHaveBeenCalled();
});
/**
* @example
* expect(connector.status).toBe('error');
*/
it('delegates a connected-account 404 to ConnectorModel for manual execution', async () => {
const notFound = Object.assign(new Error('connected account not found'), {
code: 'CONNECTED_ACCOUNT_NOT_FOUND',
});
mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
mocks.toolsExecute.mockRejectedValue(notFound);
mocks.markComposioUnavailable.mockResolvedValue(true);
await expect(caller().executeAction(input)).rejects.toMatchObject({
message: 'connected account not found',
});
expect(mocks.connectorForRow).toHaveBeenCalledWith(
expect.objectContaining({ id: 'conn-gmail' }),
);
expect(mocks.markComposioUnavailable).toHaveBeenCalledWith('conn-gmail', 'ca-connector');
});
/**
* @example
* expect(connector.status).toBe('connected');
*/
it('does not disable a connector when manual execution reports a remote resource 404', async () => {
// ROOT CAUSE:
//
// Tool actions can return 404 for the target resource while their connected account is healthy.
// Only Composio's explicit connected-account-not-found error may update connector health here.
mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
mocks.toolsExecute.mockRejectedValue(
Object.assign(new Error('message not found'), { status: 404 }),
);
await expect(caller().executeAction(input)).rejects.toMatchObject({
message: 'message not found',
});
expect(mocks.markComposioUnavailable).not.toHaveBeenCalled();
});
it('falls back to plugin customParams when no connector projection exists', async () => {
mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
mocks.pluginQueryMirrors.mockResolvedValue([
{
customParams: { composio: { connectedAccountId: 'ca-plugin' } },
identifier: 'gmail',
userId: 'user-2',
},
]);
await caller().executeAction(input);
expect(mocks.toolsExecute).toHaveBeenCalledWith(
'GMAIL_SEND_EMAIL',
expect.objectContaining({ connectedAccountId: 'ca-plugin' }),
);
});
/**
* @example
* expect(executeAction()).rejects.toMatchObject({ code: 'NOT_FOUND' });
*/
it('does not run the plugin mirror of a connector the caller cannot see', async () => {
// ROOT CAUSE:
//
// The shared-row lookup misses a connector its creator made private, and the route read
// that miss as a pre-connector legacy connection. The workspace-wide plugin projection
// still mirrors the account, so any member ran it as the creator's Composio entity.
mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
mocks.connectorPickLegacyMirrors.mockResolvedValue([]);
mocks.pluginQueryMirrors.mockResolvedValue([
{
customParams: { composio: { connectedAccountId: 'ca-private', linkedByUserId: 'user-2' } },
identifier: 'gmail',
userId: 'user-2',
},
]);
await expect(caller().executeAction(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
expect(mocks.pluginQueryMirrors).toHaveBeenCalledWith(['gmail']);
expect(mocks.connectorPickLegacyMirrors).toHaveBeenCalledWith([
expect.objectContaining({
connectedAccountId: 'ca-private',
identifier: 'gmail',
ownerUserId: 'user-2',
}),
]);
expect(mocks.toolsExecute).not.toHaveBeenCalled();
});
it('resolves the account in the conversation the call came from', async () => {
// ROOT CAUSE:
//
// The client runtime ran every Composio call with no conversation named, so the server
// resolved the workspace's shared rows only. A private agent's own Composio connection,
// which the server runtime runs in that agent's direct topic, came back NOT_FOUND or ran
// the shared account of the same app. The scope proof (the caller's own private agent and
// its own direct topic) stays in SQL, in `connectorRunScope`.
mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-private', metadata: { composio: { connectedAccountId: 'ca-private' } } },
]);
await caller().executeAction({ ...input, agentId: 'agt-private', topicId: 'tpc-direct' });
expect(mocks.agentExistsById).toHaveBeenCalledWith('agt-private');
expect(mocks.connectorResolveByIdentifiers).toHaveBeenCalledWith(['gmail'], {
agentId: 'agt-private',
topicId: 'tpc-direct',
});
expect(mocks.toolsExecute).toHaveBeenCalledWith(
'GMAIL_SEND_EMAIL',
expect.objectContaining({ connectedAccountId: 'ca-private' }),
);
});
/**
* @example
* expect(executeAction({ agentId: hiddenAgent })).rejects.toMatchObject({ code: 'NOT_FOUND' });
*/
it('refuses to run as an agent the caller cannot see', async () => {
// ROOT CAUSE:
//
// The route forwarded the client's agentId to the resolver unchecked, and an agent's own
// rows (`agent_id = agentId`) are scoped by workspace only. A teammate who kept the id of
// an agent made private since ran its agent-owned Composio account with any tool and
// arguments. Connector calls check the agent first (`resolveConnectorForRun`).
mocks.agentExistsById.mockResolvedValue(false);
mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-agent', metadata: { composio: { connectedAccountId: 'ca-agent' } } },
]);
await expect(
caller().executeAction({ ...input, agentId: 'agt-hidden', topicId: 'tpc-any' }),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
expect(mocks.agentExistsById).toHaveBeenCalledWith('agt-hidden');
expect(mocks.connectorResolveByIdentifiers).not.toHaveBeenCalled();
expect(mocks.pluginQueryMirrors).not.toHaveBeenCalled();
expect(mocks.toolsExecute).not.toHaveBeenCalled();
});
/**
* @example
* expect(executeAction({ toolSlug: 'GMAIL_DELETE_ALL' })).rejects.toMatchObject({ code: 'NOT_FOUND' });
*/
it("refuses a slug the resolved connector's tool list does not hold", async () => {
// ROOT CAUSE:
//
// Only a `disabled` row was blocked: a slug with no tool row passed as allowed, so a member
// who could resolve a workspace agent's Composio account ran any provider action under its
// owner's account. The synced tool rows are the full list the runtime offers.
mocks.connectorResolveByIdentifiers.mockResolvedValue([
{ id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },
]);
await expect(
caller().executeAction({ ...input, toolSlug: 'GMAIL_DELETE_ALL' }),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
expect(mocks.connectorToolQueryByConnector).toHaveBeenCalledWith('conn-gmail');
expect(mocks.toolsExecute).not.toHaveBeenCalled();
});
it('throws NOT_FOUND when neither source has a connection', async () => {
mocks.connectorResolveByIdentifiers.mockResolvedValue([]);
await expect(caller().executeAction(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
expect(mocks.toolsExecute).not.toHaveBeenCalled();
});
});
describe('executeAction role gate', () => {
it('refuses a workspace viewer before resolving any account', async () => {
// Regression: a viewer named a public agent and ran its owner's
// agent-scoped Composio connection (e.g. GMAIL_SEND_EMAIL).
const viewer = composioToolsRouter.createCaller({
userId: 'viewer-1',
workspaceId: 'ws-1',
workspaceRole: 'viewer',
} as any);
await expect(viewer.executeAction({ ...input, agentId: 'agt-public' })).rejects.toMatchObject({
code: 'FORBIDDEN',
});
expect(mocks.connectorResolveByIdentifiers).not.toHaveBeenCalled();
expect(mocks.toolsExecute).not.toHaveBeenCalled();
});
});