@devries-cameron20 / composio Mirror · read-only
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, 06:00 UTC

next
ts 652 lines 22.7 KB
Raw
1 import { BadRequestError } from '@composio/client/effect';
2 import { describe, expect, it, layer } from '@effect/vitest';
3 import { ConfigProvider, Console, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { makeSessionInfo } from 'test/__utils__/models/account';
7 import type { MockRequestScope } from 'test/__utils__/services/test-layer';
8 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
9 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
10 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
11 import { ComposioUserContext } from 'src/services/user-context';
12 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
13 import open from 'open';
14 import { afterEach, vi } from 'vitest';
15
16 vi.mock('open', () => ({
17 default: vi.fn(async () => undefined),
18 }));
19
20 /** The command's JSON result: `ui.output` prints it as the last console line. */
21 const parseLastLine = (lines: ReadonlyArray<string>): unknown => JSON.parse(String(lines.at(-1)));
22
23 const makeConnectedAccount = (overrides?: Partial<ConnectedAccountItem>): ConnectedAccountItem => ({
24 id: 'con_test_link',
25 alias: 'default',
26 word_id: 'castle',
27 status: 'ACTIVE',
28 status_reason: null,
29 is_disabled: false,
30 user_id: 'consumer-user-org_test',
31 toolkit: { slug: 'gmail' },
32 auth_config: {
33 id: 'ac_gmail_oauth',
34 auth_scheme: 'OAUTH2',
35 is_composio_managed: true,
36 is_disabled: false,
37 },
38 created_at: '2026-01-01T00:00:00Z',
39 updated_at: '2026-01-15T00:00:00Z',
40 test_request_endpoint: '',
41 ...overrides,
42 });
43
44 const makeConnectedAccountsData = (
45 overrides?: Partial<NonNullable<TestLiveInput['connectedAccountsData']>>
46 ): NonNullable<TestLiveInput['connectedAccountsData']> => ({
47 items: [makeConnectedAccount()],
48 ...overrides,
49 });
50
51 const connectedAccountWithCredentialFields = {
52 ...makeConnectedAccount(),
53 state: { access_token: 'must-not-leak' },
54 data: { refresh_token: 'must-not-leak' },
55 };
56
57 const noManagedAuth = {
58 message: 'No managed auth',
59 code: 400,
60 slug: 'ToolRouterV2_NoManagedAuth',
61 status: 400,
62 };
63
64 const testConfigProvider = ConfigProvider.fromEnv({
65 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
66 });
67
68 const RecordingTerminalUI = TerminalUI.of({
69 capabilities: Effect.succeed(
70 getTerminalCapabilities({
71 stdin: { isTTY: true },
72 stdout: { isTTY: true },
73 stderr: { isTTY: true },
74 })
75 ),
76 output: (data, options) =>
77 Console.log(
78 JSON.stringify({
79 channel: options?.force ? 'FORCED' : 'NORMAL',
80 data,
81 })
82 ),
83 stdoutClosed: Effect.never,
84 error: data => Console.error(data),
85 intro: title => Console.log(title),
86 outro: message => Console.log(message),
87 log: {
88 info: message => Console.log(message),
89 success: message => Console.log(message),
90 warn: message => Console.log(message),
91 error: message => Console.log(message),
92 step: message => Console.log(message),
93 message: message => Console.log(message),
94 },
95 note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
96 confirm: () => Effect.succeed(true),
97 select: (_message, options) => Effect.succeed(options[0].value),
98 withSpinner: (_message, effect) => effect,
99 useMakeSpinner: (_message, use) =>
100 use({
101 message: () => Effect.void,
102 stop: () => Effect.void,
103 error: () => Effect.void,
104 }),
105 });
106
107 describe('CLI: composio dev connected-accounts link', () => {
108 const toolRouterCreateSpy = vi.fn(() =>
109 Effect.succeed({
110 session_id: 'trs_test_session',
111 config: {
112 user_id: 'consumer-user-org_test',
113 execute: {},
114 search: {},
115 preload: { tools: [] },
116 instant: false as const,
117 },
118 config_version: 1,
119 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
120 tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
121 })
122 );
123 const toolRouterLinkSpy = vi.fn(() =>
124 Effect.succeed({
125 connected_account_id: 'con_test_link',
126 link_token: 'lt_test_token',
127 redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
128 account_type: 'PRIVATE' as const,
129 })
130 );
131
132 afterEach(() => {
133 vi.restoreAllMocks();
134 vi.clearAllMocks();
135 });
136
137 layer(
138 TestLive({
139 baseConfigProvider: testConfigProvider,
140 connectedAccountsData: makeConnectedAccountsData(),
141 fixture: 'global-test-user-id',
142 })
143 )('[Given] valid toolkit link [Then] creates link and waits (default)', it => {
144 it.effect('creates link and waits for ACTIVE', () =>
145 Effect.gen(function* () {
146 yield* cli(['link', 'gmail']);
147 const lines = yield* MockConsole.getLines({ stripAnsi: true });
148
149 expect(parseLastLine(lines)).toMatchObject({
150 status: 'success',
151 connected_account_id: 'con_test_link',
152 toolkit: 'gmail',
153 });
154 expect(vi.mocked(open)).toHaveBeenCalledOnce();
155 })
156 );
157 });
158
159 layer(
160 TestLive({
161 baseConfigProvider: testConfigProvider,
162 connectedAccountsData: makeConnectedAccountsData(),
163 fixture: 'global-test-user-id',
164 })
165 )('[Given] --no-browser [Then] waits for ACTIVE without opening the browser', it => {
166 it.effect('prints the URL and waits without calling open', () =>
167 Effect.gen(function* () {
168 yield* cli(['link', 'gmail', '--no-browser']);
169 const lines = yield* MockConsole.getLines({ stripAnsi: true });
170 const output = lines.join('\n');
171
172 expect(parseLastLine(lines)).toMatchObject({
173 status: 'success',
174 connected_account_id: 'con_test_link',
175 });
176 expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');
177 expect(output).toContain('Open this URL in your browser to authorize');
178 expect(output).not.toContain('Redirecting you to the authorization page');
179 expect(vi.mocked(open)).not.toHaveBeenCalled();
180 })
181 );
182 });
183
184 layer(
185 TestLive({
186 baseConfigProvider: testConfigProvider,
187 connectedAccountsData: makeConnectedAccountsData(),
188 fixture: 'global-test-user-id',
189 })
190 )('[Given] --list [Then] it shows existing accounts without opening a new link', it => {
191 it.effect('lists alias and word_id for existing accounts', () =>
192 Effect.gen(function* () {
193 yield* cli(['link', 'gmail', '--list']);
194 const lines = yield* MockConsole.getLines({ stripAnsi: true });
195 const output = lines.join('\n');
196
197 expect(output).toContain('default');
198 expect(output).toContain('castle');
199 expect(parseLastLine(lines)).toMatchObject({ toolkit: 'gmail' });
200 expect(vi.mocked(open)).not.toHaveBeenCalled();
201 })
202 );
203 });
204
205 layer(
206 TestLive({
207 baseConfigProvider: testConfigProvider,
208 connectedAccountsData: makeConnectedAccountsData({
209 items: [
210 makeConnectedAccount(),
211 makeConnectedAccount({ id: 'con_global', alias: 'global', user_id: 'global-default' }),
212 ],
213 }),
214 fixture: 'global-test-user-id',
215 })
216 )(
217 '[Given] dev connected-accounts link --list in a developer project directory [Then] it lists the test user’s accounts',
218 it => {
219 // `link` on the dev tree acts on the developer project; it used to list the consumer
220 // user's accounts in the consumer project.
221 it.effect('lists the global test user’s accounts, not the consumer user’s', () =>
222 Effect.gen(function* () {
223 yield* cli(['dev', 'connected-accounts', 'link', 'gmail', '--list']);
224 const lines = yield* MockConsole.getLines({ stripAnsi: true });
225
226 expect(lines).toContain('Using global test user id "global-default"');
227 expect(parseLastLine(lines)).toMatchObject({
228 total: 1,
229 items: [{ id: 'con_global', user_id: 'global-default' }],
230 });
231 })
232 );
233 }
234 );
235
236 layer(
237 TestLive({
238 baseConfigProvider: testConfigProvider,
239 connectedAccountsData: makeConnectedAccountsData(),
240 fixture: 'global-test-user-id',
241 terminalUI: RecordingTerminalUI,
242 })
243 )('[Given] --no-wait [Then] emits a forced JSON payload for merged-stream shells', it => {
244 it.effect('forces the pending JSON payload through output()', () =>
245 Effect.gen(function* () {
246 yield* cli(['link', 'gmail', '--no-wait']);
247 const lines = yield* MockConsole.getLines({ stripAnsi: true });
248 const forcedLine = parseLastLine(lines) as { channel: string; data: string };
249
250 expect(forcedLine.channel).toBe('FORCED');
251 expect(JSON.parse(forcedLine.data)).toMatchObject({ status: 'pending' });
252 expect(vi.mocked(open)).not.toHaveBeenCalled();
253 })
254 );
255 });
256
257 layer(
258 TestLive({
259 baseConfigProvider: testConfigProvider,
260 connectedAccountsData: makeConnectedAccountsData(),
261 fixture: 'global-test-user-id',
262 terminalUI: RecordingTerminalUI,
263 })
264 )('[Given] --no-wait [Then] stdout remains JSON-only', it => {
265 it.effect('does not emit the raw redirect URL before the pending JSON payload', () =>
266 Effect.gen(function* () {
267 yield* cli(['link', 'gmail', '--no-wait']);
268 const lines = yield* MockConsole.getLines({ stripAnsi: true });
269 const forcedLine = parseLastLine(lines) as { channel: string; data: string };
270
271 // Every line before the payload is a log or note, never a second output().
272 expect(lines.slice(0, -1)).toEqual([
273 'Open this URL in your browser to authorize',
274 '[Redirect URL] https://app.composio.dev/link?token=lt_test_token',
275 ]);
276 expect(forcedLine.channel).toBe('FORCED');
277 // The payload parses as JSON, so nothing (such as the raw URL) precedes it.
278 expect(JSON.parse(forcedLine.data)).toMatchObject({ status: 'pending' });
279 })
280 );
281 });
282
283 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
284 it.effect('warns user to login', () =>
285 Effect.gen(function* () {
286 const error = yield* cli(['link', 'gmail']).pipe(Effect.flip);
287 expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
288 })
289 );
290 });
291
292 layer(
293 TestLive({
294 baseConfigProvider: testConfigProvider,
295 connectedAccountsData: makeConnectedAccountsData(),
296 fixture: 'global-test-user-id',
297 })
298 )('[Given] a blank --alias [Then] fails with a CLI validation error', it => {
299 // Business-level validation (only knowable after parsing) raises `CommandInputError`;
300 // see `src/commands/errors.ts`.
301 it.effect('reports the invalid option value before making a link request', () =>
302 Effect.gen(function* () {
303 const error = yield* cli(['link', 'gmail', '--alias', ' ']).pipe(Effect.flip);
304
305 expect(error).toMatchObject({
306 _tag: 'commands/CommandInputError',
307 command: 'link',
308 option: '--alias',
309 message: '`--alias` cannot be empty.',
310 });
311 expect(vi.mocked(open)).not.toHaveBeenCalled();
312 })
313 );
314
315 // Logged as decoration, this mistake vanished whenever stderr was not a TTY and the
316 // command exited 0; as a `CommandInputError` it reaches stderr and exits 1.
317 it.effect('reports a toolkit passed together with --auth-config', () =>
318 Effect.gen(function* () {
319 const error = yield* cli([
320 'dev',
321 'connected-accounts',
322 'link',
323 'gmail',
324 '--auth-config',
325 'ac_test',
326 '--no-wait',
327 ]).pipe(Effect.flip);
328
329 expect(error).toMatchObject({
330 _tag: 'commands/CommandInputError',
331 command: 'dev connected-accounts link',
332 option: '--auth-config',
333 });
334 expect(vi.mocked(open)).not.toHaveBeenCalled();
335 })
336 );
337 });
338
339 layer(
340 TestLive({
341 baseConfigProvider: testConfigProvider,
342 connectedAccountsData: {
343 items: [connectedAccountWithCredentialFields],
344 },
345 fixture: 'global-test-user-id',
346 })
347 )('[Given] raw credential fields [Then] --list emits only schema-approved fields', it => {
348 it.effect('strips state and data at the response boundary', () =>
349 Effect.gen(function* () {
350 yield* cli(['link', 'gmail', '--list']);
351
352 const lines = yield* MockConsole.getLines({ stripAnsi: true });
353 const output = lines.join('\n');
354 expect(output).not.toContain('must-not-leak');
355 expect(output).not.toContain('access_token');
356 expect(output).not.toContain('refresh_token');
357 expect(parseLastLine(lines)).toStrictEqual({
358 toolkit: 'gmail',
359 total: 1,
360 items: [makeConnectedAccount()],
361 });
362 })
363 );
364 });
365
366 layer(
367 TestLive({
368 baseConfigProvider: testConfigProvider,
369 connectedAccountsData: makeConnectedAccountsData(),
370 fixture: 'global-test-user-id',
371 })
372 )('[Given] composio link [Then] works for consumer toolkit linking', it => {
373 it.effect('root link works for consumer toolkit linking only', () =>
374 Effect.gen(function* () {
375 yield* cli(['link', 'gmail']);
376 const lines = yield* MockConsole.getLines({ stripAnsi: true });
377
378 expect(parseLastLine(lines)).toMatchObject({
379 status: 'success',
380 connected_account_id: 'con_test_link',
381 });
382 })
383 );
384 });
385
386 const sessionInfoScopes: MockRequestScope[] = [];
387 layer(
388 TestLive({
389 baseConfigProvider: testConfigProvider,
390 connectedAccountsData: makeConnectedAccountsData(),
391 fixture: 'global-test-user-id',
392 toolRouter: {
393 link: () =>
394 Effect.fail(
395 new BadRequestError({
396 message: `400 ${JSON.stringify({ error: noManagedAuth })}`,
397 method: 'POST',
398 url: 'https://mock.invalid/api/v3.1/tool_router/session/{session_id}/link',
399 status: 400,
400 requestId: undefined,
401 details: noManagedAuth,
402 body: { error: noManagedAuth },
403 })
404 ),
405 },
406 accountData: {
407 sessionInfo: scope => {
408 sessionInfoScopes.push(scope);
409 return makeSessionInfo({
410 orgId: 'org_selected',
411 orgName: 'Selected Org',
412 orgMemberId: 'member_selected',
413 projectId: 'project_id_selected',
414 projectNanoId: 'project_selected',
415 projectName: 'Selected Project',
416 });
417 },
418 },
419 })
420 )('[Given] unmanaged auth after an org switch [Then] resolves the selected membership', it => {
421 it.effect('passes the active org to session info before linking analytics identity', () =>
422 Effect.gen(function* () {
423 const userContext = yield* ComposioUserContext;
424 yield* userContext.login('test_api_key', 'org_selected', 'consumer-user-org_selected');
425
426 yield* cli(['link', 'gmail', '--no-browser']);
427
428 expect(sessionInfoScopes.map(scope => scope.orgId)).toEqual(['org_selected']);
429 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
430 expect(output).toContain('/Selected%20Org/~/connect/apps/gmail?open=true');
431 })
432 );
433 });
434
435 layer(
436 TestLive({
437 baseConfigProvider: testConfigProvider,
438 connectedAccountsData: makeConnectedAccountsData(),
439 fixture: 'global-test-user-id',
440 })
441 )('[Given] --no-wait [Then] outputs valid JSON parseable by jq', it => {
442 it.effect('prints JSON with status pending, connected_account_id, redirect_url', () =>
443 Effect.gen(function* () {
444 yield* cli(['link', 'gmail', '--no-wait']);
445 const lines = yield* MockConsole.getLines({ stripAnsi: true });
446
447 expect(parseLastLine(lines)).toMatchObject({
448 status: 'pending',
449 connected_account_id: 'con_test_link',
450 toolkit: 'gmail',
451 });
452 })
453 );
454 });
455
456 layer(
457 TestLive({
458 baseConfigProvider: testConfigProvider,
459 connectedAccountsData: makeConnectedAccountsData(),
460 fixture: 'global-test-user-id',
461 toolRouter: {
462 link: () =>
463 Effect.succeed({
464 connected_account_id: '',
465 link_token: 'lt_test_token',
466 redirect_url: '',
467 account_type: 'PRIVATE' as const,
468 }),
469 },
470 })
471 )('[Given] auth-config link returns an incomplete response [Then] reports it and exits 1', it => {
472 it.effect('reports the incomplete response instead of waiting with empty values', () =>
473 Effect.gen(function* () {
474 // Redirected streams, as under a script: only plain stderr lines and stdout data show.
475 const terminal = redirectedTerminalUI();
476 const exit = yield* Effect.exit(
477 cli(['link', 'gmail']).pipe(Effect.provide(terminal.layer))
478 );
479
480 expect(terminal.stderr()).toBe(
481 'The link response from the API is missing `connected_account_id` or `redirect_url`.\n'
482 );
483 expect(terminal.stdout()).toBe('');
484 expect(exitCodeOf(exit)).toBe(1);
485 })
486 );
487 });
488
489 layer(
490 TestLive({
491 baseConfigProvider: testConfigProvider,
492 connectedAccountsData: makeConnectedAccountsData(),
493 fixture: 'global-test-user-id',
494 })
495 )('[Given] default (wait) [Then] waits for ACTIVE and outputs success JSON for jq', it => {
496 it.effect(
497 'prints JSON with status success, message, connected_account_id, toolkit, redirect_url',
498 () =>
499 Effect.gen(function* () {
500 yield* cli(['link', 'gmail']);
501 const lines = yield* MockConsole.getLines({ stripAnsi: true });
502
503 expect(parseLastLine(lines)).toMatchObject({
504 status: 'success',
505 connected_account_id: 'con_test_link',
506 toolkit: 'gmail',
507 });
508 })
509 );
510 });
511
512 layer(
513 TestLive({
514 baseConfigProvider: testConfigProvider,
515 connectedAccountsData: makeConnectedAccountsData({
516 items: [makeConnectedAccount({ status: 'INITIATED' })],
517 }),
518 cliUserConfig: { experimentalFeatures: { multi_account: false } },
519 toolRouter: {
520 create: toolRouterCreateSpy,
521 link: toolRouterLinkSpy,
522 },
523 fixture: 'global-test-user-id',
524 })
525 )('[Given] --alias [Then] it passes alias during link creation', it => {
526 it.effect('sends alias to the tool router link API instead of patching afterward', () =>
527 Effect.gen(function* () {
528 yield* cli(['link', 'gmail', '--alias', 'work', '--no-wait']);
529 expect(toolRouterCreateSpy).toHaveBeenCalledWith(
530 expect.objectContaining({
531 connected_accounts: undefined,
532 manage_connections: { enable: true },
533 multi_account: {
534 enable: true,
535 max_accounts_per_toolkit: undefined,
536 require_explicit_selection: undefined,
537 },
538 })
539 );
540 expect(toolRouterLinkSpy).toHaveBeenCalledWith('trs_test_session', {
541 toolkit: 'gmail',
542 alias: 'work',
543 });
544 })
545 );
546 });
547
548 layer(
549 TestLive({
550 baseConfigProvider: testConfigProvider,
551 connectedAccountsData: makeConnectedAccountsData(),
552 toolRouter: {
553 link: () =>
554 Effect.succeed({
555 connected_account_id: 'con_second_link',
556 link_token: 'lt_test_token',
557 redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
558 account_type: 'PRIVATE' as const,
559 }),
560 },
561 fixture: 'global-test-user-id',
562 })
563 )(
564 '[Given] an existing active account and no --alias [Then] link blocks the second connected account',
565 it => {
566 it.effect('fails locally and tells the user to pass --alias', () =>
567 Effect.gen(function* () {
568 const exit = yield* Effect.exit(cli(['link', 'gmail']));
569 const lines = yield* MockConsole.getLines({ stripAnsi: true });
570 const output = lines.join('\n');
571
572 expect(exitCodeOf(exit)).toBe(1);
573 expect(output).toContain('Pass --alias to create another one');
574 expect(output).toContain('con_test_link');
575 expect(output).not.toContain('"status"');
576 })
577 );
578 }
579 );
580
581 layer(
582 TestLive({
583 baseConfigProvider: testConfigProvider,
584 connectedAccountsData: makeConnectedAccountsData({
585 items: [makeConnectedAccount({ alias: 'work' })],
586 }),
587 toolRouter: { create: toolRouterCreateSpy, link: toolRouterLinkSpy },
588 fixture: 'global-test-user-id',
589 })
590 )('[Given] a duplicate alias [Then] link explains how to use the existing account', it => {
591 it.effect('detects the exact existing alias before creating a link', () =>
592 Effect.gen(function* () {
593 const exit = yield* Effect.exit(cli(['link', 'gmail', '--alias', 'work']));
594 const lines = yield* MockConsole.getLines({ stripAnsi: true });
595 const output = lines.join('\n');
596
597 expect(exitCodeOf(exit)).toBe(1);
598 expect(output).toContain('Alias "work" is already in use');
599 expect(output).toContain('composio execute <TOOL_SLUG> --account work');
600 expect(output).toContain('composio connections list --toolkit gmail');
601 expect(toolRouterCreateSpy).not.toHaveBeenCalled();
602 expect(toolRouterLinkSpy).not.toHaveBeenCalled();
603 })
604 );
605 });
606 });
607
608 describe('CLI: link --help on each tree', () => {
609 /** What `--help` printed on stdout, and how it exited. */
610 const help = (args: ReadonlyArray<string>) =>
611 Effect.gen(function* () {
612 const exitCode = exitCodeOf(yield* Effect.exit(cli([...args, '--help'])));
613 const stdout = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' });
614 return { exitCode, stdout: stdout.join('\n') };
615 }).pipe(Effect.provide(TestLive()));
616
617 const examples = (stdout: string) =>
618 (stdout.split(/^EXAMPLES$/m)[1] ?? '')
619 .split('\n')
620 .map(line => line.trim())
621 .filter(line => line !== '');
622
623 it.effect('[Given] composio link --help [Then] its examples are root `composio link`', () =>
624 Effect.gen(function* () {
625 const { exitCode, stdout } = yield* help(['link']);
626 expect(exitCode).toBe(0);
627 expect(examples(stdout)).toEqual([
628 'composio link github',
629 'composio link gmail --alias work',
630 'composio link github --list',
631 ]);
632 })
633 );
634
635 it.effect(
636 '[Given] composio dev connected-accounts link --help [Then] its examples stay on the dev tree',
637 () =>
638 Effect.gen(function* () {
639 const { exitCode, stdout } = yield* help(['dev', 'connected-accounts', 'link']);
640 expect(exitCode).toBe(0);
641 expect(examples(stdout)).toEqual([
642 'composio dev connected-accounts link github',
643 'composio dev connected-accounts link gmail --alias work',
644 'composio dev connected-accounts link github --list',
645 ]);
646 // The page says who it acts as, and offers the dev group's user and project flags.
647 expect(stdout).toContain('acts as a user of a developer project');
648 expect(stdout).toContain('--user-id');
649 expect(stdout).toContain('--project-name');
650 })
651 );
652 });