@devries-cameron20 / composio Mirror · read-only / commits / a0c51b01e
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, 07:15 UTC

fix(cli): page through every connected account in connections list (#5174)

## What was asked `composio connections list` returned at most 50 connected accounts with no pagination and no warning that the list was cut off. For an account with more than 50 connections, toolkits past the first page (e.g. an ACTIVE Slack connection) looked disconnected. The request was to make the list complete. ## Root cause `GET /api/v3.1/connected_accounts` caps the page size at 50: a larger `limit` is clamped without an error, and the response carries a `next_cursor`. The CLI sent `limit: 1000` once and never read `next_cursor`, in three places: - `connections list`: printed only the first 50 accounts - `connections remove <account>`: could not find an account past the first 50 - the session connection lookup (`listActiveConnectedAccounts`, used by `composio execute` sessions): left out toolkits whose accounts were past the first 50 active ones ## Change - New `listAllConnectedAccounts` (`src/services/list-all-connected-accounts.ts`) follows `next_cursor` to the last page with `limit: 50`. - `connections list`, `connections remove`, and both session lookups use it. - New `decodeAllConnectedAccountPages` decodes the collected items with the same allowlist and redacted error as `decodeConnectedAccountList`. - Since the shared active-accounts list is now complete, `listConnectedAccountsForToolkit` always derives from it. The toolkit-filtered fallback (and its "first 100" slice) is removed. - CHANGELOG entry under Unreleased → Patch Changes. `--toolkit <slug>` was only a partial workaround before this change: it was also capped at 50 accounts per toolkit. ## Tests - New argv-level test: 50 accounts on page 1, Slack on page 2 → `connections list` prints both and makes 2 requests. It fails on the old handler. - Replaced the two fallback tests in `connected-account-selection.test.ts` with one that pages via `next_cursor` (asserts `limit=50`, `cursor=page-2`, no toolkit-filtered request). - `request-failures.client.test.ts`: expected listing query is now `limit=50`. Checks run locally: - `pnpm --filter @composio/cli run typecheck`: 0 errors - `pnpm --filter @composio/cli run lint:effect`: 0 errors - `vitest run` (full CLI suite): 2900 passed, 1 skipped - `validate:skills`, `validate:boundaries`, `validate:command-tests`: OK Not verified: a live run against an account with more than 50 connections. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Mustafa Ansari [zen] <mustafa@composio.dev> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: jkomyno <alberto@composio.dev>

composio-zen[bot] committed Nov 2, 2026 at 21:03 UTC a0c51b01ea6325ca46b1fb3393fe574dffa57ffe
16 files changed +490 -219
ts/packages/cli/CHANGELOG.md
+11
@@ -55,6 +55,17 @@
55 omit command input properties instead of reporting synthetic defaults, false
56 booleans, or zero counts for input that was never parsed.
57
58 +- `composio connections list` now prints every connection. The server serves
59 + at most 50 connected accounts per request and the CLI read only the first
60 + page, so a user with more than 50 saw a partial list with no sign it was cut
61 + off, and a connected toolkit (such as an active Slack account) looked
62 + disconnected. `composio connections remove` could not find an account past
63 + the first 50, and `composio execute` sessions left out toolkits whose
64 + accounts were past the first 50 active ones. All three now follow
65 + `next_cursor` through every page.
66 + `composio link --list` and alias-conflict checks when linking also read
67 + every page, including accounts filtered by an auth config.
68 +
69 - `composio dev triggers listen --toolkits` now matches toolkits whose slug
70 contains an underscore, such as `one_drive`, `launch_darkly` and
71 `agent_mail`. Events carry no toolkit slug, so the listener took the first
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+18 -28
@@ -25,6 +25,7 @@ import {
25 } from 'src/services/connected-account-selection';
26 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
27 import { idempotent } from 'src/services/composio-request';
28 +import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
29 import {
30 BrowserOpenError,
31 ConnectedAccountsDecodeError,
@@ -114,23 +115,19 @@ const resolveNormalizedAliasOption = (alias: Option.Option<string>, tree: Comman
115 )
116 );
117
117 -/** The user's active accounts in a toolkit or an auth config, up to one page of 100. */
118 +/** Every active account in the user's toolkit or auth config. */
119 const listActiveConnectedAccounts = (params: {
120 readonly client: ComposioClientShape;
121 readonly userId: string;
122 readonly toolkitSlug?: string;
123 readonly authConfigId?: string;
124 }) =>
124 - params.client.connectedAccounts.list(
125 - {
126 - user_ids: [params.userId],
127 - toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
128 - auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
129 - statuses: ['ACTIVE'],
130 - limit: 100,
131 - },
132 - idempotent
133 - );
125 + listAllConnectedAccounts(params.client, {
126 + user_ids: [params.userId],
127 + toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
128 + auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
129 + statuses: ['ACTIVE'],
130 + });
131
132 /**
133 * The accounts that power the `--alias` hints. This fetch is auxiliary: a transient list
@@ -138,7 +135,6 @@ const listActiveConnectedAccounts = (params: {
135 */
136 const existingAccountsForHints = (params: Parameters<typeof listActiveConnectedAccounts>[0]) =>
137 listActiveConnectedAccounts(params).pipe(
141 - Effect.map((response): ReadonlyArray<ExistingAccountLabel> => response.items),
138 Effect.catch(() => Effect.succeed<ReadonlyArray<ExistingAccountLabel>>([]))
139 );
140
@@ -396,24 +392,18 @@ export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams)
392
393 const accounts = yield* ui.withSpinner(
394 `Listing connected accounts for "${toolkitSlug}"...`,
399 - client.connectedAccounts
400 - .list(
401 - {
402 - toolkit_slugs: [toolkitSlug],
403 - user_ids: [resolvedUserId],
404 - statuses: ['ACTIVE'],
405 - limit: 100,
406 - },
407 - idempotent
408 - )
409 - .pipe(
410 - failedWith(
411 - ConnectedAccountsRequestError,
412 - `Failed to list connected accounts for "${toolkitSlug}".`
413 - )
395 + listAllConnectedAccounts(client, {
396 + toolkit_slugs: [toolkitSlug],
397 + user_ids: [resolvedUserId],
398 + statuses: ['ACTIVE'],
399 + }).pipe(
400 + failedWith(
401 + ConnectedAccountsRequestError,
402 + `Failed to list connected accounts for "${toolkitSlug}".`
403 )
404 + )
405 );
416 - const connectedAccounts = yield* decodeConnectedAccountItems(accounts.items).pipe(
406 + const connectedAccounts = yield* decodeConnectedAccountItems(accounts).pipe(
407 Effect.mapError(
408 cause =>
409 new ConnectedAccountsDecodeError({
ts/packages/cli/src/commands/connections/list/connections.list.handler.ts
+24 -16
@@ -1,7 +1,7 @@
1 -import { Effect, Option } from 'effect';
1 +import { Effect, Match, Option } from 'effect';
2 import {
3 CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
4 - decodeConnectedAccountList,
4 + decodeAllConnectedAccountPages,
5 } from 'src/effects/decode-connected-account-list';
6 import { failedWith } from 'src/effects/request-error';
7 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -11,7 +11,7 @@ import {
11 getConnectedAccountPermissionGroup,
12 getConsumerPermissionSnapshot,
13 } from 'src/services/tool-permissions';
14 -import { idempotent } from 'src/services/composio-request';
14 +import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
15 import { ConnectionsListRequestError } from './connections.list.errors';
16 import { formatConnectionsJson } from './connections.list.format';
17
@@ -35,27 +35,35 @@ export const runConnectionsList = ({ toolkit }: ConnectionsListParams) =>
35 orgId: resolvedProject.orgId,
36 projectId: resolvedProject.projectId,
37 });
38 - const rawResult = yield* client.connectedAccounts
39 - .list(
40 - {
41 - toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
42 - user_ids: [consumerUserId],
43 - limit: 1000,
44 - },
45 - idempotent
38 + const rawItems = yield* listAllConnectedAccounts(client, {
39 + toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
40 + user_ids: [consumerUserId],
41 + }).pipe(
42 + Effect.mapError(
43 + cause =>
44 + new ConnectionsListRequestError({
45 + message: Match.value(cause).pipe(
46 + Match.tag(
47 + 'effects/ConnectedAccountListShapeError',
48 + () => CONNECTED_ACCOUNTS_SHAPE_MESSAGE
49 + ),
50 + Match.orElse(() => 'Failed to list connections.')
51 + ),
52 + cause,
53 + })
54 )
47 - .pipe(failedWith(ConnectionsListRequestError, 'Failed to list connections.'));
48 - const result = yield* decodeConnectedAccountList(rawResult).pipe(
55 + );
56 + const items = yield* decodeAllConnectedAccountPages(rawItems).pipe(
57 failedWith(ConnectionsListRequestError, CONNECTED_ACCOUNTS_SHAPE_MESSAGE)
58 );
59 const permissionSnapshot = yield* getConsumerPermissionSnapshot({
60 orgId: resolvedProject.orgId,
61 projectId: resolvedProject.projectId,
62 consumerUserId,
55 - connectedAccountIds: result.items.map(item => item.id),
63 + connectedAccountIds: items.map(item => item.id),
64 });
65 const permissionGroups = new Map(
58 - result.items.map(item => [
66 + items.map(item => [
67 item.id,
68 getConnectedAccountPermissionGroup({
69 snapshot: permissionSnapshot,
@@ -64,5 +72,5 @@ export const runConnectionsList = ({ toolkit }: ConnectionsListParams) =>
72 ])
73 );
74
67 - yield* ui.output(formatConnectionsJson(result.items, permissionGroups), { force: true });
75 + yield* ui.output(formatConnectionsJson(items, permissionGroups), { force: true });
76 });
ts/packages/cli/src/commands/connections/remove/connections.remove.handler.ts
+21 -9
@@ -1,8 +1,8 @@
1 -import { Effect } from 'effect';
1 +import { Effect, Match } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 import {
4 CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
5 - decodeConnectedAccountList,
5 + decodeAllConnectedAccountPages,
6 } from 'src/effects/decode-connected-account-list';
7 import { failedWith } from 'src/effects/request-error';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -11,7 +11,7 @@ import { actingUser } from 'src/commands/surface';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold } from 'src/ui/colors';
13 import { redact } from 'src/ui/redact';
14 -import { idempotent } from 'src/services/composio-request';
14 +import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
15 import { ConnectionsRemovalRequestError } from './connections.remove.errors';
16
17 /** The flags of `composio connections remove`. */
@@ -108,16 +108,28 @@ export const runConnectionsRemove = ({ account, yes }: ConnectionsRemoveParams)
108 orgId: resolvedProject.orgId,
109 projectId: resolvedProject.projectId,
110 });
111 - const rawResult = yield* ui.withSpinner(
111 + const rawItems = yield* ui.withSpinner(
112 'Fetching connections...',
113 - client.connectedAccounts
114 - .list({ user_ids: [consumerUserId], limit: 1000 }, idempotent)
115 - .pipe(failedWith(ConnectionsRemovalRequestError, 'Failed to list connections.'))
113 + listAllConnectedAccounts(client, { user_ids: [consumerUserId] }).pipe(
114 + Effect.mapError(
115 + cause =>
116 + new ConnectionsRemovalRequestError({
117 + message: Match.value(cause).pipe(
118 + Match.tag(
119 + 'effects/ConnectedAccountListShapeError',
120 + () => CONNECTED_ACCOUNTS_SHAPE_MESSAGE
121 + ),
122 + Match.orElse(() => 'Failed to list connections.')
123 + ),
124 + cause,
125 + })
126 + )
127 + )
128 );
117 - const result = yield* decodeConnectedAccountList(rawResult).pipe(
129 + const accounts = yield* decodeAllConnectedAccountPages(rawItems).pipe(
130 failedWith(ConnectionsRemovalRequestError, CONNECTED_ACCOUNTS_SHAPE_MESSAGE)
131 );
120 - const resolved = resolveAccount({ accounts: result.items, selector: account });
132 + const resolved = resolveAccount({ accounts, selector: account });
133
134 if ('error' in resolved) {
135 return yield* invalidInput(resolved.error, '<account>');
ts/packages/cli/src/effects/decode-connected-account-list.ts
+19
@@ -89,6 +89,25 @@ export const decodeConnectedAccountList = (
89 Effect.tap(result => warnOnUnknownStatuses(result.items))
90 );
91
92 +/**
93 + * Decodes the accounts of every page of a connected-accounts listing (see
94 + * `listAllConnectedAccounts`) through the same allowlist as
95 + * {@link decodeConnectedAccountList}, failing with the same redacted
96 + * {@link ConnectedAccountListShapeError}, for commands that print the accounts.
97 + */
98 +export const decodeAllConnectedAccountPages = (
99 + items: ApiConnectedAccountListResponse['items']
100 +): Effect.Effect<ConnectedAccountItems, ConnectedAccountListShapeError, TerminalUI> =>
101 + Schema.decodeEffect(ConnectedAccountItems)(items).pipe(
102 + Effect.mapError(
103 + error =>
104 + new ConnectedAccountListShapeError({
105 + message: `Mismatched fields: ${formatParseErrorRedacted(error)}`,
106 + })
107 + ),
108 + Effect.tap(decoded => warnOnUnknownStatuses(decoded))
109 + );
110 +
111 /**
112 * Item-level variant of {@link decodeConnectedAccountList} for call sites
113 * that decode `response.items` rather than the whole list response. It fails
ts/packages/cli/src/services/connected-account-selection.ts
+14 -64
@@ -5,8 +5,8 @@ import type { ConnectedAccountItem } from 'src/models/connected-accounts';
5 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
6 import type { TerminalUI } from 'src/services/terminal-ui';
7 import { memoizeInProcess } from 'src/utils/memoize-in-process';
8 -import { idempotent } from 'src/services/composio-request';
8 import { clientScopeKey } from 'src/services/composio-clients';
9 +import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
10
11 // `status` is an open enum, so this is shape-identical to
12 // `ConnectedAccountItem`; tool-router rows normalize statuses outside the
@@ -155,66 +155,25 @@ export const formatConnectedAccountChoices = (
155 * view is a subset of this list, so both read from here instead of issuing
156 * their own `GET /connected_accounts`.
157 *
158 - * The page size is the session path's existing one; a user with more active
159 - * accounts than that was already truncated there. Fails with the client's
160 - * error; each caller wraps it in its own error.
158 + * Every page is fetched (`listAllConnectedAccounts`): the server serves at
159 + * most 50 accounts per request, and a first page alone dropped connected
160 + * toolkits from the session for users with more active accounts than that.
161 + * Fails with the client's error; each caller wraps it in its own error.
162 */
162 -const ACTIVE_ACCOUNTS_PAGE_SIZE = 1000;
163 -
163 export const listActiveConnectedAccounts = memoizeInProcess({
164 keyOf: (input: { readonly client: ComposioClientShape; readonly userId: string }) =>
165 `${clientScopeKey(input.client)}\u0000${input.userId}`,
166 make: ({ client, userId }) =>
168 - client.connectedAccounts.list(
169 - {
170 - user_ids: [userId],
171 - statuses: ['ACTIVE'],
172 - limit: ACTIVE_ACCOUNTS_PAGE_SIZE,
173 - },
174 - idempotent
175 - ),
167 + listAllConnectedAccounts(client, { user_ids: [userId], statuses: ['ACTIVE'] }),
168 });
169
178 -const TOOLKIT_ACCOUNTS_PAGE_SIZE = 100;
179 -
180 -// The account picker's own query: one toolkit, first 100 active accounts, in
181 -// server order. Kept as the fallback so results stay identical when the
182 -// shared list cannot stand in for it.
183 -const fetchConnectedAccountsForToolkit = (params: {
184 - readonly client: ComposioClientShape;
185 - readonly userId: string;
186 - readonly toolkitSlug: string;
187 -}) =>
188 - params.client.connectedAccounts
189 - .list(
190 - {
191 - toolkit_slugs: [params.toolkitSlug],
192 - user_ids: [params.userId],
193 - statuses: ['ACTIVE'],
194 - limit: TOOLKIT_ACCOUNTS_PAGE_SIZE,
195 - },
196 - idempotent
197 - )
198 - .pipe(Effect.map(response => response.items));
199 -
170 /**
201 - * The active accounts of one toolkit, derived from the shared per-user list
202 - * when that list is complete, so `composio execute` does not issue a second,
171 + * The active accounts of one toolkit, in server order, derived from the
172 + * shared per-user list so `composio execute` does not issue a second,
173 * toolkit-filtered `GET /connected_accounts` next to the one session creation
204 - * needs anyway.
205 - *
206 - * Derivation reproduces the server query: same slug match, server order
207 - * preserved, first 100. If the shared list may be truncated (more active
208 - * accounts than its page holds), the toolkit's accounts may sit past the cut,
209 - * so the original filtered request runs instead. A page is taken as complete
210 - * when it is shorter than the requested size and carries no cursor.
211 - * `total_items` is deliberately not consulted: whether it honors the status
212 - * filter is a server detail, and a count that did not would make the derived
213 - * path look truncated on every call and silently fall back forever.
214 - *
215 - * The slug is trimmed and lower-cased the way the grouping helpers above
216 - * normalize toolkit slugs, and the trimmed slug is what the fallback sends,
217 - * so a padded `--toolkit` value resolves the same way on both paths.
174 + * needs anyway. The slug is trimmed and lower-cased the way the grouping
175 + * helpers above normalize toolkit slugs, so a padded `--toolkit` value still
176 + * matches.
177 */
178 export const listConnectedAccountsForToolkit = (params: {
179 readonly client: ComposioClientShape;
@@ -222,21 +181,12 @@ export const listConnectedAccountsForToolkit = (params: {
181 readonly toolkitSlug: string;
182 }) =>
183 Effect.gen(function* () {
225 - const toolkitSlug = params.toolkitSlug.trim();
226 - const shared = yield* listActiveConnectedAccounts({
184 + const items = yield* listActiveConnectedAccounts({
185 client: params.client,
186 userId: params.userId,
187 });
230 - const items = shared.items;
231 - const complete = shared.next_cursor == null && items.length < ACTIVE_ACCOUNTS_PAGE_SIZE;
232 - if (!complete) {
233 - return yield* fetchConnectedAccountsForToolkit({ ...params, toolkitSlug });
234 - }
235 -
236 - const wantedToolkit = normalizeSelector(toolkitSlug);
237 - return items
238 - .filter(item => normalizeSelector(item.toolkit.slug) === wantedToolkit)
239 - .slice(0, TOOLKIT_ACCOUNTS_PAGE_SIZE);
188 + const wantedToolkit = normalizeSelector(params.toolkitSlug);
189 + return items.filter(item => normalizeSelector(item.toolkit.slug) === wantedToolkit);
190 });
191
192 export class ConnectedAccountResolutionError extends Data.TaggedError(
ts/packages/cli/src/services/list-all-connected-accounts.ts new
+49
@@ -0,0 +1,49 @@
1 +import type { ComposioClientShape, ComposioError } from '@composio/client/effect';
2 +import type {
3 + ConnectedAccountListParams,
4 + ConnectedAccountListResponse,
5 +} from '@composio/client/resources/connected-accounts';
6 +import { Effect, Stream } from 'effect';
7 +import { ConnectedAccountListShapeError } from 'src/effects/decode-connected-account-list';
8 +import { idempotent } from 'src/services/composio-request';
9 +
10 +/**
11 + * The largest page `GET /connected_accounts` serves. The server clamps a
12 + * larger `limit` to this without an error, so a single request for more
13 + * returns 50 items and a `next_cursor`.
14 + */
15 +export const CONNECTED_ACCOUNTS_MAX_PAGE_SIZE = 50;
16 +
17 +/**
18 + * Lists every connected account matching `query`, following `next_cursor`
19 + * page by page until the server reports no next page. A single
20 + * `connectedAccounts.list` call returns at most
21 + * {@link CONNECTED_ACCOUNTS_MAX_PAGE_SIZE} accounts, so a caller that needs
22 + * the whole list (e.g. "is this toolkit connected?") must come through here.
23 + * The client's stream owns cursor traversal and pagination guards. Callers
24 + * decode the collected accounts; pagination failures keep the CLI's redacted
25 + * shape-error contract.
26 + */
27 +export const listAllConnectedAccounts = (
28 + client: ComposioClientShape,
29 + query: Omit<ConnectedAccountListParams, 'cursor' | 'limit'>
30 +): Effect.Effect<
31 + ConnectedAccountListResponse['items'],
32 + ComposioError | ConnectedAccountListShapeError
33 +> =>
34 + client.connectedAccounts
35 + .listStream({ ...query, limit: CONNECTED_ACCOUNTS_MAX_PAGE_SIZE }, idempotent)
36 + .pipe(
37 + Stream.runCollect,
38 + Effect.catchTag(
39 + '@composio/client/ConfigurationError',
40 + (error): Effect.Effect<never, ComposioError | ConnectedAccountListShapeError> =>
41 + error.message.startsWith('Pagination ')
42 + ? Effect.fail(
43 + new ConnectedAccountListShapeError({
44 + message: 'Invalid connected-account pagination response.',
45 + })
46 + )
47 + : Effect.fail(error)
48 + )
49 + );
ts/packages/cli/src/services/tool-router-session-connections.ts
+8 -12
@@ -8,7 +8,7 @@ import {
8 resolveDefaultConnectedAccountsByToolkit,
9 type SelectableConnectedAccount,
10 } from 'src/services/connected-account-selection';
11 -import { idempotent } from 'src/services/composio-request';
11 +import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
12
13 type RawConnectedAccount = {
14 readonly id: string;
@@ -58,15 +58,11 @@ const listConnectedAccountsForToolkits = (
58 userId: string,
59 toolkits: ReadonlyArray<string>
60 ) =>
61 - client.connectedAccounts.list(
62 - {
63 - user_ids: [userId],
64 - statuses: ['ACTIVE'],
65 - toolkit_slugs: [...toolkits],
66 - limit: 1000,
67 - },
68 - idempotent
69 - );
61 + listAllConnectedAccounts(client, {
62 + user_ids: [userId],
63 + statuses: ['ACTIVE'],
64 + toolkit_slugs: [...toolkits],
65 + });
66
67 export const resolveToolRouterSessionConnections = (
68 client: ComposioClientShape,
@@ -81,8 +77,8 @@ export const resolveToolRouterSessionConnections = (
77 // account picker, so it is fetched once per process and shared.
78 listActiveConnectedAccounts({ client, userId })
79 ).pipe(
84 - Effect.map(response => {
85 - const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;
80 + Effect.map(accounts => {
81 + const items = accounts as ReadonlyArray<RawConnectedAccount>;
82 const unknownStatuses = new Set<string>();
83 const normalizedItems: SelectableConnectedAccount[] = items.map(item => {
84 const normalizedStatus = normalizeConnectedAccountStatus(item.status);
ts/packages/cli/test/__utils__/layers/connected-accounts.ts
+69 -54
@@ -3,7 +3,7 @@ import type {
3 AuthConfigCreateResponse,
4 } from '@composio/client/resources/auth-configs';
5 import type { LinkCreateResponse } from '@composio/client/resources/link';
6 -import { Array as Arr, Effect, Layer } from 'effect';
6 +import { Array as Arr, Effect, Layer, Stream } from 'effect';
7 import type { AuthConfigItem } from 'src/models/auth-configs';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 import {
@@ -179,64 +179,79 @@ export const connectedAccountRepositoryMethods = (
179 */
180 export const mockConnectedAccountResources = (
181 connectedAccountsData: ResolvedConnectedAccountsTestData
182 -) => ({
183 - link: {
184 - create: (_params: { auth_config_id: string; user_id: string }) =>
185 - Effect.succeed(
186 - connectedAccountsData.linkResponse ?? {
187 - connected_account_id: 'con_test_link',
188 - expires_at: '2026-12-31T23:59:59Z',
189 - link_token: 'lt_test_token',
190 - redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
191 - }
192 - ),
193 - },
194 - connectedAccounts: {
195 - list: (params?: {
196 - toolkit_slugs?: string[];
197 - user_ids?: string[];
198 - statuses?: string[];
199 - limit?: number;
200 - }) => {
201 - let results = [...connectedAccountsData.items];
182 +) => {
183 + const resources = {
184 + link: {
185 + create: (_params: { auth_config_id: string; user_id: string }) =>
186 + Effect.succeed(
187 + connectedAccountsData.linkResponse ?? {
188 + connected_account_id: 'con_test_link',
189 + expires_at: '2026-12-31T23:59:59Z',
190 + link_token: 'lt_test_token',
191 + redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
192 + }
193 + ),
194 + },
195 + connectedAccounts: {
196 + list: (params?: {
197 + toolkit_slugs?: string[];
198 + user_ids?: string[];
199 + statuses?: string[];
200 + limit?: number;
201 + }) => {
202 + let results = [...connectedAccountsData.items];
203
203 - if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
204 - const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
205 - results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
206 - }
204 + if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
205 + const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
206 + results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
207 + }
208
208 - if (params?.user_ids && params.user_ids.length > 0) {
209 - const userIds = new Set(params.user_ids);
210 - results = results.filter(item => userIds.has(item.user_id));
211 - }
209 + if (params?.user_ids && params.user_ids.length > 0) {
210 + const userIds = new Set(params.user_ids);
211 + results = results.filter(item => userIds.has(item.user_id));
212 + }
213
213 - if (params?.statuses && params.statuses.length > 0) {
214 - const statuses = new Set(params.statuses);
215 - results = results.filter(item => statuses.has(item.status));
216 - }
214 + if (params?.statuses && params.statuses.length > 0) {
215 + const statuses = new Set(params.statuses);
216 + results = results.filter(item => statuses.has(item.status));
217 + }
218
218 - const limit = params?.limit ?? DEFAULT_PAGE_LIMIT;
219 - return Effect.succeed({
220 - items: results.slice(0, limit),
221 - total_items: results.length,
222 - total_pages: Math.ceil(results.length / limit),
223 - current_page: 1,
224 - next_cursor: null,
225 - });
219 + const limit = params?.limit ?? DEFAULT_PAGE_LIMIT;
220 + return Effect.succeed({
221 + items: results.slice(0, limit),
222 + total_items: results.length,
223 + total_pages: Math.ceil(results.length / limit),
224 + current_page: 1,
225 + next_cursor: null,
226 + });
227 + },
228 + retrieve: (nanoid: string) =>
229 + findById(connectedAccountsData.items, nanoid, () =>
230 + notFoundError(`Connected account "${nanoid}" not found`)
231 + ),
232 + delete: (nanoid: string) =>
233 + findById(connectedAccountsData.items, nanoid, () =>
234 + notFoundError(`Connected account "${nanoid}" not found`)
235 + ).pipe(
236 + Effect.tap(() => Effect.sync(() => connectedAccountsData.onDelete?.(nanoid))),
237 + Effect.as({})
238 + ),
239 },
227 - retrieve: (nanoid: string) =>
228 - findById(connectedAccountsData.items, nanoid, () =>
229 - notFoundError(`Connected account "${nanoid}" not found`)
230 - ),
231 - delete: (nanoid: string) =>
232 - findById(connectedAccountsData.items, nanoid, () =>
233 - notFoundError(`Connected account "${nanoid}" not found`)
234 - ).pipe(
235 - Effect.tap(() => Effect.sync(() => connectedAccountsData.onDelete?.(nanoid))),
236 - Effect.as({})
237 - ),
238 - },
239 -});
240 + };
241 + return {
242 + ...resources,
243 + connectedAccounts: {
244 + ...resources.connectedAccounts,
245 + listStream: (params?: Parameters<typeof resources.connectedAccounts.list>[0]) =>
246 + Stream.fromEffect(
247 + resources.connectedAccounts.list({
248 + ...params,
249 + limit: Math.max(connectedAccountsData.items.length, 1),
250 + })
251 + ).pipe(Stream.flatMap(page => Stream.fromIterable(page.items))),
252 + },
253 + };
254 +};
255
256 /**
257 * A `ComposioToolkitsRepository` that serves only auth configs and connected
ts/packages/cli/test/__utils__/services/stub-composio-client.ts
+2 -2
@@ -58,8 +58,8 @@ export const stubComposioClient = (
58 * client to `respond`; every other resource keeps the test layer's answers.
59 *
60 * The test layer's answers do not model request options (`signal`,
61 - * `maxRetries`, or any header beyond `decode`) and `connectedAccounts.list`
62 - * never returns a `next_cursor`, so pagination, retries, and abort are
61 + * `maxRetries`, or any header beyond `decode`), and its connected-account
62 + * shadows serve fixtures without cursor traversal, so pagination, retries, and abort are
63 * exercised through {@link stubComposioClient}, the real `make` over a
64 * recording transport.
65 */
ts/packages/cli/test/__utils__/services/test-layer.ts
+9 -5
@@ -25,6 +25,7 @@ import {
25 Path,
26 References,
27 Schedule,
28 + Stream,
29 } from 'effect';
30 import { CliConfig, type Command as CliCommand } from 'effect/cli';
31 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
@@ -766,20 +767,23 @@ export const TestLayer = (input?: TestLiveInput) =>
767 Effect.die(new Error(`unexpected network call from the mock Composio client: ${request.url}`))
768 );
769
769 - // Each shadow answers with an Effect, built when the call runs. A shadow
770 + // Each shadow builds its Effect or Stream when consumed. A shadow
771 // ignores the request options
772 // (`signal`, `maxRetries`, headers beyond `decode`), and the
772 - // `connectedAccounts.list` shadow never pages (`next_cursor` is null):
773 + // connected-account shadows serve fixture data without cursor traversal:
774 // pagination, retries, and abort are covered by `stubComposioClient`,
775 // the real `make` over a recording transport.
776 const withShadows = <Resources extends object>(base: Resources, shadows: object): Resources => {
777 const shadowed = { ...base } as Record<string, unknown>;
778 for (const [key, shadow] of Object.entries(shadows) as Array<[string, unknown]>) {
779 shadowed[key] =
779 - typeof shadow === 'function'
780 + typeof shadow === 'function' && key === 'listStream'
781 ? (...args: ReadonlyArray<unknown>) =>
781 - Effect.suspend(() => shadow(...args) as Effect.Effect<unknown, unknown>)
782 - : withShadows((shadowed[key] ?? {}) as object, shadow as object);
782 + Stream.suspend(() => shadow(...args) as Stream.Stream<unknown, unknown>)
783 + : typeof shadow === 'function'
784 + ? (...args: ReadonlyArray<unknown>) =>
785 + Effect.suspend(() => shadow(...args) as Effect.Effect<unknown, unknown>)
786 + : withShadows((shadowed[key] ?? {}) as object, shadow as object);
787 }
788 return shadowed as Resources;
789 };
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.client.cmd.test.ts
+117
@@ -1,5 +1,6 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
@@ -12,7 +13,123 @@ const testLayer = TestLive({
13 const rejection = (status: number, message: string, slug: string) =>
14 Response.json({ error: { message, code: 1000 + status, slug, status } }, { status });
15
16 +const account = (id: string): ConnectedAccountItem => ({
17 + id,
18 + alias: null,
19 + status: 'ACTIVE',
20 + status_reason: null,
21 + is_disabled: false,
22 + user_id: 'consumer-user-org_test',
23 + toolkit: { slug: 'gmail' },
24 + auth_config: {
25 + id: 'ac_gmail',
26 + auth_scheme: 'OAUTH2',
27 + is_composio_managed: true,
28 + is_disabled: false,
29 + },
30 + created_at: '2026-01-01T00:00:00Z',
31 + updated_at: '2026-01-01T00:00:00Z',
32 + test_request_endpoint: '',
33 +});
34 +
35 describe('CLI: composio link over the API client', () => {
36 + layer(testLayer)(it => {
37 + it.effect('lists active accounts beyond the first server page', () =>
38 + Effect.gen(function* () {
39 + const firstPage = Array.from({ length: 50 }, (_, index) => account(`con_${index}`));
40 + const stub = stubClientResources(['connectedAccounts'], request => {
41 + const cursor = new URL(request.path, 'https://stub.invalid').searchParams.get('cursor');
42 + return Response.json({
43 + items: cursor === 'page-2' ? [account('con_last')] : firstPage,
44 + next_cursor: cursor === 'page-2' ? null : 'page-2',
45 + });
46 + });
47 +
48 + yield* cli(['link', 'gmail', '--list']).pipe(Effect.provide(stub.layer));
49 +
50 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
51 + const result = JSON.parse(String(lines.at(-1)));
52 + expect(result.total).toBe(51);
53 + expect(result.items.at(-1).id).toBe('con_last');
54 + expect(stub.requests).toHaveLength(2);
55 + const query = {
56 + user_ids: 'consumer-user-org_test',
57 + toolkit_slugs: 'gmail',
58 + statuses: 'ACTIVE',
59 + limit: '50',
60 + };
61 + expect(
62 + stub.requests.map(request =>
63 + Object.fromEntries(new URL(request.path, 'https://stub.invalid').searchParams)
64 + )
65 + ).toEqual([query, { ...query, cursor: 'page-2' }]);
66 + })
67 + );
68 + });
69 +
70 + describe.each([
71 + {
72 + scope: 'toolkit',
73 + args: ['link', 'gmail', '--alias', 'work', '--no-wait'],
74 + userId: 'consumer-user-org_test',
75 + filter: 'toolkit_slugs',
76 + value: 'gmail',
77 + },
78 + {
79 + scope: 'auth config',
80 + args: [
81 + 'dev',
82 + 'connected-accounts',
83 + 'link',
84 + '--auth-config',
85 + 'ac_1',
86 + '--user-id',
87 + 'user_1',
88 + '--alias',
89 + 'work',
90 + '--no-wait',
91 + ],
92 + userId: 'user_1',
93 + filter: 'auth_config_ids',
94 + value: 'ac_1',
95 + },
96 + ])('alias conflicts in a $scope', ({ args, userId, filter, value }) => {
97 + layer(testLayer)(it => {
98 + it.effect('rejects an alias held by an account on a later page before creating a link', () =>
99 + Effect.gen(function* () {
100 + const pages = [
101 + {
102 + items: Array.from({ length: 50 }, (_, i) => account(`con_${i}`)),
103 + next_cursor: 'page-2',
104 + },
105 + { items: [{ ...account('con_hidden'), alias: 'Work' }], next_cursor: null },
106 + ];
107 + const stub = stubClientResources(['connectedAccounts', 'toolRouter', 'link'], () => {
108 + const page = pages.shift();
109 + return page === undefined
110 + ? rejection(403, 'Unexpected request', 'Forbidden')
111 + : Response.json(page);
112 + });
113 +
114 + const exit = yield* Effect.exit(cli(args).pipe(Effect.provide(stub.layer)));
115 +
116 + expect(exitCodeOf(exit)).toBe(1);
117 + expect((yield* MockConsole.getLines({ stripAnsi: true })).join('\n')).toContain(
118 + 'Alias "work" is already in use by connected account "con_hidden".'
119 + );
120 + expect(stub.requests).toHaveLength(2);
121 + expect(stub.requests.every(request => request.method === 'GET')).toBe(true);
122 + const query = { user_ids: userId, [filter]: value, statuses: 'ACTIVE', limit: '50' };
123 + expect(
124 + stub.requests.map(request =>
125 + Object.fromEntries(new URL(request.path, 'https://stub.invalid').searchParams)
126 + )
127 + ).toEqual([query, { ...query, cursor: 'page-2' }]);
128 + })
129 + );
130 + });
131 + });
132 +
133 layer(testLayer)('[Given] the API rejects the link for a toolkit', it => {
134 it.effect('[Then] the API message and the browse hint are printed', () =>
135 Effect.gen(function* () {
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+4 -1
@@ -2,7 +2,7 @@ import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 import * as BunPath from '@effect/platform-bun/BunPath';
4 import { describe, expect, it } from '@effect/vitest';
5 -import { ConfigProvider, Console, Effect, Fiber, Layer, Option } from 'effect';
5 +import { ConfigProvider, Console, Effect, Fiber, Layer, Option, Stream } from 'effect';
6 import { HttpClient } from 'effect/http';
7 import { TestClock } from 'effect/testing';
8 import * as tempy from 'tempy';
@@ -184,6 +184,9 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
184 list: fixture.connectedAccountsListFails
185 ? () => Effect.fail(new Error('connectedAccounts.list is down'))
186 : connectedAccounts.connectedAccounts.list,
187 + listStream: fixture.connectedAccountsListFails
188 + ? () => Stream.fail(new Error('connectedAccounts.list is down'))
189 + : connectedAccounts.connectedAccounts.listStream,
190 retrieve: (nanoid: string) => {
191 retrieveAttempts += 1;
192 return retrieveAttempts <= (fixture.retrieveFailsFirst ?? 0)
ts/packages/cli/test/src/commands/connections/list/connections.list.cmd.test.ts
+50
@@ -225,6 +225,56 @@ describe('CLI: composio connections list', () => {
225 });
226 });
227
228 +describe('CLI: composio connections list pagination', () => {
229 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
230 + it.effect(
231 + '[Given] more accounts than one page holds [Then] prints the accounts of every page',
232 + () =>
233 + Effect.gen(function* () {
234 + // The server serves at most 50 accounts per page; the slack account
235 + // sits on the second one.
236 + const firstPage = Array.from({ length: 50 }, (_, index) => ({
237 + ...testConnections[0]!,
238 + id: `con_gmail_${index}`,
239 + }));
240 + const slack = { ...testConnections[0]!, id: 'con_slack', toolkit: { slug: 'slack' } };
241 + const stub = stubClientResources(['connectedAccounts'], request =>
242 + new URL(request.path, 'https://stub.invalid').searchParams.get('cursor') === 'page-2'
243 + ? Response.json({
244 + items: [slack],
245 + total_items: 51,
246 + total_pages: 2,
247 + current_page: 2,
248 + next_cursor: null,
249 + })
250 + : Response.json({
251 + items: firstPage,
252 + total_items: 51,
253 + total_pages: 2,
254 + current_page: 1,
255 + next_cursor: 'page-2',
256 + })
257 + );
258 + const userContext = yield* ComposioUserContext;
259 + yield* userContext.login('test_api_key', 'org_test');
260 + yield* cli(['connections', 'list']).pipe(Effect.provide(stub.layer));
261 +
262 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
263 + const parsed = JSON.parse(String(lines.at(-1))) as Record<string, ReadonlyArray<unknown>>;
264 +
265 + expect(parsed.gmail).toHaveLength(50);
266 + expect(parsed.slack).toEqual([
267 + { id: 'con_slack', status: 'ACTIVE', permission_group: null },
268 + ]);
269 + const listings = stub.requests.filter(request =>
270 + request.path.startsWith('/api/v3.1/connected_accounts')
271 + );
272 + expect(listings).toHaveLength(2);
273 + })
274 + );
275 + });
276 +});
277 +
278 describe('CLI: composio connections list account identity', () => {
279 layer(
280 TestLive({
ts/packages/cli/test/src/commands/request-failures.client.test.ts
+54 -3
@@ -3,6 +3,7 @@ import { ConfigProvider, Effect, Fiber } from 'effect';
3 import { TestClock } from 'effect/testing';
4 import type { ComposioClientShape } from '@composio/client/effect';
5 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
6 +import { CONNECTED_ACCOUNTS_SHAPE_MESSAGE } from 'src/effects/decode-connected-account-list';
7 import { cli, MockConsole, TestLive } from 'test/__utils__';
8 import { exitCodeOf } from 'test/__utils__/exit-code';
9 import {
@@ -102,6 +103,56 @@ const rejectedRequests: ReadonlyArray<{
103 },
104 ];
105
106 +describe('CLI: malformed connected-account pages', () => {
107 + describe.each([
108 + { args: ['connections', 'list'], tag: 'commands/ConnectionsListRequestError' },
109 + {
110 + args: ['connections', 'remove', 'gmail', '--yes'],
111 + tag: 'commands/ConnectionsRemovalRequestError',
112 + },
113 + ])('$args', ({ args, tag }) => {
114 + layer(testLayer())(it => {
115 + it.effect.each([
116 + { shape: 'missing items', body: { next_cursor: null } },
117 + { shape: 'null items', body: { items: null, next_cursor: null } },
118 + {
119 + shape: 'object items',
120 + body: { items: { state: { access_token: 'must-not-leak' } }, next_cursor: null },
121 + },
122 + {
123 + shape: 'a repeated cursor',
124 + body: { items: [], next_cursor: 'page-2' },
125 + },
126 + {
127 + shape: 'a missing nonterminal cursor',
128 + body: { items: [], current_page: 2, total_pages: 3 },
129 + },
130 + ])('fails safely when page two has $shape', ({ body }) =>
131 + Effect.gen(function* () {
132 + const pages = [{ items: [], next_cursor: 'page-2' }, body];
133 + const stub = stubClientResources(['connectedAccounts'], () => {
134 + const page = pages.shift();
135 + return page === undefined ? forbidden() : Response.json(page);
136 + });
137 + const failure = yield* cli(args).pipe(Effect.provide(stub.layer), Effect.flip);
138 +
139 + expect(failure).toMatchObject({
140 + _tag: tag,
141 + message: CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
142 + cause: { _tag: 'effects/ConnectedAccountListShapeError' },
143 + });
144 + expect(extractErrorDetails(failure).message).not.toContain('must-not-leak');
145 + const lines = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
146 + expect(lines).toContain(CONNECTED_ACCOUNTS_SHAPE_MESSAGE);
147 + expect(lines).not.toContain('must-not-leak');
148 + expect(stub.requests).toHaveLength(2);
149 + expect(stub.requests.every(request => request.method === 'GET')).toBe(true);
150 + })
151 + );
152 + });
153 + });
154 +});
155 +
156 describe('CLI: a request the API rejects', () => {
157 describe.each(rejectedRequests)(
158 '[Given] composio $command',
@@ -223,8 +274,8 @@ describe('CLI: a rejected request the command recovers from', () => {
274 pending({ toolkit: 'gmail', project_type: 'CONSUMER' }),
275 ]);
276 expect(stub.requests.map(request => request.path)).toEqual([
226 - `${LISTING}user_ids=consumer-user-org_test&toolkit_slugs=gmail&statuses=ACTIVE&limit=100`,
227 - `${LISTING}user_ids=consumer-user-org_test&statuses=ACTIVE&limit=1000`,
277 + `${LISTING}user_ids=consumer-user-org_test&toolkit_slugs=gmail&statuses=ACTIVE&limit=50`,
278 + `${LISTING}user_ids=consumer-user-org_test&statuses=ACTIVE&limit=50`,
279 ]);
280 })
281 );
@@ -252,7 +303,7 @@ describe('CLI: a rejected request the command recovers from', () => {
303 pending({ project_type: 'DEVELOPER' }),
304 ]);
305 expect(stub.requests.map(request => request.path)).toEqual([
255 - `${LISTING}user_ids=user_1&auth_config_ids=ac_1&statuses=ACTIVE&limit=100`,
306 + `${LISTING}user_ids=user_1&auth_config_ids=ac_1&statuses=ACTIVE&limit=50`,
307 ]);
308 })
309 );
ts/packages/cli/test/src/services/connected-account-selection.test.ts
+21 -25
@@ -132,43 +132,34 @@ const toolkitSlugsQuery = (path: string) =>
132 new URL(path, 'https://stub.invalid').searchParams.get('toolkit_slugs');
133
134 describe('listConnectedAccountsForToolkit', () => {
135 - it.effect('matches toolkit slugs the way the grouping helpers do, from the shared list', () =>
135 + it.effect('stops at an empty terminal cursor without duplicating accounts', () =>
136 Effect.gen(function* () {
137 const { client, requests } = stubComposioClient(
138 pagesInOrder(
139 - page([
140 - makeAccount({ id: 'con_github', toolkit: { slug: 'GitHub ' } }),
141 - makeAccount({ id: 'con_gmail', toolkit: { slug: 'gmail' } }),
142 - ])
139 + page([makeAccount({ id: 'con_gmail' })], { total_items: 1, next_cursor: '' }),
140 + page([makeAccount({ id: 'con_gmail' })])
141 )
142 );
143
144 const accounts = yield* listConnectedAccountsForToolkit({
145 client,
146 userId: 'default',
149 - toolkitSlug: ' github',
147 + toolkitSlug: 'gmail',
148 });
149
152 - expect(accounts.map(item => item.id)).toEqual(['con_github']);
150 + expect(accounts.map(item => item.id)).toEqual(['con_gmail']);
151 expect(requests).toHaveLength(1);
154 - expect(toolkitSlugsQuery(requests[0]!.path)).toBeNull();
152 })
153 );
154
158 - it.effect('matches toolkit slugs the way the grouping helpers do, on the filtered request', () =>
155 + it.effect('matches toolkit slugs the way the grouping helpers do, from the shared list', () =>
156 Effect.gen(function* () {
160 - // A shared list that pages is incomplete, so the filtered request runs
161 - // and its answer is taken as is.
157 const { client, requests } = stubComposioClient(
158 pagesInOrder(
164 - page(
165 - [
166 - makeAccount({ id: 'con_github', toolkit: { slug: 'GitHub ' } }),
167 - makeAccount({ id: 'con_gmail', toolkit: { slug: 'gmail' } }),
168 - ],
169 - { total_items: 2, next_cursor: 'more' }
170 - ),
171 - page([makeAccount({ id: 'con_github', toolkit: { slug: 'GitHub ' } })])
159 + page([
160 + makeAccount({ id: 'con_github', toolkit: { slug: 'GitHub ' } }),
161 + makeAccount({ id: 'con_gmail', toolkit: { slug: 'gmail' } }),
162 + ])
163 )
164 );
165
@@ -179,8 +170,8 @@ describe('listConnectedAccountsForToolkit', () => {
170 });
171
172 expect(accounts.map(item => item.id)).toEqual(['con_github']);
182 - expect(requests).toHaveLength(2);
183 - expect(toolkitSlugsQuery(requests[1]!.path)).toBe('github');
173 + expect(requests).toHaveLength(1);
174 + expect(toolkitSlugsQuery(requests[0]!.path)).toBeNull();
175 })
176 );
177
@@ -208,14 +199,16 @@ describe('listConnectedAccountsForToolkit', () => {
199 })
200 );
201
211 - it.effect('falls back to the filtered request when the shared page is full', () =>
202 + it.effect('derives from every page of the shared list, following next_cursor', () =>
203 Effect.gen(function* () {
213 - const fullPage = Array.from({ length: 1000 }, (_, index) =>
204 + // The server serves at most 50 accounts per page, so the toolkit's
205 + // account can sit past the first page.
206 + const firstPage = Array.from({ length: 50 }, (_, index) =>
207 makeAccount({ id: `con_slack_${index}`, toolkit: { slug: 'slack' } })
208 );
209 const { client, requests } = stubComposioClient(
210 pagesInOrder(
218 - page(fullPage, { total_items: 1001, next_cursor: null }),
211 + page(firstPage, { total_items: 51, next_cursor: 'page-2' }),
212 page([makeAccount({ id: 'con_gmail', toolkit: { slug: 'gmail' } })])
213 )
214 );
@@ -228,7 +221,10 @@ describe('listConnectedAccountsForToolkit', () => {
221
222 expect(accounts.map(item => item.id)).toEqual(['con_gmail']);
223 expect(requests).toHaveLength(2);
231 - expect(toolkitSlugsQuery(requests[1]!.path)).toBe('gmail');
224 + const query = (path: string) => new URL(path, 'https://stub.invalid').searchParams;
225 + expect(query(requests[0]!.path).get('limit')).toBe('50');
226 + expect(query(requests[1]!.path).get('cursor')).toBe('page-2');
227 + expect(requests.map(request => toolkitSlugsQuery(request.path))).toEqual([null, null]);
228 })
229 );
230 });