8
import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
9
import * as BunPath from '@effect/platform-bun/BunPath';
10
import { describe, expect, it } from '@effect/vitest';
11
-import { ConfigProvider, Console, DateTime, Effect, Layer, Option } from 'effect';
11
+import { ConfigProvider, Console, DateTime, Effect, Fiber, Layer, Option } from 'effect';
12
+import { TestClock } from 'effect/testing';
13
import { HttpClient } from 'effect/http';
14
import * as tempy from 'tempy';
15
import {
24
AGENT_WITH_OTHER_FLAGS_MESSAGE,
25
ALREADY_LOGGED_IN_MESSAGE,
26
INVALID_ORGANIZATION_MESSAGE,
27
+ invalidTimeoutMessage,
28
KEY_AND_USER_API_KEY_MESSAGE,
29
ORG_WITHOUT_USER_API_KEY_MESSAGE,
30
POLL_WITH_OTHER_FLAGS_MESSAGE,
31
SESSION_NOT_FOUND_MESSAGE,
32
SESSION_NOT_LINKED_MESSAGE,
33
+ TIMEOUT_WITHOUT_POLL_MESSAGE,
34
USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE,
35
} from 'src/commands/login/login.format';
36
+import { AUTHORIZATION_TIMEOUT_SECONDS } from 'src/effects/authorization-poll';
37
import type { RetrievedSession } from 'src/models/session';
38
import type { OrganizationSummary } from 'src/services/composio-account';
39
import { ComposioClientSingleton, ComposioSessionRepository } from 'src/services/composio-clients';
102
const params = (overrides: Partial<LoginParams> = {}): LoginParams => ({
103
noBrowser: false,
104
poll: false,
105
+ timeout: Option.none(),
106
noWait: false,
107
key: Option.none(),
108
userApiKey: Option.none(),
163
}> = [];
164
const outputs: Array<string> = [];
165
const createdSessions: Array<string> = [];
166
+ /** How many times a wait checked the session, which shows how long it waited. */
167
+ const sessionLookups: Array<string> = [];
168
const pending = PendingLoginSessionTest(fixture.pending);
169
const apiKey = fixture.apiKey ?? Option.none();
170
230
status: 'pending' as const,
231
};
232
}),
226
- getSession: () => fixture.session ?? Effect.succeed(linkedSession('session-key')),
233
+ getSession: ({ id }) =>
234
+ Effect.suspend(() => {
235
+ sessionLookups.push(id);
236
+ return fixture.session ?? Effect.succeed(linkedSession('session-key'));
237
+ }),
238
getRealtimeCredentials: () => Effect.die(new Error('unexpected realtime credentials')),
239
authRealtimeChannel: () => Effect.die(new Error('unexpected realtime auth')),
240
})
274
),
275
ConfigProvider.layer(hostOnlyEnvConfigProvider)
276
);
266
- return { layer, logins, outputs, createdSessions, pending };
277
+ return { layer, logins, outputs, createdSessions, sessionLookups, pending };
278
};
279
280
const stderr = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
281
282
+/**
283
+ * Runs an effect whose context is already provided on the test clock, with a pump fiber that
284
+ * keeps advancing the clock while it runs: every pump iteration lets the effect reach its next
285
+ * scheduled sleep, then moves the clock past it. Answers what the effect answered once done.
286
+ */
287
+const runWithAdvancingClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
288
+ Effect.gen(function* () {
289
+ const run = yield* Effect.forkChild(effect);
290
+ const pump = yield* Effect.forkChild(
291
+ Effect.forever(Effect.andThen(Effect.yieldNow, () => TestClock.adjust('10 seconds')))
292
+ );
293
+ const result = yield* Fiber.join(run);
294
+ yield* Fiber.interrupt(pump);
295
+ return result;
296
+ });
297
+
298
describe('runLogin', () => {
299
// The checks run in a fixed order; each row also proves the earlier checks let it through.
300
it.effect.each([
328
message: POLL_WITH_OTHER_FLAGS_MESSAGE,
329
option: '--poll',
330
},
331
+ {
332
+ name: '--timeout without --poll',
333
+ flags: { timeout: Option.some('60') },
334
+ message: TIMEOUT_WITHOUT_POLL_MESSAGE,
335
+ option: '--timeout',
336
+ },
337
+ {
338
+ name: '--timeout with --no-browser',
339
+ flags: { timeout: Option.some('60'), noBrowser: true },
340
+ message: TIMEOUT_WITHOUT_POLL_MESSAGE,
341
+ option: '--timeout',
342
+ },
343
{
344
name: '--agent with --no-wait',
345
flags: { agent: true, noWait: true },
389
}).pipe(Effect.provide(layer));
390
});
391
392
+ // A --timeout the parser accepts is only known to be usable once the poll has something to
393
+ // wait for, which no cached login here provides.
394
+ it.effect.each([
395
+ { name: '0', timeout: '0', outcome: 'is rejected' },
396
+ { name: '-5', timeout: '-5', outcome: 'is rejected' },
397
+ { name: '1.5', timeout: '1.5', outcome: 'is rejected' },
398
+ { name: 'a duration instead of seconds', timeout: '2m', outcome: 'is rejected' },
399
+ { name: 'empty', timeout: '', outcome: 'is rejected' },
400
+ { name: 'one more than a pending login lives', timeout: '601', outcome: 'is rejected' },
401
+ { name: 'one second', timeout: '1', outcome: 'is accepted' },
402
+ { name: 'the pending login lifetime', timeout: '600', outcome: 'is accepted' },
403
+ ])('[Given] --poll --timeout $name [Then] it $outcome', ({ timeout, outcome }) => {
404
+ const accepted = outcome === 'is accepted';
405
+ const { layer } = loginHandlerTest();
406
+ return Effect.gen(function* () {
407
+ const error = yield* Effect.flip(
408
+ runLogin(params({ poll: true, timeout: Option.some(timeout) }))
409
+ );
410
+
411
+ if (accepted) {
412
+ expect(error).toMatchObject({ _tag: 'commands/PendingLoginError', reason: 'missing' });
413
+ } else {
414
+ expect(error).toMatchObject({
415
+ _tag: 'commands/CommandInputError',
416
+ command: 'login',
417
+ message: invalidTimeoutMessage(AUTHORIZATION_TIMEOUT_SECONDS),
418
+ option: '--timeout',
419
+ });
420
+ }
421
+ }).pipe(Effect.provide(layer));
422
+ });
423
+
424
it.effect('[Given] --user-api-key [Then] runs the direct flow, not the browser one', () => {
425
const { layer, logins, createdSessions } = loginHandlerTest();
426
return Effect.gen(function* () {
442
});
443
444
describe('handlePollLogin', () => {
445
+ const cachedLogin = {
446
+ key: 'session-key',
447
+ loginUrl: 'https://platform.mock.invalid/?cliKey=session-key',
448
+ expiresAt: '2026-01-01T00:10:00.000Z',
449
+ cachedAt: '2026-01-01T00:00:00.000Z',
450
+ };
451
+
452
it.effect(
453
'[Given] a cached login that is linked [Then] stores the first org, clears the cache, and prints the summary JSON',
454
() => {
455
const { layer, logins, outputs, pending } = loginHandlerTest({
378
- pending: Option.some({
379
- key: 'session-key',
380
- loginUrl: 'https://platform.mock.invalid/?cliKey=session-key',
381
- expiresAt: '2026-01-01T00:10:00.000Z',
382
- cachedAt: '2026-01-01T00:00:00.000Z',
383
- }),
456
+ pending: Option.some(cachedLogin),
457
});
458
return Effect.gen(function* () {
386
- yield* handlePollLogin({ noSkillInstall: true });
459
+ yield* handlePollLogin({ noSkillInstall: true, timeout: Option.none() });
460
461
expect(logins).toEqual([
462
{ apiKey: 'uak_linked', orgId: 'org_first', testUserId: 'pg-test-member_org_first' },
481
}).pipe(Effect.provide(layer));
482
}
483
);
484
+
485
+ it.effect(
486
+ '[Given] --timeout long enough for the person to finish [Then] completes the login as the default wait does',
487
+ () => {
488
+ const { layer, logins, pending } = loginHandlerTest({ pending: Option.some(cachedLogin) });
489
+ return Effect.gen(function* () {
490
+ yield* handlePollLogin({ noSkillInstall: true, timeout: Option.some('60') });
491
+
492
+ expect(logins.map(login => login.apiKey)).toEqual(['uak_linked']);
493
+ expect(Option.isNone(pending.current())).toBe(true);
494
+ }).pipe(Effect.provide(layer));
495
+ }
496
+ );
497
+
498
+ it.effect(
499
+ '[Given] a lookup slower than the whole bound [When] --timeout runs out [Then] reports it still pending without waiting for the answer',
500
+ () => {
501
+ // A check in flight is not interrupted by the retry schedule, so without a deadline of its
502
+ // own the wait would sit on this one answer long past its bound.
503
+ const { layer, logins, pending } = loginHandlerTest({
504
+ pending: Option.some(cachedLogin),
505
+ session: Effect.never,
506
+ });
507
+ return Effect.gen(function* () {
508
+ const error = yield* Effect.flip(
509
+ runWithAdvancingClock(
510
+ handlePollLogin({ noSkillInstall: true, timeout: Option.some('5') })
511
+ )
512
+ );
513
+
514
+ expect(error).toMatchObject({
515
+ _tag: 'commands/LoginSessionError',
516
+ operation: 'poll',
517
+ status: 'pending',
518
+ });
519
+ expect(error.message).toContain('Login still pending');
520
+ expect(error.message).toContain('composio login --poll --timeout 5');
521
+ expect(logins).toEqual([]);
522
+ expect(pending.current()).toEqual(Option.some(cachedLogin));
523
+ }).pipe(Effect.provide(layer));
524
+ }
525
+ );
526
+
527
+ it.effect(
528
+ '[Given] a session that never links [When] the --timeout runs out [Then] reports it still pending, with the URL and the command to run again, and keeps the cached login',
529
+ () => {
530
+ const { layer, logins, outputs, sessionLookups, pending } = loginHandlerTest({
531
+ pending: Option.some(cachedLogin),
532
+ session: Effect.succeed(pendingSession('session-key')),
533
+ });
534
+ return Effect.gen(function* () {
535
+ const error = yield* Effect.flip(
536
+ runWithAdvancingClock(
537
+ handlePollLogin({ noSkillInstall: true, timeout: Option.some('5') })
538
+ )
539
+ );
540
+
541
+ expect(error).toMatchObject({
542
+ _tag: 'commands/LoginSessionError',
543
+ operation: 'poll',
544
+ status: 'pending',
545
+ });
546
+ expect(isUsageFailure(error)).toBe(true);
547
+ expect(error.message).toContain("Login still pending: session status is 'pending'");
548
+ expect(error.message).toContain(cachedLogin.loginUrl);
549
+ expect(error.message).toContain('composio login --poll --timeout 5');
550
+ // The wait stopped at its own bound instead of running the ten-minute default: with the
551
+ // clock the pump advances, that default would have checked the session dozens of times.
552
+ expect(sessionLookups.length).toBeLessThan(10);
553
+ expect(logins).toEqual([]);
554
+ expect(outputs).toEqual([]);
555
+ expect(pending.current()).toEqual(Option.some(cachedLogin));
556
+ }).pipe(Effect.provide(layer));
557
+ }
558
+ );
559
});
560
561
describe('handleSessionKeyLogin', () => {