Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { |
| 2 | APIConnectionError, |
| 3 | Auth, |
| 4 | make, |
| 5 | type ComposioClientShape, |
| 6 | type NotFoundError, |
| 7 | } from '@composio/client/effect'; |
| 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, 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 { |
| 16 | handleBrowserLogin, |
| 17 | handleDirectLogin, |
| 18 | handlePollLogin, |
| 19 | handleSessionKeyLogin, |
| 20 | runLogin, |
| 21 | type LoginParams, |
| 22 | } from 'src/commands/login/login.handler'; |
| 23 | 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'; |
| 40 | import { NodeOs } from 'src/services/node-os'; |
| 41 | import { NodeProcess } from 'src/services/node-process'; |
| 42 | import { ProjectContext } from 'src/services/project-context'; |
| 43 | import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui'; |
| 44 | import { ComposioUserContext } from 'src/services/user-context'; |
| 45 | import { isUsageFailure } from 'src/commands/errors'; |
| 46 | import { MockConsole, ToolkitsTest } from 'test/__utils__'; |
| 47 | import { notFoundError } from 'test/__utils__/layers/not-found'; |
| 48 | import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts'; |
| 49 | import { PendingLoginSessionTest } from 'test/__utils__/layers/pending-login-session'; |
| 50 | import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider'; |
| 51 | import { makeSessionInfo } from 'test/__utils__/models/account'; |
| 52 | import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test'; |
| 53 | import { afterEach, vi } from 'vitest'; |
| 54 | |
| 55 | vi.mock('open', () => ({ |
| 56 | default: vi.fn(async () => undefined), |
| 57 | })); |
| 58 | |
| 59 | const analytics = vi.hoisted(() => ({ linked: [] as Array<string> })); |
| 60 | |
| 61 | // Records each analytics identity link instead of enqueueing an event. |
| 62 | vi.mock('src/analytics/dispatch', async importOriginal => { |
| 63 | const actual = await importOriginal<typeof import('src/analytics/dispatch')>(); |
| 64 | const { Effect } = await import('effect'); |
| 65 | return { |
| 66 | ...actual, |
| 67 | analyticsIdentityLinkingEnabled: Effect.succeed(true), |
| 68 | linkApolloIdentityForAnalytics: ((apolloUserId: string) => |
| 69 | Effect.sync(() => { |
| 70 | analytics.linked.push(apolloUserId); |
| 71 | })) as unknown as typeof actual.linkApolloIdentityForAnalytics, |
| 72 | }; |
| 73 | }); |
| 74 | |
| 75 | afterEach(() => { |
| 76 | analytics.linked.length = 0; |
| 77 | }); |
| 78 | |
| 79 | const ORGANIZATIONS: ReadonlyArray<OrganizationSummary> = [ |
| 80 | { id: 'org_first', name: 'First Org' }, |
| 81 | { id: 'org_second', name: 'Second Org' }, |
| 82 | ]; |
| 83 | |
| 84 | const HOME_SESSION_INFO = makeSessionInfo({ |
| 85 | orgId: 'org_home', |
| 86 | orgName: 'Home Org', |
| 87 | orgMemberId: 'member_home', |
| 88 | email: 'cli@example.com', |
| 89 | }); |
| 90 | |
| 91 | /** The key's home org without an org scope, otherwise the requested org with its own member. */ |
| 92 | const sessionInfoFor = (scope: MockRequestScope) => |
| 93 | scope.orgId === undefined |
| 94 | ? HOME_SESSION_INFO |
| 95 | : makeSessionInfo({ |
| 96 | orgId: scope.orgId, |
| 97 | orgName: `${scope.orgId} name`, |
| 98 | orgMemberId: `member_${scope.orgId}`, |
| 99 | email: 'cli@example.com', |
| 100 | }); |
| 101 | |
| 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(), |
| 109 | org: Option.none(), |
| 110 | yes: false, |
| 111 | noSkillInstall: true, |
| 112 | agent: false, |
| 113 | ...overrides, |
| 114 | }); |
| 115 | |
| 116 | const pendingSession = (id: string): RetrievedSession => ({ |
| 117 | id, |
| 118 | code: '001122', |
| 119 | expiresAt: DateTime.makeUnsafe('2026-01-01T00:10:00.000Z'), |
| 120 | status: 'pending', |
| 121 | api_key: null, |
| 122 | }); |
| 123 | |
| 124 | const linkedSession = (id: string): RetrievedSession => ({ |
| 125 | id, |
| 126 | code: '001122', |
| 127 | expiresAt: DateTime.makeUnsafe('2026-01-01T00:10:00.000Z'), |
| 128 | status: 'linked', |
| 129 | api_key: 'uak_linked', |
| 130 | account: { id: 'account_id', name: 'Poll User', email: 'poll@example.com' }, |
| 131 | }); |
| 132 | |
| 133 | interface LoginFixture { |
| 134 | /** The stored login the user context starts with. */ |
| 135 | readonly apiKey?: Option.Option<string>; |
| 136 | readonly orgId?: Option.Option<string>; |
| 137 | readonly pending?: Parameters<typeof PendingLoginSessionTest>[0]; |
| 138 | /** What `getSession` answers; a failure stands for an unknown or expired session. */ |
| 139 | readonly session?: Effect.Effect<RetrievedSession, NotFoundError | APIConnectionError>; |
| 140 | } |
| 141 | |
| 142 | // A resource the account mocks do not shadow reaches this transport and dies with its URL. |
| 143 | const baseClient = make( |
| 144 | { |
| 145 | auth: Auth.project('test'), |
| 146 | baseURL: 'https://mock.invalid', |
| 147 | }, |
| 148 | HttpClient.make(request => |
| 149 | Effect.die(new Error(`unexpected network call from the login handler test: ${request.url}`)) |
| 150 | ) |
| 151 | ); |
| 152 | |
| 153 | /** |
| 154 | * What a login handler needs and nothing more: the account family of the mock client, a CLI |
| 155 | * session double, an in-memory pending login, a user context that records `login` calls, and a |
| 156 | * headless terminal whose stdout data lands in `outputs`. |
| 157 | */ |
| 158 | const loginHandlerTest = (fixture: LoginFixture = {}) => { |
| 159 | const logins: Array<{ |
| 160 | readonly apiKey: string; |
| 161 | readonly orgId?: string; |
| 162 | readonly testUserId?: string; |
| 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 | |
| 171 | const clientFor = (scope: MockRequestScope): ComposioClientShape => |
| 172 | // The shadows answer only the fields the handlers read; `test-layer.ts` shadows its mock |
| 173 | // client the same way. |
| 174 | ({ |
| 175 | ...baseClient, |
| 176 | ...mockAccountResources({ sessionInfo: sessionInfoFor, organizations: ORGANIZATIONS }, scope), |
| 177 | }) as unknown as ComposioClientShape; |
| 178 | |
| 179 | const dir = tempy.temporaryDirectory({ prefix: 'login-handler' }); |
| 180 | const layer = Layer.mergeAll( |
| 181 | Layer.effect(Console.Console, MockConsole.make), |
| 182 | Layer.succeed( |
| 183 | TerminalUI, |
| 184 | TerminalUI.of({ |
| 185 | ...terminalUITestImpl, |
| 186 | capabilities: Effect.succeed( |
| 187 | getTerminalCapabilities({ |
| 188 | stdin: { isTTY: false }, |
| 189 | stdout: { isTTY: false }, |
| 190 | stderr: { isTTY: false }, |
| 191 | }) |
| 192 | ), |
| 193 | output: data => |
| 194 | Effect.sync(() => { |
| 195 | outputs.push(data); |
| 196 | }), |
| 197 | }) |
| 198 | ), |
| 199 | Layer.succeed( |
| 200 | ComposioUserContext, |
| 201 | ComposioUserContext.of({ |
| 202 | data: { |
| 203 | apiKey, |
| 204 | baseURL: 'https://mock.invalid', |
| 205 | webURL: 'https://platform.mock.invalid/', |
| 206 | orgId: fixture.orgId ?? Option.none(), |
| 207 | projectId: Option.none(), |
| 208 | testUserId: Option.none(), |
| 209 | }, |
| 210 | backendMismatch: Option.none(), |
| 211 | isLoggedIn: () => Option.isSome(apiKey), |
| 212 | logout: Effect.void, |
| 213 | login: (loginApiKey, orgId, testUserId) => |
| 214 | Effect.sync(() => { |
| 215 | logins.push({ apiKey: loginApiKey, orgId, testUserId }); |
| 216 | }), |
| 217 | update: () => Effect.void, |
| 218 | }) |
| 219 | ), |
| 220 | Layer.succeed( |
| 221 | ComposioSessionRepository, |
| 222 | ComposioSessionRepository.of({ |
| 223 | createSession: ({ scope } = {}) => |
| 224 | Effect.sync(() => { |
| 225 | createdSessions.push(scope ?? 'user'); |
| 226 | return { |
| 227 | id: 'session-new', |
| 228 | code: '001122', |
| 229 | expiresAt: DateTime.makeUnsafe('2026-01-01T00:10:00.000Z'), |
| 230 | status: 'pending' as const, |
| 231 | }; |
| 232 | }), |
| 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 | }) |
| 241 | ), |
| 242 | Layer.succeed( |
| 243 | ComposioClientSingleton, |
| 244 | ComposioClientSingleton.of({ |
| 245 | get: () => Effect.succeed(clientFor({})), |
| 246 | getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)), |
| 247 | getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }), |
| 248 | }) |
| 249 | ), |
| 250 | pending.layer, |
| 251 | // The consumer-toolkits cache refresh a login starts in the background reads these. |
| 252 | ToolkitsTest(), |
| 253 | Layer.succeed(ProjectContext, ProjectContext.of({ resolve: Effect.succeed(Option.none()) })), |
| 254 | Layer.succeed( |
| 255 | HttpClient.HttpClient, |
| 256 | HttpClient.make(request => |
| 257 | Effect.die(new Error(`unexpected HTTP call from the login handler test: ${request.url}`)) |
| 258 | ) |
| 259 | ), |
| 260 | BunFileSystem.layer, |
| 261 | BunPath.layer, |
| 262 | Layer.succeed( |
| 263 | NodeOs, |
| 264 | NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' }) |
| 265 | ), |
| 266 | Layer.succeed( |
| 267 | NodeProcess, |
| 268 | NodeProcess.of({ |
| 269 | cwd: dir, |
| 270 | execPath: `${dir}/composio`, |
| 271 | platform: 'darwin', |
| 272 | arch: 'arm64', |
| 273 | }) |
| 274 | ), |
| 275 | ConfigProvider.layer(hostOnlyEnvConfigProvider) |
| 276 | ); |
| 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([ |
| 301 | { |
| 302 | name: '--key with --user-api-key', |
| 303 | flags: { key: Option.some('k'), userApiKey: Option.some('uak') }, |
| 304 | message: KEY_AND_USER_API_KEY_MESSAGE, |
| 305 | option: undefined, |
| 306 | }, |
| 307 | { |
| 308 | name: '--key, --user-api-key and --poll (the pair is reported first)', |
| 309 | flags: { key: Option.some('k'), userApiKey: Option.some('uak'), poll: true }, |
| 310 | message: KEY_AND_USER_API_KEY_MESSAGE, |
| 311 | option: undefined, |
| 312 | }, |
| 313 | { |
| 314 | name: '--poll with --no-browser', |
| 315 | flags: { poll: true, noBrowser: true }, |
| 316 | message: POLL_WITH_OTHER_FLAGS_MESSAGE, |
| 317 | option: '--poll', |
| 318 | }, |
| 319 | { |
| 320 | name: '--poll with --user-api-key', |
| 321 | flags: { poll: true, userApiKey: Option.some('uak') }, |
| 322 | message: POLL_WITH_OTHER_FLAGS_MESSAGE, |
| 323 | option: '--poll', |
| 324 | }, |
| 325 | { |
| 326 | name: '--poll with --agent (before the --agent check)', |
| 327 | flags: { poll: true, agent: true }, |
| 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 }, |
| 346 | message: AGENT_WITH_OTHER_FLAGS_MESSAGE, |
| 347 | option: '--agent', |
| 348 | }, |
| 349 | { |
| 350 | name: '--agent with --key', |
| 351 | flags: { agent: true, key: Option.some('k') }, |
| 352 | message: AGENT_WITH_OTHER_FLAGS_MESSAGE, |
| 353 | option: '--agent', |
| 354 | }, |
| 355 | { |
| 356 | name: '--org without --user-api-key', |
| 357 | flags: { org: Option.some('org_first'), key: Option.some('k') }, |
| 358 | message: ORG_WITHOUT_USER_API_KEY_MESSAGE, |
| 359 | option: '--org', |
| 360 | }, |
| 361 | { |
| 362 | name: '--user-api-key with --no-wait', |
| 363 | flags: { userApiKey: Option.some('uak'), noWait: true }, |
| 364 | message: USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE, |
| 365 | option: '--user-api-key', |
| 366 | }, |
| 367 | ])('[Given] $name [Then] fails with a usage error', ({ flags, message, option }) => { |
| 368 | const { layer, logins, createdSessions } = loginHandlerTest(); |
| 369 | return Effect.gen(function* () { |
| 370 | const error = yield* Effect.flip(runLogin(params(flags))); |
| 371 | |
| 372 | expect(error).toMatchObject({ |
| 373 | _tag: 'commands/CommandInputError', |
| 374 | command: 'login', |
| 375 | message, |
| 376 | option, |
| 377 | }); |
| 378 | expect(logins).toEqual([]); |
| 379 | expect(createdSessions).toEqual([]); |
| 380 | }).pipe(Effect.provide(layer)); |
| 381 | }); |
| 382 | |
| 383 | it.effect('[Given] --poll and nothing cached [Then] runs the poll flow', () => { |
| 384 | const { layer } = loginHandlerTest(); |
| 385 | return Effect.gen(function* () { |
| 386 | const error = yield* Effect.flip(runLogin(params({ poll: true }))); |
| 387 | |
| 388 | expect(error).toMatchObject({ _tag: 'commands/PendingLoginError', reason: 'missing' }); |
| 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* () { |
| 427 | yield* runLogin(params({ userApiKey: Option.some('uak_direct') })); |
| 428 | |
| 429 | expect(logins.map(login => login.apiKey)).toEqual(['uak_direct']); |
| 430 | expect(createdSessions).toEqual([]); |
| 431 | }).pipe(Effect.provide(layer)); |
| 432 | }); |
| 433 | |
| 434 | it.effect('[Given] no flags [Then] runs the browser flow', () => { |
| 435 | const { layer, createdSessions } = loginHandlerTest(); |
| 436 | return Effect.gen(function* () { |
| 437 | yield* runLogin(params()); |
| 438 | |
| 439 | expect(createdSessions).toEqual(['user']); |
| 440 | }).pipe(Effect.provide(layer)); |
| 441 | }); |
| 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({ |
| 456 | pending: Option.some(cachedLogin), |
| 457 | }); |
| 458 | return Effect.gen(function* () { |
| 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' }, |
| 463 | ]); |
| 464 | expect(analytics.linked).toEqual(['member_org_first']); |
| 465 | expect(Option.isNone(pending.current())).toBe(true); |
| 466 | expect(outputs).toEqual([ |
| 467 | JSON.stringify( |
| 468 | { |
| 469 | email: 'poll@example.com', |
| 470 | current_org: { id: 'org_first', name: 'First Org' }, |
| 471 | organizations: [ |
| 472 | { id: 'org_first', name: 'First Org', selected: true }, |
| 473 | { id: 'org_second', name: 'Second Org', selected: false }, |
| 474 | ], |
| 475 | switch_command: 'composio orgs switch --org-id <org_id>', |
| 476 | }, |
| 477 | null, |
| 478 | 2 |
| 479 | ), |
| 480 | ]); |
| 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', () => { |
| 562 | it.effect('[Given] an unknown session key [Then] fails to load the session', () => { |
| 563 | const { layer, logins } = loginHandlerTest({ |
| 564 | session: Effect.fail(notFoundError('session not found')), |
| 565 | }); |
| 566 | return Effect.gen(function* () { |
| 567 | const error = yield* Effect.flip( |
| 568 | handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true }) |
| 569 | ); |
| 570 | |
| 571 | expect(error).toMatchObject({ |
| 572 | _tag: 'commands/LoginSessionError', |
| 573 | operation: 'load', |
| 574 | message: SESSION_NOT_FOUND_MESSAGE, |
| 575 | }); |
| 576 | expect(isUsageFailure(error)).toBe(true); |
| 577 | expect(logins).toEqual([]); |
| 578 | }).pipe(Effect.provide(layer)); |
| 579 | }); |
| 580 | |
| 581 | it.effect( |
| 582 | '[Given] the session lookup fails to connect [Then] keeps the cause and does not report an expired session', |
| 583 | () => { |
| 584 | const connectionError = new APIConnectionError({ |
| 585 | message: 'Connection error.', |
| 586 | method: 'GET', |
| 587 | url: 'https://mock.invalid', |
| 588 | reason: 'TransportError', |
| 589 | description: 'fetch failed: connect ECONNREFUSED 127.0.0.1:1', |
| 590 | }); |
| 591 | const { layer, logins } = loginHandlerTest({ session: Effect.fail(connectionError) }); |
| 592 | return Effect.gen(function* () { |
| 593 | const error = yield* Effect.flip( |
| 594 | handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true }) |
| 595 | ); |
| 596 | |
| 597 | expect(error).toMatchObject({ |
| 598 | _tag: 'commands/LoginSessionRequestError', |
| 599 | cause: connectionError, |
| 600 | }); |
| 601 | expect(error.message).not.toBe(SESSION_NOT_FOUND_MESSAGE); |
| 602 | expect(isUsageFailure(error)).toBe(false); |
| 603 | expect(logins).toEqual([]); |
| 604 | }).pipe(Effect.provide(layer)); |
| 605 | } |
| 606 | ); |
| 607 | |
| 608 | it.effect( |
| 609 | '[Given] --no-wait and a session still pending [Then] reports it and stores nothing', |
| 610 | () => { |
| 611 | const { layer, logins, outputs } = loginHandlerTest({ |
| 612 | session: Effect.succeed(pendingSession('session-key')), |
| 613 | }); |
| 614 | return Effect.gen(function* () { |
| 615 | const error = yield* Effect.flip( |
| 616 | handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true }) |
| 617 | ); |
| 618 | |
| 619 | expect(error).toMatchObject({ |
| 620 | _tag: 'commands/LoginSessionError', |
| 621 | operation: 'poll', |
| 622 | status: 'pending', |
| 623 | }); |
| 624 | expect(yield* stderr).toContain(SESSION_NOT_LINKED_MESSAGE); |
| 625 | expect(logins).toEqual([]); |
| 626 | expect(outputs).toEqual([]); |
| 627 | }).pipe(Effect.provide(layer)); |
| 628 | } |
| 629 | ); |
| 630 | |
| 631 | it.effect( |
| 632 | '[Given] --no-wait and a linked session [Then] stores the key and prints the login JSON', |
| 633 | () => { |
| 634 | const { layer, logins, outputs } = loginHandlerTest(); |
| 635 | return Effect.gen(function* () { |
| 636 | yield* handleSessionKeyLogin({ key: 'session-key', noWait: true, noSkillInstall: true }); |
| 637 | |
| 638 | expect(logins.map(login => login.apiKey)).toEqual(['uak_linked']); |
| 639 | expect(outputs).toEqual([ |
| 640 | JSON.stringify({ email: 'poll@example.com', org_id: 'org_home', org_name: 'Home Org' }), |
| 641 | ]); |
| 642 | expect(analytics.linked).toEqual(['member_org_home']); |
| 643 | }).pipe(Effect.provide(layer)); |
| 644 | } |
| 645 | ); |
| 646 | }); |
| 647 | |
| 648 | describe('handleDirectLogin', () => { |
| 649 | it.effect('[Given] --org naming an org by name [Then] stores that org', () => { |
| 650 | const { layer, logins, outputs } = loginHandlerTest(); |
| 651 | return Effect.gen(function* () { |
| 652 | yield* handleDirectLogin({ |
| 653 | userApiKey: 'uak_direct', |
| 654 | org: Option.some('Second Org'), |
| 655 | noSkillInstall: true, |
| 656 | }); |
| 657 | |
| 658 | expect(logins).toEqual([ |
| 659 | { apiKey: 'uak_direct', orgId: 'org_second', testUserId: 'pg-test-member_home' }, |
| 660 | ]); |
| 661 | expect(outputs).toEqual([ |
| 662 | JSON.stringify({ email: 'cli@example.com', org_id: 'org_second', org_name: 'Second Org' }), |
| 663 | ]); |
| 664 | }).pipe(Effect.provide(layer)); |
| 665 | }); |
| 666 | |
| 667 | it.effect('[Given] an empty --org [Then] keeps the home org of the key', () => { |
| 668 | const { layer, logins } = loginHandlerTest(); |
| 669 | return Effect.gen(function* () { |
| 670 | yield* handleDirectLogin({ |
| 671 | userApiKey: 'uak_direct', |
| 672 | org: Option.some(''), |
| 673 | noSkillInstall: true, |
| 674 | }); |
| 675 | |
| 676 | expect(logins.map(login => login.orgId)).toEqual(['org_home']); |
| 677 | expect(analytics.linked).toEqual(['member_home']); |
| 678 | }).pipe(Effect.provide(layer)); |
| 679 | }); |
| 680 | |
| 681 | it.effect('[Given] --org naming no visible org [Then] fails without storing the key', () => { |
| 682 | const { layer, logins, outputs } = loginHandlerTest(); |
| 683 | return Effect.gen(function* () { |
| 684 | const error = yield* Effect.flip( |
| 685 | handleDirectLogin({ |
| 686 | userApiKey: 'uak_direct', |
| 687 | org: Option.some('Missing Org'), |
| 688 | noSkillInstall: true, |
| 689 | }) |
| 690 | ); |
| 691 | |
| 692 | expect(error).toMatchObject({ |
| 693 | _tag: 'commands/InvalidOrganizationError', |
| 694 | message: INVALID_ORGANIZATION_MESSAGE, |
| 695 | requestedOrg: 'Missing Org', |
| 696 | }); |
| 697 | expect(yield* stderr).toContain('Organization "Missing Org" was not found for this API key.'); |
| 698 | expect(logins).toEqual([]); |
| 699 | expect(outputs).toEqual([]); |
| 700 | }).pipe(Effect.provide(layer)); |
| 701 | }); |
| 702 | }); |
| 703 | |
| 704 | describe('handleBrowserLogin', () => { |
| 705 | it.effect('[Given] a stored login with an org [Then] warns and starts no session', () => { |
| 706 | const { layer, createdSessions, outputs } = loginHandlerTest({ |
| 707 | apiKey: Option.some('uak_existing'), |
| 708 | orgId: Option.some('org_existing'), |
| 709 | }); |
| 710 | return Effect.gen(function* () { |
| 711 | yield* handleBrowserLogin(params()); |
| 712 | |
| 713 | expect(yield* stderr).toContain(ALREADY_LOGGED_IN_MESSAGE); |
| 714 | expect(createdSessions).toEqual([]); |
| 715 | expect(outputs).toEqual([]); |
| 716 | }).pipe(Effect.provide(layer)); |
| 717 | }); |
| 718 | |
| 719 | it.effect( |
| 720 | '[Given] a headless run and no stored agent [Then] caches the session and prints the poll instructions', |
| 721 | () => { |
| 722 | const { layer, createdSessions, outputs, pending, logins } = loginHandlerTest(); |
| 723 | return Effect.gen(function* () { |
| 724 | yield* handleBrowserLogin(params()); |
| 725 | |
| 726 | expect(createdSessions).toEqual(['user']); |
| 727 | expect(pending.current()).toEqual( |
| 728 | Option.some({ |
| 729 | key: 'session-new', |
| 730 | loginUrl: 'https://platform.mock.invalid/?cliKey=session-new', |
| 731 | expiresAt: '2026-01-01T00:10:00.000Z', |
| 732 | cachedAt: '2026-01-01T00:00:00.000Z', |
| 733 | }) |
| 734 | ); |
| 735 | expect(outputs).toHaveLength(1); |
| 736 | expect(outputs[0]).toContain('https://platform.mock.invalid/?cliKey=session-new'); |
| 737 | expect(outputs[0]).toContain('composio login --poll'); |
| 738 | expect(logins).toEqual([]); |
| 739 | }).pipe(Effect.provide(layer)); |
| 740 | } |
| 741 | ); |
| 742 | }); |