@devries-cameron20 / composio Mirror · read-only / commits / a24ef6277
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, 08:30 UTC

refactor(cli): move `connected-accounts info`, `list` and `whoami` into the directory shape (#4994)

This PR: - moves `dev connected-accounts info`, `list` and `whoami` from `connected-accounts/commands/` to `connected-accounts/<name>/connected-accounts.<name>.{cmd,handler,format}.ts`, plus `list.errors.ts` for `ConnectedAccountsListRequestError` (same tag); `connected-accounts/commands/` no longer exists - keeps `format.ts` as the group's shared module: the accounts table (`list` and `link`), and the fetch spinner, failure hint, missing-id warning and status color that `info` and `whoami` share - replaces the `if`/`else` empty-page hint chain with an `Option.orElse` pipeline, the missing-id guard with `Option.match`, and the empty check with `Array.match`; messages, streams and exit codes are unchanged - moves the three `.cmd.test.ts` suites to mirrored paths and adds handler tests: stdout JSON for each command, the request filters (`--toolkits` split and trim, `--status`, shared `--user-id`, clamped `--limit`), the `--project-name` scope, the empty-page message order, the inactive-status warning, and exit 1 on an unknown id - part of the CLI command-layout series (legacy-shape cleanup before U10); no user-visible change, so no CHANGELOG entry ## Context Verified: `pnpm --filter @composio/cli test` (190 files, 2059 passed, 1 skipped; `validate:command-tests` at 2 exemptions), CLI `typecheck`, `lint:effect` (0 diagnostics), oxlint (warnings only, none in touched files), prettier, root `pnpm typecheck`. Binary smoke against an `origin/next` binary: `--help` of the group and of `list`, `info`, `whoami` and `link` on both trees, root and `dev` help, logged-out runs of each moved command, missing-id runs, `--user-id`/`--project-name` rejections, a bad `--status`, and logged-in runs against an unreachable API all match byte for byte, exit codes included; the only difference is the minified stack-frame name in the `ConnectedAccountsListRequestError` trace.

Alberto Schiabel committed Oct 20, 2026 at 20:00 UTC a24ef627722e0b11003611afb2de52bb810954fa
21 files changed +1011 -330
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.info.cmd.ts deleted
-62
@@ -1,62 +0,0 @@
1 -import { Argument, Command } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 -import { TerminalUI } from 'src/services/terminal-ui';
5 -import { handleClientApiError } from 'src/effects/handle-http-error';
6 -import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 -import { formatConnectedAccountInfo } from '../format';
8 -
9 -const id = Argument.String('id').pipe(
10 - Argument.withDescription('Connected account ID (nanoid)'),
11 - Argument.optional
12 -);
13 -
14 -/**
15 - * View details of a specific connected account.
16 - *
17 - * @example
18 - * ```bash
19 - * composio dev connected-accounts info "con_1a2b3c4d5e6f"
20 - * ```
21 - */
22 -export const connectedAccountsCmd$Info = Command.make('info', { id }, ({ id }) =>
23 - Effect.gen(function* () {
24 - const ui = yield* TerminalUI;
25 - const repo = yield* ComposioToolkitsRepository;
26 -
27 - // Missing ID guard
28 - if (Option.isNone(id)) {
29 - yield* ui.log.warn('Missing required argument: <id>');
30 - yield* ui.log.step(
31 - 'Try specifying a connected account ID, e.g.:\n> composio dev connected-accounts info "con_1a2b3c4d5e6f"\n\nTo find connected account IDs:\n> composio dev connected-accounts list'
32 - );
33 - return;
34 - }
35 -
36 - const idValue = id.value;
37 -
38 - const itemOpt = yield* ui
39 - .withSpinner(`Fetching connected account "${idValue}"...`, repo.getConnectedAccount(idValue))
40 - .pipe(
41 - Effect.asSome,
42 - Effect.catchTag(
43 - CLIENT_API_ERROR_TAGS,
44 - handleClientApiError(ui, {
45 - fallbackMessage: `Failed to fetch connected account "${idValue}".`,
46 - hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
47 - fallbackValue: Option.none(),
48 - })
49 - )
50 - );
51 -
52 - if (Option.isNone(itemOpt)) {
53 - return;
54 - }
55 -
56 - const item = itemOpt.value;
57 -
58 - yield* ui.note(formatConnectedAccountInfo(item), `Connected Account: ${item.toolkit.slug}`);
59 -
60 - yield* ui.output(JSON.stringify(item, null, 2));
61 - })
62 -).pipe(Command.withDescription('View details of a specific connected account.'));
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts deleted
-115
@@ -1,115 +0,0 @@
1 -import { Command, Flag } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { ComposioClientSingleton } from 'src/services/composio-clients';
4 -import { TerminalUI } from 'src/services/terminal-ui';
5 -import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
6 -import { failedWith, requestError } from 'src/effects/request-error';
7 -import { clampLimit } from 'src/ui/clamp-limit';
8 -import { redact } from 'src/ui/redact';
9 -import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
10 -import { formatConnectedAccountsTable, formatConnectedAccountsJson } from '../format';
11 -import { idempotent } from 'src/services/composio-request';
12 -
13 -class ConnectedAccountsListRequestError extends requestError(
14 - 'commands/ConnectedAccountsListRequestError'
15 -) {}
16 -
17 -const toolkits = Flag.String('toolkits').pipe(
18 - Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
19 - Flag.optional
20 -);
21 -
22 -const status = Flag.Literals('status', [
23 - 'INITIALIZING',
24 - 'INITIATED',
25 - 'ACTIVE',
26 - 'FAILED',
27 - 'EXPIRED',
28 - 'INACTIVE',
29 - 'REVOKED',
30 -] as const).pipe(Flag.withDescription('Filter by connection status'), Flag.optional);
31 -
32 -const limit = Flag.Int('limit').pipe(
33 - Flag.withDefault(30),
34 - Flag.withDescription('Number of results per page (1-1000)')
35 -);
36 -
37 -/**
38 - * List connected accounts with optional filters.
39 - *
40 - * @example
41 - * ```bash
42 - * composio dev connected-accounts list
43 - * composio dev connected-accounts list --toolkits "gmail"
44 - * composio dev connected-accounts list --user-id "default" --status ACTIVE
45 - * ```
46 - */
47 -export const connectedAccountsCmd$List = Command.make(
48 - 'list',
49 - { toolkits, status, limit },
50 - ({ toolkits, status, limit }) =>
51 - Effect.gen(function* () {
52 - const { userId } = yield* CommandSurface;
53 - const ui = yield* TerminalUI;
54 - const clientSingleton = yield* ComposioClientSingleton;
55 -
56 - const toolkitSlugs = Option.isSome(toolkits)
57 - ? toolkits.value.split(',').map(s => s.trim())
58 - : undefined;
59 - const resolvedProject = yield* resolveSurfaceProject('developer');
60 - const client = yield* clientSingleton.getFor({
61 - orgId: resolvedProject.orgId,
62 - projectId: resolvedProject.projectId,
63 - });
64 -
65 - const rawResult = yield* ui.withSpinner(
66 - 'Fetching connected accounts...',
67 - client.connectedAccounts
68 - .list(
69 - {
70 - toolkit_slugs: toolkitSlugs,
71 - user_ids: Option.isSome(userId) ? [userId.value] : undefined,
72 - statuses: Option.isSome(status) ? [status.value] : undefined,
73 - limit: clampLimit(limit),
74 - },
75 - idempotent
76 - )
77 - .pipe(failedWith(ConnectedAccountsListRequestError, 'Failed to list connected accounts.'))
78 - );
79 - const result = yield* decodeConnectedAccountListWithFallback(rawResult);
80 -
81 - if (result.items.length === 0) {
82 - let hint: string;
83 - if (Option.isSome(toolkits)) {
84 - hint = `No connected accounts found for toolkit "${toolkits.value}". Verify the toolkit slug with:\n> composio dev toolkits list`;
85 - } else if (Option.isSome(userId)) {
86 - hint = `No connected accounts found for user "${userId.value}".`;
87 - } else if (Option.isSome(status)) {
88 - hint = `No connected accounts found with status "${status.value}".`;
89 - } else {
90 - hint = 'No connected accounts found.';
91 - }
92 - yield* ui.log.warn(hint);
93 - return;
94 - }
95 -
96 - const showing = result.items.length;
97 - const total = result.total_items;
98 -
99 - yield* ui.log.info(
100 - `Listing ${showing} of ${total} connected accounts\n\n${formatConnectedAccountsTable(result.items)}`
101 - );
102 -
103 - // Next step hint
104 - const firstId = result.items[0]?.id;
105 - const redactedId = redact({ value: firstId, prefix: 'con_' });
106 -
107 - if (firstId) {
108 - yield* ui.log.step(
109 - `To view details of a connected account:\n> composio dev connected-accounts info "${redactedId}"`
110 - );
111 - }
112 -
113 - yield* ui.output(formatConnectedAccountsJson(result.items));
114 - })
115 -).pipe(Command.withDescription('List connected accounts.'));
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.whoami.cmd.ts deleted
-86
@@ -1,86 +0,0 @@
1 -import { Argument, Command } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 -import { TerminalUI } from 'src/services/terminal-ui';
5 -import { handleClientApiError } from 'src/effects/handle-http-error';
6 -import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 -import { formatConnectedAccountWhoami } from '../format';
8 -
9 -const id = Argument.String('id').pipe(
10 - Argument.withDescription('Connected account ID (nanoid)'),
11 - Argument.optional
12 -);
13 -
14 -/**
15 - * Show the external account profile for a connected account.
16 - *
17 - * Retrieves the connected account details and displays a summary
18 - * of who is connected (toolkit, user, status). Warns when the
19 - * connection is in a non-ACTIVE state.
20 - *
21 - * @example
22 - * ```bash
23 - * composio dev connected-accounts whoami "con_1a2b3c4d5e6f"
24 - * ```
25 - */
26 -export const connectedAccountsCmd$Whoami = Command.make('whoami', { id }, ({ id }) =>
27 - Effect.gen(function* () {
28 - const ui = yield* TerminalUI;
29 - const repo = yield* ComposioToolkitsRepository;
30 -
31 - // Missing ID guard
32 - if (Option.isNone(id)) {
33 - yield* ui.log.warn('Missing required argument: <id>');
34 - yield* ui.log.step(
35 - 'Try specifying a connected account ID, e.g.:\n> composio dev connected-accounts whoami "con_1a2b3c4d5e6f"\n\nTo find connected account IDs:\n> composio dev connected-accounts list'
36 - );
37 - return;
38 - }
39 -
40 - const idValue = id.value;
41 -
42 - const itemOpt = yield* ui
43 - .withSpinner(`Fetching connected account "${idValue}"...`, repo.getConnectedAccount(idValue))
44 - .pipe(
45 - Effect.asSome,
46 - Effect.catchTag(
47 - CLIENT_API_ERROR_TAGS,
48 - handleClientApiError(ui, {
49 - fallbackMessage: `Failed to fetch connected account "${idValue}".`,
50 - hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
51 - fallbackValue: Option.none(),
52 - })
53 - )
54 - );
55 -
56 - if (Option.isNone(itemOpt)) {
57 - return;
58 - }
59 -
60 - const item = itemOpt.value;
61 -
62 - // Warn for non-ACTIVE connections
63 - if (item.status !== 'ACTIVE') {
64 - yield* ui.log.warn(`This connected account has status ${item.status}.`);
65 - }
66 -
67 - yield* ui.note(formatConnectedAccountWhoami(item), `whoami: ${item.toolkit.slug}`);
68 -
69 - yield* ui.output(
70 - JSON.stringify(
71 - {
72 - id: item.id,
73 - alias: item.alias,
74 - word_id: item.word_id,
75 - toolkit: item.toolkit.slug,
76 - user_id: item.user_id,
77 - status: item.status,
78 - auth_config_id: item.auth_config.id,
79 - auth_scheme: item.auth_config.auth_scheme,
80 - },
81 - null,
82 - 2
83 - )
84 - );
85 - })
86 -).pipe(Command.withDescription('Show the external account profile for a connected account.'));
ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts
+3 -3
@@ -1,9 +1,9 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { rejectsSharedFlags } from 'src/commands/surface';
4 -import { connectedAccountsCmd$List } from './commands/connected-accounts.list.cmd';
5 -import { connectedAccountsCmd$Info } from './commands/connected-accounts.info.cmd';
6 -import { connectedAccountsCmd$Whoami } from './commands/connected-accounts.whoami.cmd';
4 +import { connectedAccountsCmd$List } from './list/connected-accounts.list.cmd';
5 +import { connectedAccountsCmd$Info } from './info/connected-accounts.info.cmd';
6 +import { connectedAccountsCmd$Whoami } from './whoami/connected-accounts.whoami.cmd';
7 import { connectedAccountsCmd$Link } from './link/connected-accounts.link.cmd';
8
9 /**
ts/packages/cli/src/commands/connected-accounts/format.ts
+15 -64
@@ -19,78 +19,29 @@ export function formatConnectedAccountsTable(items: ReadonlyArray<ConnectedAccou
19 18
20 );
21 const authScheme = truncate(item.auth_config.auth_scheme || '-', 14).padEnd(14);
22 - const status = item.status === 'ACTIVE' ? item.status : gray(item.status);
22 + const status = formatStatus(item.status);
23 return `${id} ${alias} ${wordId} ${userId} ${toolkit} ${authConfig} ${authScheme} ${status}`;
24 });
25
26 return [header, ...rows].join('\n');
27 }
28
29 -/**
30 - * Format connected accounts as JSON for piped output.
31 - */
32 -export function formatConnectedAccountsJson(items: ReadonlyArray<ConnectedAccountItem>): string {
33 - return JSON.stringify(
34 - items.map(item => ({
35 - id: item.id,
36 - alias: item.alias,
37 - word_id: item.word_id,
38 - user_id: item.user_id,
39 - toolkit_slug: item.toolkit.slug,
40 - auth_config_id: item.auth_config.id,
41 - auth_scheme: item.auth_config.auth_scheme,
42 - status: item.status,
43 - created_at: item.created_at,
44 - })),
45 - null,
46 - 2
47 - );
48 -}
49 -
50 -/**
51 - * Format a single connected account for interactive display.
52 - */
53 -export function formatConnectedAccountInfo(item: ConnectedAccountItem): string {
54 - const lines: string[] = [];
29 +// --- shared by `info` and `whoami` ------------------------------------------------------------
30
56 - lines.push(`${bold('Id:')} ${redact({ value: item.id, prefix: 'con_' })}`);
57 - lines.push(`${bold('Alias:')} ${item.alias || '-'}`);
58 - lines.push(`${bold('Word Id:')} ${item.word_id || '-'}`);
59 - lines.push(`${bold('Status:')} ${item.status === 'ACTIVE' ? item.status : gray(item.status)}`);
31 +/** The spinner label while `info` or `whoami` fetches one connected account. */
32 +export const fetchingConnectedAccountMessage = (id: string) =>
33 + `Fetching connected account "${id}"...`;
34
61 - if (item.status_reason) {
62 - lines.push(`${bold('Status Reason:')} ${item.status_reason}`);
63 - }
35 +/** The hint after `info` or `whoami` fails to fetch the account. */
36 +export const BROWSE_CONNECTED_ACCOUNTS_HINT =
37 + 'Browse available connected accounts:\n> composio dev connected-accounts list';
38
65 - lines.push(`${bold('Toolkit:')} ${item.toolkit.slug}`);
66 - lines.push(`${bold('User Id:')} ${item.user_id}`);
67 - lines.push(
68 - `${bold('Auth Config:')} ${redact({ value: item.auth_config.id, prefix: 'ac_' })} (${item.auth_config.auth_scheme})`
69 - );
70 - lines.push(`${bold('Composio Managed:')} ${item.auth_config.is_composio_managed ? 'Yes' : 'No'}`);
71 - lines.push(`${bold('Disabled:')} ${item.is_disabled ? 'Yes' : 'No'}`);
72 - lines.push(`${bold('Created:')} ${item.created_at}`);
73 - lines.push(`${bold('Updated:')} ${item.updated_at}`);
39 +/** The warning when `info` or `whoami` is given no id. */
40 +export const MISSING_ID_MESSAGE = 'Missing required argument: <id>';
41
75 - if (item.test_request_endpoint) {
76 - lines.push(`${bold('Test Endpoint:')} ${item.test_request_endpoint}`);
77 - }
42 +/** The hint after `MISSING_ID_MESSAGE`, naming the subcommand that was run. */
43 +export const missingIdHint = (subcommand: 'info' | 'whoami') =>
44 + `Try specifying a connected account ID, e.g.:\n> composio dev connected-accounts ${subcommand} "con_1a2b3c4d5e6f"\n\nTo find connected account IDs:\n> composio dev connected-accounts list`;
45
79 - return lines.join('\n');
80 -}
81 -
82 -/**
83 - * Format a connected account for the whoami display (compact 6-field subset).
84 - */
85 -export function formatConnectedAccountWhoami(item: ConnectedAccountItem): string {
86 - const lines: string[] = [];
87 - lines.push(`${bold('Id:')} ${redact({ value: item.id, prefix: 'con_' })}`);
88 - lines.push(`${bold('Alias:')} ${item.alias || '-'}`);
89 - lines.push(`${bold('Word Id:')} ${item.word_id || '-'}`);
90 - lines.push(`${bold('Status:')} ${item.status === 'ACTIVE' ? item.status : gray(item.status)}`);
91 - lines.push(`${bold('Toolkit:')} ${item.toolkit.slug}`);
92 - lines.push(`${bold('User Id:')} ${item.user_id}`);
93 - lines.push(`${bold('Auth Config:')} ${redact({ value: item.auth_config.id, prefix: 'ac_' })}`);
94 - lines.push(`${bold('Auth Scheme:')} ${item.auth_config.auth_scheme}`);
95 - return lines.join('\n');
96 -}
46 +/** The `Status:` value: plain when active, gray otherwise. */
47 +export const formatStatus = (status: string) => (status === 'ACTIVE' ? status : gray(status));
ts/packages/cli/src/commands/connected-accounts/info/connected-accounts.info.cmd.ts new
+13
@@ -0,0 +1,13 @@
1 +import { Argument, Command } from 'effect/cli';
2 +import { runConnectedAccountsInfo } from './connected-accounts.info.handler';
3 +
4 +const id = Argument.String('id').pipe(
5 + Argument.withDescription('Connected account ID (nanoid)'),
6 + Argument.optional
7 +);
8 +
9 +export const connectedAccountsCmd$Info = Command.make(
10 + 'info',
11 + { id },
12 + runConnectedAccountsInfo
13 +).pipe(Command.withDescription('View details of a specific connected account.'));
ts/packages/cli/src/commands/connected-accounts/info/connected-accounts.info.format.ts new
+48
@@ -0,0 +1,48 @@
1 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
2 +import { bold } from 'src/ui/colors';
3 +import { redact } from 'src/ui/redact';
4 +import { formatStatus } from '../format';
5 +
6 +// --- stderr -----------------------------------------------------------------------------------
7 +
8 +/** The title of the note `formatConnectedAccountInfo` fills. */
9 +export const connectedAccountInfoTitle = (item: ConnectedAccountItem) =>
10 + `Connected Account: ${item.toolkit.slug}`;
11 +
12 +/**
13 + * Format a single connected account for interactive display.
14 + */
15 +export function formatConnectedAccountInfo(item: ConnectedAccountItem): string {
16 + const lines: string[] = [];
17 +
18 + lines.push(`${bold('Id:')} ${redact({ value: item.id, prefix: 'con_' })}`);
19 + lines.push(`${bold('Alias:')} ${item.alias || '-'}`);
20 + lines.push(`${bold('Word Id:')} ${item.word_id || '-'}`);
21 + lines.push(`${bold('Status:')} ${formatStatus(item.status)}`);
22 +
23 + if (item.status_reason) {
24 + lines.push(`${bold('Status Reason:')} ${item.status_reason}`);
25 + }
26 +
27 + lines.push(`${bold('Toolkit:')} ${item.toolkit.slug}`);
28 + lines.push(`${bold('User Id:')} ${item.user_id}`);
29 + lines.push(
30 + `${bold('Auth Config:')} ${redact({ value: item.auth_config.id, prefix: 'ac_' })} (${item.auth_config.auth_scheme})`
31 + );
32 + lines.push(`${bold('Composio Managed:')} ${item.auth_config.is_composio_managed ? 'Yes' : 'No'}`);
33 + lines.push(`${bold('Disabled:')} ${item.is_disabled ? 'Yes' : 'No'}`);
34 + lines.push(`${bold('Created:')} ${item.created_at}`);
35 + lines.push(`${bold('Updated:')} ${item.updated_at}`);
36 +
37 + if (item.test_request_endpoint) {
38 + lines.push(`${bold('Test Endpoint:')} ${item.test_request_endpoint}`);
39 + }
40 +
41 + return lines.join('\n');
42 +}
43 +
44 +// --- stdout -----------------------------------------------------------------------------------
45 +
46 +/** The whole decoded account, as JSON. */
47 +export const formatConnectedAccountInfoJson = (item: ConnectedAccountItem) =>
48 + JSON.stringify(item, null, 2);
ts/packages/cli/src/commands/connected-accounts/info/connected-accounts.info.handler.ts new
+62
@@ -0,0 +1,62 @@
1 +import { Effect, Option } from 'effect';
2 +import { handleClientApiError } from 'src/effects/handle-http-error';
3 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 +import { TerminalUI } from 'src/services/terminal-ui';
6 +import {
7 + BROWSE_CONNECTED_ACCOUNTS_HINT,
8 + MISSING_ID_MESSAGE,
9 + fetchingConnectedAccountMessage,
10 + missingIdHint,
11 +} from '../format';
12 +import {
13 + connectedAccountInfoTitle,
14 + formatConnectedAccountInfo,
15 + formatConnectedAccountInfoJson,
16 +} from './connected-accounts.info.format';
17 +
18 +/** The arguments of `composio dev connected-accounts info`. */
19 +export type ConnectedAccountsInfoParams = {
20 + readonly id: Option.Option<string>;
21 +};
22 +
23 +const showConnectedAccount = (id: string) =>
24 + Effect.gen(function* () {
25 + const ui = yield* TerminalUI;
26 + const repo = yield* ComposioToolkitsRepository;
27 +
28 + const item = yield* ui
29 + .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(id))
30 + .pipe(
31 + Effect.asSome,
32 + Effect.catchTag(
33 + CLIENT_API_ERROR_TAGS,
34 + handleClientApiError(ui, {
35 + fallbackMessage: `Failed to fetch connected account "${id}".`,
36 + hint: BROWSE_CONNECTED_ACCOUNTS_HINT,
37 + fallbackValue: Option.none(),
38 + })
39 + )
40 + );
41 +
42 + yield* Option.match(item, {
43 + onNone: () => Effect.void,
44 + onSome: account =>
45 + Effect.gen(function* () {
46 + yield* ui.note(formatConnectedAccountInfo(account), connectedAccountInfoTitle(account));
47 + yield* ui.output(formatConnectedAccountInfoJson(account));
48 + }),
49 + });
50 + });
51 +
52 +/** Shows one connected account; a missing id warns and exits 0, as it always has. */
53 +export const runConnectedAccountsInfo = ({ id }: ConnectedAccountsInfoParams) =>
54 + Option.match(id, {
55 + onNone: () =>
56 + Effect.gen(function* () {
57 + const ui = yield* TerminalUI;
58 + yield* ui.log.warn(MISSING_ID_MESSAGE);
59 + yield* ui.log.step(missingIdHint('info'));
60 + }),
61 + onSome: showConnectedAccount,
62 + });
ts/packages/cli/src/commands/connected-accounts/list/connected-accounts.list.cmd.ts new
+28
@@ -0,0 +1,28 @@
1 +import { Command, Flag } from 'effect/cli';
2 +import { runConnectedAccountsList } from './connected-accounts.list.handler';
3 +
4 +const toolkits = Flag.String('toolkits').pipe(
5 + Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
6 + Flag.optional
7 +);
8 +
9 +const status = Flag.Literals('status', [
10 + 'INITIALIZING',
11 + 'INITIATED',
12 + 'ACTIVE',
13 + 'FAILED',
14 + 'EXPIRED',
15 + 'INACTIVE',
16 + 'REVOKED',
17 +] as const).pipe(Flag.withDescription('Filter by connection status'), Flag.optional);
18 +
19 +const limit = Flag.Int('limit').pipe(
20 + Flag.withDefault(30),
21 + Flag.withDescription('Number of results per page (1-1000)')
22 +);
23 +
24 +export const connectedAccountsCmd$List = Command.make(
25 + 'list',
26 + { toolkits, status, limit },
27 + runConnectedAccountsList
28 +).pipe(Command.withDescription('List connected accounts.'));
ts/packages/cli/src/commands/connected-accounts/list/connected-accounts.list.errors.ts new
+5
@@ -0,0 +1,5 @@
1 +import { requestError } from 'src/effects/request-error';
2 +
3 +export class ConnectedAccountsListRequestError extends requestError(
4 + 'commands/ConnectedAccountsListRequestError'
5 +) {}
ts/packages/cli/src/commands/connected-accounts/list/connected-accounts.list.format.ts new
+64
@@ -0,0 +1,64 @@
1 +import { Option, pipe } from 'effect';
2 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
3 +import { redact } from 'src/ui/redact';
4 +import { formatConnectedAccountsTable } from '../format';
5 +
6 +// --- stderr -----------------------------------------------------------------------------------
7 +
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 +/**
12 + * The warning for an empty page, naming the first filter that was given: `--toolkits`, then
13 + * `--user-id`, then `--status`.
14 + */
15 +export const noConnectedAccountsMessage = (filters: {
16 + readonly toolkits: Option.Option<string>;
17 + readonly userId: Option.Option<string>;
18 + readonly status: Option.Option<string>;
19 +}) =>
20 + pipe(
21 + Option.map(
22 + filters.toolkits,
23 + toolkits =>
24 + `No connected accounts found for toolkit "${toolkits}". Verify the toolkit slug with:\n> composio dev toolkits list`
25 + ),
26 + Option.orElse(() =>
27 + Option.map(filters.userId, userId => `No connected accounts found for user "${userId}".`)
28 + ),
29 + Option.orElse(() =>
30 + Option.map(filters.status, status => `No connected accounts found with status "${status}".`)
31 + ),
32 + Option.getOrElse(() => 'No connected accounts found.')
33 + );
34 +
35 +/** The page as a table, under how many of the total it shows. */
36 +export const listingMessage = (items: ReadonlyArray<ConnectedAccountItem>, total: number) =>
37 + `Listing ${items.length} of ${total} connected accounts\n\n${formatConnectedAccountsTable(items)}`;
38 +
39 +/** The next step after a listing, naming the first account. */
40 +export const viewDetailsHint = (id: string) =>
41 + `To view details of a connected account:\n> composio dev connected-accounts info "${redact({ value: id, prefix: 'con_' })}"`;
42 +
43 +// --- stdout -----------------------------------------------------------------------------------
44 +
45 +/**
46 + * Format connected accounts as JSON for piped output.
47 + */
48 +export function formatConnectedAccountsJson(items: ReadonlyArray<ConnectedAccountItem>): string {
49 + return JSON.stringify(
50 + items.map(item => ({
51 + id: item.id,
52 + alias: item.alias,
53 + word_id: item.word_id,
54 + user_id: item.user_id,
55 + toolkit_slug: item.toolkit.slug,
56 + auth_config_id: item.auth_config.id,
57 + auth_scheme: item.auth_config.auth_scheme,
58 + status: item.status,
59 + created_at: item.created_at,
60 + })),
61 + null,
62 + 2
63 + );
64 +}
ts/packages/cli/src/commands/connected-accounts/list/connected-accounts.list.handler.ts new
+77
@@ -0,0 +1,77 @@
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';
4 +import { failedWith } from 'src/effects/request-error';
5 +import type { KnownConnectedAccountStatus } from 'src/models/connected-accounts';
6 +import { ComposioClientSingleton } from 'src/services/composio-clients';
7 +import { idempotent } from 'src/services/composio-request';
8 +import { TerminalUI } from 'src/services/terminal-ui';
9 +import { clampLimit } from 'src/ui/clamp-limit';
10 +import { ConnectedAccountsListRequestError } from './connected-accounts.list.errors';
11 +import {
12 + FETCHING_CONNECTED_ACCOUNTS_MESSAGE,
13 + LIST_CONNECTED_ACCOUNTS_FAILED_MESSAGE,
14 + formatConnectedAccountsJson,
15 + listingMessage,
16 + noConnectedAccountsMessage,
17 + viewDetailsHint,
18 +} from './connected-accounts.list.format';
19 +
20 +/**
21 + * The flags of `composio dev connected-accounts list`. The `dev` group's `--user-id` and
22 + * `--project-name` come from `CommandSurface`, not from here.
23 + */
24 +export type ConnectedAccountsListParams = {
25 + readonly toolkits: Option.Option<string>;
26 + readonly status: Option.Option<KnownConnectedAccountStatus>;
27 + readonly limit: number;
28 +};
29 +
30 +/** Lists one page of connected accounts in the developer project, filtered by the flags. */
31 +export const runConnectedAccountsList = ({
32 + toolkits,
33 + status,
34 + limit,
35 +}: ConnectedAccountsListParams) =>
36 + Effect.gen(function* () {
37 + const { userId } = yield* CommandSurface;
38 + const ui = yield* TerminalUI;
39 + const clientSingleton = yield* ComposioClientSingleton;
40 +
41 + const resolvedProject = yield* resolveSurfaceProject('developer');
42 + const client = yield* clientSingleton.getFor({
43 + orgId: resolvedProject.orgId,
44 + projectId: resolvedProject.projectId,
45 + });
46 +
47 + const rawResult = yield* ui.withSpinner(
48 + FETCHING_CONNECTED_ACCOUNTS_MESSAGE,
49 + client.connectedAccounts
50 + .list(
51 + {
52 + toolkit_slugs: Option.getOrUndefined(
53 + Option.map(toolkits, csv => csv.split(',').map(slug => slug.trim()))
54 + ),
55 + user_ids: Option.getOrUndefined(Option.map(userId, Arr.of)),
56 + statuses: Option.getOrUndefined(Option.map(status, Arr.of)),
57 + limit: clampLimit(limit),
58 + },
59 + idempotent
60 + )
61 + .pipe(failedWith(ConnectedAccountsListRequestError, LIST_CONNECTED_ACCOUNTS_FAILED_MESSAGE))
62 + );
63 + const result = yield* decodeConnectedAccountListWithFallback(rawResult);
64 +
65 + yield* Arr.match(result.items, {
66 + onEmpty: () => ui.log.warn(noConnectedAccountsMessage({ toolkits, userId, status })),
67 + onNonEmpty: items =>
68 + Effect.gen(function* () {
69 + yield* ui.log.info(listingMessage(items, result.total_items));
70 + const firstId = Arr.headNonEmpty(items).id;
71 + if (firstId) {
72 + yield* ui.log.step(viewDetailsHint(firstId));
73 + }
74 + yield* ui.output(formatConnectedAccountsJson(items));
75 + }),
76 + });
77 + });
ts/packages/cli/src/commands/connected-accounts/whoami/connected-accounts.whoami.cmd.ts new
+13
@@ -0,0 +1,13 @@
1 +import { Argument, Command } from 'effect/cli';
2 +import { runConnectedAccountsWhoami } from './connected-accounts.whoami.handler';
3 +
4 +const id = Argument.String('id').pipe(
5 + Argument.withDescription('Connected account ID (nanoid)'),
6 + Argument.optional
7 +);
8 +
9 +export const connectedAccountsCmd$Whoami = Command.make(
10 + 'whoami',
11 + { id },
12 + runConnectedAccountsWhoami
13 +).pipe(Command.withDescription('Show the external account profile for a connected account.'));
ts/packages/cli/src/commands/connected-accounts/whoami/connected-accounts.whoami.format.ts new
+49
@@ -0,0 +1,49 @@
1 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
2 +import { bold } from 'src/ui/colors';
3 +import { redact } from 'src/ui/redact';
4 +import { formatStatus } from '../format';
5 +
6 +// --- stderr -----------------------------------------------------------------------------------
7 +
8 +/** The warning for an account that is not ACTIVE. */
9 +export const inactiveStatusMessage = (status: string) =>
10 + `This connected account has status ${status}.`;
11 +
12 +/** The title of the note `formatConnectedAccountWhoami` fills. */
13 +export const connectedAccountWhoamiTitle = (item: ConnectedAccountItem) =>
14 + `whoami: ${item.toolkit.slug}`;
15 +
16 +/**
17 + * Format a connected account for the whoami display (compact 6-field subset).
18 + */
19 +export function formatConnectedAccountWhoami(item: ConnectedAccountItem): string {
20 + const lines: string[] = [];
21 + lines.push(`${bold('Id:')} ${redact({ value: item.id, prefix: 'con_' })}`);
22 + lines.push(`${bold('Alias:')} ${item.alias || '-'}`);
23 + lines.push(`${bold('Word Id:')} ${item.word_id || '-'}`);
24 + lines.push(`${bold('Status:')} ${formatStatus(item.status)}`);
25 + lines.push(`${bold('Toolkit:')} ${item.toolkit.slug}`);
26 + lines.push(`${bold('User Id:')} ${item.user_id}`);
27 + lines.push(`${bold('Auth Config:')} ${redact({ value: item.auth_config.id, prefix: 'ac_' })}`);
28 + lines.push(`${bold('Auth Scheme:')} ${item.auth_config.auth_scheme}`);
29 + return lines.join('\n');
30 +}
31 +
32 +// --- stdout -----------------------------------------------------------------------------------
33 +
34 +/** Who the account is connected as, as JSON. */
35 +export const formatConnectedAccountWhoamiJson = (item: ConnectedAccountItem) =>
36 + JSON.stringify(
37 + {
38 + id: item.id,
39 + alias: item.alias,
40 + word_id: item.word_id,
41 + toolkit: item.toolkit.slug,
42 + user_id: item.user_id,
43 + status: item.status,
44 + auth_config_id: item.auth_config.id,
45 + auth_scheme: item.auth_config.auth_scheme,
46 + },
47 + null,
48 + 2
49 + );
ts/packages/cli/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.ts new
+72
@@ -0,0 +1,72 @@
1 +import { Effect, Option } from 'effect';
2 +import { handleClientApiError } from 'src/effects/handle-http-error';
3 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 +import { TerminalUI } from 'src/services/terminal-ui';
6 +import {
7 + BROWSE_CONNECTED_ACCOUNTS_HINT,
8 + MISSING_ID_MESSAGE,
9 + fetchingConnectedAccountMessage,
10 + missingIdHint,
11 +} from '../format';
12 +import {
13 + connectedAccountWhoamiTitle,
14 + formatConnectedAccountWhoami,
15 + formatConnectedAccountWhoamiJson,
16 + inactiveStatusMessage,
17 +} from './connected-accounts.whoami.format';
18 +
19 +/** The arguments of `composio dev connected-accounts whoami`. */
20 +export type ConnectedAccountsWhoamiParams = {
21 + readonly id: Option.Option<string>;
22 +};
23 +
24 +const showConnectedAccountProfile = (id: string) =>
25 + Effect.gen(function* () {
26 + const ui = yield* TerminalUI;
27 + const repo = yield* ComposioToolkitsRepository;
28 +
29 + const item = yield* ui
30 + .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(id))
31 + .pipe(
32 + Effect.asSome,
33 + Effect.catchTag(
34 + CLIENT_API_ERROR_TAGS,
35 + handleClientApiError(ui, {
36 + fallbackMessage: `Failed to fetch connected account "${id}".`,
37 + hint: BROWSE_CONNECTED_ACCOUNTS_HINT,
38 + fallbackValue: Option.none(),
39 + })
40 + )
41 + );
42 +
43 + yield* Option.match(item, {
44 + onNone: () => Effect.void,
45 + onSome: account =>
46 + Effect.gen(function* () {
47 + if (account.status !== 'ACTIVE') {
48 + yield* ui.log.warn(inactiveStatusMessage(account.status));
49 + }
50 + yield* ui.note(
51 + formatConnectedAccountWhoami(account),
52 + connectedAccountWhoamiTitle(account)
53 + );
54 + yield* ui.output(formatConnectedAccountWhoamiJson(account));
55 + }),
56 + });
57 + });
58 +
59 +/**
60 + * Shows who a connected account is connected as (toolkit, user, status), warning when the
61 + * connection is not ACTIVE; a missing id warns and exits 0, as it always has.
62 + */
63 +export const runConnectedAccountsWhoami = ({ id }: ConnectedAccountsWhoamiParams) =>
64 + Option.match(id, {
65 + onNone: () =>
66 + Effect.gen(function* () {
67 + const ui = yield* TerminalUI;
68 + yield* ui.log.warn(MISSING_ID_MESSAGE);
69 + yield* ui.log.step(missingIdHint('whoami'));
70 + }),
71 + onSome: showConnectedAccountProfile,
72 + });
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.cmd.test.ts renamed
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.handler.test.ts new
+127
@@ -0,0 +1,127 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Console, Effect, Layer, Option } from 'effect';
3 +import { runConnectedAccountsInfo } from 'src/commands/connected-accounts/info/connected-accounts.info.handler';
4 +import { MISSING_ID_MESSAGE, missingIdHint } from 'src/commands/connected-accounts/format';
5 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 +import { NodeProcess } from 'src/services/node-process';
7 +import { TerminalUI } from 'src/services/terminal-ui';
8 +import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
9 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
10 +
11 +const EXPIRED_ACCOUNT: ConnectedAccountItem = {
12 + id: 'con_github_expired',
13 + alias: 'work',
14 + word_id: 'castle',
15 + status: 'EXPIRED',
16 + status_reason: 'Token expired',
17 + is_disabled: false,
18 + user_id: 'default',
19 + toolkit: { slug: 'github' },
20 + auth_config: {
21 + id: 'ac_github_oauth',
22 + auth_scheme: 'OAUTH2',
23 + is_composio_managed: false,
24 + is_disabled: false,
25 + },
26 + created_at: '2026-02-01T00:00:00Z',
27 + updated_at: '2026-02-10T00:00:00Z',
28 + test_request_endpoint: 'https://api.github.com/user',
29 +};
30 +
31 +/**
32 + * What `runConnectedAccountsInfo` reads: the connected-account repository, a headless terminal
33 + * whose stdout data lands in `outputs`, and a process whose exit codes land in `exitCodes`.
34 + */
35 +const infoTest = (items: ReadonlyArray<ConnectedAccountItem> = [EXPIRED_ACCOUNT]) => {
36 + const outputs: Array<string> = [];
37 + const exitCodes: Array<number> = [];
38 + const layer = Layer.mergeAll(
39 + Layer.effect(Console.Console, MockConsole.make),
40 + Layer.succeed(
41 + TerminalUI,
42 + TerminalUI.of({
43 + ...terminalUITestImpl,
44 + output: data =>
45 + Effect.sync(() => {
46 + outputs.push(data);
47 + }),
48 + })
49 + ),
50 + ConnectedAccountsTest({ connectedAccountsData: { items: [...items] } }),
51 + Layer.succeed(
52 + NodeProcess,
53 + NodeProcess.of({
54 + cwd: '/tmp',
55 + execPath: '/tmp/composio',
56 + platform: 'darwin',
57 + arch: 'arm64',
58 + setExitCode: code =>
59 + Effect.sync(() => {
60 + exitCodes.push(code);
61 + }),
62 + })
63 + )
64 + );
65 + return { layer, outputs, exitCodes };
66 +};
67 +
68 +const stdoutLines = MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
69 +const stderrLines = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
70 +
71 +describe('runConnectedAccountsInfo', () => {
72 + it.effect('[Given] an existing id [Then] prints the whole account as JSON on stdout', () => {
73 + const { layer, outputs, exitCodes } = infoTest();
74 + return Effect.gen(function* () {
75 + yield* runConnectedAccountsInfo({ id: Option.some('con_github_expired') });
76 +
77 + expect(outputs.map(output => JSON.parse(output))).toEqual([EXPIRED_ACCOUNT]);
78 + expect(exitCodes).toEqual([]);
79 + }).pipe(Effect.provide(layer));
80 + });
81 +
82 + it.effect(
83 + '[Given] an account with a status reason and test endpoint [Then] the note shows both',
84 + () => {
85 + const { layer } = infoTest();
86 + return Effect.gen(function* () {
87 + yield* runConnectedAccountsInfo({ id: Option.some('con_github_expired') });
88 + const note = (yield* stdoutLines).find(line =>
89 + line.startsWith('[Connected Account: github]')
90 + );
91 +
92 + expect(note).toBeDefined();
93 + expect(note).toContain('Alias: work');
94 + expect(note).toContain('Word Id: castle');
95 + expect(note).toContain('Status Reason: Token expired');
96 + expect(note).toContain('Auth Config: ac_github_oauth (OAUTH2)');
97 + expect(note).toContain('Composio Managed: No');
98 + expect(note).toContain('Test Endpoint: https://api.github.com/user');
99 + }).pipe(Effect.provide(layer));
100 + }
101 + );
102 +
103 + it.effect('[Given] no id [Then] warns with an example and fetches nothing', () => {
104 + const { layer, outputs, exitCodes } = infoTest();
105 + return Effect.gen(function* () {
106 + yield* runConnectedAccountsInfo({ id: Option.none() });
107 +
108 + expect(yield* stderrLines).toEqual([MISSING_ID_MESSAGE]);
109 + expect(yield* stdoutLines).toEqual([missingIdHint('info')]);
110 + expect(outputs).toEqual([]);
111 + expect(exitCodes).toEqual([]);
112 + }).pipe(Effect.provide(layer));
113 + });
114 +
115 + it.effect('[Given] an unknown id [Then] reports it, prints no data, and exits 1', () => {
116 + const { layer, outputs, exitCodes } = infoTest();
117 + return Effect.gen(function* () {
118 + yield* runConnectedAccountsInfo({ id: Option.some('con_missing') });
119 + const stderr = (yield* stderrLines).join('\n');
120 +
121 + expect(stderr).toContain('Connected account "con_missing" not found.');
122 + expect(stderr).toContain('composio dev connected-accounts list');
123 + expect(outputs).toEqual([]);
124 + expect(exitCodes).toEqual([1]);
125 + }).pipe(Effect.provide(layer));
126 + });
127 +});
ts/packages/cli/test/src/commands/connected-accounts/list/connected-accounts.list.cmd.test.ts renamed
ts/packages/cli/test/src/commands/connected-accounts/list/connected-accounts.list.handler.test.ts new
+300
@@ -0,0 +1,300 @@
1 +import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 +import { describe, expect, it } from '@effect/vitest';
3 +import { Console, Effect, Layer, Option } from 'effect';
4 +import { HttpClient } from 'effect/http';
5 +import {
6 + runConnectedAccountsList,
7 + type ConnectedAccountsListParams,
8 +} from 'src/commands/connected-accounts/list/connected-accounts.list.handler';
9 +import { viewDetailsHint } from 'src/commands/connected-accounts/list/connected-accounts.list.format';
10 +import { CommandSurface } from 'src/commands/surface';
11 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
12 +import type { ProjectKeys } from 'src/models/project-keys';
13 +import { ComposioClientSingleton } from 'src/services/composio-clients';
14 +import { ProjectContext } from 'src/services/project-context';
15 +import { TerminalUI } from 'src/services/terminal-ui';
16 +import { ComposioUserContext } from 'src/services/user-context';
17 +import { MockConsole } from 'test/__utils__';
18 +import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts';
19 +import {
20 + mockConnectedAccountResources,
21 + resolveConnectedAccountsTestData,
22 +} from 'test/__utils__/layers/connected-accounts';
23 +import { makeOrgProject } from 'test/__utils__/models/account';
24 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
25 +
26 +const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({
27 + id: 'con_gmail_active',
28 + alias: null,
29 + word_id: null,
30 + status: 'ACTIVE',
31 + status_reason: null,
32 + is_disabled: false,
33 + user_id: 'default',
34 + toolkit: { slug: 'gmail' },
35 + auth_config: {
36 + id: 'ac_gmail_oauth',
37 + auth_scheme: 'OAUTH2',
38 + is_composio_managed: true,
39 + is_disabled: false,
40 + },
41 + created_at: '2026-01-01T00:00:00Z',
42 + updated_at: '2026-01-15T00:00:00Z',
43 + test_request_endpoint: '',
44 + ...overrides,
45 +});
46 +
47 +const ACCOUNTS: ReadonlyArray<ConnectedAccountItem> = [
48 + account(),
49 + account({ id: 'con_slack_active', user_id: 'user-123', toolkit: { slug: 'slack' } }),
50 +];
51 +
52 +const DIRECTORY_PROJECT: ProjectKeys = {
53 + orgId: 'org_test',
54 + projectId: 'proj_directory',
55 + projectName: Option.some('directory'),
56 + orgName: Option.none(),
57 + email: Option.none(),
58 + testUserId: Option.none(),
59 +};
60 +
61 +const NAMED_PROJECT = makeOrgProject({ id: 'proj_named', name: 'named', orgId: 'org_test' });
62 +
63 +// A resource the mocks below do not shadow reaches this transport and dies with its URL.
64 +const baseClient = make(
65 + { auth: Auth.project('test'), baseURL: 'https://mock.invalid' },
66 + HttpClient.make(request =>
67 + Effect.die(
68 + new Error(`unexpected network call from the connected-accounts list test: ${request.url}`)
69 + )
70 + )
71 +);
72 +
73 +/** One `connectedAccounts.list` call, with the scope of the client it went through. */
74 +interface ListRequest {
75 + readonly scope: MockRequestScope;
76 + readonly params: unknown;
77 +}
78 +
79 +interface ListFixture {
80 + readonly accounts?: ReadonlyArray<ConnectedAccountItem>;
81 + readonly userId?: Option.Option<string>;
82 + readonly projectName?: Option.Option<string>;
83 +}
84 +
85 +/**
86 + * What `runConnectedAccountsList` reads: the `dev` surface, a user with an org, a directory
87 + * project, the account and connected-account families of the mock client, and a headless
88 + * terminal whose stdout data lands in `outputs`. `requests` records every list call.
89 + */
90 +const listTest = (fixture: ListFixture = {}) => {
91 + const outputs: Array<string> = [];
92 + const requests: Array<ListRequest> = [];
93 + const resources = mockConnectedAccountResources(
94 + resolveConnectedAccountsTestData({ items: [...(fixture.accounts ?? ACCOUNTS)] })
95 + );
96 + const clientFor = (scope: MockRequestScope): ComposioClientShape =>
97 + // The shadows answer only the fields the handler reads, as in `test-layer.ts`.
98 + ({
99 + ...baseClient,
100 + ...mockAccountResources({ projects: [NAMED_PROJECT] }, scope),
101 + connectedAccounts: {
102 + ...resources.connectedAccounts,
103 + list: (params: Parameters<typeof resources.connectedAccounts.list>[0]) =>
104 + Effect.sync(() => requests.push({ scope, params })).pipe(
105 + Effect.andThen(resources.connectedAccounts.list(params))
106 + ),
107 + },
108 + }) as unknown as ComposioClientShape;
109 +
110 + const layer = Layer.mergeAll(
111 + Layer.effect(Console.Console, MockConsole.make),
112 + Layer.succeed(
113 + TerminalUI,
114 + TerminalUI.of({
115 + ...terminalUITestImpl,
116 + output: data =>
117 + Effect.sync(() => {
118 + outputs.push(data);
119 + }),
120 + })
121 + ),
122 + CommandSurface.dev({
123 + userId: fixture.userId ?? Option.none(),
124 + projectName: fixture.projectName ?? Option.none(),
125 + }),
126 + Layer.succeed(
127 + ComposioUserContext,
128 + ComposioUserContext.of({
129 + data: {
130 + apiKey: Option.some('uak_test'),
131 + baseURL: 'https://mock.invalid',
132 + webURL: 'https://platform.mock.invalid',
133 + orgId: Option.some('org_test'),
134 + projectId: Option.none(),
135 + testUserId: Option.none(),
136 + },
137 + isLoggedIn: () => true,
138 + logout: Effect.void,
139 + login: () => Effect.void,
140 + update: () => Effect.void,
141 + })
142 + ),
143 + Layer.succeed(
144 + ProjectContext,
145 + ProjectContext.of({ resolve: Effect.succeed(Option.some(DIRECTORY_PROJECT)) })
146 + ),
147 + Layer.succeed(
148 + ComposioClientSingleton,
149 + ComposioClientSingleton.of({
150 + get: () => Effect.succeed(clientFor({})),
151 + getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)),
152 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
153 + })
154 + )
155 + );
156 + return { layer, outputs, requests };
157 +};
158 +
159 +const params = (
160 + overrides: Partial<ConnectedAccountsListParams> = {}
161 +): ConnectedAccountsListParams => ({
162 + toolkits: Option.none(),
163 + status: Option.none(),
164 + limit: 30,
165 + ...overrides,
166 +});
167 +
168 +const stderrLines = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
169 +const allLines = MockConsole.getLines({ stripAnsi: true });
170 +
171 +describe('runConnectedAccountsList', () => {
172 + it.effect('[Given] no filters [Then] lists the directory project without filters', () => {
173 + const { layer, requests } = listTest();
174 + return Effect.gen(function* () {
175 + yield* runConnectedAccountsList(params());
176 +
177 + expect(requests).toEqual([
178 + {
179 + scope: { orgId: 'org_test', projectId: 'proj_directory' },
180 + params: { toolkit_slugs: undefined, user_ids: undefined, statuses: undefined, limit: 30 },
181 + },
182 + ]);
183 + }).pipe(Effect.provide(layer));
184 + });
185 +
186 + it.effect(
187 + '[Given] --toolkits, --status and the shared --user-id [Then] sends each as a filter',
188 + () => {
189 + const { layer, requests } = listTest({ userId: Option.some('default') });
190 + return Effect.gen(function* () {
191 + yield* runConnectedAccountsList(
192 + params({ toolkits: Option.some('gmail, slack'), status: Option.some('ACTIVE') })
193 + );
194 +
195 + expect(requests.map(request => request.params)).toEqual([
196 + {
197 + toolkit_slugs: ['gmail', 'slack'],
198 + user_ids: ['default'],
199 + statuses: ['ACTIVE'],
200 + limit: 30,
201 + },
202 + ]);
203 + }).pipe(Effect.provide(layer));
204 + }
205 + );
206 +
207 + it.effect.each([
208 + { limit: 0, expected: 1 },
209 + { limit: 1001, expected: 1000 },
210 + ])('[Given] --limit $limit [Then] requests $expected accounts', ({ limit, expected }) => {
211 + const { layer, requests } = listTest();
212 + return Effect.gen(function* () {
213 + yield* runConnectedAccountsList(params({ limit }));
214 +
215 + expect(requests.map(request => request.params)).toMatchObject([{ limit: expected }]);
216 + }).pipe(Effect.provide(layer));
217 + });
218 +
219 + it.effect('[Given] the shared --project-name [Then] lists that developer project', () => {
220 + const { layer, requests } = listTest({ projectName: Option.some('named') });
221 + return Effect.gen(function* () {
222 + yield* runConnectedAccountsList(params());
223 +
224 + expect(requests.map(request => request.scope)).toEqual([
225 + { orgId: 'org_test', projectId: 'proj_named' },
226 + ]);
227 + }).pipe(Effect.provide(layer));
228 + });
229 +
230 + it.effect('[Given] accounts [Then] prints them as JSON on stdout and hints at `info`', () => {
231 + const { layer, outputs } = listTest();
232 + return Effect.gen(function* () {
233 + yield* runConnectedAccountsList(params());
234 +
235 + expect(outputs.map(output => JSON.parse(output))).toEqual([
236 + [
237 + {
238 + id: 'con_gmail_active',
239 + alias: null,
240 + word_id: null,
241 + user_id: 'default',
242 + toolkit_slug: 'gmail',
243 + auth_config_id: 'ac_gmail_oauth',
244 + auth_scheme: 'OAUTH2',
245 + status: 'ACTIVE',
246 + created_at: '2026-01-01T00:00:00Z',
247 + },
248 + {
249 + id: 'con_slack_active',
250 + alias: null,
251 + word_id: null,
252 + user_id: 'user-123',
253 + toolkit_slug: 'slack',
254 + auth_config_id: 'ac_gmail_oauth',
255 + auth_scheme: 'OAUTH2',
256 + status: 'ACTIVE',
257 + created_at: '2026-01-01T00:00:00Z',
258 + },
259 + ],
260 + ]);
261 + const lines = yield* allLines;
262 + expect(lines.some(line => line.startsWith('Listing 2 of 2 connected accounts'))).toBe(true);
263 + expect(lines).toContain(viewDetailsHint('con_gmail_active'));
264 + }).pipe(Effect.provide(layer));
265 + });
266 +
267 + it.effect.each([
268 + {
269 + given: 'every filter',
270 + fixture: { userId: Option.some('nobody') },
271 + flags: { toolkits: Option.some('notion'), status: Option.some('REVOKED' as const) },
272 + expected:
273 + 'No connected accounts found for toolkit "notion". Verify the toolkit slug with:\n> composio dev toolkits list',
274 + },
275 + {
276 + given: '--user-id and --status',
277 + fixture: { userId: Option.some('nobody') },
278 + flags: { status: Option.some('REVOKED' as const) },
279 + expected: 'No connected accounts found for user "nobody".',
280 + },
281 + {
282 + given: '--status',
283 + fixture: {},
284 + flags: { status: Option.some('REVOKED' as const) },
285 + expected: 'No connected accounts found with status "REVOKED".',
286 + },
287 + { given: 'no filter', fixture: {}, flags: {}, expected: 'No connected accounts found.' },
288 + ])(
289 + '[Given] an empty page and $given [Then] warns about the first filter and prints no data',
290 + ({ fixture, flags, expected }) => {
291 + const { layer, outputs } = listTest({ ...fixture, accounts: [] });
292 + return Effect.gen(function* () {
293 + yield* runConnectedAccountsList(params(flags));
294 +
295 + expect(yield* stderrLines).toEqual([expected]);
296 + expect(outputs).toEqual([]);
297 + }).pipe(Effect.provide(layer));
298 + }
299 + );
300 +});
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.cmd.test.ts renamed
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.test.ts new
+135
@@ -0,0 +1,135 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Console, Effect, Layer, Option } from 'effect';
3 +import { runConnectedAccountsWhoami } from 'src/commands/connected-accounts/whoami/connected-accounts.whoami.handler';
4 +import { inactiveStatusMessage } from 'src/commands/connected-accounts/whoami/connected-accounts.whoami.format';
5 +import { MISSING_ID_MESSAGE, missingIdHint } from 'src/commands/connected-accounts/format';
6 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7 +import { NodeProcess } from 'src/services/node-process';
8 +import { TerminalUI } from 'src/services/terminal-ui';
9 +import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
10 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
11 +
12 +const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({
13 + id: 'con_gmail_active',
14 + alias: 'personal',
15 + word_id: 'harbor',
16 + status: 'ACTIVE',
17 + status_reason: null,
18 + is_disabled: false,
19 + user_id: 'default',
20 + toolkit: { slug: 'gmail' },
21 + auth_config: {
22 + id: 'ac_gmail_oauth',
23 + auth_scheme: 'OAUTH2',
24 + is_composio_managed: true,
25 + is_disabled: false,
26 + },
27 + created_at: '2026-01-01T00:00:00Z',
28 + updated_at: '2026-01-15T00:00:00Z',
29 + test_request_endpoint: '',
30 + ...overrides,
31 +});
32 +
33 +const ACTIVE_ACCOUNT = account();
34 +const EXPIRED_ACCOUNT = account({ id: 'con_gmail_expired', status: 'EXPIRED' });
35 +
36 +/**
37 + * What `runConnectedAccountsWhoami` reads: the connected-account repository, a headless
38 + * terminal whose stdout data lands in `outputs`, and a process whose exit codes land in
39 + * `exitCodes`.
40 + */
41 +const whoamiTest = () => {
42 + const outputs: Array<string> = [];
43 + const exitCodes: Array<number> = [];
44 + const layer = Layer.mergeAll(
45 + Layer.effect(Console.Console, MockConsole.make),
46 + Layer.succeed(
47 + TerminalUI,
48 + TerminalUI.of({
49 + ...terminalUITestImpl,
50 + output: data =>
51 + Effect.sync(() => {
52 + outputs.push(data);
53 + }),
54 + })
55 + ),
56 + ConnectedAccountsTest({ connectedAccountsData: { items: [ACTIVE_ACCOUNT, EXPIRED_ACCOUNT] } }),
57 + Layer.succeed(
58 + NodeProcess,
59 + NodeProcess.of({
60 + cwd: '/tmp',
61 + execPath: '/tmp/composio',
62 + platform: 'darwin',
63 + arch: 'arm64',
64 + setExitCode: code =>
65 + Effect.sync(() => {
66 + exitCodes.push(code);
67 + }),
68 + })
69 + )
70 + );
71 + return { layer, outputs, exitCodes };
72 +};
73 +
74 +const stdoutLines = MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
75 +const stderrLines = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
76 +
77 +describe('runConnectedAccountsWhoami', () => {
78 + it.effect('[Given] an active account [Then] prints its profile fields as JSON on stdout', () => {
79 + const { layer, outputs, exitCodes } = whoamiTest();
80 + return Effect.gen(function* () {
81 + yield* runConnectedAccountsWhoami({ id: Option.some('con_gmail_active') });
82 +
83 + expect(outputs.map(output => JSON.parse(output))).toEqual([
84 + {
85 + id: 'con_gmail_active',
86 + alias: 'personal',
87 + word_id: 'harbor',
88 + toolkit: 'gmail',
89 + user_id: 'default',
90 + status: 'ACTIVE',
91 + auth_config_id: 'ac_gmail_oauth',
92 + auth_scheme: 'OAUTH2',
93 + },
94 + ]);
95 + expect(yield* stderrLines).toEqual([]);
96 + expect(exitCodes).toEqual([]);
97 + }).pipe(Effect.provide(layer));
98 + });
99 +
100 + it.effect('[Given] an account that is not ACTIVE [Then] warns before the profile', () => {
101 + const { layer, outputs } = whoamiTest();
102 + return Effect.gen(function* () {
103 + yield* runConnectedAccountsWhoami({ id: Option.some('con_gmail_expired') });
104 +
105 + expect(yield* stderrLines).toEqual([inactiveStatusMessage('EXPIRED')]);
106 + expect((yield* stdoutLines).some(line => line.startsWith('[whoami: gmail]'))).toBe(true);
107 + expect(JSON.parse(outputs[0] ?? '{}')).toMatchObject({ status: 'EXPIRED' });
108 + }).pipe(Effect.provide(layer));
109 + });
110 +
111 + it.effect('[Given] no id [Then] warns with an example and fetches nothing', () => {
112 + const { layer, outputs, exitCodes } = whoamiTest();
113 + return Effect.gen(function* () {
114 + yield* runConnectedAccountsWhoami({ id: Option.none() });
115 +
116 + expect(yield* stderrLines).toEqual([MISSING_ID_MESSAGE]);
117 + expect(yield* stdoutLines).toEqual([missingIdHint('whoami')]);
118 + expect(outputs).toEqual([]);
119 + expect(exitCodes).toEqual([]);
120 + }).pipe(Effect.provide(layer));
121 + });
122 +
123 + it.effect('[Given] an unknown id [Then] reports it, prints no data, and exits 1', () => {
124 + const { layer, outputs, exitCodes } = whoamiTest();
125 + return Effect.gen(function* () {
126 + yield* runConnectedAccountsWhoami({ id: Option.some('con_missing') });
127 +
128 + expect((yield* stderrLines).join('\n')).toContain(
129 + 'Connected account "con_missing" not found.'
130 + );
131 + expect(outputs).toEqual([]);
132 + expect(exitCodes).toEqual([1]);
133 + }).pipe(Effect.provide(layer));
134 + });
135 +});