@devries-cameron20 / composio Mirror · read-only / commits / a402b1f7c
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, 03:37 UTC

fix(cli): bound `composio login --poll` with a `--timeout` flag (#5431)

This PR: - adds `--timeout <seconds>` to `composio login --poll`, bounding the wait from 1s to the pending login's own lifetime (600s); without the flag nothing changes, so a human's `composio login --poll` still waits up to ten minutes - moves the wait onto `authorizationPollScheduleFor(timeoutSeconds)`, so `--poll`, `--key` and the browser flow share one bounded implementation and keep their current defaults (`composio link` is untouched) - gives the whole wait a hard deadline, not just its retries, so a slow session lookup cannot outlast `--timeout`; a wait that runs out is answerable: `LoginSessionError` (`operation: 'poll'`, the status it saw) whose message says the login is still pending, repeats the URL, and names the command to run again; nothing is stored and the cached login stays, so the re-run resumes it - rewrites the non-interactive login hint that taught the blocking call, so an agent shows the URL, polls with a bound, and repeats once the person has clicked - updates `docs/content/docs/agent-setup/unattended-authentication.mdx`, which taught the same unbounded call ## Why Our agent-journey baseline loses half the `first-run-login` runs, and every one of those failures is the same command: `composio login --poll` still running when the run's six-minute deadline kills it. Five of that journey's ten runs ended this way (three skill, two no-skill), with Bash heartbeats at 240s, 270s, 300s and 330s. One run wrapped the command in its own `timeout 600` — the caller had to invent a bound the CLI did not offer. The CLI was telling agents to do it. The hint read "polls for up to 10 minutes, and exits once credentials are saved. Do not ask the user whether to poll", and a wait that ran out produced a spinner line, not something a caller could act on. Measured on that journey, three runs against this branch: ``` composio login -> prints the URL, hints --timeout 120 composio login --poll --timeout 120 -> exits 1, "Login still pending", prints the URL again composio login --poll --timeout 120 ; composio whoami -> exit 0, logged in ``` 3/3 passed, in 138s, 139s and 262s, none near the deadline. Before the change the same arm passed 2/5 with three deadline kills. Both figures are three-to-five runs, so the arrow is directional; the defect and the mechanism are what the two batches agree on. ## Follow-ups, not done here - A bounded wait can still overshoot by one poll interval (~5s), because the schedule notices the deadline after the delay that reaches it; the new hard deadline means an in-flight lookup cannot add to that. Documented on `authorizationPollScheduleFor`. - `composio link` keeps its ten-minute default. It shares the schedule but is a different authorization flow, and was out of scope. - `--timeout` takes a whole number of seconds, while `listen --timeout` accepts durations like `5m`. Worth unifying. No changeset: `@composio/cli` is in `.changeset/config.json`'s `ignore` list and ships through the CLI release workflow. ## Verification - `pnpm --filter @composio/cli test`: 229 files, 3223 passed, 1 skipped - `npx vitest run test/src/commands/login test/src/effects/authorization-poll.test.ts`: 56 passed — `--timeout` accepted and rejected values, `--timeout` without `--poll`, a poll completing inside its bound, and a poll that runs out (message, no credentials stored, cached login intact, lookup count stops at the bound); the slow-lookup case uses a lookup that never answers, which had nothing to end the wait before the hard deadline and timed out - `pnpm typecheck` (14 tasks), `pnpm run lint:effect` (0 errors), `validate-skills`, `validate-lint-boundaries`, `validate-command-tests`, `validate:agent-skills`, `validate:skill-routing`, and prettier on the changed files - manual run of the real binary against a stub session endpoint answering `pending`: exits 1 with the still-pending message, the URL and the resume command, leaves the cached login in place, stores no user API key

Alberto Schiabel committed Nov 18, 2026 at 16:22 UTC a402b1f7cc8812baea95881ee313736971925108
9 files changed +523 -73
docs/content/docs/agent-setup/unattended-authentication.mdx
+3 -3
@@ -115,10 +115,10 @@ When a human is available but your terminal cannot open a browser, print a login
115 composio login --no-wait
116 ```
117
118 -Share the URL with the human so they can sign in to their account, then complete login:
118 +Share the URL with the human so they can sign in to their account, then complete login. Bound the poll so it returns before your turn ends:
119
120 ```bash
121 -composio login --poll
121 +composio login --poll --timeout 120
122 ```
123
124 -The pending login expires after ten minutes. Run `composio login --no-wait` again if it expires. For a human account, obtain a [project API key](/reference/authenticating-to-composio#project-api-key) from the dashboard.
124 +`--timeout` takes seconds, from 1 to 600. A poll that runs out exits non-zero, prints the login URL again, and says to run the same command again once the human has clicked. The pending login expires after ten minutes; run `composio login --no-wait` again if it expires. For a human account, obtain a [project API key](/reference/authenticating-to-composio#project-api-key) from the dashboard.
ts/packages/cli/src/commands/login/login.cmd.ts
+12
@@ -1,5 +1,6 @@
1 import { telemetry, withCommandTelemetry } from 'src/analytics/command-input';
2 import { Command, Flag } from 'effect/cli';
3 +import { AUTHORIZATION_TIMEOUT_SECONDS } from 'src/effects/authorization-poll';
4 import { runLogin } from './login.handler';
5
6 const noBrowser = Flag.Boolean('no-browser').pipe(
@@ -12,6 +13,13 @@ const pollOpt = Flag.Boolean('poll').pipe(
13 Flag.withDescription('Poll the most recent pending browser login and complete it')
14 );
15
16 +const timeoutOpt = Flag.String('timeout').pipe(
17 + Flag.withDescription(
18 + `Bound the --poll wait at N seconds (1-${AUTHORIZATION_TIMEOUT_SECONDS}); default ${AUTHORIZATION_TIMEOUT_SECONDS}`
19 + ),
20 + Flag.optional
21 +);
22 +
23 const noWait = Flag.Boolean('no-wait').pipe(
24 Flag.withDefault(false),
25 Flag.withDescription(
@@ -58,6 +66,8 @@ const agentOpt = Flag.Boolean('agent').pipe(
66 * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
67 * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
68 * with --no-wait, checks once and fails if not linked.
69 + * Use --timeout with --poll to bound the wait, in seconds; a wait that runs out exits non-zero with
70 + * the login URL and says to run --poll again.
71 * Use --user-api-key to log in directly without a browser flow, and --org to override the current org.
72 * Use --agent to sign up or log in using a Composio agent identity.
73 * Use -y to skip org picker and use current org.
@@ -70,6 +80,7 @@ const agentOpt = Flag.Boolean('agent').pipe(
80 * composio login
81 * composio login --no-browser
82 * composio login --no-wait
83 + * composio login --poll --timeout 120
84 * composio login --key <key>
85 * composio login --key <key> --no-wait
86 * composio login --user-api-key <uak>
@@ -83,6 +94,7 @@ const loginCmdBase = Command.make(
94 {
95 noBrowser,
96 poll: pollOpt,
97 + timeout: timeoutOpt,
98 noWait,
99 key: keyOpt,
100 userApiKey: userApiKeyOpt,
ts/packages/cli/src/commands/login/login.format.ts
+25
@@ -11,6 +11,11 @@ export const AGENT_WITH_OTHER_FLAGS_MESSAGE =
11 export const ORG_WITHOUT_USER_API_KEY_MESSAGE = '`--org` requires `--user-api-key`.';
12 export const USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE =
13 '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.';
14 +export const TIMEOUT_WITHOUT_POLL_MESSAGE = '`--timeout` requires `--poll`.';
15 +
16 +/** `--timeout` names something other than a whole number of seconds a pending login can last. */
17 +export const invalidTimeoutMessage = (maxSeconds: number) =>
18 + `Invalid --timeout value. Use a whole number of seconds from 1 to ${maxSeconds}.`;
19
20 // --- stderr -----------------------------------------------------------------------------------
21
@@ -25,6 +30,26 @@ export const SESSION_NOT_LINKED_MESSAGE =
30 'Login not complete. Open the URL and finish authentication.';
31 export const SESSION_NOT_LINKED_HINT = 'Then run `composio login --key <key>` again.';
32
33 +/**
34 + * What a bounded wait answers when it runs out on a session that is still pending: the URL that
35 + * finishes the login, and the command that picks the same login up again. The URL and the
36 + * command are part of the message because a caller reading stderr through a pipe gets no
37 + * decoration and no spinner — this text is the whole answer.
38 + */
39 +export const formatLoginStillPending = (params: {
40 + readonly status: string;
41 + readonly loginUrl: string;
42 + readonly resumeCommand: string;
43 +}) => `Login still pending: session status is '${params.status}', waiting for 'linked'.
44 +
45 +Open this URL and finish authenticating:
46 +
47 + ${params.loginUrl}
48 +
49 +Then run this again to complete the login:
50 +
51 + ${params.resumeCommand}`;
52 +
53 export const organizationNotFoundMessage = (requestedOrg: string) =>
54 `Organization "${requestedOrg}" was not found for this API key.`;
55 export const INVALID_ORGANIZATION_MESSAGE =
ts/packages/cli/src/commands/login/login.handler.ts
+64 -6
@@ -1,13 +1,17 @@
1 import { Array as Arr, Data, Effect, Match, Option, Predicate, pipe } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 import { APP_VERSION } from 'src/constants';
4 +import { AUTHORIZATION_TIMEOUT_SECONDS } from 'src/effects/authorization-poll';
5 import {
6 browserLogin,
7 emitLoginComplete,
8 + loginUrlFor,
9 LoginSessionError,
10 playgroundTestUserId,
11 + POLL_COMMAND,
12 storeCredentials,
13 waitForLinkedSession,
14 + type PendingLoginAnswer,
15 } from 'src/effects/browser-login';
16 import type { RetrievedSession } from 'src/models/session';
17 import { completeAgentLogin } from 'src/effects/complete-agent-login';
@@ -37,6 +41,7 @@ import {
41 ALREADY_LOGGED_IN_MESSAGE,
42 ALREADY_LOGGED_IN_OUTRO,
43 INVALID_ORGANIZATION_MESSAGE,
44 + invalidTimeoutMessage,
45 KEY_AND_USER_API_KEY_MESSAGE,
46 ORG_WITHOUT_USER_API_KEY_MESSAGE,
47 POLL_WITH_OTHER_FLAGS_MESSAGE,
@@ -44,6 +49,7 @@ import {
49 SESSION_NOT_FOUND_MESSAGE,
50 SESSION_NOT_LINKED_HINT,
51 SESSION_NOT_LINKED_MESSAGE,
52 + TIMEOUT_WITHOUT_POLL_MESSAGE,
53 USER_API_KEY_WITH_SESSION_FLAGS_MESSAGE,
54 formatPollLoginComplete,
55 formatPollLoginJson,
@@ -55,6 +61,7 @@ import {
61 export type LoginParams = {
62 readonly noBrowser: boolean;
63 readonly poll: boolean;
64 + readonly timeout: Option.Option<string>;
65 readonly noWait: boolean;
66 readonly key: Option.Option<string>;
67 readonly userApiKey: Option.Option<string>;
@@ -78,6 +85,25 @@ const invalidOptionValue = commandInputError('login');
85
86 // --- shared steps -----------------------------------------------------------------------------
87
88 +/**
89 + * Seconds `composio login --poll` may wait: a whole number from 1 to a pending login's lifetime,
90 + * which is also the default. A longer wait would outlive the login it waits for.
91 + */
92 +const parsePollTimeout = (timeout: Option.Option<string>) =>
93 + Effect.gen(function* () {
94 + if (Option.isNone(timeout)) {
95 + return AUTHORIZATION_TIMEOUT_SECONDS;
96 + }
97 + const trimmed = timeout.value.trim();
98 + const seconds = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;
99 + if (seconds >= 1 && seconds <= AUTHORIZATION_TIMEOUT_SECONDS) {
100 + return seconds;
101 + }
102 + return yield* Effect.fail(
103 + invalidOptionValue(invalidTimeoutMessage(AUTHORIZATION_TIMEOUT_SECONDS), '--timeout')
104 + );
105 + });
106 +
107 /** Installs the composio-cli skill after a login, unless skipped or nobody can answer a prompt. */
108 const offerSkillInstall = (skip: boolean) =>
109 Effect.gen(function* () {
@@ -115,6 +141,10 @@ const loginWithKey = (params: {
141 readonly noWait: boolean;
142 readonly announce: boolean;
143 readonly defaultToFirstOrg?: boolean;
144 + /** Where the person finishes this login, and how a wait that runs out resumes it. */
145 + readonly pending: PendingLoginAnswer;
146 + /** How long to wait for the session to link; a pending login's lifetime when omitted. */
147 + readonly timeoutSeconds?: number;
148 }) =>
149 Effect.gen(function* () {
150 const client = yield* ComposioSessionRepository;
@@ -128,7 +158,10 @@ const loginWithKey = (params: {
158 );
159 const linkedSession = yield* params.noWait
160 ? Effect.flatMap(getSession, requireLinkedNow)
131 - : waitForLinkedSession(getSession);
161 + : waitForLinkedSession(getSession, {
162 + ...params.pending,
163 + timeoutSeconds: params.timeoutSeconds,
164 + });
165
166 const uakApiKey = linkedSession.api_key;
167 const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey: uakApiKey });
@@ -216,10 +249,15 @@ const reusableStoredAgent = (requestedExplicitLoginFlow: boolean) =>
249
250 // --- flows ------------------------------------------------------------------------------------
251
219 -/** `login --poll`: completes the browser login a headless `login` cached. */
220 -export const handlePollLogin = (params: Pick<LoginParams, 'noSkillInstall'>) =>
252 +/**
253 + * `login --poll`: completes the browser login a headless `login` cached, waiting at most
254 + * `--timeout` seconds. A wait that runs out leaves the cached login in place and fails with the
255 + * status it saw, the URL, and the same command to run again.
256 + */
257 +export const handlePollLogin = (params: Pick<LoginParams, 'noSkillInstall' | 'timeout'>) =>
258 Effect.gen(function* () {
259 const ui = yield* TerminalUI;
260 + const timeoutSeconds = yield* parsePollTimeout(params.timeout);
261 const pendingLoginSession = yield* PendingLoginSession;
262 const pendingLogin = yield* pendingLoginSession.read;
263 const result = yield* loginWithKey({
@@ -227,6 +265,11 @@ export const handlePollLogin = (params: Pick<LoginParams, 'noSkillInstall'>) =>
265 noWait: false,
266 announce: false,
267 defaultToFirstOrg: true,
268 + pending: {
269 + loginUrl: pendingLogin.loginUrl,
270 + resumeCommand: `${POLL_COMMAND} --timeout ${timeoutSeconds}`,
271 + },
272 + timeoutSeconds,
273 });
274 yield* pendingLoginSession.clear;
275
@@ -259,9 +302,19 @@ const handleAgentLogin = (params: Pick<LoginParams, 'noSkillInstall'>) =>
302 export const handleSessionKeyLogin = (
303 params: Pick<LoginParams, 'noWait' | 'noSkillInstall'> & { readonly key: string }
304 ) =>
262 - loginWithKey({ key: params.key, noWait: params.noWait, announce: true }).pipe(
263 - Effect.andThen(offerSkillInstall(params.noSkillInstall))
264 - );
305 + Effect.gen(function* () {
306 + const ctx = yield* ComposioUserContext;
307 + yield* loginWithKey({
308 + key: params.key,
309 + noWait: params.noWait,
310 + announce: true,
311 + pending: {
312 + loginUrl: loginUrlFor(ctx.data.webURL, params.key),
313 + resumeCommand: `composio login --key ${params.key}`,
314 + },
315 + });
316 + yield* offerSkillInstall(params.noSkillInstall);
317 + });
318
319 /** `login --user-api-key [--org]`: stores a user API key without a browser. */
320 export const handleDirectLogin = (
@@ -348,6 +401,7 @@ const selectLoginFlow = (params: LoginParams) => {
401 org: Option.isSome(params.org),
402 browserOrSession: params.noBrowser || params.noWait,
403 poll: params.poll,
404 + timeout: Option.isSome(params.timeout),
405 agent: params.agent,
406 };
407 type Flags = typeof flags;
@@ -359,6 +413,10 @@ const selectLoginFlow = (params: LoginParams) => {
413 (f: Flags) => f.poll && (f.browserOrSession || f.key || f.userApiKey || f.agent),
414 () => reject(POLL_WITH_OTHER_FLAGS_MESSAGE, '--poll')
415 ),
416 + Match.when(
417 + (f: Flags) => f.timeout && !f.poll,
418 + () => reject(TIMEOUT_WITHOUT_POLL_MESSAGE, '--timeout')
419 + ),
420 Match.when(
421 (f: Flags) => f.agent && (f.browserOrSession || f.key || f.userApiKey),
422 () => reject(AGENT_WITH_OTHER_FLAGS_MESSAGE, '--agent')
ts/packages/cli/src/effects/authorization-poll.ts
+24 -10
@@ -1,4 +1,4 @@
1 -import { Schedule } from 'effect';
1 +import { Duration, Schedule } from 'effect';
2
3 /**
4 * How long `composio login` and `composio link` wait for the person to finish in the browser.
@@ -6,22 +6,36 @@ import { Schedule } from 'effect';
6 */
7 export const AUTHORIZATION_TIMEOUT_MINUTES = 10;
8
9 +/**
10 + * The default wait, and the longest one `composio login --poll --timeout` accepts: a longer
11 + * wait outlives the pending login it waits for.
12 + */
13 +export const AUTHORIZATION_TIMEOUT_SECONDS = AUTHORIZATION_TIMEOUT_MINUTES * 60;
14 +
15 /** The longest wait between two checks, once the ramp has reached it. */
16 export const AUTHORIZATION_POLL_INTERVAL_SECONDS = 5;
17
18 /**
19 * When to check a pending authorization again: after 0.3s, doubling until one check every
14 - * `AUTHORIZATION_POLL_INTERVAL_SECONDS`, for `AUTHORIZATION_TIMEOUT_MINUTES` in all.
20 + * `AUTHORIZATION_POLL_INTERVAL_SECONDS`, for `timeoutSeconds` in all.
21 *
22 * `Schedule.min` waits for the shorter of the ramp and the spacing, which caps the ramp.
23 * (`Schedule.max` would wait for the longer one, and the ramp keeps doubling: fifteen checks
24 * that way take hours.) `Schedule.max` with `Schedule.during`, whose delay is zero, keeps those
19 - * delays and stops once the time is up.
25 + * delays and stops once the time is up — after one more check, since the deadline is noticed
26 + * after the delay that reaches it. A wait can therefore overshoot its bound by one poll
27 + * interval.
28 */
21 -export const authorizationPollSchedule = Schedule.max([
22 - Schedule.min([
23 - Schedule.exponential('0.3 seconds'),
24 - Schedule.spaced(`${AUTHORIZATION_POLL_INTERVAL_SECONDS} seconds`),
25 - ]),
26 - Schedule.during(`${AUTHORIZATION_TIMEOUT_MINUTES} minutes`),
27 -]);
29 +export const authorizationPollScheduleFor = (timeoutSeconds: number) =>
30 + Schedule.max([
31 + Schedule.min([
32 + Schedule.exponential('0.3 seconds'),
33 + Schedule.spaced(`${AUTHORIZATION_POLL_INTERVAL_SECONDS} seconds`),
34 + ]),
35 + Schedule.during(Duration.seconds(timeoutSeconds)),
36 + ]);
37 +
38 +/** The schedule a wait keeps when its caller asks for no particular bound. */
39 +export const authorizationPollSchedule = authorizationPollScheduleFor(
40 + AUTHORIZATION_TIMEOUT_SECONDS
41 +);
ts/packages/cli/src/effects/browser-login.ts
+74 -21
@@ -3,10 +3,12 @@
3 * `composio dev init` (project scope): create the session, show or open its URL, wait for it
4 * to be linked, then store the user API key it carries.
5 */
6 -import { Data, DateTime, Effect, Option, pipe } from 'effect';
6 +import { Data, DateTime, Duration, Effect, Option, Predicate, Ref, pipe } from 'effect';
7 +import { formatLoginStillPending } from 'src/commands/login/login.format';
8 import {
9 AUTHORIZATION_TIMEOUT_MINUTES,
9 - authorizationPollSchedule,
10 + AUTHORIZATION_TIMEOUT_SECONDS,
11 + authorizationPollScheduleFor,
12 } from 'src/effects/authorization-poll';
13 import { ExpectedFailure } from 'src/effects/expected-failure';
14 import open from 'open';
@@ -44,7 +46,14 @@ class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenE
46
47 export type LinkedSession = Extract<RetrievedSession, { readonly status: 'linked' }>;
48
47 -const POLL_COMMAND = 'composio login --poll';
49 +/** The command that completes a browser login another process cached. */
50 +export const POLL_COMMAND = 'composio login --poll';
51 +
52 +/**
53 + * The bound the login instructions teach an agent, in seconds: short enough to fit inside a turn
54 + * of the caller's own deadline, long enough not to give up while a person finds the page.
55 + */
56 +const AGENT_POLL_TIMEOUT_SECONDS = 120;
57
58 // --- presentation -----------------------------------------------------------------------------
59
@@ -59,7 +68,7 @@ Then run this command to complete login:
68
69 ${params.pollCommand}
70
62 -hint: For agents: Show the URL above to the user to click, then run the command above. The command uses the cached login key, polls for up to ${AUTHORIZATION_TIMEOUT_MINUTES} minutes, and exits once credentials are saved. Do not ask the user whether to poll — they already requested login.
71 +hint: For agents: Show the URL above to the user to click, then run \`${params.pollCommand} --timeout ${AGENT_POLL_TIMEOUT_SECONDS}\`. It waits at most that long and exits once credentials are saved; the pending login lives ${AUTHORIZATION_TIMEOUT_MINUTES} minutes. If it exits with the login still pending, it prints the URL again — wait for the user to click, then run the same command again. Do not ask the user whether to poll — they already requested login.
72
73 hint: For unattended agents: If no human is available to open the URL, run \`composio login --agent\` instead — it signs the CLI in with a Composio agent account (creating one if needed) without a browser. Never use it when a human is present to log in with their own account.`;
74
@@ -115,32 +124,73 @@ export const playgroundTestUserId = (
124 Option.getOrUndefined
125 );
126
118 -/** The session, or a `poll` failure naming its status while it is not linked yet. */
119 -const requireLinkedSession = (session: RetrievedSession) =>
127 +/** The URL a person opens to link the CLI session `sessionId`. */
128 +export const loginUrlFor = (webURL: string, sessionId: string) => `${webURL}?cliKey=${sessionId}`;
129 +
130 +/** Where a waiting login sends the person when it runs out, and how to pick it up again. */
131 +export type PendingLoginAnswer = {
132 + /** The URL that finishes this login. */
133 + readonly loginUrl: string;
134 + /** The command that resumes the wait on the same login. */
135 + readonly resumeCommand: string;
136 +};
137 +
138 +/** The answer a wait gives about a session that is still not linked. */
139 +const pendingLoginError = (status: string, pending: PendingLoginAnswer) =>
140 + new LoginSessionError({
141 + message: formatLoginStillPending({ status, ...pending }),
142 + operation: 'poll',
143 + status,
144 + });
145 +
146 +/** The session, or a `poll` failure carrying the status it is waiting on and where to finish it. */
147 +const requireLinkedSession = (session: RetrievedSession, pending: PendingLoginAnswer) =>
148 session.status === 'linked'
149 ? Effect.succeed(session)
122 - : Effect.fail(
123 - new LoginSessionError({
124 - message: `Session status is still '${session.status}', waiting for 'linked'`,
125 - operation: 'poll',
126 - status: session.status,
127 - })
128 - );
150 + : Effect.fail(pendingLoginError(session.status, pending));
151
152 /**
131 - * Checks the session behind a spinner until it is linked, on `authorizationPollSchedule`: for
132 - * up to `AUTHORIZATION_TIMEOUT_MINUTES`, which is also how long a pending login lives.
153 + * Checks the session behind a spinner until it is linked, on `authorizationPollScheduleFor`:
154 + * `timeoutSeconds` at most, a pending login's own lifetime by default. A wait that runs out fails
155 + * with the status it last saw and where to finish the login, and never stores anything.
156 + *
157 + * The schedule bounds the retries, not a check already in flight: a slow answer, and the client's
158 + * own retries of it, would outlast the bound. So the wait also gets a deadline of its own, and
159 + * reports the last status it saw rather than nothing.
160 */
134 -export const waitForLinkedSession = <E, R>(getSession: Effect.Effect<RetrievedSession, E, R>) =>
161 +export const waitForLinkedSession = <E, R>(
162 + getSession: Effect.Effect<RetrievedSession, E, R>,
163 + pending: PendingLoginAnswer & { readonly timeoutSeconds?: number }
164 +) =>
165 Effect.gen(function* () {
166 const ui = yield* TerminalUI;
167 + const timeoutSeconds = pending.timeoutSeconds ?? AUTHORIZATION_TIMEOUT_SECONDS;
168 + const lastStatus = yield* Ref.make('pending');
169 return yield* ui.useMakeSpinner('Waiting for login...', spinner =>
170 Effect.retry(
139 - Effect.flatMap(getSession, requireLinkedSession),
140 - authorizationPollSchedule
171 + Effect.flatMap(getSession, session =>
172 + Effect.andThen(
173 + Ref.set(lastStatus, session.status),
174 + requireLinkedSession(session, pending)
175 + )
176 + ),
177 + authorizationPollScheduleFor(timeoutSeconds)
178 ).pipe(
179 + Effect.timeoutOrElse({
180 + duration: Duration.seconds(timeoutSeconds),
181 + orElse: () =>
182 + Effect.flatMap(Ref.get(lastStatus), status =>
183 + Effect.fail(pendingLoginError(status, pending))
184 + ),
185 + }),
186 Effect.tap(() => spinner.stop('Login successful')),
143 - Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
187 + Effect.tapError(error =>
188 + spinner.error(
189 + Predicate.isTagged(error, 'commands/LoginSessionError')
190 + ? 'Login still pending'
191 + : 'Login failed'
192 + )
193 + )
194 )
195 );
196 });
@@ -326,7 +376,7 @@ export const browserLogin = (params: {
376 const session = yield* client.createSession({ scope: params.scope });
377 yield* Effect.logDebug(`Created session: ${session.id}`);
378
329 - const url = `${ctx.data.webURL}?cliKey=${session.id}`;
379 + const url = loginUrlFor(ctx.data.webURL, session.id);
380 yield* pendingLogin.write({
381 key: session.id,
382 loginUrl: url,
@@ -360,7 +410,10 @@ export const browserLogin = (params: {
410 yield* openLoginUrl(url);
411 }
412
363 - const linkedSession = yield* waitForLinkedSession(client.getSession({ id: session.id }));
413 + const linkedSession = yield* waitForLinkedSession(client.getSession({ id: session.id }), {
414 + loginUrl: url,
415 + resumeCommand: POLL_COMMAND,
416 + });
417 yield* Effect.logDebug(`Linked session ID: ${linkedSession.id}`);
418
419 // e.g., "uak_b813ydmoEYdB_xBxGHeW"
ts/packages/cli/test/src/commands/login/login.cmd.test.ts
+127 -4
@@ -1,9 +1,15 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 -import { Console, DateTime, Effect, Exit, Option } from 'effect';
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';
6 -import { cli, MockConsole, TestLive } from 'test/__utils__';
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';
@@ -97,6 +103,22 @@ const headlessStdinUI = terminalUIWithTtyState({
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', () => {
@@ -120,6 +142,7 @@ describe('CLI: composio login', () => {
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 );
@@ -159,8 +182,10 @@ describe('CLI: composio login', () => {
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:');
162 - expect(output).toContain('cached login key');
163 - expect(output).toContain('polls for up to 10 minutes');
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:');
@@ -353,6 +378,104 @@ describe('CLI: composio login', () => {
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',
ts/packages/cli/test/src/commands/login/login.handler.test.ts
+158 -10
@@ -8,7 +8,8 @@ import {
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 {
@@ -23,13 +24,16 @@ 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';
@@ -98,6 +102,7 @@ const sessionInfoFor = (scope: MockRequestScope) =>
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(),
@@ -158,6 +163,8 @@ const loginHandlerTest = (fixture: LoginFixture = {}) => {
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
@@ -223,7 +230,11 @@ const loginHandlerTest = (fixture: LoginFixture = {}) => {
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 })
@@ -263,11 +274,27 @@ const loginHandlerTest = (fixture: LoginFixture = {}) => {
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([
@@ -301,6 +328,18 @@ describe('runLogin', () => {
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 },
@@ -350,6 +389,38 @@ describe('runLogin', () => {
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* () {
@@ -371,19 +442,21 @@ describe('runLogin', () => {
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' },
@@ -408,6 +481,81 @@ describe('handlePollLogin', () => {
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', () => {
ts/packages/cli/test/src/effects/authorization-poll.test.ts
+36 -19
@@ -4,32 +4,33 @@ import { TestClock } from 'effect/testing';
4 import {
5 AUTHORIZATION_POLL_INTERVAL_SECONDS,
6 AUTHORIZATION_TIMEOUT_MINUTES,
7 + AUTHORIZATION_TIMEOUT_SECONDS,
8 authorizationPollSchedule,
9 + authorizationPollScheduleFor,
10 } from 'src/effects/authorization-poll';
11
12 /** The test-clock times of every check of an authorization that never completes. */
11 -const checksOfAPendingAuthorization = Effect.gen(function* () {
12 - const checkedAt: number[] = [];
13 - const check = Effect.flatMap(Clock.currentTimeMillis, now => {
14 - checkedAt.push(now);
15 - return Effect.fail('still pending' as const);
13 +const checksOfAPendingAuthorization = (schedule: ReturnType<typeof authorizationPollScheduleFor>) =>
14 + Effect.gen(function* () {
15 + const checkedAt: number[] = [];
16 + const check = Effect.flatMap(Clock.currentTimeMillis, now => {
17 + checkedAt.push(now);
18 + return Effect.fail('still pending' as const);
19 + });
20 + const fiber = yield* Effect.forkChild(Effect.exit(Effect.retry(check, schedule)));
21 + // Moves the clock in 100ms steps for as long as the retry runs; it ends by itself.
22 + const pump = yield* Effect.forkChild(
23 + Effect.forever(Effect.andThen(Effect.yieldNow, () => TestClock.adjust('100 millis')))
24 + );
25 + const exit = yield* Fiber.join(fiber);
26 + yield* Fiber.interrupt(pump);
27 + return { exit, checkedAt };
28 });
17 - const fiber = yield* Effect.forkChild(
18 - Effect.exit(Effect.retry(check, authorizationPollSchedule))
19 - );
20 - // Moves the clock in 100ms steps for as long as the retry runs; it ends by itself.
21 - const pump = yield* Effect.forkChild(
22 - Effect.forever(Effect.andThen(Effect.yieldNow, () => TestClock.adjust('100 millis')))
23 - );
24 - const exit = yield* Fiber.join(fiber);
25 - yield* Fiber.interrupt(pump);
26 - return { exit, checkedAt };
27 -});
29
30 describe('authorizationPollSchedule', () => {
31 it.effect('ramps from 0.3s and never waits longer than the interval between checks', () =>
32 Effect.gen(function* () {
32 - const { checkedAt } = yield* checksOfAPendingAuthorization;
33 + const { checkedAt } = yield* checksOfAPendingAuthorization(authorizationPollSchedule);
34 const gaps = checkedAt.slice(1).map((time, index) => time - checkedAt[index]!);
35
36 expect(gaps.slice(0, 6)).toEqual([300, 600, 1200, 2400, 4800, 5000]);
@@ -39,12 +40,28 @@ describe('authorizationPollSchedule', () => {
40
41 it.effect('gives up once the timeout has passed, not hours later', () =>
42 Effect.gen(function* () {
42 - const { exit, checkedAt } = yield* checksOfAPendingAuthorization;
43 - const timeoutMs = AUTHORIZATION_TIMEOUT_MINUTES * 60_000;
43 + // The wait a caller asks for no particular bound keeps: a pending login's whole lifetime.
44 + expect(AUTHORIZATION_TIMEOUT_SECONDS).toBe(AUTHORIZATION_TIMEOUT_MINUTES * 60);
45 +
46 + const { exit, checkedAt } = yield* checksOfAPendingAuthorization(authorizationPollSchedule);
47 + const timeoutMs = AUTHORIZATION_TIMEOUT_SECONDS * 1000;
48
49 expect(Exit.isFailure(exit)).toBe(true);
50 expect(checkedAt.at(-1)).toBeGreaterThan(timeoutMs - 5_000);
51 expect(checkedAt.at(-1)).toBeLessThanOrEqual(timeoutMs + 5_000);
52 })
53 );
54 +
55 + it.effect('stops at the shorter bound a caller asks for', () =>
56 + Effect.gen(function* () {
57 + const { exit, checkedAt } = yield* checksOfAPendingAuthorization(
58 + authorizationPollScheduleFor(30)
59 + );
60 + const lastCheckMs = checkedAt.at(-1)!;
61 +
62 + expect(Exit.isFailure(exit)).toBe(true);
63 + expect(lastCheckMs).toBeGreaterThan(25_000);
64 + expect(lastCheckMs).toBeLessThanOrEqual(35_000);
65 + })
66 + );
67 });