@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, 04:45 UTC

next
ts 716 lines 27.1 KB
Raw
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 import { Console, DateTime, Effect, Exit, Fiber, Option } from 'effect';
4 import { TestClock } from 'effect/testing';
5 import path from 'node:path';
6 import * as FileSystem from 'effect/FileSystem';
7 import { AUTHORIZATION_TIMEOUT_SECONDS } from 'src/effects/authorization-poll';
8 import {
9 invalidTimeoutMessage,
10 TIMEOUT_WITHOUT_POLL_MESSAGE,
11 } from 'src/commands/login/login.format';
12 import { cli, cliExit, MockConsole, TestLive } from 'test/__utils__';
13 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
14 import * as constants from 'src/constants';
15 import { setupCacheDir } from 'src/effects/setup-cache-dir';
16 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
17 import { writeStoredAgentIdentity } from 'src/services/agents';
18 import { ComposioUserContext } from 'src/services/user-context';
19 import { InternalServerError } from '@composio/client/effect';
20 import { ComposioSessionRepository } from 'src/services/composio-clients';
21 import { makeSessionInfo } from 'test/__utils__/models/account';
22 import type { MockAccountRequest } from 'test/__utils__/services/test-layer';
23 import { routeRequests, type StubRoute } from 'test/__utils__/services/stub-composio-client';
24
25 vi.mock('open', () => ({
26 default: vi.fn(async () => undefined),
27 }));
28
29 const analyticsMocks = vi.hoisted(() => ({
30 linkCalls: [] as Array<{ apolloUserId: string; loggedInAtLinkTime: boolean }>,
31 }));
32
33 // Records each identity link and whether the credential had already been
34 // stored via ctx.login at call time — the link-after-persistence ordering.
35 vi.mock('src/analytics/dispatch', async importOriginal => {
36 const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
37 const { Effect } = await import('effect');
38 const { ComposioUserContext } = await import('src/services/user-context');
39 return {
40 ...actual,
41 analyticsIdentityLinkingEnabled: Effect.succeed(true),
42 linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
43 Effect.map(ComposioUserContext, ctx => {
44 analyticsMocks.linkCalls.push({ apolloUserId, loggedInAtLinkTime: ctx.isLoggedIn() });
45 })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
46 };
47 });
48
49 const mockFetchResponse = (body: unknown, status = 200) =>
50 new Response(JSON.stringify(body), {
51 status,
52 headers: { 'Content-Type': 'application/json' },
53 });
54
55 const requestUrl = (requestInput: RequestInfo | URL): string => new Request(requestInput).url;
56
57 const WHOAMI = '/api/whoami';
58
59 /** Answers agents API requests through `routes`, and every other request with `{}`. */
60 const stubFetch = (routes: ReadonlyArray<StubRoute>) =>
61 vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
62 const request = new Request(requestInput, init);
63 const url = new URL(request.url);
64 return routeRequests(routes, () => mockFetchResponse({}))({
65 method: request.method,
66 path: `${url.pathname}${url.search}`,
67 body: undefined,
68 });
69 });
70
71 const storedAgentIdentity = {
72 status: 'READY',
73 slug: 'test-agent',
74 email: 'test-agent@agent.composio.ai',
75 composio_agent_key: 'cak_test_agent',
76 composio: {
77 member_id: 'mem_agent',
78 org_id: 'org_agent',
79 project_id: 'proj_agent',
80 user_api_key: 'uak_agent',
81 },
82 };
83
84 const terminalUIWithTtyState = (state: {
85 readonly stdin: boolean;
86 readonly stdout: boolean;
87 readonly stderr: boolean;
88 }) =>
89 TerminalUI.of({
90 ...terminalUITestImpl,
91 capabilities: Effect.succeed(
92 getTerminalCapabilities({
93 stdin: { isTTY: state.stdin },
94 stdout: { isTTY: state.stdout },
95 stderr: { isTTY: state.stderr },
96 })
97 ),
98 });
99
100 const headlessStdinUI = terminalUIWithTtyState({
101 stdin: false,
102 stdout: false,
103 stderr: false,
104 });
105
106 /**
107 * Runs an effect whose context is already provided on the test clock, with a pump fiber that
108 * keeps advancing the clock while it runs: every pump iteration lets the effect reach its next
109 * scheduled sleep, then moves the clock past it. Answers what the effect answered once done.
110 */
111 const runWithAdvancingClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
112 Effect.gen(function* () {
113 const run = yield* Effect.forkChild(effect);
114 const pump = yield* Effect.forkChild(
115 Effect.forever(Effect.andThen(Effect.yieldNow, () => TestClock.adjust('10 seconds')))
116 );
117 const result = yield* Fiber.join(run);
118 yield* Fiber.interrupt(pump);
119 return result;
120 });
121
122 // ── Tests ────────────────────────────────────────────────────────────────────
123
124 describe('CLI: composio login', () => {
125 afterEach(() => {
126 vi.restoreAllMocks();
127 analyticsMocks.linkCalls.length = 0;
128 });
129
130 describe('login --help', () => {
131 layer(TestLive())(it => {
132 it.effect('[Then] shows browser, session, direct-login flags and no legacy --api-key', () =>
133 Effect.gen(function* () {
134 yield* cli(['login', '--help']);
135 const lines = yield* MockConsole.getLines();
136 const output = lines.join('\n');
137 expect(output).toContain('--no-browser');
138 expect(output).toContain('--no-wait');
139 expect(output).toContain('--poll');
140 expect(output).toContain('--key');
141 expect(output).toContain('--user-api-key');
142 expect(output).toContain('--org');
143 expect(output).toContain('--yes');
144 expect(output).toContain('-y');
145 expect(output).toContain('--timeout');
146 expect(output).not.toMatch(/(^|\s)--api-key(?:\s|$)/);
147 })
148 );
149 });
150 });
151
152 // Business-level validation (only knowable after parsing) raises `CommandInputError`,
153 // not a `CliError.InvalidValue`; see `src/commands/errors.ts`.
154 layer(TestLive())(it => {
155 it.effect('[Given] conflicting login options [Then] fails with a CLI validation error', () =>
156 Effect.gen(function* () {
157 const error = yield* cli([
158 'login',
159 '--key',
160 'cli_session_key',
161 '--user-api-key',
162 'uak_direct_key',
163 ]).pipe(Effect.flip);
164
165 expect(error).toMatchObject({
166 message: 'Use either `--key` or `--user-api-key`, not both.',
167 });
168 })
169 );
170 });
171
172 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
173 it.effect('[When] stdin is non-interactive [Then] login prints agent instructions', () =>
174 Effect.gen(function* () {
175 yield* cli(['login']);
176
177 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
178 expect(output).toContain('Open this URL in your browser to log in:');
179 expect(output).toContain(
180 'https://dashboard.composio.dev/?cliKey=te00st11-d0c4-4efa-8117-c638886063e0'
181 );
182 expect(output).toContain('Then run this command to complete login:');
183 expect(output).toContain('composio login --poll');
184 expect(output).toContain('hint: For agents:');
185 // The hint bounds the poll itself: one ten-minute call is longer than any agent turn.
186 expect(output).toContain('composio login --poll --timeout 120');
187 expect(output).toContain('the pending login lives 10 minutes');
188 expect(output).toContain('it prints the URL again');
189 expect(output).not.toContain('Expires at:');
190 expect(output).toContain('Do not ask the user whether to poll');
191 expect(output).toContain('hint: For unattended agents:');
192 expect(output).toContain('composio login --agent');
193
194 const fs = yield* FileSystem.FileSystem;
195 const cacheDir = yield* setupCacheDir;
196 const pendingLoginRaw = yield* fs.readFileString(
197 path.join(cacheDir, 'pending-login-session.json'),
198 'utf8'
199 );
200 const pendingLogin = JSON.parse(pendingLoginRaw) as Record<string, unknown>;
201 expect(pendingLogin.key).toBe('te00st11-d0c4-4efa-8117-c638886063e0');
202 expect(
203 (yield* fs.stat(path.join(cacheDir, 'pending-login-session.json'))).mode & 0o777
204 ).toBe(0o600);
205
206 expect(output).not.toContain('-- composio login --');
207 expect(output).not.toContain('Please login using the following URL');
208 expect(output).not.toContain('Login URL');
209 expect(output).not.toContain('Login instructions');
210 expect(output).not.toContain('Installed composio-cli skill');
211 })
212 );
213 });
214
215 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
216 it.effect(
217 '[Given] a stored READY agent identity [When] login runs headlessly [Then] completes agent login unattended',
218 () =>
219 Effect.gen(function* () {
220 yield* writeStoredAgentIdentity(storedAgentIdentity);
221 stubFetch([
222 { method: 'GET', path: WHOAMI, respond: () => mockFetchResponse(storedAgentIdentity) },
223 ]);
224
225 yield* cli(['login']);
226
227 const ctx = yield* ComposioUserContext;
228 expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
229 expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
230
231 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
232 expect(output).toContain('"account_type":"agent"');
233 expect(output).toContain('"logged_in":true');
234 expect(output).not.toContain('Open this URL in your browser to log in:');
235
236 const fs = yield* FileSystem.FileSystem;
237 const cacheDir = yield* setupCacheDir;
238 const pendingExists = yield* fs.exists(path.join(cacheDir, 'pending-login-session.json'));
239 expect(pendingExists).toBe(false);
240 })
241 );
242 });
243
244 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
245 it.effect(
246 '[Given] a stored READY agent identity the API rejects [When] login runs headlessly [Then] does not reuse the revoked identity',
247 () =>
248 Effect.gen(function* () {
249 yield* writeStoredAgentIdentity(storedAgentIdentity);
250 stubFetch([
251 {
252 method: 'GET',
253 path: WHOAMI,
254 respond: () => mockFetchResponse({ message: 'Invalid agent key' }, 401),
255 },
256 ]);
257
258 yield* cli(['login']);
259
260 const ctx = yield* ComposioUserContext;
261 expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
262
263 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
264 expect(output).not.toContain('"logged_in":true');
265 expect(output).toContain('Open this URL in your browser to log in:');
266 })
267 );
268 });
269
270 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
271 it.effect(
272 '[Given] a stored READY agent identity and an unreachable agents API [When] login runs headlessly [Then] still reuses the on-disk identity',
273 () =>
274 Effect.gen(function* () {
275 yield* writeStoredAgentIdentity(storedAgentIdentity);
276 stubFetch([
277 {
278 method: 'GET',
279 path: WHOAMI,
280 respond: () => {
281 throw new Error('network unreachable');
282 },
283 },
284 ]);
285
286 yield* cli(['login']);
287
288 const ctx = yield* ComposioUserContext;
289 expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
290 expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
291 })
292 );
293 });
294
295 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
296 it.effect(
297 '[Given] a stored PENDING agent identity [When] login runs headlessly [Then] prints instructions without logging in',
298 () =>
299 Effect.gen(function* () {
300 yield* writeStoredAgentIdentity({ ...storedAgentIdentity, status: 'PENDING' });
301 stubFetch([
302 {
303 method: 'GET',
304 path: WHOAMI,
305 respond: () => mockFetchResponse({ ...storedAgentIdentity, status: 'PENDING' }),
306 },
307 ]);
308
309 yield* cli(['login']);
310
311 const ctx = yield* ComposioUserContext;
312 expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
313
314 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
315 expect(output).toContain('Open this URL in your browser to log in:');
316 expect(output).toContain('composio login --agent');
317 })
318 );
319 });
320
321 layer(TestLive({ terminalUI: headlessStdinUI }))(it => {
322 it.effect(
323 '[Given] no stored agent identity [When] login runs headlessly [Then] never auto-signs-up an agent',
324 () =>
325 Effect.gen(function* () {
326 const requestedUrls: string[] = [];
327 vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
328 requestedUrls.push(requestUrl(requestInput));
329 return mockFetchResponse({});
330 });
331
332 yield* cli(['login']);
333
334 expect(requestedUrls.filter(url => url.includes('/api/signup'))).toEqual([]);
335
336 const ctx = yield* ComposioUserContext;
337 expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
338
339 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
340 expect(output).toContain('Open this URL in your browser to log in:');
341 })
342 );
343 });
344
345 describe('login with stdout piped', () => {
346 const pipedStdoutUI = TerminalUI.of({
347 ...terminalUIWithTtyState({ stdin: true, stdout: false, stderr: true }),
348 useMakeSpinner: (message, _use) =>
349 Console.log(`[spinner] ${message}`).pipe(
350 Effect.andThen(Effect.die(new Error('test: interactive poll loop entered')))
351 ),
352 });
353
354 layer(TestLive({ terminalUI: pipedStdoutUI }))(it => {
355 it.effect(
356 '[Given] a stored agent [When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive',
357 () =>
358 Effect.gen(function* () {
359 yield* writeStoredAgentIdentity(storedAgentIdentity);
360 const requestedUrls: string[] = [];
361 vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
362 requestedUrls.push(requestUrl(requestInput));
363 return mockFetchResponse(storedAgentIdentity);
364 });
365
366 const exit = yield* Effect.exit(cli(['login']));
367
368 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
369 expect(output).toContain('[spinner] Waiting for login...');
370 expect(output).toContain('Redirecting you to the login page');
371 expect(output).not.toContain('Open this URL in your browser to log in:');
372 expect(output).not.toContain('hint: For agents:');
373 expect(output).not.toContain('Then run this command to complete login:');
374 expect(requestedUrls).not.toContainEqual(expect.stringContaining('/api/whoami'));
375 expect(Exit.isFailure(exit)).toBe(true);
376 })
377 );
378 });
379 });
380
381 layer(TestLive())(it => {
382 it.effect.each([
383 { name: 'names no whole number', timeout: 'soon' },
384 { name: 'names zero', timeout: '0' },
385 { name: 'outlives the pending login', timeout: `${AUTHORIZATION_TIMEOUT_SECONDS + 1}` },
386 ])('[Given] --poll --timeout that $name [Then] fails as a usage error', ({ timeout }) =>
387 Effect.gen(function* () {
388 const error = yield* cli(['login', '--poll', '--timeout', timeout]).pipe(Effect.flip);
389
390 expect(error).toMatchObject({
391 _tag: 'commands/CommandInputError',
392 command: 'login',
393 message: invalidTimeoutMessage(AUTHORIZATION_TIMEOUT_SECONDS),
394 option: '--timeout',
395 });
396 })
397 );
398
399 it.effect('[Given] --timeout without --poll [Then] fails as a usage error', () =>
400 Effect.gen(function* () {
401 const error = yield* cli(['login', '--timeout', '60']).pipe(Effect.flip);
402
403 expect(error).toMatchObject({
404 _tag: 'commands/CommandInputError',
405 command: 'login',
406 message: TIMEOUT_WITHOUT_POLL_MESSAGE,
407 option: '--timeout',
408 });
409 })
410 );
411 });
412
413 layer(TestLive())(it => {
414 it.effect(
415 '[Given] a cached login nobody completes [When] the --timeout runs out [Then] exits 1 with the URL and the command to run again, storing nothing',
416 () =>
417 Effect.gen(function* () {
418 const fs = yield* FileSystem.FileSystem;
419 const cacheDir = yield* setupCacheDir;
420 const now = yield* DateTime.now;
421 const expiresAt = DateTime.add(now, { minutes: 10 });
422 const sessionId = 'pending-poll-session';
423 const pendingPath = path.join(cacheDir, 'pending-login-session.json');
424 const pendingLogin = `${JSON.stringify(
425 {
426 key: sessionId,
427 loginUrl: `https://dashboard.composio.dev/?cliKey=${sessionId}`,
428 expiresAt: DateTime.formatIso(expiresAt),
429 cachedAt: new Date().toISOString(),
430 },
431 null,
432 2
433 )}\n`;
434 yield* fs.writeFileString(pendingPath, pendingLogin);
435
436 yield* cliExit(['login', '--poll', '--timeout', '30', '--no-skill-install']).pipe(
437 Effect.provideService(
438 ComposioSessionRepository,
439 ComposioSessionRepository.of({
440 createSession: () => Effect.die(new Error('unexpected session creation')),
441 getSession: () =>
442 Effect.succeed({
443 id: sessionId,
444 code: '001122',
445 expiresAt,
446 status: 'pending' as const,
447 api_key: null,
448 }),
449 getRealtimeCredentials: () =>
450 Effect.die(new Error('unexpected realtime credentials')),
451 authRealtimeChannel: () => Effect.die(new Error('unexpected realtime auth')),
452 })
453 ),
454 runWithAdvancingClock,
455 Effect.flatMap(({ exitCode }) =>
456 Effect.gen(function* () {
457 expect(exitCode).toBe(1);
458
459 const errors = (yield* MockConsole.getLines({
460 stream: 'stderr',
461 stripAnsi: true,
462 })).join('\n');
463 expect(errors).toContain(
464 "Login still pending: session status is 'pending', waiting for 'linked'."
465 );
466 expect(errors).toContain(`https://dashboard.composio.dev/?cliKey=${sessionId}`);
467 expect(errors).toContain('composio login --poll --timeout 30');
468
469 const ctx = yield* ComposioUserContext;
470 expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
471 expect(yield* fs.readFileString(pendingPath, 'utf8')).toBe(pendingLogin);
472 })
473 )
474 );
475 })
476 );
477 });
478
479 layer(TestLive())(it => {
480 it.effect(
481 '[Given] an unreadable pending login cache [Then] poll reports the read failure, not a decode failure',
482 () =>
483 Effect.gen(function* () {
484 const fs = yield* FileSystem.FileSystem;
485 const cacheDir = yield* setupCacheDir;
486 // A directory at the cache path passes the exists check but fails the read.
487 yield* fs.makeDirectory(path.join(cacheDir, 'pending-login-session.json'), {
488 recursive: true,
489 });
490
491 const error = yield* cli(['login', '--poll']).pipe(Effect.flip);
492
493 expect(error).toMatchObject({
494 _tag: 'commands/PendingLoginError',
495 reason: 'io',
496 message: 'Failed to read pending login cache',
497 });
498 })
499 );
500 });
501
502 const stopBeforeSessionPollUI = TerminalUI.of({
503 ...headlessStdinUI,
504 useMakeSpinner: () => Effect.die(new Error('test: stop before session poll')),
505 });
506
507 layer(TestLive({ terminalUI: stopBeforeSessionPollUI }))(it => {
508 it.effect('repairs permissions on an existing pending login session before reading it', () =>
509 Effect.gen(function* () {
510 const fs = yield* FileSystem.FileSystem;
511 const cacheDir = yield* setupCacheDir;
512 const pendingPath = path.join(cacheDir, 'pending-login-session.json');
513 const cachedAt = new Date().toISOString();
514 const pendingLogin = `${JSON.stringify(
515 {
516 key: 'legacy-session-id',
517 loginUrl: 'https://dashboard.composio.dev/?cliKey=legacy-session-id',
518 expiresAt: cachedAt,
519 cachedAt,
520 },
521 null,
522 2
523 )}\n`;
524 yield* fs.writeFileString(pendingPath, pendingLogin);
525 yield* fs.chmod(pendingPath, 0o644);
526 expect((yield* fs.stat(pendingPath)).mode & 0o777).toBe(0o644);
527
528 const exit = yield* Effect.exit(cli(['login', '--poll']));
529
530 expect(Exit.isFailure(exit)).toBe(true);
531 expect(yield* fs.readFileString(pendingPath, 'utf8')).toBe(pendingLogin);
532 expect((yield* fs.stat(pendingPath)).mode & 0o777).toBe(0o600);
533 })
534 );
535 });
536
537 const directLoginRequests: MockAccountRequest[] = [];
538 layer(
539 TestLive({
540 accountData: {
541 organizations: [
542 { id: 'org_default', name: 'Example Org' },
543 { id: 'org_selected', name: 'Selected Org' },
544 ],
545 sessionInfo: scope =>
546 scope.orgId === undefined
547 ? makeSessionInfo({
548 orgId: 'org_default',
549 orgMemberId: 'member_default',
550 })
551 : makeSessionInfo({
552 orgId: scope.orgId,
553 orgName: 'Selected Org',
554 orgMemberId: 'member_selected',
555 }),
556 onRequest: request => directLoginRequests.push(request),
557 },
558 })
559 )(it => {
560 it.effect('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
561 Effect.gen(function* () {
562 yield* cli([
563 'login',
564 '--user-api-key',
565 'uak_direct_key',
566 '--org',
567 'org_selected',
568 '--no-skill-install',
569 ]);
570
571 const fs = yield* FileSystem.FileSystem;
572 const cacheDir = yield* setupCacheDir;
573 const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
574 const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
575 const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
576 // Default `security: "auto"` keeps the API key in plaintext
577 // `user_data.json` for backwards compatibility — same as
578 // every prior CLI release. Users opt into keyring storage
579 // by setting `security: "keychain-subprocess"` (or
580 // `"keychain"` for the experimental FFI path) in
581 // `~/.composio/config.json`.
582 expect(userConfig.api_key).toBe('uak_direct_key');
583 expect(userConfig.org_id).toBe('org_selected');
584 expect(
585 directLoginRequests
586 .filter(request => request.operation === 'org.list')
587 .map(request => request.scope.userApiKey)
588 ).toEqual(['uak_direct_key']);
589 expect((yield* fs.stat(userConfigPath)).mode & 0o777).toBe(0o600);
590
591 // ComposioUserContext also exposes the resolved key in-memory
592 // for subsequent API calls in this process.
593 const ctx = yield* ComposioUserContext;
594 expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_direct_key');
595
596 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
597 expect(output).toContain('Logged in as cli@example.com in "Selected Org"');
598
599 // The analytics identity is linked exactly once, and only after the
600 // credential was stored via ctx.login, using the selected org's
601 // membership rather than the API key's home-org membership.
602 expect(analyticsMocks.linkCalls).toEqual([
603 { apolloUserId: 'member_selected', loggedInAtLinkTime: true },
604 ]);
605 })
606 );
607 });
608
609 layer(
610 TestLive({
611 accountData: {
612 organizations: [
613 { id: 'org_selected', name: 'Selected Org' },
614 { id: 'org_home', name: 'Home Org' },
615 ],
616 sessionInfo: scope => {
617 if (scope.projectId !== undefined) {
618 throw new InternalServerError({
619 message: 'Selected-org enrichment failed',
620 method: 'GET',
621 url: 'https://mock.invalid/api/v3.1/auth/session/info',
622 status: 500,
623 requestId: undefined,
624 details: undefined,
625 body: { message: 'Selected-org enrichment failed' },
626 });
627 }
628 return scope.orgId === undefined
629 ? makeSessionInfo({
630 orgId: 'org_home',
631 orgName: 'Home Org',
632 orgMemberId: 'member_home',
633 email: 'poll@example.com',
634 name: 'Poll User',
635 })
636 : makeSessionInfo({
637 orgId: scope.orgId,
638 orgName: 'Selected Org',
639 orgMemberId: 'member_selected',
640 email: 'poll@example.com',
641 name: 'Poll User',
642 });
643 },
644 },
645 })
646 )(it => {
647 it.effect(
648 '[Given] selected-org enrichment fails [When] completing --poll [Then] links the selected org membership',
649 () =>
650 Effect.gen(function* () {
651 const fs = yield* FileSystem.FileSystem;
652 const cacheDir = yield* setupCacheDir;
653 const now = yield* DateTime.now;
654 const expiresAt = DateTime.add(now, { minutes: 10 });
655 const sessionId = 'poll-session-id';
656 const sessionRepository = ComposioSessionRepository.of({
657 createSession: () =>
658 Effect.succeed({
659 id: sessionId,
660 code: '001122',
661 expiresAt,
662 status: 'pending',
663 }),
664 getSession: () =>
665 Effect.succeed({
666 id: sessionId,
667 code: '001122',
668 expiresAt,
669 status: 'linked',
670 api_key: 'uak_poll_key',
671 account: {
672 id: 'account_id',
673 name: 'Poll User',
674 email: 'poll@example.com',
675 },
676 }),
677 getRealtimeCredentials: () =>
678 Effect.succeed({
679 project_id: 'proj_test',
680 pusher_key: 'pusher_test_key',
681 pusher_cluster: 'mt1',
682 }),
683 authRealtimeChannel: () =>
684 Effect.succeed({
685 auth: 'mock:auth',
686 channel_data: undefined,
687 }),
688 });
689
690 yield* fs.writeFileString(
691 path.join(cacheDir, 'pending-login-session.json'),
692 `${JSON.stringify(
693 {
694 key: sessionId,
695 loginUrl: `https://dashboard.composio.dev/?cliKey=${sessionId}`,
696 expiresAt: DateTime.formatIso(expiresAt),
697 cachedAt: new Date().toISOString(),
698 },
699 null,
700 2
701 )}\n`
702 );
703
704 yield* cli(['login', '--poll', '--no-skill-install']).pipe(
705 Effect.provideService(ComposioSessionRepository, sessionRepository)
706 );
707
708 const ctx = yield* ComposioUserContext;
709 expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_selected');
710 expect(analyticsMocks.linkCalls).toEqual([
711 { apolloUserId: 'member_selected', loggedInAtLinkTime: true },
712 ]);
713 })
714 );
715 });
716 });