@devries-cameron20 / composio Mirror · read-only / commits / f241ff375
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 09:45 UTC

refactor(cli): extract the account and connected-account families from the test layer (#4913)

This PR: - moves the account, session-info, and consumer endpoints of the mock Composio client out of `test/__utils__/services/test-layer.ts` into `test/__utils__/layers/accounts.ts`: the input type (`AccountTestData`, formerly the inline `accountData` shape), `MockRequestScope`, `MockAccountRequest`, and `mockAccountResources(accountData, scope)`, which returns the per-scope `org.*`, `auth.session.retrieveInfo`, and `get`/`post` resources with the same request recording; `mockClientFor(scope)` stays one function and shadows the client with it - moves the auth-config and connected-account family into `test/__utils__/layers/connected-accounts.ts`: `AuthConfigsTestData`, `ConnectedAccountsTestData` and their defaults, `connectedAccountRepositoryMethods` (`listAuthConfigs`, `getAuthConfig`, `createAuthConfig`, `getConnectedAccount`, spread into the test repository next to `toolkitCatalogMethods`), and `mockConnectedAccountResources` (`link.create`, `connectedAccounts.list`/`retrieve`/`delete`, spread into the mock client's resource shadows) - keeps `TestLive(input)` unchanged: `TestLiveInput`'s `accountData`, `authConfigsData`, and `connectedAccountsData` now name the extracted types (same fields), and `services/test-layer` re-exports `MockRequestScope` and `MockAccountRequest`, so no suite import changes - `NonCatalogMethod` in `layers/toolkits.ts` names `ConnectedAccountRepositoryMethod` instead of listing the four methods; the `Omit`-based check still covers every repository method - names the mock lists' default page size `DEFAULT_PAGE_LIMIT` (`test/__utils__/layers/page.ts`) in place of the literal `30` in every mock list (auth configs, connected accounts, toolkit and tool search, active triggers), and looks up auth configs and connected accounts by id with `Effect.fromOption` (`findById`); answers and errors are unchanged - adds `ConnectedAccountsTest({ authConfigsData?, connectedAccountsData? })` (exported from `test/__utils__`): a repository that serves only auth configs and connected accounts, built on `makeToolkitsRepositoryStub`, for handler tests of `auth-configs list|info|create` and `connected-accounts info|whoami`; any other repository method dies - extends `test/src/services/test-layer.test.ts`: `ConnectedAccountsTest` and `TestLive` give the same answers (a filtered auth-config list, a connected-account lookup, a 404), and `ConnectedAccountsTest` dies on a catalog method ## Context Unit U3 of the command-layout series (KTD5), second family: the account and connected-account pieces `link` (U5) relies on. Every mock keeps its behaviour, including evaluation order and the recorded `MockAccountRequest`s; the moved bodies are unchanged apart from indentation, the named page size, and the `findById` lookups. No suite under `test/src/commands/` changes. `test-layer.ts` goes from 1466 to 1161 lines. The account endpoints get no standalone layer: they live on the mock `ComposioClientSingleton`, whose client builder (`withShadows`, the dying transport, the Tool Router and trigger shadows) stays in `test-layer.ts`, and `link`'s handler also needs the Tool Router session. A standalone client layer fits once that builder moves out. Next family: setup and the command runner (U7). ## Verification On the branch tip: - `pnpm typecheck`: 14/14 tasks, `@composio/cli:typecheck` a cache miss (src and test configs) - `pnpm --filter @composio/cli test`: 153 files, 1815 passed, 1 skipped (the three new cases included); `validate:command-tests` at 18 exemptions, unchanged - `pnpm --filter @composio/cli run lint:effect`: 0 errors, 0 warnings - `oxlint` and `prettier --check` clean on every touched file

Alberto Schiabel committed Oct 16, 2026 at 02:41 UTC f241ff37511577b684c9be11eb3e08d417652f8f
7 files changed +526 -339
ts/packages/cli/test/__utils__/index.ts
+1
@@ -4,6 +4,7 @@ export * as MockConsole from './services/mock-console';
4 export * as MockTerminal from './services/mock-terminal';
5 export { TestLayer as TestLive } from './services/test-layer';
6 export { ToolkitsTest } from './layers/toolkits';
7 +export { ConnectedAccountsTest } from './layers/connected-accounts';
8 export { cli } from './cli';
9 export { pkg };
10 export { withHttpServer } from './http-server';
ts/packages/cli/test/__utils__/layers/accounts.ts new
+185
@@ -0,0 +1,185 @@
1 +import { APIConnectionError, type RequestOptions } from '@composio/client/effect';
2 +import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
3 +import type { OrganizationSummary, OrgProject } from 'src/services/composio-account';
4 +import { TIMESTAMP } from '../models/account';
5 +
6 +/**
7 + * The credentials and scope one mock-client request carries: the parameters
8 + * the client was obtained with, overridden by per-request headers.
9 + */
10 +export interface MockRequestScope {
11 + readonly userApiKey?: string;
12 + readonly apiKey?: string;
13 + readonly orgId?: string;
14 + readonly projectId?: string;
15 +}
16 +
17 +/**
18 + * One call to an account, session-info, or consumer endpoint of the mock client.
19 + */
20 +export interface MockAccountRequest {
21 + readonly operation:
22 + | 'org.list'
23 + | 'org.project.list'
24 + | 'org.consumer.project.resolve'
25 + | 'org.consumer.listConnectedToolkits'
26 + | 'auth.session.retrieveInfo'
27 + | 'tools.getLatestVersion'
28 + | 'org.project.createApiKey'
29 + | 'org.consumer.config'
30 + | 'consumer.permissions.resolve';
31 + readonly scope: MockRequestScope;
32 + readonly params?: unknown;
33 + readonly options?: RequestOptions;
34 +}
35 +
36 +/**
37 + * Account, session-info, and consumer data served by the mock client's
38 + * `org.*` and `auth.session.retrieveInfo` resources and its `get`/`post`
39 + * escape hatch. An endpoint without data rejects with a connection error,
40 + * as an unreachable backend would; consumer project resolution always
41 + * answers, echoing the requested org.
42 + */
43 +export interface AccountTestData {
44 + sessionInfo?:
45 + SessionRetrieveInfoResponse | ((scope: MockRequestScope) => SessionRetrieveInfoResponse);
46 + organizations?: ReadonlyArray<OrganizationSummary>;
47 + projects?: ReadonlyArray<OrgProject>;
48 + connectedToolkits?: ReadonlyArray<string>;
49 + latestToolVersion?: { readonly tool_slug: string; readonly version: string };
50 + projectApiKey?: string;
51 + onRequest?: (request: MockAccountRequest) => void;
52 +}
53 +
54 +const noTestData = (operation: MockAccountRequest['operation']) =>
55 + new APIConnectionError({
56 + message: `No test data for ${operation}`,
57 + method: 'GET',
58 + url: 'https://mock.invalid',
59 + reason: 'TransportError',
60 + description: `No test data for ${operation}`,
61 + });
62 +
63 +const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
64 + // The CLI only ever passes plain header records.
65 + const headers = (options?.headers ?? {}) as Record<string, string | null | undefined>;
66 + const userApiKey = headers['x-user-api-key'];
67 + return {
68 + userApiKey: userApiKey === null ? undefined : (userApiKey ?? base.userApiKey),
69 + apiKey: headers['x-api-key'] ?? undefined,
70 + orgId: headers['x-org-id'] ?? base.orgId,
71 + projectId: headers['x-project-id'] ?? base.projectId,
72 + };
73 +};
74 +
75 +/**
76 + * The account, session-info, and consumer resources of a mock client obtained
77 + * with `base`, answering from `accountData` and recording each call through
78 + * `accountData.onRequest`. Served per client scope, so a handler sees the
79 + * credentials and org or project the real client would have placed in its
80 + * default headers.
81 + */
82 +export const mockAccountResources = (accountData: AccountTestData, base: MockRequestScope) => {
83 + const record = (
84 + operation: MockAccountRequest['operation'],
85 + options: RequestOptions | undefined,
86 + params?: unknown
87 + ): MockRequestScope => {
88 + const scope = scopeOf(base, options);
89 + accountData.onRequest?.({ operation, scope, params, options });
90 + return scope;
91 + };
92 + const timestamps = {
93 + created_at: TIMESTAMP,
94 + updated_at: TIMESTAMP,
95 + };
96 +
97 + return {
98 + org: {
99 + list: async (query?: { limit?: number } | null, options?: RequestOptions) => {
100 + record('org.list', options, query);
101 + if (!accountData.organizations) throw noTestData('org.list');
102 + const organizations = accountData.organizations.map(org => ({ ...org, ...timestamps }));
103 + return {
104 + organizations,
105 + next_cursor: null,
106 + total_pages: 1,
107 + current_page: 1,
108 + total_items: organizations.length,
109 + };
110 + },
111 + project: {
112 + list: async (
113 + query?: { limit?: number; list_all_org_projects?: boolean | null } | null,
114 + options?: RequestOptions
115 + ) => {
116 + record('org.project.list', options, query);
117 + if (!accountData.projects) throw noTestData('org.project.list');
118 + return {
119 + data: [...accountData.projects],
120 + next_cursor: null,
121 + total_pages: 1,
122 + current_page: 1,
123 + total_items: accountData.projects.length,
124 + };
125 + },
126 + },
127 + consumer: {
128 + project: {
129 + resolve: async (
130 + params: { 'x-user-api-key': string; 'x-org-id': string },
131 + options?: RequestOptions
132 + ) => {
133 + record('org.consumer.project.resolve', options, params);
134 + const orgId = params['x-org-id'];
135 + return {
136 + project_id: 'consumer_project_id_test',
137 + project_nano_id: 'consumer_project_test',
138 + project_name: 'Consumer Project',
139 + org_id: orgId,
140 + project_type: 'CONSUMER' as const,
141 + config: { consumer_experience_enabled: true, enhanced_controls: false },
142 + consumer_user_id: `consumer-user-${orgId}`,
143 + };
144 + },
145 + },
146 + listConnectedToolkits: async (
147 + params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
148 + options?: RequestOptions
149 + ) => {
150 + record('org.consumer.listConnectedToolkits', options, params);
151 + if (!accountData.connectedToolkits) {
152 + throw noTestData('org.consumer.listConnectedToolkits');
153 + }
154 + return { toolkits: [...accountData.connectedToolkits] };
155 + },
156 + },
157 + },
158 + auth: {
159 + session: {
160 + retrieveInfo: async (options?: RequestOptions) => {
161 + const scope = record('auth.session.retrieveInfo', options);
162 + const sessionInfo = accountData.sessionInfo;
163 + if (sessionInfo === undefined) throw noTestData('auth.session.retrieveInfo');
164 + return typeof sessionInfo === 'function' ? sessionInfo(scope) : sessionInfo;
165 + },
166 + },
167 + },
168 + get: async (path: string, options?: RequestOptions) => {
169 + if (/^\/api\/v3\/tools\/[^/]+\/get_latest_version$/.test(path)) {
170 + record('tools.getLatestVersion', options, { path });
171 + if (!accountData.latestToolVersion) throw noTestData('tools.getLatestVersion');
172 + return accountData.latestToolVersion;
173 + }
174 + throw new Error(`Unhandled GET path "${path}"`);
175 + },
176 + post: async (path: string, options?: RequestOptions & { body?: unknown }) => {
177 + if (/^\/api\/v3\/org\/project\/[^/]+\/api_keys\/create$/.test(path)) {
178 + record('org.project.createApiKey', options, { path, body: options?.body });
179 + if (!accountData.projectApiKey) throw noTestData('org.project.createApiKey');
180 + return { api_key: accountData.projectApiKey };
181 + }
182 + throw new Error(`Unhandled POST path "${path}"`);
183 + },
184 + };
185 +};
ts/packages/cli/test/__utils__/layers/connected-accounts.ts new
+238
@@ -0,0 +1,238 @@
1 +import type {
2 + AuthConfigCreateParams,
3 + AuthConfigCreateResponse,
4 +} from '@composio/client/resources/auth-configs';
5 +import type { LinkCreateResponse } from '@composio/client/resources/link';
6 +import { Array as Arr, Effect, Layer } from 'effect';
7 +import type { AuthConfigItem } from 'src/models/auth-configs';
8 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 +import {
10 + ComposioToolkitsRepository,
11 + type ComposioToolkitsRepositoryShape,
12 +} from 'src/services/composio-clients';
13 +import { makeToolkitsRepositoryStub } from '../services/toolkits-repository-stub';
14 +import { notFoundError } from './not-found';
15 +import { DEFAULT_PAGE_LIMIT } from './page';
16 +
17 +/**
18 + * The auth configs a test repository serves, and what creating one answers.
19 + */
20 +export interface AuthConfigsTestData {
21 + items?: AuthConfigItem[];
22 + createResponse?: AuthConfigCreateResponse;
23 + onCreate?: (params: AuthConfigCreateParams) => void;
24 +}
25 +
26 +/**
27 + * The connected accounts a test serves, and what linking a new one answers.
28 + */
29 +export interface ConnectedAccountsTestData {
30 + items?: ConnectedAccountItem[];
31 + linkResponse?: LinkCreateResponse;
32 + onDelete?: (nanoid: string) => void;
33 +}
34 +
35 +/**
36 + * `AuthConfigsTestData` with no auth configs and the default create response
37 + * when the test left them out.
38 + */
39 +export const resolveAuthConfigsTestData = (data?: AuthConfigsTestData) => {
40 + const defaults = {
41 + items: [] as AuthConfigItem[],
42 + createResponse: undefined as AuthConfigCreateResponse | undefined,
43 + } satisfies AuthConfigsTestData;
44 + return {
45 + ...defaults,
46 + ...(data ?? {}),
47 + };
48 +};
49 +
50 +/**
51 + * `ConnectedAccountsTestData` with no connected accounts and the default link
52 + * response when the test left them out.
53 + */
54 +export const resolveConnectedAccountsTestData = (data?: ConnectedAccountsTestData) => {
55 + const defaults = {
56 + items: [] as ConnectedAccountItem[],
57 + linkResponse: undefined as LinkCreateResponse | undefined,
58 + } satisfies ConnectedAccountsTestData;
59 + return {
60 + ...defaults,
61 + ...(data ?? {}),
62 + };
63 +};
64 +
65 +export type ResolvedAuthConfigsTestData = ReturnType<typeof resolveAuthConfigsTestData>;
66 +export type ResolvedConnectedAccountsTestData = ReturnType<typeof resolveConnectedAccountsTestData>;
67 +
68 +/**
69 + * The item with `id`, or the 404 `notFound` describes.
70 + */
71 +const findById = <A extends { readonly id: string }>(
72 + items: ReadonlyArray<A>,
73 + id: string,
74 + notFound: () => ReturnType<typeof notFoundError>
75 +) =>
76 + Effect.fromOption(
77 + Arr.findFirst(items, item => item.id === id),
78 + notFound
79 + );
80 +
81 +/**
82 + * The repository methods this family serves.
83 + */
84 +export type ConnectedAccountRepositoryMethod =
85 + 'listAuthConfigs' | 'getAuthConfig' | 'createAuthConfig' | 'getConnectedAccount';
86 +
87 +export type ConnectedAccountRepositoryMethods = Pick<
88 + ComposioToolkitsRepositoryShape,
89 + ConnectedAccountRepositoryMethod
90 +>;
91 +
92 +/**
93 + * The repository's auth-config and connected-account methods, answering from
94 + * the test data the way the API would.
95 + */
96 +export const connectedAccountRepositoryMethods = (
97 + authConfigsData: ResolvedAuthConfigsTestData,
98 + connectedAccountsData: ResolvedConnectedAccountsTestData
99 +): ConnectedAccountRepositoryMethods => ({
100 + listAuthConfigs: (params: {
101 + search?: string;
102 + toolkit_slug?: string;
103 + limit?: number;
104 + show_disabled?: boolean;
105 + }) => {
106 + let results = [...authConfigsData.items];
107 +
108 + if (params.toolkit_slug) {
109 + const slugs = params.toolkit_slug.split(',').map(s => s.trim().toLowerCase());
110 + results = results.filter(item => slugs.includes(item.toolkit.slug.toLowerCase()));
111 + }
112 +
113 + if (params.search) {
114 + const q = params.search.toLowerCase();
115 + results = results.filter(
116 + item => item.name.toLowerCase().includes(q) || item.id.toLowerCase().includes(q)
117 + );
118 + }
119 +
120 + const limit = params.limit ?? DEFAULT_PAGE_LIMIT;
121 + const items = results.slice(0, limit);
122 + return Effect.succeed({
123 + items,
124 + total_items: results.length,
125 + total_pages: Math.ceil(results.length / limit),
126 + current_page: 1,
127 + next_cursor: null,
128 + });
129 + },
130 + getAuthConfig: (nanoid: string) =>
131 + findById(authConfigsData.items, nanoid, () =>
132 + notFoundError(`Auth config "${nanoid}" not found`, {
133 + message: `Auth config "${nanoid}" not found.`,
134 + suggested_fix: 'Check the auth config ID and try again.',
135 + })
136 + ),
137 + createAuthConfig: (params: AuthConfigCreateParams) => {
138 + authConfigsData.onCreate?.(params);
139 + return Effect.succeed(
140 + authConfigsData.createResponse ?? {
141 + auth_config: { id: 'ac_test', auth_scheme: 'OAUTH2', is_composio_managed: true },
142 + toolkit: { slug: 'test' },
143 + }
144 + );
145 + },
146 + getConnectedAccount: (nanoid: string) =>
147 + findById(connectedAccountsData.items, nanoid, () =>
148 + notFoundError(`Connected account "${nanoid}" not found`, {
149 + message: `Connected account "${nanoid}" not found.`,
150 + suggested_fix: 'Check the connected account ID and try again.',
151 + })
152 + ),
153 +});
154 +
155 +/**
156 + * The mock client's `link` and `connectedAccounts` resources, answering from
157 + * `connectedAccountsData`. The `connectedAccounts.list` answer never pages
158 + * (`next_cursor` is null).
159 + */
160 +export const mockConnectedAccountResources = (
161 + connectedAccountsData: ResolvedConnectedAccountsTestData
162 +) => ({
163 + link: {
164 + create: async (params: { auth_config_id: string; user_id: string }) => {
165 + const response = connectedAccountsData.linkResponse ?? {
166 + connected_account_id: 'con_test_link',
167 + expires_at: '2026-12-31T23:59:59Z',
168 + link_token: 'lt_test_token',
169 + redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
170 + };
171 + return response;
172 + },
173 + },
174 + connectedAccounts: {
175 + list: async (params?: {
176 + toolkit_slugs?: string[];
177 + user_ids?: string[];
178 + statuses?: string[];
179 + limit?: number;
180 + }) => {
181 + let results = [...connectedAccountsData.items];
182 +
183 + if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
184 + const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
185 + results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
186 + }
187 +
188 + if (params?.user_ids && params.user_ids.length > 0) {
189 + const userIds = new Set(params.user_ids);
190 + results = results.filter(item => userIds.has(item.user_id));
191 + }
192 +
193 + if (params?.statuses && params.statuses.length > 0) {
194 + const statuses = new Set(params.statuses);
195 + results = results.filter(item => statuses.has(item.status));
196 + }
197 +
198 + const limit = params?.limit ?? DEFAULT_PAGE_LIMIT;
199 + return {
200 + items: results.slice(0, limit),
201 + total_items: results.length,
202 + total_pages: Math.ceil(results.length / limit),
203 + current_page: 1,
204 + next_cursor: null,
205 + };
206 + },
207 + retrieve: (nanoid: string) =>
208 + findById(connectedAccountsData.items, nanoid, () =>
209 + notFoundError(`Connected account "${nanoid}" not found`)
210 + ),
211 + delete: (nanoid: string) =>
212 + findById(connectedAccountsData.items, nanoid, () =>
213 + notFoundError(`Connected account "${nanoid}" not found`)
214 + ).pipe(
215 + Effect.tap(() => Effect.sync(() => connectedAccountsData.onDelete?.(nanoid))),
216 + Effect.as({})
217 + ),
218 + },
219 +});
220 +
221 +/**
222 + * A `ComposioToolkitsRepository` that serves only auth configs and connected
223 + * accounts, for a test that needs nothing else from the full `TestLive` layer.
224 + * Any other repository method dies.
225 + */
226 +export const ConnectedAccountsTest = (data?: {
227 + readonly authConfigsData?: AuthConfigsTestData;
228 + readonly connectedAccountsData?: ConnectedAccountsTestData;
229 +}) =>
230 + Layer.succeed(
231 + ComposioToolkitsRepository,
232 + makeToolkitsRepositoryStub(
233 + connectedAccountRepositoryMethods(
234 + resolveAuthConfigsTestData(data?.authConfigsData),
235 + resolveConnectedAccountsTestData(data?.connectedAccountsData)
236 + )
237 + )
238 + );
ts/packages/cli/test/__utils__/layers/page.ts new
+4
@@ -0,0 +1,4 @@
1 +/**
2 + * The page size a mock list answers with when the caller passes no `limit`.
3 + */
4 +export const DEFAULT_PAGE_LIMIT = 30;
ts/packages/cli/test/__utils__/layers/toolkits.ts
+7 -8
@@ -18,7 +18,9 @@ import {
18 type InvalidVersionDetail,
19 } from 'src/services/toolkit-version-validation';
20 import { makeToolkitsRepositoryStub } from '../services/toolkits-repository-stub';
21 +import type { ConnectedAccountRepositoryMethod } from './connected-accounts';
22 import { notFoundError } from './not-found';
23 +import { DEFAULT_PAGE_LIMIT } from './page';
24
25 /**
26 * The toolkit, tool, and trigger-type catalogs a test repository serves.
@@ -68,14 +70,11 @@ export const resolveToolkitsTestData = (data?: ToolkitsTestData) => {
70 export type ResolvedToolkitsTestData = ReturnType<typeof resolveToolkitsTestData>;
71
72 /**
71 - * The repository methods other families serve: auth configs, connected accounts, and trigger
72 - * instances.
73 + * The repository methods other families serve: auth configs and connected accounts
74 + * (`connected-accounts.ts`), and trigger instances.
75 */
76 type NonCatalogMethod =
75 - | 'listAuthConfigs'
76 - | 'getAuthConfig'
77 - | 'createAuthConfig'
78 - | 'getConnectedAccount'
77 + | ConnectedAccountRepositoryMethod
78 | 'listActiveTriggers'
79 | 'createTrigger'
80 | 'enableTrigger'
@@ -262,7 +261,7 @@ export const toolkitCatalogMethods = (
261 );
262 }
263
265 - const limit = params.limit ?? 30;
264 + const limit = params.limit ?? DEFAULT_PAGE_LIMIT;
265 const items = results.slice(0, limit);
266 return Effect.succeed({
267 items,
@@ -302,7 +301,7 @@ export const toolkitCatalogMethods = (
301 );
302 }
303
305 - const limit = params.limit ?? 30;
304 + const limit = params.limit ?? DEFAULT_PAGE_LIMIT;
305 const items = results.slice(0, limit).map(toClientTool);
306 return Effect.succeed({
307 items,
ts/packages/cli/test/__utils__/services/test-layer.ts
+26 -330
@@ -1,21 +1,14 @@
1 import path from 'node:path';
2 import * as tempy from 'tempy';
3 -import type {
4 - AuthConfigCreateParams,
5 - AuthConfigCreateResponse,
6 -} from '@composio/client/resources/auth-configs';
3 import {
8 - APIConnectionError,
4 make as makeComposioClient,
5 type ComposioError,
6 type RequestOptions,
7 } from '@composio/client/effect';
13 -import type { LinkCreateResponse } from '@composio/client/resources/link';
8 import type {
9 TriggerInstanceListActiveParams,
10 TriggerInstanceUpsertParams,
11 } from '@composio/client/resources/trigger-instances';
18 -import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
12 import { TIMESTAMP } from '../models/account';
13 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
14 import * as BunPath from '@effect/platform-bun/BunPath';
@@ -46,10 +39,7 @@ import {
39 ComposioSessionRepository,
40 ComposioToolkitsRepository,
41 } from 'src/services/composio-clients';
49 -import { type OrganizationSummary, type OrgProject } from 'src/services/composio-account';
42 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
51 -import type { AuthConfigItem } from 'src/models/auth-configs';
52 -import type { ConnectedAccountItem } from 'src/models/connected-accounts';
43 import type { TriggerInstanceItem } from 'src/models/triggers';
44 import { ComposioUserContextLive } from 'src/services/user-context';
45 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -88,41 +78,27 @@ import {
78 import { FetchHttpClient, HttpClient } from 'effect/http';
79 import * as BunServices from '@effect/platform-bun/BunServices';
80 import { notFoundError } from '../layers/not-found';
81 +import { DEFAULT_PAGE_LIMIT } from '../layers/page';
82 import {
83 resolveToolkitsTestData,
84 toolkitCatalogMethods,
85 type ToolkitsTestData,
86 } from '../layers/toolkits';
87 +import {
88 + mockAccountResources,
89 + type AccountTestData,
90 + type MockRequestScope,
91 +} from '../layers/accounts';
92 +import {
93 + connectedAccountRepositoryMethods,
94 + mockConnectedAccountResources,
95 + resolveAuthConfigsTestData,
96 + resolveConnectedAccountsTestData,
97 + type AuthConfigsTestData,
98 + type ConnectedAccountsTestData,
99 +} from '../layers/connected-accounts';
100
97 -/**
98 - * The credentials and scope one mock-client request carries: the parameters
99 - * the client was obtained with, overridden by per-request headers.
100 - */
101 -export interface MockRequestScope {
102 - readonly userApiKey?: string;
103 - readonly apiKey?: string;
104 - readonly orgId?: string;
105 - readonly projectId?: string;
106 -}
107 -
108 -/**
109 - * One call to an account, session-info, or consumer endpoint of the mock client.
110 - */
111 -export interface MockAccountRequest {
112 - readonly operation:
113 - | 'org.list'
114 - | 'org.project.list'
115 - | 'org.consumer.project.resolve'
116 - | 'org.consumer.listConnectedToolkits'
117 - | 'auth.session.retrieveInfo'
118 - | 'tools.getLatestVersion'
119 - | 'org.project.createApiKey'
120 - | 'org.consumer.config'
121 - | 'consumer.permissions.resolve';
122 - readonly scope: MockRequestScope;
123 - readonly params?: unknown;
124 - readonly options?: RequestOptions;
125 -}
101 +export type { MockAccountRequest, MockRequestScope } from '../layers/accounts';
102
103 export interface TestLiveInput {
104 /**
@@ -158,38 +134,19 @@ export interface TestLiveInput {
134 /**
135 * Account, session-info, and consumer data served by the mock client's
136 * `org.*` and `auth.session.retrieveInfo` resources and its `get`/`post`
161 - * escape hatch. An endpoint without data rejects with a connection error,
162 - * as an unreachable backend would; consumer project resolution always
163 - * answers, echoing the requested org.
137 + * escape hatch.
138 */
165 - accountData?: {
166 - sessionInfo?:
167 - SessionRetrieveInfoResponse | ((scope: MockRequestScope) => SessionRetrieveInfoResponse);
168 - organizations?: ReadonlyArray<OrganizationSummary>;
169 - projects?: ReadonlyArray<OrgProject>;
170 - connectedToolkits?: ReadonlyArray<string>;
171 - latestToolVersion?: { readonly tool_slug: string; readonly version: string };
172 - projectApiKey?: string;
173 - onRequest?: (request: MockAccountRequest) => void;
174 - };
139 + accountData?: AccountTestData;
140
141 /**
142 * Mock auth-config data to use in test.
143 */
179 - authConfigsData?: {
180 - items?: AuthConfigItem[];
181 - createResponse?: AuthConfigCreateResponse;
182 - onCreate?: (params: AuthConfigCreateParams) => void;
183 - };
144 + authConfigsData?: AuthConfigsTestData;
145
146 /**
147 * Mock connected-account data to use in test.
148 */
188 - connectedAccountsData?: {
189 - items?: ConnectedAccountItem[];
190 - linkResponse?: LinkCreateResponse;
191 - onDelete?: (nanoid: string) => void;
192 - };
149 + connectedAccountsData?: ConnectedAccountsTestData;
150
151 /**
152 * Mock trigger instance data to use in test.
@@ -331,23 +288,8 @@ export const TestLayer = (input?: TestLiveInput) =>
288 const fixture = input?.fixture;
289 const toolkitsData = resolveToolkitsTestData(input?.toolkitsData);
290
334 - const defaultAuthConfigsData = {
335 - items: [] as AuthConfigItem[],
336 - createResponse: undefined as AuthConfigCreateResponse | undefined,
337 - } satisfies TestLiveInput['authConfigsData'];
338 - const authConfigsData = {
339 - ...defaultAuthConfigsData,
340 - ...(input?.authConfigsData ?? {}),
341 - };
342 -
343 - const defaultConnectedAccountsData = {
344 - items: [] as ConnectedAccountItem[],
345 - linkResponse: undefined as LinkCreateResponse | undefined,
346 - } satisfies TestLiveInput['connectedAccountsData'];
347 - const connectedAccountsData = {
348 - ...defaultConnectedAccountsData,
349 - ...(input?.connectedAccountsData ?? {}),
350 - };
291 + const authConfigsData = resolveAuthConfigsTestData(input?.authConfigsData);
292 + const connectedAccountsData = resolveConnectedAccountsTestData(input?.connectedAccountsData);
293
294 const defaultRealtimeData = {
295 events: [] as ReadonlyArray<Record<string, unknown>>,
@@ -372,69 +314,7 @@ export const TestLayer = (input?: TestLiveInput) =>
314 ComposioToolkitsRepository,
315 ComposioToolkitsRepository.of({
316 ...toolkitCatalogMethods(toolkitsData),
375 - listAuthConfigs: (params: {
376 - search?: string;
377 - toolkit_slug?: string;
378 - limit?: number;
379 - show_disabled?: boolean;
380 - }) => {
381 - let results = [...authConfigsData.items];
382 -
383 - if (params.toolkit_slug) {
384 - const slugs = params.toolkit_slug.split(',').map(s => s.trim().toLowerCase());
385 - results = results.filter(item => slugs.includes(item.toolkit.slug.toLowerCase()));
386 - }
387 -
388 - if (params.search) {
389 - const q = params.search.toLowerCase();
390 - results = results.filter(
391 - item => item.name.toLowerCase().includes(q) || item.id.toLowerCase().includes(q)
392 - );
393 - }
394 -
395 - const limit = params.limit ?? 30;
396 - const items = results.slice(0, limit);
397 - return Effect.succeed({
398 - items,
399 - total_items: results.length,
400 - total_pages: Math.ceil(results.length / limit),
401 - current_page: 1,
402 - next_cursor: null,
403 - });
404 - },
405 - getAuthConfig: (nanoid: string) => {
406 - const found = authConfigsData.items.find(item => item.id === nanoid);
407 - if (!found) {
408 - return Effect.fail(
409 - notFoundError(`Auth config "${nanoid}" not found`, {
410 - message: `Auth config "${nanoid}" not found.`,
411 - suggested_fix: 'Check the auth config ID and try again.',
412 - })
413 - );
414 - }
415 - return Effect.succeed(found);
416 - },
417 - createAuthConfig: (params: AuthConfigCreateParams) => {
418 - authConfigsData.onCreate?.(params);
419 - return Effect.succeed(
420 - authConfigsData.createResponse ?? {
421 - auth_config: { id: 'ac_test', auth_scheme: 'OAUTH2', is_composio_managed: true },
422 - toolkit: { slug: 'test' },
423 - }
424 - );
425 - },
426 - getConnectedAccount: (nanoid: string) => {
427 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
428 - if (!found) {
429 - return Effect.fail(
430 - notFoundError(`Connected account "${nanoid}" not found`, {
431 - message: `Connected account "${nanoid}" not found.`,
432 - suggested_fix: 'Check the connected account ID and try again.',
433 - })
434 - );
435 - }
436 - return Effect.succeed(found);
437 - },
317 + ...connectedAccountRepositoryMethods(authConfigsData, connectedAccountsData),
318 listActiveTriggers: (params: TriggerInstanceListActiveParams) => {
319 let results = [...triggersData.items];
320
@@ -473,7 +353,7 @@ export const TestLayer = (input?: TestLiveInput) =>
353 results = results.filter(item => item.disabled_at === null);
354 }
355
476 - const limit = params.limit ?? 30;
356 + const limit = params.limit ?? DEFAULT_PAGE_LIMIT;
357 const items = results.slice(0, limit);
358 return Effect.succeed({
359 items,
@@ -716,65 +596,7 @@ export const TestLayer = (input?: TestLiveInput) =>
596
597 // What the mock client answers with instead of calling the network.
598 const resourceShadows = {
719 - link: {
720 - create: async (params: { auth_config_id: string; user_id: string }) => {
721 - const response = connectedAccountsData.linkResponse ?? {
722 - connected_account_id: 'con_test_link',
723 - expires_at: '2026-12-31T23:59:59Z',
724 - link_token: 'lt_test_token',
725 - redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
726 - };
727 - return response;
728 - },
729 - },
730 - connectedAccounts: {
731 - list: async (params?: {
732 - toolkit_slugs?: string[];
733 - user_ids?: string[];
734 - statuses?: string[];
735 - limit?: number;
736 - }) => {
737 - let results = [...connectedAccountsData.items];
738 -
739 - if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
740 - const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
741 - results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
742 - }
743 -
744 - if (params?.user_ids && params.user_ids.length > 0) {
745 - const userIds = new Set(params.user_ids);
746 - results = results.filter(item => userIds.has(item.user_id));
747 - }
748 -
749 - if (params?.statuses && params.statuses.length > 0) {
750 - const statuses = new Set(params.statuses);
751 - results = results.filter(item => statuses.has(item.status));
752 - }
753 -
754 - const limit = params?.limit ?? 30;
755 - return {
756 - items: results.slice(0, limit),
757 - total_items: results.length,
758 - total_pages: Math.ceil(results.length / limit),
759 - current_page: 1,
760 - next_cursor: null,
761 - };
762 - },
763 - retrieve: (nanoid: string) => {
764 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
765 - return found
766 - ? Effect.succeed(found)
767 - : Effect.fail(notFoundError(`Connected account "${nanoid}" not found`));
768 - },
769 - delete: (nanoid: string) => {
770 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
771 - if (!found) {
772 - return Effect.fail(notFoundError(`Connected account "${nanoid}" not found`));
773 - }
774 - connectedAccountsData.onDelete?.(nanoid);
775 - return Effect.succeed({});
776 - },
777 - },
599 + ...mockConnectedAccountResources(connectedAccountsData),
600 triggersTypes: {
601 retrieve: (slug: string) => {
602 const found = toolkitsData.triggerTypes.find(
@@ -956,141 +778,15 @@ export const TestLayer = (input?: TestLiveInput) =>
778 );
779
780 // --- Account, session-info, and consumer endpoints ---
959 - // Served per client scope, so a handler sees the credentials and org or
960 - // project the real client would have placed in its default headers.
781 + // Served per client scope; see `mockAccountResources`.
782 const accountData = input?.accountData ?? {};
962 - const noTestData = (operation: MockAccountRequest['operation']) =>
963 - new APIConnectionError({
964 - message: `No test data for ${operation}`,
965 - method: 'GET',
966 - url: 'https://mock.invalid',
967 - reason: 'TransportError',
968 - description: `No test data for ${operation}`,
969 - });
970 -
971 - const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
972 - // The CLI only ever passes plain header records.
973 - const headers = (options?.headers ?? {}) as Record<string, string | null | undefined>;
974 - const userApiKey = headers['x-user-api-key'];
975 - return {
976 - userApiKey: userApiKey === null ? undefined : (userApiKey ?? base.userApiKey),
977 - apiKey: headers['x-api-key'] ?? undefined,
978 - orgId: headers['x-org-id'] ?? base.orgId,
979 - projectId: headers['x-project-id'] ?? base.projectId,
980 - };
981 - };
982 -
983 - const accountBranches = (base: MockRequestScope) => {
984 - const record = (
985 - operation: MockAccountRequest['operation'],
986 - options: RequestOptions | undefined,
987 - params?: unknown
988 - ): MockRequestScope => {
989 - const scope = scopeOf(base, options);
990 - accountData.onRequest?.({ operation, scope, params, options });
991 - return scope;
992 - };
993 - const timestamps = {
994 - created_at: TIMESTAMP,
995 - updated_at: TIMESTAMP,
996 - };
997 -
998 - return {
999 - org: {
1000 - list: async (query?: { limit?: number } | null, options?: RequestOptions) => {
1001 - record('org.list', options, query);
1002 - if (!accountData.organizations) throw noTestData('org.list');
1003 - const organizations = accountData.organizations.map(org => ({ ...org, ...timestamps }));
1004 - return {
1005 - organizations,
1006 - next_cursor: null,
1007 - total_pages: 1,
1008 - current_page: 1,
1009 - total_items: organizations.length,
1010 - };
1011 - },
1012 - project: {
1013 - list: async (
1014 - query?: { limit?: number; list_all_org_projects?: boolean | null } | null,
1015 - options?: RequestOptions
1016 - ) => {
1017 - record('org.project.list', options, query);
1018 - if (!accountData.projects) throw noTestData('org.project.list');
1019 - return {
1020 - data: [...accountData.projects],
1021 - next_cursor: null,
1022 - total_pages: 1,
1023 - current_page: 1,
1024 - total_items: accountData.projects.length,
1025 - };
1026 - },
1027 - },
1028 - consumer: {
1029 - project: {
1030 - resolve: async (
1031 - params: { 'x-user-api-key': string; 'x-org-id': string },
1032 - options?: RequestOptions
1033 - ) => {
1034 - record('org.consumer.project.resolve', options, params);
1035 - const orgId = params['x-org-id'];
1036 - return {
1037 - project_id: 'consumer_project_id_test',
1038 - project_nano_id: 'consumer_project_test',
1039 - project_name: 'Consumer Project',
1040 - org_id: orgId,
1041 - project_type: 'CONSUMER' as const,
1042 - config: { consumer_experience_enabled: true, enhanced_controls: false },
1043 - consumer_user_id: `consumer-user-${orgId}`,
1044 - };
1045 - },
1046 - },
1047 - listConnectedToolkits: async (
1048 - params: { user_id: string; 'x-user-api-key': string; 'x-org-id': string },
1049 - options?: RequestOptions
1050 - ) => {
1051 - record('org.consumer.listConnectedToolkits', options, params);
1052 - if (!accountData.connectedToolkits) {
1053 - throw noTestData('org.consumer.listConnectedToolkits');
1054 - }
1055 - return { toolkits: [...accountData.connectedToolkits] };
1056 - },
1057 - },
1058 - },
1059 - auth: {
1060 - session: {
1061 - retrieveInfo: async (options?: RequestOptions) => {
1062 - const scope = record('auth.session.retrieveInfo', options);
1063 - const sessionInfo = accountData.sessionInfo;
1064 - if (sessionInfo === undefined) throw noTestData('auth.session.retrieveInfo');
1065 - return typeof sessionInfo === 'function' ? sessionInfo(scope) : sessionInfo;
1066 - },
1067 - },
1068 - },
1069 - get: async (path: string, options?: RequestOptions) => {
1070 - if (/^\/api\/v3\/tools\/[^/]+\/get_latest_version$/.test(path)) {
1071 - record('tools.getLatestVersion', options, { path });
1072 - if (!accountData.latestToolVersion) throw noTestData('tools.getLatestVersion');
1073 - return accountData.latestToolVersion;
1074 - }
1075 - throw new Error(`Unhandled GET path "${path}"`);
1076 - },
1077 - post: async (path: string, options?: RequestOptions & { body?: unknown }) => {
1078 - if (/^\/api\/v3\/org\/project\/[^/]+\/api_keys\/create$/.test(path)) {
1079 - record('org.project.createApiKey', options, { path, body: options?.body });
1080 - if (!accountData.projectApiKey) throw noTestData('org.project.createApiKey');
1081 - return { api_key: accountData.projectApiKey };
1082 - }
1083 - throw new Error(`Unhandled POST path "${path}"`);
1084 - },
1085 - };
1086 - };
783
784 const scopedClients = new Map<string, typeof mockComposioClient>();
785 const mockClientFor = (scope: MockRequestScope) => {
786 const key = JSON.stringify([scope.userApiKey, scope.orgId, scope.projectId]);
787 const cached = scopedClients.get(key);
788 if (cached) return cached;
1093 - const scoped = withShadows(mockComposioClient, accountBranches(scope));
789 + const scoped = withShadows(mockComposioClient, mockAccountResources(accountData, scope));
790 scopedClients.set(key, scoped);
791 return scoped;
792 };
ts/packages/cli/test/src/services/test-layer.test.ts
+65 -1
@@ -6,7 +6,9 @@ import {
6 listOrganizations,
7 resolveConsumerProject,
8 } from 'src/services/composio-account';
9 -import { TestLive, ToolkitsTest } from 'test/__utils__';
9 +import type { AuthConfigItem } from 'src/models/auth-configs';
10 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
11 +import { ConnectedAccountsTest, TestLive, ToolkitsTest } from 'test/__utils__';
12 import { makeSessionInfo } from 'test/__utils__/models/account';
13 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
14
@@ -87,3 +89,65 @@ describe('ToolkitsTest', () => {
89 }).pipe(Effect.provide(ToolkitsTest()))
90 );
91 });
92 +
93 +describe('ConnectedAccountsTest', () => {
94 + const authConfig = (id: string, toolkitSlug: string): AuthConfigItem => ({
95 + id,
96 + name: id,
97 + no_of_connections: 0,
98 + status: 'ENABLED',
99 + type: 'default',
100 + uuid: `uuid-${id}`,
101 + toolkit: { logo: '', slug: toolkitSlug },
102 + auth_scheme: 'OAUTH2',
103 + is_composio_managed: true,
104 + is_enabled_for_tool_router: true,
105 + created_at: '2026-01-01T00:00:00Z',
106 + });
107 + const connectedAccount: ConnectedAccountItem = {
108 + id: 'con_gmail',
109 + status: 'ACTIVE',
110 + status_reason: null,
111 + is_disabled: false,
112 + user_id: 'default',
113 + toolkit: { slug: 'gmail' },
114 + auth_config: {
115 + id: 'ac_gmail',
116 + auth_scheme: 'OAUTH2',
117 + is_composio_managed: true,
118 + is_disabled: false,
119 + },
120 + created_at: '2026-01-01T00:00:00Z',
121 + updated_at: '2026-01-01T00:00:00Z',
122 + test_request_endpoint: '',
123 + };
124 + const input = {
125 + authConfigsData: { items: [authConfig('ac_gmail', 'gmail'), authConfig('ac_slack', 'slack')] },
126 + connectedAccountsData: { items: [connectedAccount] },
127 + };
128 +
129 + it.effect.each([
130 + { name: 'ConnectedAccountsTest', layer: ConnectedAccountsTest(input) },
131 + { name: 'TestLive', layer: TestLive(input) },
132 + ])('serves the same auth-config and connected-account answers through $name', ({ layer }) =>
133 + Effect.gen(function* () {
134 + const repo = yield* ComposioToolkitsRepository;
135 + const authConfigs = yield* repo.listAuthConfigs({ toolkit_slug: 'slack' });
136 + const found = yield* repo.getConnectedAccount('con_gmail');
137 + const missing = yield* repo.getAuthConfig('ac_nope').pipe(Effect.flip);
138 +
139 + expect(authConfigs.items.map(item => item.id)).toEqual(['ac_slack']);
140 + expect(found.toolkit.slug).toBe('gmail');
141 + expect(missing).toMatchObject({ _tag: '@composio/client/NotFoundError', status: 404 });
142 + }).pipe(Effect.provide(layer), Effect.scoped)
143 + );
144 +
145 + it.effect('dies on a repository method another family serves', () =>
146 + Effect.gen(function* () {
147 + const repo = yield* ComposioToolkitsRepository;
148 + const exit = yield* repo.getToolkits().pipe(Effect.exit);
149 +
150 + expect(Exit.hasDies(exit)).toBe(true);
151 + }).pipe(Effect.provide(ConnectedAccountsTest()))
152 + );
153 +});