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

next
ts 303 lines 11 KB
Raw
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect, Fiber } from 'effect';
3 import { TestClock } from 'effect/testing';
4 import type { ComposioClientShape } from '@composio/client/effect';
5 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
6 import { CONNECTED_ACCOUNTS_SHAPE_MESSAGE } from 'src/effects/decode-connected-account-list';
7 import { cli, MockConsole, TestLive } from 'test/__utils__';
8 import { exitCodeOf } from 'test/__utils__/exit-code';
9 import {
10 routeRequests,
11 stubClientResources,
12 type StubRequest,
13 } from 'test/__utils__/services/stub-composio-client';
14
15 const testLayer = () =>
16 TestLive({
17 baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
18 fixture: 'global-test-user-id',
19 });
20
21 const forbidden = () =>
22 Response.json(
23 { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
24 { status: 403 }
25 );
26 const FORBIDDEN_DETAIL =
27 '403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}';
28
29 const session = () =>
30 Response.json({
31 session_id: 'trs_stub_session',
32 config: { user_id: 'consumer-user-org_test' },
33 mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
34 tool_router_tools: [],
35 });
36
37 const failureOf = (
38 args: ReadonlyArray<string>,
39 resources: ReadonlyArray<keyof ComposioClientShape>,
40 respond: (request: StubRequest) => Response = forbidden
41 ) =>
42 Effect.gen(function* () {
43 const stub = stubClientResources(resources, respond);
44 return yield* cli(args).pipe(Effect.provide(stub.layer), Effect.flip);
45 });
46
47 const rejectedRequests: ReadonlyArray<{
48 readonly command: string;
49 readonly args: ReadonlyArray<string>;
50 readonly resources: ReadonlyArray<keyof ComposioClientShape>;
51 readonly tag: string;
52 readonly message: string;
53 }> = [
54 {
55 command: 'dev logs tools <id>',
56 args: ['dev', 'logs', 'tools', 'log_1'],
57 resources: ['logs'],
58 tag: 'commands/ToolLogsRequestError',
59 message: 'Failed to fetch tool log "log_1".',
60 },
61 {
62 command: 'dev logs triggers',
63 args: ['dev', 'logs', 'triggers'],
64 resources: ['_internal'],
65 tag: 'commands/TriggerLogsRequestError',
66 message: 'Failed to fetch trigger logs.',
67 },
68 {
69 command: 'dev logs triggers <id>',
70 args: ['dev', 'logs', 'triggers', 'log_1'],
71 resources: ['_internal'],
72 tag: 'commands/TriggerLogsRequestError',
73 message: 'Failed to fetch trigger log "log_1".',
74 },
75 {
76 command: 'connections list',
77 args: ['connections', 'list'],
78 resources: ['connectedAccounts'],
79 tag: 'commands/ConnectionsListRequestError',
80 message: 'Failed to list connections.',
81 },
82 {
83 command: 'connections remove',
84 // Without a terminal, removing needs --yes before any request is sent.
85 args: ['connections', 'remove', 'gmail', '--yes'],
86 resources: ['connectedAccounts'],
87 tag: 'commands/ConnectionsRemovalRequestError',
88 message: 'Failed to list connections.',
89 },
90 {
91 command: 'dev connected-accounts list',
92 args: ['dev', 'connected-accounts', 'list'],
93 resources: ['connectedAccounts'],
94 tag: 'commands/ConnectedAccountsListRequestError',
95 message: 'Failed to list connected accounts.',
96 },
97 {
98 command: 'link <toolkit> --list',
99 args: ['link', 'gmail', '--list'],
100 resources: ['connectedAccounts'],
101 tag: 'commands/ConnectedAccountsRequestError',
102 message: 'Failed to list connected accounts for "gmail".',
103 },
104 ];
105
106 describe('CLI: malformed connected-account pages', () => {
107 describe.each([
108 { args: ['connections', 'list'], tag: 'commands/ConnectionsListRequestError' },
109 {
110 args: ['connections', 'remove', 'gmail', '--yes'],
111 tag: 'commands/ConnectionsRemovalRequestError',
112 },
113 ])('$args', ({ args, tag }) => {
114 layer(testLayer())(it => {
115 it.effect.each([
116 { shape: 'missing items', body: { next_cursor: null } },
117 { shape: 'null items', body: { items: null, next_cursor: null } },
118 {
119 shape: 'object items',
120 body: { items: { state: { access_token: 'must-not-leak' } }, next_cursor: null },
121 },
122 {
123 shape: 'a repeated cursor',
124 body: { items: [], next_cursor: 'page-2' },
125 },
126 {
127 shape: 'a missing nonterminal cursor',
128 body: { items: [], current_page: 2, total_pages: 3 },
129 },
130 ])('fails safely when page two has $shape', ({ body }) =>
131 Effect.gen(function* () {
132 const pages = [{ items: [], next_cursor: 'page-2' }, body];
133 const stub = stubClientResources(['connectedAccounts'], () => {
134 const page = pages.shift();
135 return page === undefined ? forbidden() : Response.json(page);
136 });
137 const failure = yield* cli(args).pipe(Effect.provide(stub.layer), Effect.flip);
138
139 expect(failure).toMatchObject({
140 _tag: tag,
141 message: CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
142 cause: { _tag: 'effects/ConnectedAccountListShapeError' },
143 });
144 expect(extractErrorDetails(failure).message).not.toContain('must-not-leak');
145 const lines = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
146 expect(lines).toContain(CONNECTED_ACCOUNTS_SHAPE_MESSAGE);
147 expect(lines).not.toContain('must-not-leak');
148 expect(stub.requests).toHaveLength(2);
149 expect(stub.requests.every(request => request.method === 'GET')).toBe(true);
150 })
151 );
152 });
153 });
154 });
155
156 describe('CLI: a request the API rejects', () => {
157 describe.each(rejectedRequests)(
158 '[Given] composio $command',
159 ({ args, resources, tag, message }) => {
160 layer(testLayer())(it => {
161 it.effect(
162 '[Then] the command fails with its own message and the response as the cause',
163 () =>
164 Effect.gen(function* () {
165 const failure = yield* failureOf(args, resources);
166
167 expect(failure).toMatchObject({ _tag: tag, message });
168 expect(extractErrorDetails(failure).message).toBe(
169 `${message}\nCaused by: ${FORBIDDEN_DETAIL}`
170 );
171 })
172 );
173 });
174 }
175 );
176
177 layer(testLayer())('[Given] composio link while the new account cannot be fetched', it => {
178 it.effect('[Then] the wait fails with the fetch message once its retries run out', () =>
179 Effect.gen(function* () {
180 const stub = stubClientResources(
181 ['connectedAccounts'],
182 routeRequests(
183 [
184 {
185 method: 'GET',
186 path: '/api/v3.1/connected_accounts/con_test_link',
187 respond: forbidden,
188 },
189 ],
190 () => Response.json({ items: [], total_pages: 1, current_page: 1, total_items: 0 })
191 )
192 );
193 const fiber = yield* cli(['link', 'gmail', '--no-browser']).pipe(
194 Effect.provide(stub.layer),
195 Effect.flip,
196 Effect.forkChild
197 );
198 // Each retry waits on the test clock and then on the stub transport's promise.
199 yield* TestClock.adjust('2 hours').pipe(
200 Effect.andThen(TestClock.withLive(Effect.sleep('5 millis'))),
201 Effect.repeat({ times: 40 })
202 );
203 const failure = yield* Fiber.join(fiber);
204
205 expect(failure).toMatchObject({ _tag: 'commands/ConnectedAccountsRequestError' });
206 expect(extractErrorDetails(failure).message).toBe(
207 `Failed to fetch connected account "con_test_link".\nCaused by: ${FORBIDDEN_DETAIL}`
208 );
209 })
210 );
211 });
212 });
213
214 describe('CLI: a rejected request the command recovers from', () => {
215 const SESSION_TOOLKITS = '/api/v3.1/tool_router/session/trs_stub_session/toolkits?toolkits=gmail';
216 const toolkitsInfo = (toolkits: () => Response) =>
217 Effect.gen(function* () {
218 const stub = stubClientResources(
219 ['toolRouter'],
220 routeRequests([{ method: 'GET', path: SESSION_TOOLKITS, respond: toolkits }], session)
221 );
222 const exit = yield* Effect.exit(
223 cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.provide(stub.layer))
224 );
225 const lines = yield* MockConsole.getLines({ stripAnsi: true });
226 return { lines, lastPath: stub.requests.at(-1)?.path, exitCode: exitCodeOf(exit) };
227 });
228
229 layer(testLayer())('[Given] composio dev toolkits info and rejected session toolkits', it => {
230 it.effect('[Then] the API message and the browse hint are printed', () =>
231 Effect.gen(function* () {
232 const { lines, lastPath, exitCode } = yield* toolkitsInfo(forbidden);
233
234 expect(lines).toEqual([
235 'Using global test user id "global-default"',
236 'Not allowed',
237 'Browse available toolkits:\n> composio dev toolkits list',
238 ]);
239 expect(lastPath).toBe(SESSION_TOOLKITS);
240 expect(exitCode).toBe(1);
241 })
242 );
243 });
244
245 const LISTING = '/api/v3.1/connected_accounts?';
246 const withoutExistingAccounts = () => stubClientResources(['connectedAccounts'], forbidden);
247 const pending = (fields: Record<string, string>) =>
248 JSON.stringify(
249 {
250 status: 'pending',
251 message: 'Complete authorization by opening the URL',
252 connected_account_id: 'con_test_link',
253 redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
254 ...fields,
255 },
256 null,
257 2
258 );
259
260 layer(testLayer())('[Given] composio link <toolkit> and a rejected account listing', it => {
261 it.effect('[Then] the link is created as if the user had no account yet', () =>
262 Effect.gen(function* () {
263 const stub = withoutExistingAccounts();
264 yield* cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer));
265 const lines = yield* MockConsole.getLines({ stripAnsi: true });
266
267 expect(lines).toEqual([
268 'Linking gmail...',
269 // Off a terminal `--no-wait` prints the URL only in its JSON.
270 pending({ toolkit: 'gmail', project_type: 'CONSUMER' }),
271 ]);
272 expect(stub.requests.map(request => request.path)).toEqual([
273 `${LISTING}user_ids=consumer-user-org_test&toolkit_slugs=gmail&statuses=ACTIVE&limit=50`,
274 `${LISTING}user_ids=consumer-user-org_test&statuses=ACTIVE&limit=50`,
275 ]);
276 })
277 );
278 });
279
280 layer(testLayer())('[Given] composio link --auth-config and a rejected account listing', it => {
281 it.effect('[Then] the link is created as if the user had no account yet', () =>
282 Effect.gen(function* () {
283 const stub = withoutExistingAccounts();
284 yield* cli([
285 'dev',
286 'connected-accounts',
287 'link',
288 '--auth-config',
289 'ac_1',
290 '--user-id',
291 'user_1',
292 '--no-wait',
293 ]).pipe(Effect.provide(stub.layer));
294 const lines = yield* MockConsole.getLines({ stripAnsi: true });
295
296 expect(lines).toEqual(['Creating link session...', pending({ project_type: 'DEVELOPER' })]);
297 expect(stub.requests.map(request => request.path)).toEqual([
298 `${LISTING}user_ids=user_1&auth_config_ids=ac_1&statuses=ACTIVE&limit=50`,
299 ]);
300 })
301 );
302 });
303 });