@devries-cameron20 / composio Mirror · read-only / commits / c2275b141
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 06:00 UTC

fix(cli): print the `link` authorization URL off a terminal (#5326)

This PR: - prints the authorization URL on stderr, with an agent hint naming `--no-wait`, when `composio link` / `composio dev connected-accounts link` wait and stderr is not a terminal; it used to go through `ui.log.step` / `ui.note`, which `TerminalUI` drops off a terminal, so `--no-browser` printed nothing until it timed out - adds `authorizationPollSchedule` (`src/effects/authorization-poll.ts`), shared by `login` and `link`: a 0.3s ramp capped at one check every 5 seconds, for 10 minutes; the old `Schedule.max` of the ramp and the spacing waited for the longer one, about 2h44m in all, although `login`'s hint promised 10 minutes - keeps `--no-wait` quiet on stderr: its stdout JSON already carries `redirect_url` - teaches `composio link … --no-browser --no-wait` in the `composio-cli` skill, with showing the user the `redirect_url` - tests: off-terminal handler tests on the real redirected `TerminalUI` for the toolkit and `--auth-config` paths (stderr holds the URL at the first poll, stdout the JSON after); `TestClock` tests for the schedule's gaps and its 10-minute end; two browser tests now run on a terminal that decorates ## Context Found by live agent runs in https://github.com/ComposioHQ/composio/pull/5312: Claude Code on `claude-haiku-5-5` stalled at `composio dev connected-accounts link slack --no-browser` in every run of a developer task. With this change, that journey went from 0/5 to 5/5. #5312 is based on this PR; it turns the `it.failing` e2e test for this behaviour (`operations/process-streams.test.ts`) into a passing one.

Alberto Schiabel committed Nov 12, 2026 at 14:29 UTC c2275b141e1182174f1c85e72e8b7c1b8c7c3bc7
10 files changed +242 -56
ts/packages/cli/CHANGELOG.md
+13
@@ -4,6 +4,19 @@
4
5 ### Patch Changes
6
7 +- `composio link` and `composio dev connected-accounts link` now print the
8 + authorization URL when stderr is not a terminal, as under a script, CI or a
9 + coding agent, before they wait for the authorization. The URL used to go
10 + through terminal decoration that is dropped off a terminal, so a run with
11 + `--no-browser` printed nothing until it timed out and an agent had no URL to
12 + show the person. The instructions name `--no-wait`, which returns the URL as
13 + JSON at once, and the `composio-cli` skill now teaches it.
14 +
15 +- `composio login` and `composio link` stop waiting for an authorization after
16 + 10 minutes, checking every 5 seconds once a short ramp is over. The wait used
17 + to double after every check, so it took about 2 hours 44 minutes to give up,
18 + although `composio login`'s hint promised 10 minutes.
19 +
20 - Update @composio/client to 2.1.17 to include the latest API changes.
21
22 - Update @composio/client to 2.1.16 to include the latest API changes.
ts/packages/cli/skills-src/composio-cli/index.ts
+10 -2
@@ -131,17 +131,25 @@ const commands: SkillCommand[] = [
131 'Use `link` when `execute` reports that a toolkit is not connected, or when the user explicitly wants to authorize an account.',
132 examples: [
133 {
134 - code: 'composio link gmail\ncomposio link googlecalendar --no-browser',
134 + code: 'composio link gmail\ncomposio link googlecalendar --no-browser --no-wait',
135 },
136 ],
137 flags: [
138 + {
139 + name: '`--no-wait`',
140 + description:
141 + 'Print the authorization URL as JSON (`redirect_url`) and return at once instead of waiting for the authorization.',
142 + },
143 {
144 name: '`--alias`',
145 description:
146 'Assign an alias to the connected account. Required when creating an additional account for the same toolkit.',
147 },
148 ],
144 - notes: ['Retry the original `execute` command after linking succeeds.'],
149 + notes: [
150 + "When the user has to open the page themselves, run `link` with `--no-wait`, show them the `redirect_url`, and wait for them to say they approved. Without `--no-wait` the command blocks until the authorization completes, so the URL reaches the user only if they can see the command's output.",
151 + 'Retry the original `execute` command after linking succeeds.',
152 + ],
153 },
154 {
155 id: 'listen',
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.format.ts
+25 -2
@@ -1,5 +1,6 @@
1 import { Array as Arr, Effect, Option } from 'effect';
2 import type { CommandTree } from 'src/commands/surface';
3 +import { AUTHORIZATION_TIMEOUT_MINUTES } from 'src/effects/authorization-poll';
4 import { BROWSE_TOOLKITS_HINT } from 'src/commands/toolkits/format';
5 import { printFailure, ReportedFailure } from 'src/effects/report-failure';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -57,16 +58,38 @@ export const BROWSE_AUTH_CONFIGS_HINT =
58
59 // --- human renderers (stderr) ---------------------------------------------------------------
60
61 +/**
62 + * What a command that waits for an authorization writes when stderr is not a terminal: the
63 + * step line and the note are decoration and would be dropped, and the URL with them, leaving
64 + * an agent nothing to show the person it waits for.
65 + */
66 +export const formatNonInteractiveAuthorizationInstructions = (
67 + redirectUrl: string
68 +) => `Open this URL in your browser to authorize the connection:
69 +
70 + ${redirectUrl}
71 +
72 +hint: For agents: Show the URL above to the user to open. This command waits up to ${AUTHORIZATION_TIMEOUT_MINUTES} minutes for the authorization, then prints the connected account as JSON if stdout is redirected. To return right away with the URL instead, run the same command with --no-wait.`;
73 +
74 /**
75 * Points the user at the authorization page: a step line and the URL as a note. `manual` is
62 - * for a page the CLI does not open itself.
76 + * for a page the CLI does not open itself; `waiting` is for a command that then waits for the
77 + * authorization. Off a terminal, a waiting command writes the URL with plain instructions
78 + * instead, since nothing else would show it; one that does not wait prints it on stdout.
79 */
80 export const showRedirectUrl = (
81 ui: TerminalUI,
82 redirectUrl: string,
67 - options: { readonly manual: boolean }
83 + options: { readonly manual: boolean; readonly waiting: boolean }
84 ) =>
85 Effect.gen(function* () {
86 + const { canDecorate } = yield* ui.capabilities;
87 + if (!canDecorate) {
88 + if (options.waiting) {
89 + yield* ui.error(formatNonInteractiveAuthorizationInstructions(redirectUrl));
90 + }
91 + return;
92 + }
93 yield* ui.log.step(
94 options.manual
95 ? 'Open this URL in your browser to authorize'
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+9 -7
@@ -1,4 +1,5 @@
1 -import { Effect, Match, Option, Schedule, pipe } from 'effect';
1 +import { Effect, Match, Option, pipe } from 'effect';
2 +import { authorizationPollSchedule } from 'src/effects/authorization-poll';
3 import type { ComposioClientShape } from '@composio/client/effect';
4 import open from 'open';
5 import { commandInputError } from 'src/commands/errors';
@@ -227,7 +228,7 @@ const openBrowser = (url: string) =>
228 catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
229 });
230
230 -/** Polls the account until it is `ACTIVE`: a 0.3s exponential ramp capped at 5s, 15 attempts. */
231 +/** Polls the account until it is `ACTIVE`, on `authorizationPollSchedule` (ten minutes at most). */
232 const pollUntilActive = (client: ComposioClientShape, connectedAccountId: string) =>
233 Effect.retry(
234 Effect.gen(function* () {
@@ -248,9 +249,7 @@ const pollUntilActive = (client: ComposioClientShape, connectedAccountId: string
249 status: account.status,
250 });
251 }),
251 - Schedule.max([Schedule.exponential('0.3 seconds'), Schedule.spaced('5 seconds')]).pipe(
252 - Schedule.upTo({ times: 15 })
253 - )
252 + authorizationPollSchedule
253 );
254
255 /** Opens the authorization page unless `noBrowser`, then waits for the account to turn `ACTIVE`. */
@@ -261,7 +260,7 @@ const waitForActiveConnection = (
260 noBrowser: boolean
261 ) =>
262 Effect.gen(function* () {
264 - yield* showRedirectUrl(ui, target.redirectUrl, { manual: noBrowser });
263 + yield* showRedirectUrl(ui, target.redirectUrl, { manual: noBrowser, waiting: true });
264
265 const urlSchemeValid = Option.exists(
266 Option.liftThrowable((value: string) => new URL(value))(target.redirectUrl),
@@ -310,7 +309,10 @@ const finishLink = (params: {
309 }) =>
310 params.noWait
311 ? Effect.gen(function* () {
313 - yield* showRedirectUrl(params.ui, params.target.redirectUrl, { manual: true });
312 + yield* showRedirectUrl(params.ui, params.target.redirectUrl, {
313 + manual: true,
314 + waiting: false,
315 + });
316 yield* params.ui.output(
317 formatPendingLinkJson({
318 target: params.target,
ts/packages/cli/src/commands/login/login.handler.ts
+1 -8
@@ -4,7 +4,6 @@ import { APP_VERSION } from 'src/constants';
4 import {
5 browserLogin,
6 emitLoginComplete,
7 - LOGIN_POLL_INTERVAL_SECONDS,
7 LoginSessionError,
8 playgroundTestUserId,
9 storeCredentials,
@@ -75,10 +74,6 @@ type LoginFlow = Data.TaggedEnum<{
74 }>;
75 const LoginFlow = Data.taggedEnum<LoginFlow>();
76
78 -const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;
79 -/** `--poll` keeps checking for the pending login's whole TTL. */
80 -const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);
81 -
77 const invalidOptionValue = commandInputError('login');
78
79 // --- shared steps -----------------------------------------------------------------------------
@@ -119,7 +114,6 @@ const loginWithKey = (params: {
114 readonly key: string;
115 readonly noWait: boolean;
116 readonly announce: boolean;
122 - readonly pollRetries?: number;
117 readonly defaultToFirstOrg?: boolean;
118 }) =>
119 Effect.gen(function* () {
@@ -134,7 +128,7 @@ const loginWithKey = (params: {
128 );
129 const linkedSession = yield* params.noWait
130 ? Effect.flatMap(getSession, requireLinkedNow)
137 - : waitForLinkedSession(getSession, params.pollRetries);
131 + : waitForLinkedSession(getSession);
132
133 const uakApiKey = linkedSession.api_key;
134 const sessionInfo = yield* getSessionInfoByUserApiKey({ userApiKey: uakApiKey });
@@ -232,7 +226,6 @@ export const handlePollLogin = (params: Pick<LoginParams, 'noSkillInstall'>) =>
226 key: pendingLogin.key,
227 noWait: false,
228 announce: false,
235 - pollRetries: LOGIN_POLL_RETRIES,
229 defaultToFirstOrg: true,
230 });
231 yield* pendingLoginSession.clear;
ts/packages/cli/src/effects/authorization-poll.ts new
+27
@@ -0,0 +1,27 @@
1 +import { Schedule } from 'effect';
2 +
3 +/**
4 + * How long `composio login` and `composio link` wait for the person to finish in the browser.
5 + * It is also the lifetime of a pending login, which `composio login --poll` waits out.
6 + */
7 +export const AUTHORIZATION_TIMEOUT_MINUTES = 10;
8 +
9 +/** The longest wait between two checks, once the ramp has reached it. */
10 +export const AUTHORIZATION_POLL_INTERVAL_SECONDS = 5;
11 +
12 +/**
13 + * 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.
15 + *
16 + * `Schedule.min` waits for the shorter of the ramp and the spacing, which caps the ramp.
17 + * (`Schedule.max` would wait for the longer one, and the ramp keeps doubling: fifteen checks
18 + * that way take hours.) `Schedule.max` with `Schedule.during`, whose delay is zero, keeps those
19 + * delays and stops once the time is up.
20 + */
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 +]);
ts/packages/cli/src/effects/browser-login.ts
+13 -25
@@ -3,7 +3,11 @@
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, Schedule, pipe } from 'effect';
6 +import { Data, DateTime, Effect, Option, pipe } from 'effect';
7 +import {
8 + AUTHORIZATION_TIMEOUT_MINUTES,
9 + authorizationPollSchedule,
10 +} from 'src/effects/authorization-poll';
11 import { ExpectedFailure } from 'src/effects/expected-failure';
12 import open from 'open';
13 import type { RetrievedSession } from 'src/models/session';
@@ -40,12 +44,6 @@ class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenE
44
45 export type LinkedSession = Extract<RetrievedSession, { readonly status: 'linked' }>;
46
43 -/** Seconds between two checks of a session that is not linked yet. */
44 -export const LOGIN_POLL_INTERVAL_SECONDS = 5;
45 -
46 -/** How many times a session is checked again before the wait gives up, by default. */
47 -const DEFAULT_LOGIN_POLL_RETRIES = 15;
48 -
47 const POLL_COMMAND = 'composio login --poll';
48
49 // --- presentation -----------------------------------------------------------------------------
@@ -61,7 +59,7 @@ Then run this command to complete login:
59
60 ${params.pollCommand}
61
64 -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 10 minutes, and exits once credentials are saved. Do not ask the user whether to poll — they already requested login.
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.
63
64 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.`;
65
@@ -130,27 +128,17 @@ const requireLinkedSession = (session: RetrievedSession) =>
128 );
129
130 /**
133 - * Checks the session behind a spinner until it is linked, `times` more times at most, waiting
134 - * at least `LOGIN_POLL_INTERVAL_SECONDS` between checks.
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.
133 */
136 -export const waitForLinkedSession = <E, R>(
137 - getSession: Effect.Effect<RetrievedSession, E, R>,
138 - times: number = DEFAULT_LOGIN_POLL_RETRIES
139 -) =>
134 +export const waitForLinkedSession = <E, R>(getSession: Effect.Effect<RetrievedSession, E, R>) =>
135 Effect.gen(function* () {
136 const ui = yield* TerminalUI;
137 return yield* ui.useMakeSpinner('Waiting for login...', spinner =>
143 - Effect.retry(Effect.flatMap(getSession, requireLinkedSession), {
144 - // v4 dropped `Schedule.intersect`/`Schedule.recurs`; `Schedule.max` recurs while every
145 - // schedule in the list still wants to and waits for the slowest one between attempts
146 - // (the v4 equivalent of intersecting delay-producing schedules), and the retry count
147 - // cap moves onto `Effect.retry`'s own `times` option.
148 - schedule: Schedule.max([
149 - Schedule.exponential('0.3 seconds'),
150 - Schedule.spaced(`${LOGIN_POLL_INTERVAL_SECONDS} seconds`),
151 - ]),
152 - times,
153 - }).pipe(
138 + Effect.retry(
139 + Effect.flatMap(getSession, requireLinkedSession),
140 + authorizationPollSchedule
141 + ).pipe(
142 Effect.tap(() => spinner.stop('Login successful')),
143 Effect.tapError(() => spinner.error('Login timed out. Please try again.'))
144 )
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+92 -2
@@ -22,6 +22,7 @@ import {
22 LIST_WITH_AUTH_CONFIG_MESSAGE,
23 ROOT_AUTH_CONFIG_MESSAGE,
24 TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
25 + formatNonInteractiveAuthorizationInstructions,
26 missingArgumentMessage,
27 } from 'src/commands/connected-accounts/link/connected-accounts.link.format';
28 import { CommandSurface, MissingActingUserError } from 'src/commands/surface';
@@ -32,7 +33,7 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
33 import { ComposioClientSingleton } from 'src/services/composio-clients';
34 import { NodeOs } from 'src/services/node-os';
35 import { NodeProcess } from 'src/services/node-process';
35 -import type { TerminalUI } from 'src/services/terminal-ui';
36 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
37 import { ProjectContext } from 'src/services/project-context';
38 import { ComposioUserContext } from 'src/services/user-context';
39 import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
@@ -45,7 +46,7 @@ import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provid
46 import { makeOrgProject } from 'test/__utils__/models/account';
47 import { exitCodeOf } from 'test/__utils__/exit-code';
48 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
48 -import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
49 +import { TerminalUITest, terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
50 import open from 'open';
51 import { afterEach, vi } from 'vitest';
52
@@ -121,6 +122,8 @@ interface LinkFixture {
122 readonly connectedAccountsListFails?: boolean;
123 /** Makes the first N `connectedAccounts.retrieve` calls fail, for the polling retries. */
124 readonly retrieveFailsFirst?: number;
125 + /** Runs before every `connectedAccounts.retrieve`, i.e. at every poll while the link waits. */
126 + readonly onRetrieve?: () => void;
127 /** Replaces the headless test terminal, e.g. with `redirectedTerminalUI`. */
128 readonly terminal?: Layer.Layer<TerminalUI>;
129 }
@@ -188,6 +191,7 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
191 ? () => Stream.fail(new Error('connectedAccounts.list is down'))
192 : connectedAccounts.connectedAccounts.listStream,
193 retrieve: (nanoid: string) => {
194 + fixture.onRetrieve?.();
195 retrieveAttempts += 1;
196 return retrieveAttempts <= (fixture.retrieveFailsFirst ?? 0)
197 ? Effect.fail(new Error(`transient retrieve failure ${retrieveAttempts}`))
@@ -367,6 +371,21 @@ const runWithAdvancingClock = <A, E>(effect: Effect.Effect<A, E>) =>
371 return result;
372 });
373
374 +/** The headless test terminal with stderr a TTY, so the link's decoration renders. */
375 +const decoratingTerminal = Layer.succeed(
376 + TerminalUI,
377 + TerminalUI.of({
378 + ...terminalUITestImpl,
379 + capabilities: Effect.succeed(
380 + getTerminalCapabilities({
381 + stdin: { isTTY: false },
382 + stdout: { isTTY: false },
383 + stderr: { isTTY: true },
384 + })
385 + ),
386 + })
387 +);
388 +
389 const devSurface = (flags: { userId?: string; projectName?: string } = {}) =>
390 CommandSurface.dev({
391 userId: Option.fromUndefinedOr(flags.userId),
@@ -1013,6 +1032,7 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
1032 accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })],
1033 toolRouterLink: () =>
1034 Effect.succeed({ connected_account_id: 'con_new', redirect_url: 'notaurl' }),
1035 + terminal: decoratingTerminal,
1036 });
1037 const output = yield* handleToolRouterLink(
1038 params({ toolkit: Option.some('gmail'), noWait: false })
@@ -1043,6 +1063,7 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
1063 vi.mocked(open).mockRejectedValueOnce(new Error('no browser'));
1064 const { layer } = linkHandlerTest({
1065 accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })],
1066 + terminal: decoratingTerminal,
1067 });
1068 const output = yield* handleToolRouterLink(
1069 params({ toolkit: Option.some('gmail'), noWait: false, noBrowser: false })
@@ -1126,3 +1147,72 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
1147 })
1148 );
1149 });
1150 +
1151 +describe('connected-accounts link handler: waiting off a terminal', () => {
1152 + // Every stream redirected, as an agent's shell runs the command. The first two polls find
1153 + // nothing, so the link is still waiting when `stderrWhileWaiting` is read, at the first one.
1154 + it.effect.each([
1155 + {
1156 + flow: 'a toolkit',
1157 + account: 'con_new',
1158 + redirectUrl: TOOL_ROUTER_LINK_TARGET.redirect_url,
1159 + surface: undefined,
1160 + directoryProject: undefined,
1161 + link: () => handleToolRouterLink(params({ toolkit: Option.some('gmail'), noWait: false })),
1162 + },
1163 + {
1164 + flow: 'an auth config',
1165 + account: LEGACY_LINK_TARGET.connected_account_id,
1166 + redirectUrl: LEGACY_LINK_TARGET.redirect_url,
1167 + surface: devSurface(),
1168 + directoryProject: directory(Option.some('user_directory')),
1169 + link: () =>
1170 + handleLegacyAuthConfigLink(params({ authConfig: Option.some('ac_gmail'), noWait: false })),
1171 + },
1172 + ])(
1173 + '[Given] --no-browser and $flow [Then] stderr has the URL before the wait, stdout the JSON after',
1174 + ({ account: accountId, redirectUrl, surface, directoryProject, link }) =>
1175 + Effect.gen(function* () {
1176 + const terminal = redirectedTerminalUI();
1177 + let stderrWhileWaiting: string | undefined;
1178 + const { layer } = linkHandlerTest({
1179 + ...(surface ? { surface } : {}),
1180 + ...(directoryProject ? { directoryProject } : {}),
1181 + accounts: [
1182 + account({ id: accountId, user_id: 'poll-source', alias: null, word_id: null }),
1183 + ],
1184 + retrieveFailsFirst: 2,
1185 + onRetrieve: () => {
1186 + stderrWhileWaiting ??= terminal.stderr();
1187 + },
1188 + terminal: terminal.layer,
1189 + });
1190 +
1191 + yield* runWithAdvancingClock(link().pipe(Effect.provide(layer)));
1192 +
1193 + expect(stderrWhileWaiting).toBe(
1194 + `${formatNonInteractiveAuthorizationInstructions(redirectUrl)}\n`
1195 + );
1196 + const stdout = terminal.stdout();
1197 + expect(JSON.parse(stdout)).toMatchObject({ status: 'success', redirect_url: redirectUrl });
1198 + expect(vi.mocked(open)).not.toHaveBeenCalled();
1199 + })
1200 + );
1201 +
1202 + it.effect('[Given] --no-wait [Then] stderr stays empty: the URL is in the stdout JSON', () =>
1203 + Effect.gen(function* () {
1204 + const terminal = redirectedTerminalUI();
1205 + const { layer } = linkHandlerTest({ terminal: terminal.layer });
1206 +
1207 + yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
1208 + Effect.provide(layer)
1209 + );
1210 +
1211 + expect(terminal.stderr()).toBe('');
1212 + expect(JSON.parse(terminal.stdout())).toMatchObject({
1213 + status: 'pending',
1214 + redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url,
1215 + });
1216 + })
1217 + );
1218 +});
ts/packages/cli/test/src/commands/request-failures.client.test.ts
+2 -10
@@ -244,10 +244,6 @@ describe('CLI: a rejected request the command recovers from', () => {
244
245 const LISTING = '/api/v3.1/connected_accounts?';
246 const withoutExistingAccounts = () => stubClientResources(['connectedAccounts'], forbidden);
247 - const redirect = [
248 - 'Open this URL in your browser to authorize',
249 - '[Redirect URL] https://app.composio.dev/link?token=lt_test_token',
250 - ];
247 const pending = (fields: Record<string, string>) =>
248 JSON.stringify(
249 {
@@ -270,7 +266,7 @@ describe('CLI: a rejected request the command recovers from', () => {
266
267 expect(lines).toEqual([
268 'Linking gmail...',
273 - ...redirect,
269 + // Off a terminal `--no-wait` prints the URL only in its JSON.
270 pending({ toolkit: 'gmail', project_type: 'CONSUMER' }),
271 ]);
272 expect(stub.requests.map(request => request.path)).toEqual([
@@ -297,11 +293,7 @@ describe('CLI: a rejected request the command recovers from', () => {
293 ]).pipe(Effect.provide(stub.layer));
294 const lines = yield* MockConsole.getLines({ stripAnsi: true });
295
300 - expect(lines).toEqual([
301 - 'Creating link session...',
302 - ...redirect,
303 - pending({ project_type: 'DEVELOPER' }),
304 - ]);
296 + expect(lines).toEqual(['Creating link session...', pending({ project_type: 'DEVELOPER' })]);
297 expect(stub.requests.map(request => request.path)).toEqual([
298 `${LISTING}user_ids=user_1&auth_config_ids=ac_1&statuses=ACTIVE&limit=50`,
299 ]);
ts/packages/cli/test/src/effects/authorization-poll.test.ts new
+50
@@ -0,0 +1,50 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Clock, Effect, Exit, Fiber } from 'effect';
3 +import { TestClock } from 'effect/testing';
4 +import {
5 + AUTHORIZATION_POLL_INTERVAL_SECONDS,
6 + AUTHORIZATION_TIMEOUT_MINUTES,
7 + authorizationPollSchedule,
8 +} from 'src/effects/authorization-poll';
9 +
10 +/** 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);
16 + });
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 +});
28 +
29 +describe('authorizationPollSchedule', () => {
30 + it.effect('ramps from 0.3s and never waits longer than the interval between checks', () =>
31 + Effect.gen(function* () {
32 + const { checkedAt } = yield* checksOfAPendingAuthorization;
33 + const gaps = checkedAt.slice(1).map((time, index) => time - checkedAt[index]!);
34 +
35 + expect(gaps.slice(0, 6)).toEqual([300, 600, 1200, 2400, 4800, 5000]);
36 + expect(Math.max(...gaps)).toBe(AUTHORIZATION_POLL_INTERVAL_SECONDS * 1000);
37 + })
38 + );
39 +
40 + it.effect('gives up once the timeout has passed, not hours later', () =>
41 + Effect.gen(function* () {
42 + const { exit, checkedAt } = yield* checksOfAPendingAuthorization;
43 + const timeoutMs = AUTHORIZATION_TIMEOUT_MINUTES * 60_000;
44 +
45 + expect(Exit.isFailure(exit)).toBe(true);
46 + expect(checkedAt.at(-1)).toBeGreaterThan(timeoutMs - 5_000);
47 + expect(checkedAt.at(-1)).toBeLessThanOrEqual(timeoutMs + 5_000);
48 + })
49 + );
50 +});