@devries-cameron20 / composio Mirror · read-only / commits / 3eec4b900
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

feat(cli): show account id, alias, and display name in connections list (#4946)

## Summary A UI that lists a person's connections with `composio connections list` can't label an account that is the only one for its toolkit, and can't show which provider account a connection is: - `alias` was printed only when a toolkit had more than one account, so the alias of a toolkit's only account was dropped. - The connected account `id` wasn't printed, although `execute --account`, `proxy --account` and `connections remove` accept it. - The provider identity Composio fills in for an active connection, `state.val.displayName` (documented in #4503), never reached the output, because the connected-account allowlist excludes all of `state` to keep credentials out of CLI output. Designated PR reviewer: @jkomyno Fixes #4808 ## Changes - `connections list` prints `id` on every entry, `alias` whenever the account has one (several accounts for one toolkit keep `alias: null` on entries without one, as before), and `display_name` when Composio has filled in a provider identity. - `ConnectedAccountItem`, the connected-account allowlist, gains `display_name`. It is decoded from the raw `state` key (`Schema.encodeKeys`) through a narrow schema that keeps only `state.val.displayName`: trimmed, non-empty, at most 200 characters (a longer value is left out rather than cut). It never fails the item — a missing, blank, non-string, or too long value leaves the key out — and encoding drops it, so `state` is never rebuilt from it. - The raw-response fallback in `decodeConnectedAccountListWithFallback` applies the same rule: each raw item gets the `display_name` decoded from its `state`, and any top-level `display_name` from the server is dropped, so an unchecked value can't reach the output. - Updated the command description, the CLI README command list, and an `Unreleased` entry in `ts/packages/cli/CHANGELOG.md` (`@composio/cli` is ignored by Changesets). Privacy: `state` carries OAuth tokens, refresh tokens, and API keys. The allowlist keeps excluding it; `display_name` reads exactly one value through a struct decode that drops every other key of `state` and `val`. Decoded items have no `state` key. ## Type of change - [ ] Bug fix - [x] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? New and updated vitest cases in `ts/packages/cli`: - `test/src/commands/connections/connections.list.cmd.test.ts`: every entry prints `id`; the only account of a toolkit prints its alias; with `state.val.displayName` plus credentials in `state`, `data`, and `params`, the output contains the trimmed display name and none of the credentials. - `test/src/effects/decode-connected-account-list.test.ts`: the allowlist keeps only the trimmed display name from `state` (including exactly 200 characters) and leaves the key out for null/non-object `state`, no `val`, no/blank/non-string/over-long `displayName`, or a top-level `display_name` without `state`. The raw fallback after an envelope-only mismatch derives `display_name` from `state` only. Commands (Node 24.20.0, pnpm 11.8.0, Windows): - Focused: `vitest run test/src/effects/decode-connected-account-list.test.ts test/src/commands/connections/connections.list.cmd.test.ts` — 26 passed. - `pnpm --filter @composio/cli run typecheck` — passes. `oxlint` on the changed files — 0 warnings, 0 errors. `prettier --check` on the changed files — clean. `pnpm --filter @composio/cli build` — passes. `validate:skills`, `validate:boundaries`, `validate:command-tests` — pass. - Full `@composio/cli` vitest suite on this Windows machine: 1656 passed / 176 failed, vs 1644 passed / 175 failed on the untouched base — the failures are pre-existing Windows-environment failures (e.g. no system Python, process/path handling in unrelated suites); the two files that swapped between runs pass when re-run. The repo's vitest config also assumes POSIX paths on Windows, so the suite was run with an equivalent local config (not included in this PR). Not run against the live API. The field location follows the docs from #4503 and the v3.1 OpenAPI schema, where `displayName` appears only under `state.val`. ## Screenshots (if applicable) None; the output is JSON. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the third-party links policy - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages (not applicable: `@composio/cli` is in Changesets' `ignore` list, so the note is in `ts/packages/cli/CHANGELOG.md`) ## Additional context This follows the approach discussed on the earlier attempt in #4809 (closed unmerged), including the review note about sanitizing `display_name` on the raw-fallback path. Claimed under the Greenlight Claim Protocol on #4808. --------- Signed-off-by: Rene Turcios <95189389+CloudCorpRecords@users.noreply.github.com> Co-authored-by: jkomyno <alberto@composio.dev>

Rene Turcios committed Oct 22, 2026 at 08:41 UTC 3eec4b900ad17bb1841902de2167125eb19db06f
12 files changed +417 -120
ts/packages/cli/CHANGELOG.md
+11
@@ -4,6 +4,17 @@
4
5 ### Patch Changes
6
7 +- `composio connections list` now prints each account's `id`, its `alias`
8 + whenever it has one (previously only when a toolkit had several accounts),
9 + and `display_name` — the provider identity from `state.val.displayName`,
10 + trimmed and capped at 200 characters — when Composio has filled one in.
11 + Nothing else is read from `state`.
12 +
13 +- `composio connections list`, `composio connections remove`, and
14 + `composio dev connected-accounts list` exit 1 when the connected-accounts
15 + response does not match the shape this CLI expects, naming the mismatched
16 + fields. They used to warn and continue with the unchecked response.
17 +
18 - `composio dev triggers create` now accepts `--user-id` and sends it with the
19 request, so it works on projects with 2FA enabled, which require the user who
20 owns the connected account. It used to reject `--user-id` and send no user,
ts/packages/cli/README.md
+1 -1
@@ -38,7 +38,7 @@ composio [--log-level All|Trace|Debug|Info|Warn|Error|Fatal|None]
38 - `composio proxy <url> --toolkit <toolkit> [-X method] [-H header]... [-d data]`: Call a toolkit API directly through Composio using a connected account.
39 - `composio tools list|info`: Inspect available tools and their cached schemas.
40 - `composio triggers list <toolkit>|info`: Inspect toolkit-scoped trigger types and their schemas.
41 -- `composio connections list [--toolkit <toolkit>]`: Print toolkit connection statuses as JSON.
41 +- `composio connections list [--toolkit <toolkit>]`: Print toolkit connections as JSON with each account's id, status, alias, and provider display name when available.
42 - `composio connections remove <account>`: Remove a toolkit connection after confirmation; pass `--yes` to skip the prompt, which is required when not running interactively.
43 - `composio artifacts cwd`: Print the cwd-scoped CLI session artifacts directory.
44 - `composio dev <subcommand>`: Developer workflows for init, playground execution, logs, toolkits, auth configs, accounts, triggers, orgs, and projects.
ts/packages/cli/src/commands/connected-accounts/list/connected-accounts.list.format.ts
-4
@@ -8,10 +8,6 @@ import { formatConnectedAccountsTable } from '../format';
8 export const FETCHING_CONNECTED_ACCOUNTS_MESSAGE = 'Fetching connected accounts...';
9 export const LIST_CONNECTED_ACCOUNTS_FAILED_MESSAGE = 'Failed to list connected accounts.';
10
11 -/** The failure when the response shape drifted so far that `items` is not a list. */
12 -export const CONNECTED_ACCOUNTS_LIST_SHAPE_MESSAGE =
13 - 'Connected accounts response was not the shape this CLI understands; run `composio upgrade`.';
14 -
11 /**
12 * The warning for an empty page, naming the first filter that was given: `--toolkits`, then
13 * `--user-id`, then `--status`.
ts/packages/cli/src/commands/connected-accounts/list/connected-accounts.list.handler.ts
+8 -15
@@ -1,6 +1,9 @@
1 import { Array as Arr, Effect, Option } from 'effect';
2 import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
3 -import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
3 +import {
4 + CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
5 + decodeConnectedAccountList,
6 +} from 'src/effects/decode-connected-account-list';
7 import { failedWith } from 'src/effects/request-error';
8 import type { KnownConnectedAccountStatus } from 'src/models/connected-accounts';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -9,7 +12,6 @@ import { TerminalUI } from 'src/services/terminal-ui';
12 import { clampLimit } from 'src/ui/clamp-limit';
13 import { ConnectedAccountsListRequestError } from './connected-accounts.list.errors';
14 import {
12 - CONNECTED_ACCOUNTS_LIST_SHAPE_MESSAGE,
15 FETCHING_CONNECTED_ACCOUNTS_MESSAGE,
16 LIST_CONNECTED_ACCOUNTS_FAILED_MESSAGE,
17 formatConnectedAccountsJson,
@@ -61,20 +63,11 @@ export const runConnectedAccountsList = ({
63 )
64 .pipe(failedWith(ConnectedAccountsListRequestError, LIST_CONNECTED_ACCOUNTS_FAILED_MESSAGE))
65 );
64 - const result = yield* decodeConnectedAccountListWithFallback(rawResult);
65 - // The decode fallback returns the raw payload when the response shape drifts; `items`
66 - // may then not be a list at all. Fail loudly instead of reporting an empty page,
67 - // which would tell a piped consumer there are no connected accounts.
68 - const items = Array.isArray(result.items)
69 - ? result.items
70 - : yield* Effect.fail(
71 - new ConnectedAccountsListRequestError({
72 - message: CONNECTED_ACCOUNTS_LIST_SHAPE_MESSAGE,
73 - cause: `response.items was ${typeof result.items}, expected an array`,
74 - })
75 - );
66 + const result = yield* decodeConnectedAccountList(rawResult).pipe(
67 + failedWith(ConnectedAccountsListRequestError, CONNECTED_ACCOUNTS_SHAPE_MESSAGE)
68 + );
69
77 - yield* Arr.match(items, {
70 + yield* Arr.match(result.items, {
71 onEmpty: () => ui.log.warn(noConnectedAccountsMessage({ toolkits, userId, status })),
72 onNonEmpty: nonEmptyItems =>
73 Effect.gen(function* () {
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+24 -5
@@ -1,6 +1,9 @@
1 import { Data, Effect, Option } from 'effect';
2 import { Command, Flag } from 'effect/cli';
3 -import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
3 +import {
4 + CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
5 + decodeConnectedAccountList,
6 +} from 'src/effects/decode-connected-account-list';
7 import { failedWith, requestError } from 'src/effects/request-error';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -35,14 +38,28 @@ const formatConnectionsJson = (
38 }, new Map());
39
40 const grouped = items.reduce<
38 - Record<string, Array<{ status: string; alias?: string | null; word_id?: string | null }>>
41 + Record<
42 + string,
43 + Array<{
44 + id: string;
45 + status: string;
46 + alias?: string | null;
47 + word_id?: string | null;
48 + display_name?: string;
49 + permission_group: string | null;
50 + }>
51 + >
52 >((acc, item) => {
53 const toolkit = item.toolkit.slug;
41 - const includeAlias = (toolkitCounts.get(toolkit) ?? 0) > 1;
54 + // Several accounts for one toolkit keep `alias` on every entry (null when
55 + // unset); a lone account prints it only when it actually has one.
56 + const includeAlias = item.alias != null || (toolkitCounts.get(toolkit) ?? 0) > 1;
57 const entry = {
58 + id: item.id,
59 status: item.status,
60 ...(includeAlias ? { alias: item.alias ?? null } : {}),
61 ...(item.word_id != null ? { word_id: item.word_id } : {}),
62 + ...(item.display_name !== undefined ? { display_name: item.display_name } : {}),
63 permission_group: permissionGroups.get(item.id) ?? null,
64 };
65
@@ -86,7 +103,9 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
103 idempotent
104 )
105 .pipe(failedWith(ConnectionsListRequestError, 'Failed to list connections.'));
89 - const result = yield* decodeConnectedAccountListWithFallback(rawResult);
106 + const result = yield* decodeConnectedAccountList(rawResult).pipe(
107 + failedWith(ConnectionsListRequestError, CONNECTED_ACCOUNTS_SHAPE_MESSAGE)
108 + );
109 const permissionSnapshot = yield* getConsumerPermissionSnapshot({
110 orgId: resolvedProject.orgId,
111 projectId: resolvedProject.projectId,
@@ -107,7 +126,7 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
126 })
127 ).pipe(
128 Command.withDescription(
110 - 'List connection statuses as JSON. Includes aliases for duplicate toolkits and word_ids when available.'
129 + 'List connections as JSON with each account id and status, plus its alias, word_id, and provider display name when available.'
130 ),
131 Command.withExamples([
132 {
ts/packages/cli/src/commands/connections/remove/connections.remove.handler.ts
+7 -2
@@ -1,6 +1,9 @@
1 import { Effect } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 -import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
3 +import {
4 + CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
5 + decodeConnectedAccountList,
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';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -123,7 +126,9 @@ export const runConnectionsRemove = ({ account, yes }: ConnectionsRemoveParams)
126 .list({ user_ids: [consumerUserId], limit: 1000 }, idempotent)
127 .pipe(failedWith(ConnectionsRemovalRequestError, 'Failed to list connections.'))
128 );
126 - const result = yield* decodeConnectedAccountListWithFallback(rawResult);
129 + const result = yield* decodeConnectedAccountList(rawResult).pipe(
130 + failedWith(ConnectionsRemovalRequestError, CONNECTED_ACCOUNTS_SHAPE_MESSAGE)
131 + );
132 const resolved = resolveAccount({ accounts: result.items, selector: account });
133
134 if ('error' in resolved) {
ts/packages/cli/src/effects/decode-connected-account-list.ts
+41 -47
@@ -1,11 +1,9 @@
1 -import { Effect, Match, Schema, type SchemaIssue } from 'effect';
1 +import type { ConnectedAccountListResponse as ApiConnectedAccountListResponse } from '@composio/client/resources/connected-accounts';
2 +import { Data, Effect, Match, Schema, type SchemaIssue } from 'effect';
3 import {
4 ConnectedAccountItems,
4 - isKnownConnectedAccountStatus,
5 -} from 'src/models/connected-accounts';
6 -import {
5 ConnectedAccountListResponse,
8 - type ConnectedAccountListResponse as ConnectedAccountListResponseType,
6 + isKnownConnectedAccountStatus,
7 } from 'src/models/connected-accounts';
8 import { TerminalUI } from 'src/services/terminal-ui';
9
@@ -53,56 +51,52 @@ const warnOnUnknownStatuses = (
51 );
52 });
53
54 +/** A command's failure when a connected-accounts response does not decode. */
55 +export const CONNECTED_ACCOUNTS_SHAPE_MESSAGE =
56 + 'Connected accounts response was not the shape this CLI understands; run `composio upgrade`.';
57 +
58 +/**
59 + * A list response that does not match `ConnectedAccountListResponse`. The
60 + * message names only the mismatched paths and issue kinds, never the values,
61 + * so it is safe to print as the cause of a command's failure.
62 + */
63 +export class ConnectedAccountListShapeError extends Data.TaggedError(
64 + 'effects/ConnectedAccountListShapeError'
65 +)<{
66 + readonly message: string;
67 +}> {}
68 +
69 /**
57 - * Decodes a raw `client.connectedAccounts.list(...)` response against
58 - * `ConnectedAccountListResponse`, falling back to the raw payload on
59 - * `SchemaError`.
70 + * Decodes a `client.connectedAccounts.list(...)` response into the CLI's
71 + * `ConnectedAccountListResponse`: the field allowlist that keeps
72 + * credential-bearing fields (`state`, `data`, ...) out, plus `display_name`
73 + * derived from `state`.
74 *
75 * `status` is an open enum (`ConnectedAccountStatus`), so a status newer than
62 - * this CLI build decodes fine and only triggers the "composio upgrade"
63 - * warning. The raw fallback remains for other shape skew (pagination fields,
64 - * renames, ...) — safe because the three current call sites only render
65 - * non-credential fields (`id`, `alias`, `word_id`, `toolkit.slug`,
66 - * `status`, ...).
76 + * this CLI build decodes and only triggers the "composio upgrade" warning.
77 + * Any other mismatch fails with {@link ConnectedAccountListShapeError}.
78 */
68 -export const decodeConnectedAccountListWithFallback = (
69 - rawResult: unknown
70 -): Effect.Effect<ConnectedAccountListResponseType, never, TerminalUI> =>
71 - Effect.gen(function* () {
72 - const ui = yield* TerminalUI;
73 - return yield* Schema.decodeUnknownEffect(ConnectedAccountListResponse)(rawResult).pipe(
74 - Effect.tap(result => warnOnUnknownStatuses(result.items)),
75 - Effect.catchTag('SchemaError', error =>
76 - Effect.gen(function* () {
77 - yield* ui.log.warn(
78 - `Server response did not match the shape this CLI expects. Run ` +
79 - `"composio upgrade" to pick up the latest CLI. Continuing with ` +
80 - `raw response.\n\n` +
81 - `Mismatched fields: ${formatParseErrorRedacted(error)}`
82 - );
83 - // Safe: callers only read non-credential fields.
84 - return rawResult as ConnectedAccountListResponseType;
79 +export const decodeConnectedAccountList = (
80 + response: ApiConnectedAccountListResponse
81 +): Effect.Effect<ConnectedAccountListResponse, ConnectedAccountListShapeError, TerminalUI> =>
82 + Schema.decodeEffect(ConnectedAccountListResponse)(response).pipe(
83 + Effect.mapError(
84 + error =>
85 + new ConnectedAccountListShapeError({
86 + message: `Mismatched fields: ${formatParseErrorRedacted(error)}`,
87 })
86 - )
87 - );
88 - });
88 + ),
89 + Effect.tap(result => warnOnUnknownStatuses(result.items))
90 + );
91
92 /**
91 - * Item-level variant of {@link decodeConnectedAccountListWithFallback} for
92 - * call sites that decode `response.items` rather than the whole list
93 - * response.
94 - *
95 - * `status` is an open enum, so a status newer than this CLI build decodes
96 - * instead of failing — we just warn, pointing at `composio upgrade`. Unlike
97 - * the list-response helper above, this one must NOT fall back to the raw
98 - * payload: `link --list` JSON-dumps the decoded items to stdout, so the
99 - * schema's field allowlist is what keeps credential-bearing fields (`state`,
100 - * `data`, ...) out of pipeable output. Truly malformed data fails with
101 - * `SchemaError`.
93 + * Item-level variant of {@link decodeConnectedAccountList} for call sites
94 + * that decode `response.items` rather than the whole list response. It fails
95 + * with the raw `SchemaError`, which callers wrap in their own error.
96 */
97 export const decodeConnectedAccountItems = (
104 - rawItems: unknown
98 + items: ApiConnectedAccountListResponse['items']
99 ): Effect.Effect<ConnectedAccountItems, Schema.SchemaError, TerminalUI> =>
106 - Schema.decodeUnknownEffect(ConnectedAccountItems)(rawItems).pipe(
107 - Effect.tap(items => warnOnUnknownStatuses(items))
100 + Schema.decodeEffect(ConnectedAccountItems)(items).pipe(
101 + Effect.tap(decoded => warnOnUnknownStatuses(decoded))
102 );
ts/packages/cli/src/models/connected-accounts.ts
+47 -2
@@ -1,4 +1,4 @@
1 -import { Effect, Schema } from 'effect';
1 +import { Effect, Option, Schema, SchemaGetter } from 'effect';
2
3 /**
4 * Statuses this CLI build knows about. The server owns this enum and may add
@@ -27,6 +27,46 @@ export const isKnownConnectedAccountStatus = Schema.is(KnownConnectedAccountStat
27 */
28 export const ConnectedAccountStatus = Schema.Union([KnownConnectedAccountStatus, Schema.String]);
29
30 +/** Longest provider display name the CLI will print, once trimmed. */
31 +export const CONNECTED_ACCOUNT_DISPLAY_NAME_MAX_LENGTH = 200;
32 +
33 +/**
34 + * The single value this CLI reads out of a connected account's `state`: the
35 + * provider identity Composio records at `state.val.displayName` for an active
36 + * connection (a Gmail address, a GitHub login, ...). Decoding against this
37 + * narrow shape keeps that value and discards every other key under `state`.
38 + */
39 +const ProviderIdentityFromState = Schema.Struct({
40 + val: Schema.Struct({
41 + displayName: Schema.Trim.check(
42 + Schema.isNonEmpty(),
43 + Schema.isMaxLength(CONNECTED_ACCOUNT_DISPLAY_NAME_MAX_LENGTH)
44 + ),
45 + }),
46 +});
47 +
48 +/**
49 + * The trimmed display name held in a raw `state` value, or `None` when it is
50 + * absent, blank, not a string, or longer than the limit.
51 + */
52 +const displayNameFromState = (state: unknown): Option.Option<string> =>
53 + Schema.decodeUnknownOption(ProviderIdentityFromState)(state).pipe(
54 + Option.map(identity => identity.val.displayName)
55 + );
56 +
57 +/**
58 + * `display_name` as decoded from the raw `state` key (see `encodeKeys` on
59 + * {@link ConnectedAccountItem}). Decoding never fails the item: any unusable
60 + * display name simply leaves the field out. Encoding omits it, so a decoded
61 + * item can never be turned back into a `state` payload.
62 + */
63 +const DisplayNameFromState = Schema.optionalKey(Schema.Unknown).pipe(
64 + Schema.decodeTo(Schema.optionalKey(Schema.String), {
65 + decode: SchemaGetter.transformOptional(Option.flatMap(displayNameFromState)),
66 + encode: SchemaGetter.omit(),
67 + })
68 +);
69 +
70 /**
71 * A connected account item from the list or retrieve endpoints.
72 * Field names match the raw API response (snake_case).
@@ -35,6 +75,8 @@ export const ConnectedAccountStatus = Schema.Union([KnownConnectedAccountStatus,
75 * and `deprecated` fields to prevent credential leakage in CLI output.
76 * The `state` discriminated union contains raw OAuth tokens, refresh tokens,
77 * and API keys per auth scheme — never add it without a redaction layer.
78 + * `display_name` is the one exception: it is extracted from `state` through
79 + * {@link ProviderIdentityFromState}, which retains nothing else.
80 */
81 export const ConnectedAccountItem = Schema.Struct({
82 id: Schema.String,
@@ -58,7 +100,10 @@ export const ConnectedAccountItem = Schema.Struct({
100 created_at: Schema.String,
101 updated_at: Schema.String,
102 test_request_endpoint: Schema.String.pipe(Schema.withDecodingDefaultType(Effect.succeed(''))),
61 -}).annotate({ identifier: 'ConnectedAccountItem' });
103 + display_name: DisplayNameFromState,
104 +})
105 + .pipe(Schema.encodeKeys({ display_name: 'state' }))
106 + .annotate({ identifier: 'ConnectedAccountItem' });
107 export type ConnectedAccountItem = Schema.Schema.Type<typeof ConnectedAccountItem>;
108
109 export const ConnectedAccountItems = Schema.Array(ConnectedAccountItem);
ts/packages/cli/test/src/commands/connected-accounts/list/connected-accounts.list.handler.test.ts
+8 -6
@@ -6,11 +6,9 @@ import {
6 runConnectedAccountsList,
7 type ConnectedAccountsListParams,
8 } from 'src/commands/connected-accounts/list/connected-accounts.list.handler';
9 -import {
10 - CONNECTED_ACCOUNTS_LIST_SHAPE_MESSAGE,
11 - viewDetailsHint,
12 -} from 'src/commands/connected-accounts/list/connected-accounts.list.format';
9 +import { viewDetailsHint } from 'src/commands/connected-accounts/list/connected-accounts.list.format';
10 import { CommandSurface } from 'src/commands/surface';
11 +import { CONNECTED_ACCOUNTS_SHAPE_MESSAGE } from 'src/effects/decode-connected-account-list';
12 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
13 import type { ProjectKeys } from 'src/models/project-keys';
14 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -310,7 +308,7 @@ describe('runConnectedAccountsList', () => {
308 );
309
310 it.effect(
313 - '[Given] a raw response whose items are not an array [Then] fails instead of listing zero',
311 + '[Given] a response whose items are not an array [Then] fails instead of listing zero',
312 () => {
313 const { layer, outputs } = listTest({
314 rawListResponse: { items: { pages: 2 }, total_items: 3 },
@@ -320,7 +318,11 @@ describe('runConnectedAccountsList', () => {
318
319 expect(error).toMatchObject({
320 _tag: 'commands/ConnectedAccountsListRequestError',
323 - message: CONNECTED_ACCOUNTS_LIST_SHAPE_MESSAGE,
321 + message: CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
322 + cause: {
323 + _tag: 'effects/ConnectedAccountListShapeError',
324 + message: expect.stringContaining('items'),
325 + },
326 });
327 expect(outputs).toEqual([]);
328 }).pipe(Effect.provide(layer));
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+149 -8
@@ -88,10 +88,22 @@ describe('CLI: composio connections list', () => {
88 const parsed = JSON.parse(String(lines.at(-1)));
89
90 expect(parsed).toEqual({
91 - gmail: [{ status: 'ACTIVE', permission_group: null }],
91 + gmail: [{ id: 'con_gmail_active', status: 'ACTIVE', permission_group: null }],
92 github: [
93 - { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },
94 - { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },
93 + {
94 + id: 'con_github_work',
95 + status: 'ACTIVE',
96 + alias: 'work',
97 + word_id: 'castle',
98 + permission_group: null,
99 + },
100 + {
101 + id: 'con_github_personal',
102 + status: 'FAILED',
103 + alias: 'personal',
104 + word_id: 'forest',
105 + permission_group: null,
106 + },
107 ],
108 });
109 })
@@ -115,10 +127,22 @@ describe('CLI: composio connections list', () => {
127 const parsed = JSON.parse(String(lines.at(-1)));
128
129 expect(parsed).toEqual({
118 - gmail: [{ status: 'ACTIVE', permission_group: null }],
130 + gmail: [{ id: 'con_gmail_active', status: 'ACTIVE', permission_group: null }],
131 github: [
120 - { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },
121 - { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },
132 + {
133 + id: 'con_github_work',
134 + status: 'ACTIVE',
135 + alias: 'work',
136 + word_id: 'castle',
137 + permission_group: null,
138 + },
139 + {
140 + id: 'con_github_personal',
141 + status: 'FAILED',
142 + alias: 'personal',
143 + word_id: 'forest',
144 + permission_group: null,
145 + },
146 ],
147 });
148 })
@@ -137,8 +161,20 @@ describe('CLI: composio connections list', () => {
161
162 expect(parsed).toEqual({
163 github: [
140 - { status: 'ACTIVE', alias: 'work', word_id: 'castle', permission_group: null },
141 - { status: 'FAILED', alias: 'personal', word_id: 'forest', permission_group: null },
164 + {
165 + id: 'con_github_work',
166 + status: 'ACTIVE',
167 + alias: 'work',
168 + word_id: 'castle',
169 + permission_group: null,
170 + },
171 + {
172 + id: 'con_github_personal',
173 + status: 'FAILED',
174 + alias: 'personal',
175 + word_id: 'forest',
176 + permission_group: null,
177 + },
178 ],
179 });
180 })
@@ -188,3 +224,108 @@ describe('CLI: composio connections list', () => {
224 );
225 });
226 });
227 +
228 +describe('CLI: composio connections list account identity', () => {
229 + layer(
230 + TestLive({
231 + baseConfigProvider: testConfigProvider,
232 + connectedAccountsData: {
233 + items: [
234 + {
235 + ...testConnections[0]!,
236 + id: 'con_notion_team',
237 + alias: 'team',
238 + word_id: 'harbor',
239 + toolkit: { slug: 'notion' },
240 + },
241 + ],
242 + },
243 + })
244 + )(it => {
245 + it.effect('[Given] the only account of a toolkit has an alias [Then] prints id and alias', () =>
246 + Effect.gen(function* () {
247 + const userContext = yield* ComposioUserContext;
248 + yield* userContext.login('test_api_key', 'org_test');
249 + yield* cli(['connections', 'list']);
250 +
251 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
252 + const parsed = JSON.parse(String(lines.at(-1)));
253 +
254 + expect(parsed).toEqual({
255 + notion: [
256 + {
257 + id: 'con_notion_team',
258 + status: 'ACTIVE',
259 + alias: 'team',
260 + word_id: 'harbor',
261 + permission_group: null,
262 + },
263 + ],
264 + });
265 + })
266 + );
267 + });
268 +
269 + layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(it => {
270 + it.effect('[Given] state.val.displayName [Then] prints display_name and no credentials', () =>
271 + Effect.gen(function* () {
272 + const rawItem = {
273 + ...testConnections[0]!,
274 + id: 'con_gmail_named',
275 + alias: 'work',
276 + state: {
277 + authScheme: 'OAUTH2',
278 + val: {
279 + displayName: ' ada@example.com ',
280 + access_token: 'must-not-leak',
281 + refresh_token: 'must-not-leak',
282 + },
283 + },
284 + data: { access_token: 'must-not-leak' },
285 + params: { refresh_token: 'must-not-leak' },
286 + };
287 + const stub = stubClientResources(
288 + ['connectedAccounts'],
289 + routeRequests(
290 + [
291 + {
292 + method: 'GET',
293 + path: '/api/v3.1/connected_accounts',
294 + respond: () =>
295 + Response.json({
296 + items: [rawItem],
297 + total_items: 1,
298 + total_pages: 1,
299 + current_page: 1,
300 + next_cursor: null,
301 + }),
302 + },
303 + ],
304 + () => Response.json({ items: testConnections, next_cursor: null })
305 + )
306 + );
307 + const userContext = yield* ComposioUserContext;
308 + yield* userContext.login('test_api_key', 'org_test');
309 + yield* cli(['connections', 'list']).pipe(Effect.provide(stub.layer));
310 +
311 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
312 + const output = lines.join('\n');
313 + const parsed = JSON.parse(String(lines.at(-1)));
314 +
315 + expect(parsed).toEqual({
316 + gmail: [
317 + {
318 + id: 'con_gmail_named',
319 + status: 'ACTIVE',
320 + alias: 'work',
321 + display_name: 'ada@example.com',
322 + permission_group: null,
323 + },
324 + ],
325 + });
326 + expect(output).not.toContain('must-not-leak');
327 + expect(output).not.toContain('access_token');
328 + })
329 + );
330 + });
331 +});
ts/packages/cli/test/src/commands/connections/remove/connections.remove.cmd.test.ts
+8 -1
@@ -136,7 +136,14 @@ describe('CLI: composio connections remove', () => {
136 ),
137 },
138 ],
139 - () => Response.json({ items: testConnections, next_cursor: null })
139 + () =>
140 + Response.json({
141 + items: testConnections,
142 + total_items: testConnections.length,
143 + total_pages: 1,
144 + current_page: 1,
145 + next_cursor: null,
146 + })
147 )
148 );
149 const userContext = yield* ComposioUserContext;
ts/packages/cli/test/src/effects/decode-connected-account-list.test.ts
+113 -29
@@ -1,14 +1,21 @@
1 +import type { ConnectedAccountListResponse as ApiConnectedAccountListResponse } from '@composio/client/resources/connected-accounts';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { Console, Effect, Layer, Schema } from 'effect';
4 import {
5 decodeConnectedAccountItems,
5 - decodeConnectedAccountListWithFallback,
6 + decodeConnectedAccountList,
7 } from 'src/effects/decode-connected-account-list';
8 import { MockConsole } from 'test/__utils__';
9 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
10
11 const TestLayer = Layer.mergeAll(Layer.effect(Console.Console, MockConsole.make), TerminalUITest);
12
13 +// The server can send what the client's types do not describe (a newer status, a
14 +// missing field, credentials under `state`); these fixtures model that payload.
15 +const serverItems = (items: ReadonlyArray<unknown>) =>
16 + items as ApiConnectedAccountListResponse['items'];
17 +const serverResponse = (response: unknown) => response as ApiConnectedAccountListResponse;
18 +
19 const makeItem = (overrides?: Record<string, unknown>) => ({
20 id: 'con_decode_test',
21 alias: 'default',
@@ -34,7 +41,7 @@ describe('decodeConnectedAccountItems', () => {
41 layer(TestLayer)('[Given] items with statuses this CLI build knows', it => {
42 it.effect('decodes without warning', () =>
43 Effect.gen(function* () {
37 - const items = yield* decodeConnectedAccountItems([makeItem()]);
44 + const items = yield* decodeConnectedAccountItems(serverItems([makeItem()]));
45
46 expect(items).toStrictEqual([makeItem()]);
47 expect(yield* MockConsole.getLines()).toStrictEqual([]);
@@ -51,7 +58,7 @@ describe('decodeConnectedAccountItems', () => {
58 data: { refresh_token: 'must-not-leak' },
59 });
60
54 - const items = yield* decodeConnectedAccountItems([raw]);
61 + const items = yield* decodeConnectedAccountItems(serverItems([raw]));
62
63 expect(items).toStrictEqual([makeItem({ status: 'QUANTUM_LINKED' })]);
64 expect(JSON.stringify(items)).not.toContain('must-not-leak');
@@ -64,11 +71,65 @@ describe('decodeConnectedAccountItems', () => {
71 );
72 });
73
74 + layer(TestLayer)('[Given] a state carrying a provider identity next to credentials', it => {
75 + it.effect('keeps only the trimmed display name from state', () =>
76 + Effect.gen(function* () {
77 + const raw = makeItem({
78 + state: {
79 + authScheme: 'OAUTH2',
80 + val: {
81 + displayName: ' ada@example.com ',
82 + access_token: 'must-not-leak',
83 + refresh_token: 'must-not-leak',
84 + },
85 + },
86 + data: { access_token: 'must-not-leak' },
87 + });
88 +
89 + const items = yield* decodeConnectedAccountItems(serverItems([raw]));
90 +
91 + expect(items).toStrictEqual([makeItem({ display_name: 'ada@example.com' })]);
92 + expect(JSON.stringify(items)).not.toContain('must-not-leak');
93 + })
94 + );
95 +
96 + it.effect('keeps a display name of exactly 200 characters', () =>
97 + Effect.gen(function* () {
98 + const displayName = 'a'.repeat(200);
99 +
100 + const items = yield* decodeConnectedAccountItems(
101 + serverItems([makeItem({ state: { val: { displayName } } })])
102 + );
103 +
104 + expect(items).toStrictEqual([makeItem({ display_name: displayName })]);
105 + })
106 + );
107 + });
108 +
109 + layer(TestLayer)('[Given] no usable state.val.displayName', it => {
110 + it.effect.each([
111 + ['state is null', { state: null }],
112 + ['state is not an object', { state: 'opaque' }],
113 + ['state has no val', { state: { authScheme: 'OAUTH2' } }],
114 + ['val has no displayName', { state: { val: { access_token: 'must-not-leak' } } }],
115 + ['displayName is blank', { state: { val: { displayName: ' ' } } }],
116 + ['displayName is not a string', { state: { val: { displayName: 42 } } }],
117 + ['displayName is over 200 characters', { state: { val: { displayName: 'a'.repeat(201) } } }],
118 + ['only a top-level display_name is sent', { display_name: 'ada@example.com' }],
119 + ] as const)('leaves display_name out when %s', ([, overrides]) =>
120 + Effect.gen(function* () {
121 + const items = yield* decodeConnectedAccountItems(serverItems([makeItem(overrides)]));
122 +
123 + expect(items).toStrictEqual([makeItem()]);
124 + })
125 + );
126 + });
127 +
128 layer(TestLayer)('[Given] a malformed payload', it => {
129 it.effect('fails with SchemaError', () =>
130 Effect.gen(function* () {
131 const error = yield* Effect.flip(
71 - decodeConnectedAccountItems([{ definitely: 'not-an-account' }])
132 + decodeConnectedAccountItems(serverItems([{ definitely: 'not-an-account' }]))
133 );
134
135 expect(Schema.isSchemaError(error)).toBe(true);
@@ -77,17 +138,19 @@ describe('decodeConnectedAccountItems', () => {
138 });
139 });
140
80 -describe('decodeConnectedAccountListWithFallback', () => {
141 +describe('decodeConnectedAccountList', () => {
142 layer(TestLayer)('[Given] a response with a status newer than this CLI build', it => {
82 - it.effect('decodes and warns instead of falling back to the raw payload', () =>
143 + it.effect('decodes and warns', () =>
144 Effect.gen(function* () {
84 - const result = yield* decodeConnectedAccountListWithFallback({
85 - items: [makeItem({ status: 'QUANTUM_LINKED' })],
86 - total_items: 1,
87 - total_pages: 1,
88 - current_page: 1,
89 - next_cursor: null,
90 - });
145 + const result = yield* decodeConnectedAccountList(
146 + serverResponse({
147 + items: [makeItem({ status: 'QUANTUM_LINKED' })],
148 + total_items: 1,
149 + total_pages: 1,
150 + current_page: 1,
151 + next_cursor: null,
152 + })
153 + );
154
155 expect(result.items).toStrictEqual([makeItem({ status: 'QUANTUM_LINKED' })]);
156
@@ -98,27 +161,48 @@ describe('decodeConnectedAccountListWithFallback', () => {
161 );
162 });
163
164 + layer(TestLayer)('[Given] a response whose envelope does not match', it => {
165 + it.effect('fails naming the mismatched field', () =>
166 + Effect.gen(function* () {
167 + const error = yield* Effect.flip(
168 + decodeConnectedAccountList(
169 + serverResponse({
170 + items: [makeItem()],
171 + total_items: '3',
172 + total_pages: 1,
173 + current_page: 1,
174 + next_cursor: null,
175 + })
176 + )
177 + );
178 +
179 + expect(error._tag).toBe('effects/ConnectedAccountListShapeError');
180 + expect(error.message).toContain('total_items');
181 + expect(error.message).not.toContain('"3"');
182 + })
183 + );
184 + });
185 +
186 layer(TestLayer)('[Given] a shape-skewed response carrying credential fields', it => {
102 - it.effect('falls back to raw but never echoes payload values in the warning', () =>
187 + it.effect('fails without echoing payload values', () =>
188 Effect.gen(function* () {
189 // `items` is not an array: the decode fails at the container level,
190 // where an unredacted formatter would print the whole actual value.
106 - const raw = {
107 - items: { 0: makeItem({ state: { access_token: 'must-not-leak' } }) },
108 - total_items: 1,
109 - total_pages: 1,
110 - current_page: 1,
111 - next_cursor: null,
112 - };
113 -
114 - const result = yield* decodeConnectedAccountListWithFallback(raw);
115 -
116 - expect(result).toBe(raw);
191 + const error = yield* Effect.flip(
192 + decodeConnectedAccountList(
193 + serverResponse({
194 + items: { 0: makeItem({ state: { access_token: 'must-not-leak' } }) },
195 + total_items: 1,
196 + total_pages: 1,
197 + current_page: 1,
198 + next_cursor: null,
199 + })
200 + )
201 + );
202
118 - const output = (yield* MockConsole.getLines()).join('\n');
119 - expect(output).toContain('composio upgrade');
120 - expect(output).toContain('items');
121 - expect(output).not.toContain('must-not-leak');
203 + expect(error.message).toContain('items');
204 + expect(error.message).not.toContain('must-not-leak');
205 + expect((yield* MockConsole.getLines()).join('\n')).not.toContain('must-not-leak');
206 })
207 );
208 });