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

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

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

Synced Nov 21, 07:15 UTC

fix(cli): exit 1 on the remaining silent failures (#5040)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5035 (merge that first; until then this diff also shows its commits) - makes missing input fail with `CommandInputError`/`NotLoggedInError`, so `cli-main.ts` prints it on stderr and exits 1: `whoami` without a login, `dev init` without a stored key or org, `dev projects list` without an org, `triggers info`/`dev triggers info` and `dev toolkits info` without a `<slug>`, `dev triggers disable` and `dev connected-accounts info`/`whoami` without an `<id>`, `connections remove` with a selector that matches no single connection - adds `reportFailure` (`src/effects/report-failure.ts`) for failures a command recovers from: it sets exit 1 and writes the message and hint as plain stderr lines when stderr is not a TTY; output on a terminal is still the decorated error and step - uses it for `dev toolkits info` (fetch failed / not found), `dev toolkits version`, `dev init` in an org without projects, and link's runtime failures: a failed `link.create` or Tool Router link, an incomplete link response, a taken `--alias`, an existing account without `--alias`; link's own missing-toolkit / missing `--auth-config` guards now fail with `CommandInputError` - also fixes failures that already exited 1 but printed nothing without a TTY: `dev toolkits list`/`search` request failures, the realtime subscription failure of `listen`/`dev listen`/`dev triggers listen`, and `AgentAuthError` (`agent *`, `signup`, `login`) - adds `--yes` (`-y`) to `connections remove` and to `logout` (next to its existing `--force`/`-f`). Without a TTY they used to answer their own confirmation prompt with "no" and exit 0; without `--yes` they now fail before any request with "`composio connections remove` needs --yes when not running interactively." (for `logout`, only when logged in as an agent, the case that prompts), exit 1, message on stderr. Declining the prompt on a terminal still prints the existing cancel line and exits 0; `--yes` skips the prompt either way - adds `redirectedTerminalUI` (the real `makeTerminalUI` over non-TTY streams) for tests, since `terminalUITestImpl` prints `ui.log.*` through `Console` and so hid this whole class of bug; the regression tests fail without the fix - adds a CLI changelog entry and a README note for `connections remove --yes`; messages are unchanged ## Context `ui.log.*` is decoration and is dropped when stderr is not a TTY, so a handler that reported a failure with `ui.log.error`/`ui.log.warn` and returned printed nothing and exited 0 for scripts, CI and agents. The `--yes` behaviour follows clig.dev ("If stdin is not an interactive terminal, skip prompting and just require those flags") and `gh repo delete` ("--yes required when not running interactively", exit 1). Checked and left alone: empty results (`No toolkits/triggers/auth configs/projects found`), `logout` when not logged in, and the non-fatal `.env.local`/skill-rebuild warnings in `dev init` and `config experimental`. ## Review follow-ups (post-review commits, 7fbe0c48f) - `handleClientApiError` now delegates its final rendering to `reportFailure`, so the CLI has one failure-rendering kernel; on a terminal a failure renders message + one merged hint step, and plain mode additionally prints the API's `suggested_fix` - `composio dev projects list` in an org without projects prints a parseable `[]` on stdout instead of exiting 0 in silence - usage errors on `dev connected-accounts link` now carry the full command path (`dev connected-accounts link`), matching the `errors.ts` contract per tree - `connections remove` migrated to the directory shape (`connections/remove/`), one command per the AGENTS.md layout rule; behavior and messages unchanged - `listen`/`dev listen`/`dev triggers listen` count per-event forwarding and output-file failures and print one plain stderr line per sink when the run stops — bounded (`--max-events`/timeout) or interrupted with Ctrl+C/SIGTERM; the listener still never fails over one event - shared `BROWSE_TOOLKITS_HINT`, trigger hint fields, and test terminal fixtures deduplicated; the changelog's "before any request" claim now says which commands need one lookup first --------- Co-authored-by: Sujal Gupta <sujalgupta6100@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Sujal Gupta <55016909+heysujal@users.noreply.github.com>

Alberto Schiabel committed Oct 22, 2026 at 18:33 UTC d1a317dee5cc997e4d64139939db3c4fa5933e36
64 files changed +1848 -634
ts/e2e-tests/cli/toolkits/info/README.md
+7 -7
@@ -1,15 +1,15 @@
1 # CLI `composio dev toolkits info` Test
2
3 -Verifies that `composio dev toolkits info <slug>` returns detailed toolkit JSON in piped mode, handles invalid slugs gracefully, and supports stdout redirection.
3 +Verifies that `composio dev toolkits info <slug>` returns detailed toolkit JSON in piped mode, reports an invalid or missing slug on stderr with exit 1, and supports stdout redirection.
4
5 ## What It Tests
6
7 -| Test | Description |
8 -| --- | --- |
9 -| Valid slug | `info gmail` returns JSON object with name, slug, meta, auth_config_details |
10 -| Stdout redirection | `info gmail > out.json` captures the JSON in the file |
11 -| Invalid slug | `info nonexistent_toolkit_xyz12345` exits 0, empty stdout |
12 -| Missing slug | `info` (no arg) exits 0, empty stdout |
7 +| Test | Description |
8 +| ------------------ | ---------------------------------------------------------------------------------------------------- |
9 +| Valid slug | `info gmail` returns JSON object with name, slug, meta, auth_config_details |
10 +| Stdout redirection | `info gmail > out.json` captures the JSON in the file |
11 +| Invalid slug | `info nonexistent_toolkit_xyz12345` exits 1, empty stdout, "not found" and the browse hint on stderr |
12 +| Missing slug | `info` (no arg) exits 1, empty stdout, the usage message on stderr |
13
14 ## Requirements
15
ts/e2e-tests/cli/toolkits/info/e2e.test.ts
+13 -9
@@ -2,7 +2,7 @@
2 * CLI `composio dev toolkits info` e2e test
3 *
4 * Verifies that the info subcommand returns detailed toolkit JSON in piped mode,
5 - * handles invalid slugs gracefully, and supports stdout redirection.
5 + * reports an invalid or missing slug on stderr with exit 1, and supports stdout redirection.
6 */
7
8 import {
@@ -120,30 +120,34 @@ e2e(import.meta.url, {
120 });
121
122 describe('composio dev toolkits info nonexistent_toolkit_xyz12345 (invalid slug)', () => {
123 - it('exits successfully (graceful error handling)', () => {
124 - expect(invalidResult.exitCode).toBe(0);
123 + it('exits 1', () => {
124 + expect(invalidResult.exitCode).toBe(1);
125 });
126
127 it('stdout is empty (no data on error)', () => {
128 expect(sanitizeOutput(invalidResult.stdout)).toBe('');
129 });
130
131 - it('stderr is empty (piped mode suppresses decoration)', () => {
132 - expect(invalidResult.stderr).toBe('');
131 + it('stderr names the toolkit and the browse hint as plain lines', () => {
132 + expect(invalidResult.stderr).toBe(
133 + 'Toolkit "nonexistent_toolkit_xyz12345" not found.\nBrowse available toolkits:\n> composio dev toolkits list\n'
134 + );
135 });
136 });
137
138 describe('composio dev toolkits info (missing slug)', () => {
137 - it('exits successfully (optional arg, handler guards)', () => {
138 - expect(missingSlugResult.exitCode).toBe(0);
139 + it('exits 1 (usage error)', () => {
140 + expect(missingSlugResult.exitCode).toBe(1);
141 });
142
143 it('stdout is empty', () => {
144 expect(sanitizeOutput(missingSlugResult.stdout)).toBe('');
145 });
146
145 - it('stderr is empty', () => {
146 - expect(missingSlugResult.stderr).toBe('');
147 + it('stderr asks for the slug with an example', () => {
148 + expect(missingSlugResult.stderr).toBe(
149 + 'Missing required argument: <slug>\nTry specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"\n'
150 + );
151 });
152 });
153
ts/packages/cli/CHANGELOG.md
+51
@@ -26,6 +26,57 @@
26 is on). The message, tips, and `{"successful": false, ...}` JSON on stdout
27 are unchanged, and the exit code is still 1.
28
29 +- `composio link` and `composio dev connected-accounts link` now exit 1 with
30 + the usage message on stderr when their flags can't run: a toolkit together
31 + with `--auth-config`, neither a toolkit nor `--auth-config`, `--auth-config`
32 + without a developer project, and `--list` without a toolkit or with
33 + `--auth-config`. They used to exit 0, and printed the message only when
34 + stderr was a terminal, so scripts, CI and agents saw no output and a
35 + successful exit. The messages are unchanged.
36 +- These commands now exit 1 and print their message on stderr. They used to
37 + exit 0, and printed the message only when stderr was a terminal, so scripts,
38 + CI and agents saw no output and a successful exit. The messages are
39 + unchanged.
40 + - Missing input, before any request: `composio whoami` without a login,
41 + `composio dev projects list` without `--org-id` or a current org,
42 + `composio triggers info` and `composio dev triggers info` without a
43 + `<slug>`, `composio dev toolkits info` without a `<slug>`,
44 + `composio dev triggers disable` without an `<id>`, and
45 + `composio dev connected-accounts info` and
46 + `composio dev connected-accounts whoami` without an `<id>`.
47 + - Missing input that needs one lookup first: `composio dev init` without a
48 + stored API key or org (it checks your saved login), and
49 + `composio connections remove` with a selector that matches no connection
50 + or more than one (it fetches your connections). Both fail before they
51 + change anything.
52 + - Failures after a request: `composio dev toolkits info` for a toolkit it
53 + cannot fetch or find, `composio dev toolkits version` for a toolkit it
54 + cannot fetch, `composio dev init` in an org without projects, and
55 + `composio link` and `composio dev connected-accounts link` when the link
56 + request fails, the link response is incomplete, the `--alias` is already
57 + taken, or an account already exists and no `--alias` was passed.
58 +- These commands already exited 1 but printed their message only when stderr
59 + was a terminal; they now print it on stderr either way:
60 + `composio dev toolkits list` and `composio dev toolkits search` when the
61 + request fails, `composio listen`, `composio dev listen` and
62 + `composio dev triggers listen` when the realtime subscription fails, and
63 + the `composio agent` commands, `composio signup` and `composio login` when
64 + the stored agent identity can't be used.
65 +- `composio connections remove` gains `--yes` (`-y`) to remove without the
66 + confirmation prompt, and `composio logout` accepts `--yes` (`-y`) next to
67 + `--force` (`-f`). When not running interactively, both used to answer their
68 + own prompt with "no", remove nothing and exit 0; without `--yes` they now
69 + exit 1 with "needs --yes when not running interactively" on stderr, before
70 + any request (for `logout`, only when logged in as an agent, the case that
71 + asks). Declining the prompt on a terminal still removes nothing and exits 0.
72 +- `composio listen`, `composio dev listen` and `composio dev triggers listen`
73 + now print how many events they failed to save, forward, or append to `--out`
74 + on stderr when they stop, including on Ctrl+C. The per-event warnings were
75 + shown only when stderr was a terminal. One failed event still does not stop
76 + the listener, and the exit code is unchanged.
77 +- `composio listen --max-events N` now stops after N matching events even when
78 + saving one of them fails. It used to keep listening until interrupted.
79 +
80 ## 0.5.0
81
82 ### Minor Changes
ts/packages/cli/README.md
+1 -1
@@ -39,7 +39,7 @@ composio [--log-level All|Trace|Debug|Info|Warn|Error|Fatal|None]
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.
42 -- `composio connections remove <account>`: Interactively remove a toolkit connection after confirmation.
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.
45 - `composio generate [-o, --output-dir <directory>] [--toolkits <toolkit>] [--type-tools]`: Auto-detect the project language (Python or TypeScript) and generate type stubs for toolkits, tools, and triggers.
ts/packages/cli/scripts/command-tests.ts
+1 -4
@@ -17,10 +17,7 @@ const TEST_SUFFIX = '.cmd.test.ts';
17
18 // Command paths are relative to src/commands/; tests are relative to
19 // test/src/commands/. Both use forward slashes.
20 -export const COMMAND_TEST_EXEMPTIONS: readonly CommandTestExemption[] = [
21 - { command: 'connections/commands/connections.remove.cmd.ts', reason: 'no test yet' },
22 - { command: 'triggers/commands/triggers.listen.cmd.ts', reason: 'no test yet' },
23 -];
20 +export const COMMAND_TEST_EXEMPTIONS: readonly CommandTestExemption[] = [];
21
22 // A group entry is `<dir>.cmd.ts` or `root-<dir>.cmd.ts` inside `<dir>/` when
23 // `<dir>/` holds other command modules; it only wires subcommands and is
ts/packages/cli/src/commands/connected-accounts/info/connected-accounts.info.handler.ts
+12 -9
@@ -1,4 +1,5 @@
1 import { Effect, Option } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 import { handleClientApiError } from 'src/effects/handle-http-error';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -20,6 +21,8 @@ export type ConnectedAccountsInfoParams = {
21 readonly id: Option.Option<string>;
22 };
23
24 +const invalidInput = commandInputError('dev connected-accounts info');
25 +
26 const showConnectedAccount = (id: string) =>
27 Effect.gen(function* () {
28 const ui = yield* TerminalUI;
@@ -49,14 +52,14 @@ const showConnectedAccount = (id: string) =>
52 });
53 });
54
52 -/** Shows one connected account; a missing id warns and exits 0, as it always has. */
55 +/**
56 + * Shows one connected account. A missing `<id>` fails with a `CommandInputError` before any
57 + * request; an API failure is reported with a hint and exits 1.
58 + */
59 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,
60 + Effect.gen(function* () {
61 + if (Option.isNone(id)) {
62 + return yield* invalidInput(`${MISSING_ID_MESSAGE}\n${missingIdHint('info')}`, '<id>');
63 + }
64 + yield* showConnectedAccount(id.value);
65 });
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.format.ts
+14 -6
@@ -1,5 +1,7 @@
1 import { Array as Arr, Effect, Option } from 'effect';
2 import type { CommandTree } from 'src/commands/surface';
3 +import { BROWSE_TOOLKITS_HINT } from 'src/commands/toolkits/format';
4 +import { reportFailure } from 'src/effects/report-failure';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 import type { CliProjectType } from 'src/services/command-project';
7 import type { TerminalUI } from 'src/services/terminal-ui';
@@ -46,7 +48,9 @@ export const AUTH_CONFIG_SCOPE_MESSAGE =
48 export const INCOMPLETE_LINK_RESPONSE_MESSAGE =
49 'The link response from the API is missing `connected_account_id` or `redirect_url`.';
50
49 -export const BROWSE_TOOLKITS_HINT = 'Browse available toolkits:\n> composio dev toolkits list';
51 +// The canonical constant lives with the other toolkit formatters; re-exported here for the
52 +// link flow's callers.
53 +export { BROWSE_TOOLKITS_HINT };
54
55 export const BROWSE_AUTH_CONFIGS_HINT =
56 'Browse available auth configs:\n> composio dev auth-configs list';
@@ -87,22 +91,25 @@ const formatExistingAccountLabels = (items: ReadonlyArray<ExistingAccountLabel>)
91 )
92 .join(', ');
93
90 -/** Why a second account needs `--alias`, and which accounts already exist for the scope. */
94 +/**
95 + * Why a second account needs `--alias` (exit 1), and which accounts already exist for the scope.
96 + */
97 export const showExistingAccounts = (
98 ui: TerminalUI,
99 scopeDescription: string,
100 items: ReadonlyArray<ExistingAccountLabel>
101 ) =>
102 Effect.gen(function* () {
97 - yield* ui.log.error(
103 + yield* reportFailure(
104 + ui,
105 `A connected account already exists for ${scopeDescription}. Pass --alias to create another one.`
106 );
107 yield* ui.note(formatExistingAccountLabels(items), 'Existing accounts');
108 });
109
110 /**
104 - * The alias is taken: which account holds it, and how to use that account or list them all.
105 - * The hint commands differ per tree, so the caller passes them.
111 + * The alias is taken (exit 1): which account holds it, and how to use that account or list them
112 + * all. The hint commands differ per tree, so the caller passes them.
113 */
114 export const showAliasConflict = (
115 ui: TerminalUI,
@@ -114,7 +121,8 @@ export const showAliasConflict = (
121 }
122 ) =>
123 Effect.gen(function* () {
117 - yield* ui.log.error(
124 + yield* reportFailure(
125 + ui,
126 `Alias "${params.alias}" is already in use by connected account "${params.existingId}".`
127 );
128 yield* ui.note(
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+50 -40
@@ -11,6 +11,7 @@ import {
11 import { ComposioUserContext } from 'src/services/user-context';
12 import { TerminalUI } from 'src/services/terminal-ui';
13 import { failedWith } from 'src/effects/request-error';
14 +import { reportFailure } from 'src/effects/report-failure';
15 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
16 import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
17 import { ProjectContext } from 'src/services/project-context';
@@ -76,7 +77,9 @@ export type ConnectedAccountsLinkParams = {
77 /** The three things `link` does; the flags pick one. */
78 type LinkFlow = 'list' | 'legacy' | 'tool-router';
79
79 -const invalidOptionValue = commandInputError('link');
80 +/** The command path a usage error carries, per tree: `dev connected-accounts link` under `dev`. */
81 +const invalidOptionValueFor = (tree: CommandTree) =>
82 + commandInputError(tree === 'dev' ? 'dev connected-accounts link' : 'link');
83
84 // --- shared steps -----------------------------------------------------------------------------
85
@@ -107,12 +110,12 @@ const directoryProject = Effect.gen(function* () {
110 });
111
112 /** `--alias` trimmed, or a usage error when it is blank. */
110 -const resolveNormalizedAliasOption = (alias: Option.Option<string>) =>
113 +const resolveNormalizedAliasOption = (alias: Option.Option<string>, tree: CommandTree) =>
114 Effect.transposeOption(
115 Option.map(alias, rawAlias =>
116 Effect.fromOption(
117 Option.liftPredicate(rawAlias.trim(), trimmed => trimmed.length > 0),
115 - () => invalidOptionValue('`--alias` cannot be empty.', '--alias')
118 + () => invalidOptionValueFor(tree)('`--alias` cannot be empty.', '--alias')
119 )
120 )
121 );
@@ -205,7 +208,7 @@ const ensureAliasForAdditionalAccount = (params: {
208 const nonEmpty = (value: string | null | undefined) =>
209 Option.filter(Option.fromNullishOr(value), text => text.length > 0);
210
208 -/** The link the API answered with, or none after reporting an incomplete response. */
211 +/** The link the API answered with, or none after reporting an incomplete response (exit 1). */
212 const validateLinkResponse = (
213 ui: TerminalUI,
214 linkResponse: {
@@ -223,8 +226,8 @@ const validateLinkResponse = (
226 onSome: target => Effect.succeedSome(target),
227 onNone: () =>
228 Effect.gen(function* () {
226 - yield* ui.log.error(INCOMPLETE_LINK_RESPONSE_MESSAGE);
229 yield* Effect.logDebug('Link response:', linkResponse);
230 + yield* reportFailure(ui, INCOMPLETE_LINK_RESPONSE_MESSAGE);
231 return Option.none<LinkTarget>();
232 }),
233 }
@@ -383,11 +386,16 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo
386 export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams) =>
387 Effect.gen(function* () {
388 const ui = yield* TerminalUI;
389 + const { tree } = yield* CommandSurface;
390 if (Option.isNone(params.toolkit)) {
387 - return yield* ui.log.error(LIST_REQUIRES_TOOLKIT_MESSAGE);
391 + return yield* Effect.fail(
392 + invalidOptionValueFor(tree)(LIST_REQUIRES_TOOLKIT_MESSAGE, '--list')
393 + );
394 }
395 if (Option.isSome(params.authConfig)) {
390 - return yield* ui.log.error(LIST_WITH_AUTH_CONFIG_MESSAGE);
396 + return yield* Effect.fail(
397 + invalidOptionValueFor(tree)(LIST_WITH_AUTH_CONFIG_MESSAGE, '--list')
398 + );
399 }
400 const toolkitSlug = params.toolkit.value;
401
@@ -481,7 +489,9 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
489 const { tree, userId, projectName } = yield* CommandSurface;
490 // The dispatcher never gets here without --auth-config. This narrows it for direct callers.
491 if (Option.isNone(params.authConfig)) {
484 - return yield* ui.log.error(missingArgumentMessage(tree));
492 + return yield* Effect.fail(
493 + invalidOptionValueFor(tree)(missingArgumentMessage(tree), '--auth-config')
494 + );
495 }
496 const authConfigId = params.authConfig.value;
497
@@ -513,7 +523,9 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
523 )
524 );
525 if (Option.isNone(projectName) && Option.isNone(resolvedProjectContext)) {
516 - return yield* ui.log.error(AUTH_CONFIG_SCOPE_MESSAGE);
526 + return yield* Effect.fail(
527 + invalidOptionValueFor(tree)(AUTH_CONFIG_SCOPE_MESSAGE, '--auth-config')
528 + );
529 }
530 // Without --user-id, say which test user stands in.
531 yield* Option.isSome(userId)
@@ -533,7 +545,7 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
545 onNone: () => resolveCommandProject({ mode: 'developer' }),
546 });
547 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
536 - const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias);
548 + const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
549 const existingAccounts = yield* existingAccountsForHints({
550 client,
551 userId: resolvedUserId,
@@ -561,10 +573,11 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
573 Effect.asSome,
574 Effect.catch(error =>
575 Effect.gen(function* () {
564 - yield* ui.log.error(
565 - extractMessage(error) || `Failed to create link for auth config "${authConfigId}".`
576 + yield* reportFailure(
577 + ui,
578 + extractMessage(error) || `Failed to create link for auth config "${authConfigId}".`,
579 + BROWSE_AUTH_CONFIGS_HINT
580 );
567 - yield* ui.log.step(BROWSE_AUTH_CONFIGS_HINT);
581 return Option.none();
582 })
583 )
@@ -604,11 +617,13 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
617 const { tree, userId, projectName } = yield* CommandSurface;
618 // The dispatcher never gets here without a toolkit. This narrows it for direct callers.
619 if (Option.isNone(params.toolkit)) {
607 - return yield* ui.log.error(missingArgumentMessage(tree));
620 + return yield* Effect.fail(
621 + invalidOptionValueFor(tree)(missingArgumentMessage(tree), '<toolkit>')
622 + );
623 }
624 const toolkitSlug = params.toolkit.value;
625
611 - const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias);
626 + const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
627 const clientSingleton = yield* ComposioClientSingleton;
628 const userContext = yield* ComposioUserContext;
629 const resolvedProject = yield* resolveCommandProject({
@@ -675,11 +690,12 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
690 yield* handleNoManagedAuth(ui, toolkitSlug, params.noBrowser);
691 return Option.none();
692 }
678 - yield* ui.log.error(
679 - extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`
680 - );
693 yield* Effect.logDebug('Link error:', error);
682 - yield* ui.log.step(BROWSE_TOOLKITS_HINT);
694 + yield* reportFailure(
695 + ui,
696 + extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`,
697 + BROWSE_TOOLKITS_HINT
698 + );
699 return Option.none();
700 })
701 ),
@@ -724,17 +740,13 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
740 // --- dispatch -----------------------------------------------------------------------------------
741
742 /**
727 - * Which flow the flags select, or none after reporting a usage mistake the parser cannot see.
728 - * A blank `--alias` and a root `--auth-config` (the root tree is consumer-only) are usage errors
729 - * that exit 1. The other mistakes print a message and exit 0.
743 + * Which flow the flags select. A usage mistake the parser cannot see fails with a
744 + * `CommandInputError`, so it reaches stderr and exits 1 even when stderr is not a TTY.
745 */
746 const selectLinkFlow = (params: ConnectedAccountsLinkParams, tree: CommandTree) =>
747 Effect.gen(function* () {
733 - yield* resolveNormalizedAliasOption(params.alias);
734 - const ui = yield* TerminalUI;
735 - const reject = (message: string) =>
736 - ui.log.error(message).pipe(Effect.as(Option.none<LinkFlow>()));
737 - const select = (flow: LinkFlow) => Effect.succeedSome(flow);
748 + yield* resolveNormalizedAliasOption(params.alias, tree);
749 + const select = (flow: LinkFlow) => Effect.succeed(flow);
750 return yield* Match.value({
751 tree,
752 toolkit: Option.isSome(params.toolkit),
@@ -742,12 +754,14 @@ const selectLinkFlow = (params: ConnectedAccountsLinkParams, tree: CommandTree)
754 list: params.list,
755 }).pipe(
756 Match.when({ tree: 'root', authConfig: true }, () =>
745 - Effect.fail(invalidOptionValue(ROOT_AUTH_CONFIG_MESSAGE, '--auth-config'))
757 + Effect.fail(invalidOptionValueFor(tree)(ROOT_AUTH_CONFIG_MESSAGE, '--auth-config'))
758 ),
759 Match.when({ toolkit: true, authConfig: true }, () =>
748 - reject(TOOLKIT_AND_AUTH_CONFIG_MESSAGE)
760 + Effect.fail(invalidOptionValueFor(tree)(TOOLKIT_AND_AUTH_CONFIG_MESSAGE, '--auth-config'))
761 + ),
762 + Match.when({ toolkit: false, authConfig: false }, () =>
763 + Effect.fail(invalidOptionValueFor(tree)(missingArgumentMessage(tree), '<toolkit>'))
764 ),
750 - Match.when({ toolkit: false, authConfig: false }, () => reject(missingArgumentMessage(tree))),
765 Match.when({ list: true }, () => select('list')),
766 Match.when({ authConfig: true }, () => select('legacy')),
767 Match.orElse(() => select('tool-router'))
@@ -759,14 +773,10 @@ export const runConnectedAccountsLink = (params: ConnectedAccountsLinkParams) =>
773 Effect.gen(function* () {
774 const { tree } = yield* CommandSurface;
775 const flow = yield* selectLinkFlow(params, tree);
762 - yield* Option.match(flow, {
763 - onNone: () => Effect.void,
764 - onSome: selected =>
765 - Match.value(selected).pipe(
766 - Match.when('list', () => handleListConnectedAccounts(params)),
767 - Match.when('legacy', () => handleLegacyAuthConfigLink(params)),
768 - Match.when('tool-router', () => handleToolRouterLink(params)),
769 - Match.exhaustive
770 - ),
771 - });
776 + yield* Match.value(flow).pipe(
777 + Match.when('list', () => handleListConnectedAccounts(params)),
778 + Match.when('legacy', () => handleLegacyAuthConfigLink(params)),
779 + Match.when('tool-router', () => handleToolRouterLink(params)),
780 + Match.exhaustive
781 + );
782 });
ts/packages/cli/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.ts
+10 -9
@@ -1,4 +1,5 @@
1 import { Effect, Option } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 import { handleClientApiError } from 'src/effects/handle-http-error';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -21,6 +22,8 @@ export type ConnectedAccountsWhoamiParams = {
22 readonly id: Option.Option<string>;
23 };
24
25 +const invalidInput = commandInputError('dev connected-accounts whoami');
26 +
27 const showConnectedAccountProfile = (id: string) =>
28 Effect.gen(function* () {
29 const ui = yield* TerminalUI;
@@ -58,15 +61,13 @@ const showConnectedAccountProfile = (id: string) =>
61
62 /**
63 * 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.
64 + * connection is not ACTIVE. A missing `<id>` fails with a `CommandInputError` before any request;
65 + * an API failure is reported with a hint and exits 1.
66 */
67 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,
68 + Effect.gen(function* () {
69 + if (Option.isNone(id)) {
70 + return yield* invalidInput(`${MISSING_ID_MESSAGE}\n${missingIdHint('whoami')}`, '<id>');
71 + }
72 + yield* showConnectedAccountProfile(id.value);
73 });
ts/packages/cli/src/commands/connections/connections.cmd.ts
+1 -1
@@ -1,7 +1,7 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { connectionsCmd$List } from './commands/connections.list.cmd';
4 -import { connectionsCmd$Remove } from './commands/connections.remove.cmd';
4 +import { connectionsCmd$Remove } from './remove/connections.remove.cmd';
5
6 export const rootConnectionsCmd = Command.make('connections').pipe(
7 Command.withDescription('Inspect and remove connected toolkit accounts.'),
ts/packages/cli/src/commands/connections/remove/connections.remove.cmd.ts new
+38
@@ -0,0 +1,38 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { runConnectionsRemove } from './connections.remove.handler';
3 +
4 +const account = Argument.String('account').pipe(
5 + Argument.withDescription(
6 + 'Connection selector: toolkit slug, alias, word_id, or connected account ID'
7 + )
8 +);
9 +
10 +const yes = Flag.Boolean('yes').pipe(
11 + Flag.withAlias('y'),
12 + Flag.withDefault(false),
13 + Flag.withDescription('Remove without asking for confirmation')
14 +);
15 +
16 +export const connectionsCmd$Remove = Command.make(
17 + 'remove',
18 + { account, yes },
19 + runConnectionsRemove
20 +).pipe(
21 + Command.withDescription(
22 + 'Interactively remove a connection by toolkit slug, alias, word_id, or connected account ID.'
23 + ),
24 + Command.withExamples([
25 + {
26 + command: 'composio connections remove gmail',
27 + },
28 + {
29 + command: 'composio connections remove work',
30 + },
31 + {
32 + command: 'composio connections remove castle',
33 + },
34 + {
35 + command: 'composio connections remove gmail --yes',
36 + },
37 + ])
38 +);
ts/packages/cli/src/commands/connections/remove/connections.remove.errors.ts new
+12
@@ -0,0 +1,12 @@
1 +import { Data } from 'effect';
2 +import { requestError } from 'src/effects/request-error';
3 +
4 +export class MissingConnectionRemovalConsumerUserIdError extends Data.TaggedError(
5 + 'commands/MissingConnectionRemovalConsumerUserIdError'
6 +)<{
7 + readonly message: string;
8 +}> {}
9 +
10 +export class ConnectionsRemovalRequestError extends requestError(
11 + 'commands/ConnectionsRemovalRequestError'
12 +) {}
ts/packages/cli/src/commands/connections/remove/connections.remove.handler.ts renamed
+34 -40
@@ -1,7 +1,7 @@
1 -import { Data, Effect } from 'effect';
2 -import { Argument, Command } from 'effect/cli';
1 +import { Effect } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 -import { failedWith, requestError } from 'src/effects/request-error';
4 +import { failedWith } from 'src/effects/request-error';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 import { resolveCommandProject } from 'src/services/command-project';
@@ -9,22 +9,22 @@ import { TerminalUI } from 'src/services/terminal-ui';
9 import { bold } from 'src/ui/colors';
10 import { redact } from 'src/ui/redact';
11 import { idempotent } from 'src/services/composio-request';
12 +import {
13 + ConnectionsRemovalRequestError,
14 + MissingConnectionRemovalConsumerUserIdError,
15 +} from './connections.remove.errors';
16 +
17 +/** The flags of `composio connections remove`. */
18 +export type ConnectionsRemoveParams = {
19 + readonly account: string;
20 + readonly yes: boolean;
21 +};
22
13 -class MissingConnectionRemovalConsumerUserIdError extends Data.TaggedError(
14 - 'commands/MissingConnectionRemovalConsumerUserIdError'
15 -)<{
16 - readonly message: string;
17 -}> {}
18 -
19 -class ConnectionsRemovalRequestError extends requestError(
20 - 'commands/ConnectionsRemovalRequestError'
21 -) {}
23 +const invalidInput = commandInputError('connections remove');
24
23 -const account = Argument.String('account').pipe(
24 - Argument.withDescription(
25 - 'Connection selector: toolkit slug, alias, word_id, or connected account ID'
26 - )
27 -);
25 +/** Without a terminal to confirm on, removing needs `--yes`. */
26 +const NEEDS_YES_MESSAGE =
27 + '`composio connections remove` needs --yes when not running interactively.';
28
29 const normalizeSelector = (value: string): string => value.trim().toLowerCase();
30
@@ -89,9 +89,18 @@ const resolveAccount = (params: {
89 };
90 };
91
92 -export const connectionsCmd$Remove = Command.make('remove', { account }, ({ account }) =>
92 +/**
93 + * Removes one connection after a confirmation. Without a terminal to confirm on, it needs `--yes`
94 + * and otherwise fails with a `CommandInputError` before any request; declining the prompt removes
95 + * nothing and exits 0.
96 + */
97 +export const runConnectionsRemove = ({ account, yes }: ConnectionsRemoveParams) =>
98 Effect.gen(function* () {
99 const ui = yield* TerminalUI;
100 + const { canPrompt } = yield* ui.capabilities;
101 + if (!yes && !canPrompt) {
102 + return yield* invalidInput(NEEDS_YES_MESSAGE, '--yes');
103 + }
104 const clientSingleton = yield* ComposioClientSingleton;
105 const resolvedProject = yield* resolveCommandProject({
106 mode: 'consumer',
@@ -118,8 +127,7 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
127 const resolved = resolveAccount({ accounts: result.items, selector: account });
128
129 if ('error' in resolved) {
121 - yield* ui.log.warn(resolved.error);
122 - return;
130 + return yield* invalidInput(resolved.error, '<account>');
131 }
132
133 yield* ui.note(
@@ -127,9 +135,11 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
135 'Remove Connection'
136 );
137
130 - const confirmed = yield* ui.confirm(`Remove ${resolved.toolkit.slug} connection?`, {
131 - defaultValue: false,
132 - });
138 + const confirmed =
139 + yes ||
140 + (yield* ui.confirm(`Remove ${resolved.toolkit.slug} connection?`, {
141 + defaultValue: false,
142 + }));
143 if (!confirmed) {
144 yield* ui.log.warn('No connection removed.');
145 return;
@@ -150,20 +160,4 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
160 errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,
161 }
162 );
153 - })
154 -).pipe(
155 - Command.withDescription(
156 - 'Interactively remove a connection by toolkit slug, alias, word_id, or connected account ID.'
157 - ),
158 - Command.withExamples([
159 - {
160 - command: 'composio connections remove gmail',
161 - },
162 - {
163 - command: 'composio connections remove work',
164 - },
165 - {
166 - command: 'composio connections remove castle',
167 - },
168 - ])
169 -);
163 + });
ts/packages/cli/src/commands/init.cmd.ts
+8 -5
@@ -21,6 +21,8 @@ import { TerminalUI } from 'src/services/terminal-ui';
21 import { browserLogin } from 'src/effects/browser-login';
22 import { setupCacheDir } from 'src/effects/setup-cache-dir';
23 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
24 +import { commandInputError } from 'src/commands/errors';
25 +import { reportFailure } from 'src/effects/report-failure';
26 import {
27 describeDecodeError,
28 isClientConnectionError,
@@ -289,9 +291,9 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
291 const orgIdValue = Option.getOrUndefined(ctx.data.orgId);
292 const projectIdValue = Option.getOrUndefined(ctx.data.projectId);
293 if (!globalApiKey || !orgIdValue) {
292 - yield* ui.log.warn('No global API key or org ID found. Please try `composio login` first.');
293 - yield* ui.outro('');
294 - return;
294 + return yield* commandInputError('dev init')(
295 + 'No global API key or org ID found. Please try `composio login` first.'
296 + );
297 }
298
299 const orgProjects = yield* listOrgProjects({
@@ -325,8 +327,9 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
327 );
328
329 if (orgProjects.data.length === 0) {
328 - yield* ui.log.warn('No projects found for your organization.');
329 - yield* ui.log.info(
330 + yield* reportFailure(
331 + ui,
332 + 'No projects found for your organization.',
333 'Create a project at https://platform.composio.dev, then run `composio dev init` again.'
334 );
335 yield* ui.outro('');
ts/packages/cli/src/commands/listen.cmd.ts
+64 -22
@@ -1,4 +1,5 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 +import { reportFailure } from 'src/effects/report-failure';
3 import { commandInputError } from 'src/commands/errors';
4 import { Argument, Command, Flag } from 'effect/cli';
5 import * as FileSystem from 'effect/FileSystem';
@@ -347,6 +348,30 @@ const formatStreamValue = (value: unknown): string => {
348 return JSON.stringify(value);
349 };
350
351 +/**
352 + * Saves one matched event: its payload file, its line in the stream file, then the `event:` line
353 + * and, when streaming (`streamPath` set), the `stream:` line.
354 + */
355 +const saveListenEvent = (params: {
356 + readonly fs: FileSystem.FileSystem;
357 + readonly ui: TerminalUI;
358 + readonly eventData: Record<string, unknown>;
359 + readonly eventFilePath: string;
360 + readonly streamFilePath: string;
361 + readonly streamEntry: string;
362 + readonly streamPath: ReadonlyArray<string | number> | undefined;
363 +}) =>
364 + Effect.gen(function* () {
365 + const { fs, ui, eventFilePath, streamPath } = params;
366 + yield* fs.writeFileString(eventFilePath, `${JSON.stringify(params.eventData, null, 2)}\n`);
367 + yield* fs.writeFileString(params.streamFilePath, `${params.streamEntry}\n`, { flag: 'a' });
368 + yield* emitStreamLine(`event: ${eventFilePath}`, ui);
369 + if (streamPath !== undefined) {
370 + const streamValue = applyStreamPath(params.eventData, streamPath);
371 + yield* emitStreamLine(`stream: ${formatStreamValue(streamValue)}`, ui);
372 + }
373 + });
374 +
375 const formatStopMessage = (params: {
376 matchingEvents: number;
377 timedOut: boolean;
@@ -536,6 +561,22 @@ export const listenCmd = Command.make(
561
562 const stopWhenDone = yield* Deferred.make<'max-events' | 'timeout'>();
563 let matchingEvents = 0;
564 + // Per-event write failures are recovered so one bad event never stops the listener; they
565 + // are counted here and summed up on plain stderr on every stop — including Ctrl+C and
566 + // SIGTERM, which runMain turns into a fiber interruption — since a piped caller sees
567 + // none of the `ui.log.warn` decoration. The release hook below runs on all of them.
568 + let eventWriteFailures = 0;
569 + const recordWriteFailure = (error: unknown) =>
570 + Effect.gen(function* () {
571 + eventWriteFailures += 1;
572 + yield* ui.log.warn(errorMessage(error));
573 + });
574 + const reportWriteFailures = () =>
575 + eventWriteFailures > 0
576 + ? ui.error(
577 + `${eventWriteFailures} event${eventWriteFailures === 1 ? '' : 's'} failed to write while listening.`
578 + )
579 + : Effect.void;
580 const seenEventIds = new Set<string>();
581
582 yield* Effect.acquireUseRelease(
@@ -622,7 +663,6 @@ export const listenCmd = Command.make(
663
664 matchingEvents += 1;
665 const eventFilePath = path.join(triggerDir, `${eventFileId}-payload.json`);
625 - const eventJson = JSON.stringify(eventData, null, 2);
666 const streamEntry = JSON.stringify({
667 event_id: eventFileId,
668 event_type: eventTypeOf(eventData),
@@ -632,22 +672,21 @@ export const listenCmd = Command.make(
672 received_at: new Date().toISOString(),
673 });
674
635 - yield* fs.writeFileString(eventFilePath, `${eventJson}\n`);
636 - yield* fs.writeFileString(streamFilePath, `${streamEntry}\n`, { flag: 'a' });
637 - yield* emitStreamLine(`event: ${eventFilePath}`, ui);
638 -
639 - if (shouldStream) {
640 - const streamValue = applyStreamPath(eventData, streamPath ?? []);
641 - yield* emitStreamLine(`stream: ${formatStreamValue(streamValue)}`, ui);
642 - }
675 + // A matched event counts toward --max-events even when saving it fails.
676 + yield* saveListenEvent({
677 + fs,
678 + ui,
679 + eventData,
680 + eventFilePath,
681 + streamFilePath,
682 + streamEntry,
683 + streamPath: shouldStream ? (streamPath ?? []) : undefined,
684 + }).pipe(Effect.catch(recordWriteFailure));
685
686 if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
687 yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
688 }
647 - }).pipe(
648 - Effect.tapError(error => ui.log.warn(errorMessage(error))),
649 - Effect.ignore
650 - )
689 + }).pipe(Effect.catch(recordWriteFailure))
690 );
691 };
692
@@ -697,17 +736,20 @@ export const listenCmd = Command.make(
736 }
737 }),
738 created =>
700 - created === null
701 - ? Effect.void
702 - : disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id })
703 - ).pipe(
704 - Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
739 Effect.gen(function* () {
706 - yield* ui.log.error(
707 - `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
708 - );
709 - process.exitCode = 1;
740 + if (created !== null) {
741 + yield* disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id });
742 + }
743 + // Runs on every stop of the use phase — max-events, timeout, and the interruption
744 + // of an unlimited wait — so a piped caller always gets the failure count.
745 + yield* reportWriteFailures();
746 })
747 + ).pipe(
748 + Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
749 + reportFailure(
750 + ui,
751 + `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
752 + )
753 )
754 );
755 })
ts/packages/cli/src/commands/logout.cmd.ts
+24 -10
@@ -8,22 +8,32 @@ import {
8 import { ComposioUserContext } from 'src/services/user-context';
9 import { TerminalUI } from 'src/services/terminal-ui';
10 import { clearApolloIdentityForAnalytics } from 'src/analytics/dispatch';
11 +import { commandInputError } from 'src/commands/errors';
12 +
13 +// `--force` and `-f` predate `--yes` and keep working.
14 +const yes = Flag.Boolean('yes').pipe(
15 + Flag.withAlias('y'),
16 + Flag.withAlias('force'),
17 + Flag.withAlias('f'),
18 + Flag.withDefault(false),
19 + Flag.withDescription('Skip confirmation prompts')
20 +);
21 +
22 +/** Without a terminal to confirm on, an agent logout needs `--yes`. */
23 +const NEEDS_YES_MESSAGE =
24 + '`composio logout` needs --yes when not running interactively: it removes the stored Composio agent key.';
25
26 /**
13 - * CLI command to log out from the Composio CLI.
27 + * CLI command to log out from the Composio CLI. An agent logout removes the stored agent key, so
28 + * it asks first; without a terminal to ask on it needs `--yes` and otherwise fails with a
29 + * `CommandInputError`. Declining the prompt logs nothing out and exits 0.
30 *
31 * @example
32 * ```bash
17 - * composio logout <command>
33 + * composio logout
34 * ```
35 */
20 -const force = Flag.Boolean('force').pipe(
21 - Flag.withAlias('f'),
22 - Flag.withDefault(false),
23 - Flag.withDescription('Skip confirmation prompts')
24 -);
25 -
26 -export const logoutCmd = Command.make('logout', { force }, ({ force }) =>
36 +export const logoutCmd = Command.make('logout', { yes }, ({ yes }) =>
37 Effect.gen(function* () {
38 const ui = yield* TerminalUI;
39 const ctx = yield* ComposioUserContext;
@@ -34,7 +44,11 @@ export const logoutCmd = Command.make('logout', { force }, ({ force }) =>
44 }
45
46 const loggedInAgent = yield* getCurrentLoggedInAgent;
37 - if (Option.isSome(loggedInAgent) && !force) {
47 + if (Option.isSome(loggedInAgent) && !yes) {
48 + const { canPrompt } = yield* ui.capabilities;
49 + if (!canPrompt) {
50 + return yield* commandInputError('logout')(NEEDS_YES_MESSAGE, '--yes');
51 + }
52 yield* ui.note(
53 [
54 `You are logged in as a Composio agent (${loggedInAgent.value.email ?? loggedInAgent.value.slug ?? 'unknown'}).`,
ts/packages/cli/src/commands/projects/list/projects.list.handler.ts
+10 -6
@@ -1,5 +1,5 @@
1 import { Array as Arr, Effect, Option, String as Str } from 'effect';
2 -import { notLoggedIn } from 'src/commands/errors';
2 +import { commandInputError, notLoggedIn } from 'src/commands/errors';
3 import { listOrganizationProjects } from 'src/services/composio-account';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioUserContext } from 'src/services/user-context';
@@ -24,7 +24,12 @@ export type ProjectsListParams = {
24 readonly limit: number;
25 };
26
27 -/** Lists the developer projects of `--org-id`, or of the current global org. */
27 +const invalidInput = commandInputError('dev projects list');
28 +
29 +/**
30 + * Lists the developer projects of `--org-id`, or of the current global org. With neither, it
31 + * fails with a `CommandInputError` before any request.
32 + */
33 export const runProjectsList = ({ orgId, limit }: ProjectsListParams) =>
34 Effect.gen(function* () {
35 const ui = yield* TerminalUI;
@@ -41,10 +46,7 @@ export const runProjectsList = ({ orgId, limit }: ProjectsListParams) =>
46
47 yield* Option.match(resolvedOrgId, {
48 onNone: () =>
44 - Effect.gen(function* () {
45 - yield* ui.log.warn(NO_CURRENT_ORG_MESSAGE);
46 - yield* ui.outro(NO_CURRENT_ORG_OUTRO);
47 - }),
49 + Effect.fail(invalidInput(`${NO_CURRENT_ORG_MESSAGE}\n${NO_CURRENT_ORG_OUTRO}`, '--org-id')),
50 onSome: resolvedOrgId =>
51 Effect.gen(function* () {
52 const projects = yield* ui.withSpinner(
@@ -61,6 +63,8 @@ export const runProjectsList = ({ orgId, limit }: ProjectsListParams) =>
63 Effect.gen(function* () {
64 yield* ui.log.warn(NO_PROJECTS_MESSAGE);
65 yield* ui.outro(NO_PROJECTS_OUTRO);
66 + // Piped callers need the parseable empty result, not silence.
67 + yield* ui.output(formatProjectsJson(projects.data));
68 }),
69 onNonEmpty: data =>
70 Effect.gen(function* () {
ts/packages/cli/src/commands/toolkits/format.ts
+3
@@ -5,6 +5,9 @@ import { truncate } from 'src/ui/truncate';
5
6 type SessionToolkitItem = SessionToolkitsResponse['items'][number];
7
8 +/** The next-step hint the toolkit commands print when a toolkit cannot be found or fetched. */
9 +export const BROWSE_TOOLKITS_HINT = 'Browse available toolkits:\n> composio dev toolkits list';
10 +
11 const formatAuthConfigField = (field: {
12 name: string;
13 displayName: string;
ts/packages/cli/src/commands/toolkits/info/toolkits.info.handler.ts
+16 -17
@@ -5,10 +5,12 @@ import { idempotent } from 'src/services/composio-request';
5 import { failedWith } from 'src/effects/request-error';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7 import { extractMessage } from 'src/utils/api-error-extraction';
8 +import { reportFailure } from 'src/effects/report-failure';
9 +import { commandInputError } from 'src/commands/errors';
10 import { ProjectContext } from 'src/services/project-context';
11 import { ComposioUserContext } from 'src/services/user-context';
12 import { CommandSurface, directoryTestUserId, namedProject } from 'src/commands/surface';
11 -import { formatToolkitInfo, formatToolkitInfoJson } from '../format';
13 +import { BROWSE_TOOLKITS_HINT, formatToolkitInfo, formatToolkitInfoJson } from '../format';
14 import { ToolkitsInfoRequestError } from './toolkits.info.errors';
15
16 export type ToolkitsInfoParams = {
@@ -16,9 +18,13 @@ export type ToolkitsInfoParams = {
18 readonly allDetails: boolean;
19 };
20
21 +const invalidInput = commandInputError('dev toolkits info');
22 +
23 /**
24 * Shows a toolkit with its connection status for the surface's user: the `dev`
21 - * group's `--user-id`, then the project test user id, then the global one.
25 + * group's `--user-id`, then the project test user id, then the global one. A missing
26 + * `<slug>` fails with a `CommandInputError` before any request; a failed lookup or an
27 + * unknown toolkit is reported on stderr and exits 1.
28 */
29 export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
30 Effect.gen(function* () {
@@ -28,13 +34,11 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
34 const userContext = yield* ComposioUserContext;
35 const clientSingleton = yield* ComposioClientSingleton;
36
31 - // Missing slug guard
37 if (Option.isNone(slug)) {
33 - yield* ui.log.warn('Missing required argument: <slug>');
34 - yield* ui.log.step(
35 - 'Try specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"'
38 + return yield* invalidInput(
39 + 'Missing required argument: <slug>\nTry specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"',
40 + '<slug>'
41 );
37 - return;
42 }
43
44 const slugValue = slug.value;
@@ -105,9 +109,8 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
109 Effect.catch(error =>
110 Effect.gen(function* () {
111 const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
108 - yield* ui.log.error(message);
112 yield* Effect.logDebug('Toolkit info error:', error);
110 - yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
113 + yield* reportFailure(ui, message, BROWSE_TOOLKITS_HINT);
114 return Option.none();
115 })
116 )
@@ -122,8 +125,6 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
125 const detailedToolkit = Option.getOrUndefined(result.detailedToolkitOpt);
126
127 if (!toolkit) {
125 - yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);
126 -
128 // "Did you mean?" suggestions via legacy search
129 const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(
130 Effect.map(r =>
@@ -136,12 +137,10 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
137 );
138
139 const [first] = suggestions;
139 - if (first) {
140 - const lines = suggestions.map(s => ` ${s.label}`).join('\n');
141 - yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);
142 - } else {
143 - yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
144 - }
140 + const hint = first
141 + ? `Did you mean?\n${suggestions.map(s => ` ${s.label}`).join('\n')}\n\n${first.command}`
142 + : BROWSE_TOOLKITS_HINT;
143 + yield* reportFailure(ui, `Toolkit "${slugValue}" not found.`, hint);
144 return;
145 }
146
ts/packages/cli/src/commands/toolkits/list/toolkits.list.handler.ts
+5 -4
@@ -5,7 +5,7 @@ import { resolveToolRouterSession } from 'src/effects/create-tool-router-session
5 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { idempotent } from 'src/services/composio-request';
7 import { ProjectContext } from 'src/services/project-context';
8 -import { NodeProcess } from 'src/services/node-process';
8 +import { reportFailure } from 'src/effects/report-failure';
9 import { TerminalUI } from 'src/services/terminal-ui';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { clampLimit } from 'src/ui/clamp-limit';
@@ -202,10 +202,11 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
202 Effect.catch(error =>
203 Effect.gen(function* () {
204 const ui = yield* TerminalUI;
205 - const proc = yield* NodeProcess;
206 - yield* ui.log.error(extractMessage(error) ?? 'An error occurred while fetching toolkits.');
205 + yield* reportFailure(
206 + ui,
207 + extractMessage(error) ?? 'An error occurred while fetching toolkits.'
208 + );
209 yield* ui.output('[]');
208 - yield* proc.setExitCode(1);
210 })
211 )
212 );
ts/packages/cli/src/commands/toolkits/search/toolkits.search.handler.ts
+5 -4
@@ -1,6 +1,6 @@
1 import { Effect } from 'effect';
2 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
3 -import { NodeProcess } from 'src/services/node-process';
3 +import { reportFailure } from 'src/effects/report-failure';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { clampLimit } from 'src/ui/clamp-limit';
6 import { extractMessage } from 'src/utils/api-error-extraction';
@@ -50,10 +50,11 @@ export const runToolkitsSearch = ({ query, limit }: ToolkitsSearchParams) =>
50 Effect.catch(error =>
51 Effect.gen(function* () {
52 const ui = yield* TerminalUI;
53 - const proc = yield* NodeProcess;
54 - yield* ui.log.error(extractMessage(error) ?? 'An error occurred while searching toolkits.');
53 + yield* reportFailure(
54 + ui,
55 + extractMessage(error) ?? 'An error occurred while searching toolkits.'
56 + );
57 yield* ui.output('[]');
56 - yield* proc.setExitCode(1);
58 })
59 )
60 );
ts/packages/cli/src/commands/toolkits/version/toolkits.version.handler.ts
+8 -5
@@ -1,4 +1,5 @@
1 import { Array as Arr, Effect, Option } from 'effect';
2 +import { reportFailure } from 'src/effects/report-failure';
3 import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { idempotent } from 'src/services/composio-request';
5 import { TerminalUI } from 'src/services/terminal-ui';
@@ -8,6 +9,7 @@ import {
9 formatToolkitVersionsJson,
10 type ToolkitVersions,
11 } from './toolkits.version.format';
12 +import { BROWSE_TOOLKITS_HINT } from '../format';
13
14 export type ToolkitsVersionParams = {
15 readonly slug: string;
@@ -39,7 +41,7 @@ export const toolkitVersionsOf = (toolkit: VersionedToolkit): ToolkitVersions =>
41
42 /**
43 * Shows a toolkit's latest version and its last 20 available versions. A failed lookup prints the
42 - * error and a browse hint and exits 0.
44 + * error and a browse hint on stderr and exits 1.
45 */
46 export const runToolkitsVersion = ({ slug }: ToolkitsVersionParams) =>
47 Effect.gen(function* () {
@@ -56,11 +58,12 @@ export const runToolkitsVersion = ({ slug }: ToolkitsVersionParams) =>
58 Effect.map(toolkit => Option.some(toolkitVersionsOf(toolkit))),
59 Effect.catch(error =>
60 Effect.gen(function* () {
59 - yield* ui.log.error(
60 - extractMessage(error) ?? `Failed to fetch version info for toolkit "${slug}".`
61 - );
61 yield* Effect.logDebug('Toolkit version error:', error);
63 - yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
62 + yield* reportFailure(
63 + ui,
64 + extractMessage(error) ?? `Failed to fetch version info for toolkit "${slug}".`,
65 + BROWSE_TOOLKITS_HINT
66 + );
67 return Option.none<ToolkitVersions>();
68 })
69 )
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+44 -10
@@ -1,4 +1,5 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 +import { reportFailure } from 'src/effects/report-failure';
3 import { Command, Flag } from 'effect/cli';
4 import * as FileSystem from 'effect/FileSystem';
5 import * as Path from 'effect/Path';
@@ -193,6 +194,12 @@ export const triggersCmd$Listen = Command.make(
194 const maxEventsLimit = Option.getOrUndefined(maxEvents);
195 const stopWhenDone = yield* Deferred.make<void>();
196 let matchingEvents = 0;
197 + // Per-event failures are recovered so one bad event never stops the listener; they are
198 + // counted here and summed up on plain stderr on every stop — including Ctrl+C and
199 + // SIGTERM, which runMain turns into a fiber interruption — since a piped caller sees
200 + // none of the `ui.log.warn` decoration.
201 + let outputWriteFailures = 0;
202 + let forwardFailures = 0;
203 let tableHeaderPrinted = false;
204
205 yield* ui.intro('composio dev triggers listen');
@@ -259,9 +266,14 @@ export const triggersCmd$Listen = Command.make(
266 const logLine = `${payloadForForwarding}\n`;
267
268 if (outputFilePath) {
262 - yield* fs
263 - .writeFileString(outputFilePath, logLine, { flag: 'a' })
264 - .pipe(Effect.catch(error => ui.log.warn(String(error))));
269 + yield* fs.writeFileString(outputFilePath, logLine, { flag: 'a' }).pipe(
270 + Effect.catch(error =>
271 + Effect.gen(function* () {
272 + outputWriteFailures += 1;
273 + yield* ui.log.warn(String(error));
274 + })
275 + )
276 + );
277 }
278
279 if (forwardUrl && webhookSecret) {
@@ -303,7 +315,14 @@ export const triggersCmd$Listen = Command.make(
315 catch: error =>
316 new Error(`Failed forwarding event to ${forwardUrl}: ${String(error)}`),
317 });
306 - }).pipe(Effect.catch(error => ui.log.warn(String(error))));
318 + }).pipe(
319 + Effect.catch(error =>
320 + Effect.gen(function* () {
321 + forwardFailures += 1;
322 + yield* ui.log.warn(String(error));
323 + })
324 + )
325 + );
326 }
327
328 if (maxEventsLimit !== undefined && matchingEvents >= maxEventsLimit) {
@@ -325,6 +344,22 @@ export const triggersCmd$Listen = Command.make(
344 Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
345 );
346
347 + // The summary runs in an onExit finalizer, so it fires on every stop — including the
348 + // interruption of an unlimited wait, where the code after this block would not run.
349 + const reportSinkFailures = () =>
350 + Effect.gen(function* () {
351 + if (forwardFailures > 0) {
352 + yield* ui.error(
353 + `${forwardFailures} event${forwardFailures === 1 ? '' : 's'} failed to forward to ${forwardUrl} while listening.`
354 + );
355 + }
356 + if (outputWriteFailures > 0) {
357 + yield* ui.error(
358 + `${outputWriteFailures} event${outputWriteFailures === 1 ? '' : 's'} failed to append to ${outputFilePath} while listening.`
359 + );
360 + }
361 + });
362 +
363 yield* Effect.gen(function* () {
364 if (maxEventsLimit === undefined) {
365 return yield* listenEffect;
@@ -333,13 +368,12 @@ export const triggersCmd$Listen = Command.make(
368 yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
369 yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
370 }).pipe(
371 + Effect.onExit(() => reportSinkFailures()),
372 Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
337 - Effect.gen(function* () {
338 - yield* ui.log.error(
339 - `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
340 - );
341 - process.exitCode = 1;
342 - })
373 + reportFailure(
374 + ui,
375 + `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
376 + )
377 )
378 );
379 })
ts/packages/cli/src/commands/triggers/disable/triggers.disable.handler.ts
+9 -8
@@ -11,11 +11,13 @@ export type TriggersDisableParams = {
11 readonly dangerouslyAllow: boolean;
12 };
13
14 -const notAllowed = commandInputError('dev triggers disable');
14 +const invalidInput = commandInputError('dev triggers disable');
15
16 /**
17 * Disable an existing trigger instance. A developer-destructive command: it runs only when
18 - * `developer.destructive_actions` is enabled and `--dangerously-allow` is passed.
18 + * `developer.destructive_actions` is enabled and `--dangerously-allow` is passed. A missing `<id>`
19 + * fails with a `CommandInputError` before any request; an API failure is reported with a hint and
20 + * exits 1.
21 *
22 * @example
23 * ```bash
@@ -26,12 +28,12 @@ export const runTriggersDisable = ({ id, dangerouslyAllow }: TriggersDisablePara
28 Effect.gen(function* () {
29 const config = yield* ComposioCliUserConfig;
30 if (!config.areDeveloperDangerousCommandsEnabled()) {
29 - return yield* notAllowed(
31 + return yield* invalidInput(
32 'This developer command is disabled by config. Set developer.destructive_actions to true in ~/.composio/config.json to allow it.'
33 );
34 }
35 if (!dangerouslyAllow) {
34 - return yield* notAllowed(
36 + return yield* invalidInput(
37 'This developer command requires explicit acknowledgement. Re-run with --dangerously-allow.',
38 '--dangerously-allow'
39 );
@@ -40,11 +42,10 @@ export const runTriggersDisable = ({ id, dangerouslyAllow }: TriggersDisablePara
42 const repo = yield* ComposioToolkitsRepository;
43
44 if (Option.isNone(id)) {
43 - yield* ui.log.warn('Missing required argument: <id>');
44 - yield* ui.log.step(
45 - 'Try specifying a trigger ID, e.g.:\n> composio dev triggers disable "trg_123"\n\nTo find trigger IDs:\n> composio dev triggers status'
45 + return yield* invalidInput(
46 + 'Missing required argument: <id>\nTry specifying a trigger ID, e.g.:\n> composio dev triggers disable "trg_123"\n\nTo find trigger IDs:\n> composio dev triggers status',
47 + '<id>'
48 );
47 - return;
49 }
50
51 const idValue = id.value;
ts/packages/cli/src/commands/triggers/info/triggers.info.handler.ts
+10 -8
@@ -1,4 +1,5 @@
1 import { Effect, Option } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 import { CommandSurface } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -14,19 +15,21 @@ export type TriggersInfoParams = {
15 const triggersInfoHints = Effect.map(CommandSurface, ({ tree }) =>
16 tree === 'dev'
17 ? {
17 - exampleCommand: 'composio dev triggers info',
18 + command: 'dev triggers info',
19 listCommand: 'composio dev triggers list',
20 listCommandPlaceholder: 'composio dev triggers list "<toolkit>"',
21 }
22 : {
22 - exampleCommand: 'composio triggers info',
23 + command: 'triggers info',
24 listCommand: 'composio triggers list',
25 listCommandPlaceholder: 'composio triggers list "<toolkit>"',
26 }
27 );
28
29 /**
29 - * View details of a specific trigger type including config and payload schemas.
30 + * View details of a specific trigger type including config and payload schemas. A missing
31 + * `<slug>` fails with a `CommandInputError` before any request; an API failure is reported with
32 + * a hint and exits 1.
33 *
34 * @example
35 * ```bash
@@ -36,15 +39,14 @@ const triggersInfoHints = Effect.map(CommandSurface, ({ tree }) =>
39 export const runTriggersInfo = ({ slug }: TriggersInfoParams) =>
40 Effect.gen(function* () {
41 const ui = yield* TerminalUI;
39 - const { exampleCommand, listCommand, listCommandPlaceholder } = yield* triggersInfoHints;
42 + const { command, listCommand, listCommandPlaceholder } = yield* triggersInfoHints;
43 const repo = yield* ComposioToolkitsRepository;
44
45 if (Option.isNone(slug)) {
43 - yield* ui.log.warn('Missing required argument: <slug>');
44 - yield* ui.log.step(
45 - `Try specifying a trigger slug, e.g.:\n> ${exampleCommand} "GMAIL_NEW_GMAIL_MESSAGE"`
46 + return yield* commandInputError(command)(
47 + `Missing required argument: <slug>\nTry specifying a trigger slug, e.g.:\n> composio ${command} "GMAIL_NEW_GMAIL_MESSAGE"`,
48 + '<slug>'
49 );
47 - return;
50 }
51
52 const slugValue = slug.value;
ts/packages/cli/src/commands/whoami.cmd.ts
+3 -2
@@ -1,5 +1,6 @@
1 import { Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 +import { notLoggedIn } from 'src/commands/errors';
4 import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
5 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
6 import { ComposioUserContext } from 'src/services/user-context';
@@ -10,7 +11,7 @@ import { getOrgEnhancedControlsStatus } from 'src/services/tool-permissions';
11
12 /**
13 * CLI command to display your account information.
13 - * Never prints or exposes API keys.
14 + * Never prints or exposes API keys. Without a login it fails with `NotLoggedInError`.
15 *
16 * @example
17 * ```bash
@@ -26,7 +27,7 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
27
28 yield* ctx.data.apiKey.pipe(
29 Option.match({
29 - onNone: () => ui.log.warn('You are not logged in yet. Please run `composio login`.'),
30 + onNone: () => Effect.fail(notLoggedIn()),
31 onSome: apiKey =>
32 Effect.gen(function* () {
33 const sessionInfo = yield* getSessionInfoByUserApiKey({
ts/packages/cli/src/effects/handle-agent-auth-error.ts
+9 -10
@@ -1,8 +1,9 @@
1 -import process from 'node:process';
1 import { Effect } from 'effect';
2 +import { reportFailure } from 'src/effects/report-failure';
3 import { AgentAuthError } from 'src/services/agents';
4 import { TerminalUI } from 'src/services/terminal-ui';
5
6 +/** Reports an `AgentAuthError` and its next steps on stderr and exits 1. */
7 export const handleAgentAuthError = <E, R>(effect: Effect.Effect<void, E | AgentAuthError, R>) =>
8 effect.pipe(
9 Effect.catchIf(
@@ -10,15 +11,13 @@ export const handleAgentAuthError = <E, R>(effect: Effect.Effect<void, E | Agent
11 error =>
12 Effect.gen(function* () {
13 const ui = yield* TerminalUI;
13 - yield* ui.log.warn(error.message);
14 - if (error.nextSteps.length > 0) {
15 - yield* ui.log.info(
16 - ['Next steps:', ...error.nextSteps.map((step: string) => `- ${step}`)].join('\n')
17 - );
18 - }
19 - yield* Effect.sync(() => {
20 - process.exitCode = 1;
21 - });
14 + yield* reportFailure(
15 + ui,
16 + error.message,
17 + error.nextSteps.length > 0
18 + ? ['Next steps:', ...error.nextSteps.map((step: string) => `- ${step}`)].join('\n')
19 + : undefined
20 + );
21 })
22 )
23 );
ts/packages/cli/src/effects/handle-http-error.ts
+15 -20
@@ -1,8 +1,8 @@
1 import { isAPIError } from '@composio/client/effect';
2 import { Effect } from 'effect';
3 import type { ClientApiError } from 'src/services/composio-errors';
4 -import { NodeProcess } from 'src/services/node-process';
4 import type { TerminalUI } from 'src/services/terminal-ui';
5 +import { reportFailure } from 'src/effects/report-failure';
6 import { describeDecodeError, isClientDecodeError } from 'src/utils/api-error-extraction';
7 import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
8
@@ -42,9 +42,10 @@ const reportOf = (e: ClientApiError): Effect.Effect<ErrorReport> => {
42 * details (or a fallback message) and a contextual hint, then returns a
43 * fallback value.
44 *
45 - * The process exit code is set to 1 so callers such as scripts and agents can
46 - * detect the failure. Decorated logs only render when stderr is a TTY, so the
47 - * error message and hint are also written plainly to stderr when it is not.
45 + * The final rendering is `reportFailure`'s (`src/effects/report-failure.ts`):
46 + * the exit code is set to 1 so callers such as scripts and agents can detect
47 + * the failure, and the message and hint reach stderr as plain lines when it is
48 + * not a TTY.
49 *
50 * Used by info/delete/create commands that share the same error-handling shape.
51 *
@@ -77,23 +78,13 @@ export const handleClientApiError =
78 <A>(ui: TerminalUI, opts: HandleClientApiErrorOptions<A>) =>
79 (e: ClientApiError) =>
80 Effect.gen(function* () {
80 - const proc = yield* NodeProcess;
81 - yield* proc.setExitCode(1);
82 -
81 const report = yield* reportOf(e);
82 const message = report.message ?? opts.fallbackMessage;
83 const hint = report.hint ?? opts.hint;
86 -
87 - const { canDecorate } = yield* ui.capabilities;
88 - if (!canDecorate) {
89 - yield* ui.error(message);
90 - yield* ui.error(hint);
91 - }
92 -
93 - yield* ui.log.error(message);
94 - if (report.suggestedFix !== undefined) {
95 - yield* ui.log.step(report.suggestedFix);
96 - }
84 + // The API's own suggested fix comes first, then the caller's hint — or the
85 + // "Did you mean?" suggestions that replace it.
86 + const withHint = (suffix: string) =>
87 + report.suggestedFix === undefined ? suffix : `${report.suggestedFix}\n\n${suffix}`;
88
89 if (opts.searchForSuggestions && report.hint === undefined) {
90 const suggestions = yield* opts
@@ -103,11 +94,15 @@ export const handleClientApiError =
94 const [first] = suggestions;
95 if (first) {
96 const lines = suggestions.map(s => ` ${s.label}`).join('\n');
106 - yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);
97 + yield* reportFailure(
98 + ui,
99 + message,
100 + withHint(`Did you mean?\n${lines}\n\n${first.command}`)
101 + );
102 return opts.fallbackValue;
103 }
104 }
105
111 - yield* ui.log.step(hint);
106 + yield* reportFailure(ui, message, withHint(hint));
107 return opts.fallbackValue;
108 });
ts/packages/cli/src/effects/report-failure.ts new
+24
@@ -0,0 +1,24 @@
1 +import { Effect } from 'effect';
2 +import { NodeProcess } from 'src/services/node-process';
3 +import type { TerminalUI } from 'src/services/terminal-ui';
4 +
5 +/**
6 + * Reports a failure the command recovers from instead of failing: sets the exit code to 1 and
7 + * prints `message`, then `hint` when there is one, on stderr. On a terminal they render as a
8 + * decorated error and step; otherwise as plain lines, since `ui.log.*` decoration is dropped
9 + * when stderr is not a TTY and scripts, CI and agents would see nothing.
10 + *
11 + * A usage mistake fails with a `CommandInputError` instead; see `src/commands/errors.ts`.
12 + */
13 +export const reportFailure = (ui: TerminalUI, message: string, hint?: string) =>
14 + Effect.gen(function* () {
15 + const proc = yield* NodeProcess;
16 + yield* proc.setExitCode(1);
17 +
18 + const { canDecorate } = yield* ui.capabilities;
19 + const [error, step] = canDecorate ? [ui.log.error, ui.log.step] : [ui.error, ui.error];
20 + yield* error(message);
21 + if (hint !== undefined) {
22 + yield* step(hint);
23 + }
24 + });
ts/packages/cli/test/__utils__/layers/agents.ts
+5 -1
@@ -122,7 +122,11 @@ export const AgentHandlerTest = (fixture: AgentHandlerFixture = {}) => {
122 execPath: `${homedir}/composio`,
123 platform: 'darwin',
124 arch: 'arm64',
125 - setExitCode: () => Effect.void,
125 + // Agent handler tests read the exit code off the real process.
126 + setExitCode: code =>
127 + Effect.sync(() => {
128 + process.exitCode = code;
129 + }),
130 })
131 ),
132 ConfigProvider.layer(hostOnlyEnvConfigProvider)
ts/packages/cli/test/__utils__/services/failing-file-writes.ts new
+26
@@ -0,0 +1,26 @@
1 +import { Effect, FileSystem, Layer, PlatformError } from 'effect';
2 +
3 +/**
4 + * Wraps the provided `FileSystem` so `writeFileString` fails with `PermissionDenied` for every
5 + * path `failsFor` matches; other paths and operations reach the real file system.
6 + */
7 +export const failingFileWrites = (failsFor: (path: string) => boolean) =>
8 + Layer.effect(
9 + FileSystem.FileSystem,
10 + Effect.map(FileSystem.FileSystem, fs =>
11 + FileSystem.FileSystem.of({
12 + ...fs,
13 + writeFileString: (path, data, options) =>
14 + failsFor(path)
15 + ? Effect.fail(
16 + PlatformError.systemError({
17 + _tag: 'PermissionDenied',
18 + module: 'FileSystem',
19 + method: 'writeFileString',
20 + pathOrDescriptor: path,
21 + })
22 + )
23 + : fs.writeFileString(path, data, options),
24 + })
25 + )
26 + );
ts/packages/cli/test/__utils__/services/redirected-terminal-ui.ts new
+52
@@ -0,0 +1,52 @@
1 +import { Writable } from 'node:stream';
2 +import { Effect, Layer } from 'effect';
3 +import { makeTerminalUI, TerminalUI } from 'src/services/terminal-ui';
4 +
5 +const capture = () => {
6 + const chunks: Array<string> = [];
7 + const stream = Object.assign(
8 + new Writable({
9 + write(chunk, _encoding, callback) {
10 + chunks.push(String(chunk));
11 + callback();
12 + },
13 + }),
14 + { isTTY: false }
15 + );
16 + return { stream, text: () => chunks.join('') };
17 +};
18 +
19 +/**
20 + * The real `TerminalUI` with stdin, stdout and stderr all redirected, as under a script, CI or
21 + * an agent: `ui.log.*` decoration is dropped and only `ui.output` and `ui.error` are written.
22 + * Unlike `terminalUITestImpl`, which prints decoration through `Console`, it shows what such a
23 + * caller actually sees.
24 + */
25 +export const redirectedTerminalUI = (options?: {
26 + /** Runs after a `log.warn` is logged — a signal that code behind the warn has run. */
27 + readonly onWarn?: (message: string) => void;
28 +}) => {
29 + const stdout = capture();
30 + const stderr = capture();
31 + const ui = makeTerminalUI({
32 + stdin: { isTTY: false },
33 + stdout: stdout.stream,
34 + stderr: stderr.stream,
35 + });
36 + const onWarn = options?.onWarn;
37 + const terminal =
38 + onWarn === undefined
39 + ? ui
40 + : TerminalUI.of({
41 + ...ui,
42 + log: {
43 + ...ui.log,
44 + warn: message =>
45 + Effect.andThen(
46 + ui.log.warn(message),
47 + Effect.sync(() => onWarn(message))
48 + ),
49 + },
50 + });
51 + return { layer: Layer.succeed(TerminalUI, terminal), stdout: stdout.text, stderr: stderr.text };
52 +};
ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+20
@@ -80,3 +80,23 @@ export const terminalUITestImpl = TerminalUI.of({
80 });
81
82 export const TerminalUITest = Layer.succeed(TerminalUI, terminalUITestImpl);
83 +
84 +/** An interactive terminal (all streams a TTY) whose confirmation prompt answers `confirmed`. */
85 +export const terminalUIWithConfirm = (confirmed: boolean) =>
86 + TerminalUI.of({
87 + ...terminalUITestImpl,
88 + capabilities: Effect.succeed(
89 + getTerminalCapabilities({
90 + stdin: { isTTY: true },
91 + stdout: { isTTY: true },
92 + stderr: { isTTY: true },
93 + })
94 + ),
95 + confirm: () => Effect.succeed(confirmed),
96 + });
97 +
98 +/** An interactive terminal whose confirmation prompt must never be shown. */
99 +export const terminalUIWithoutPrompt = TerminalUI.of({
100 + ...terminalUIWithConfirm(false),
101 + confirm: () => Effect.die('the confirmation prompt must not be shown'),
102 +});
ts/packages/cli/test/src/cli-main.test.ts
+69
@@ -139,6 +139,75 @@ describe('CLI process error handling', () => {
139 expect(result.stderr).not.toContain('Sources');
140 });
141
142 + // Each of these used to print its message only to a terminal and exit 0, so a script, CI or
143 + // an agent saw nothing and a successful exit; `connections remove` used to answer its own
144 + // confirmation prompt with "no".
145 + it.each([
146 + {
147 + command: 'whoami',
148 + args: ['whoami'],
149 + loggedIn: false,
150 + message: 'You are not logged in yet. Please run `composio login`.',
151 + },
152 + {
153 + command: 'dev connected-accounts info',
154 + args: ['dev', 'connected-accounts', 'info'],
155 + loggedIn: true,
156 + message: 'Missing required argument: <id>',
157 + },
158 + {
159 + command: 'triggers info',
160 + args: ['triggers', 'info'],
161 + loggedIn: true,
162 + message: 'Missing required argument: <slug>',
163 + },
164 + {
165 + command: 'connections remove gmail',
166 + args: ['connections', 'remove', 'gmail'],
167 + loggedIn: true,
168 + message: '`composio connections remove` needs --yes when not running interactively.',
169 + },
170 + {
171 + command: 'dev projects list',
172 + args: ['dev', 'projects', 'list'],
173 + loggedIn: true,
174 + message: 'No current org is configured.',
175 + },
176 + ])(
177 + 'reports `composio $command` on a redirected stderr and exits 1',
178 + ({ args, loggedIn, message }) => {
179 + const configDirectory = tempy.temporaryDirectory();
180 + if (loggedIn) {
181 + fs.writeFileSync(
182 + path.join(configDirectory, 'user_data.json'),
183 + JSON.stringify({
184 + api_key: 'test-api-key',
185 + base_url: 'https://backend.composio.dev',
186 + web_url: 'https://platform.composio.dev',
187 + org_id: null,
188 + test_user_id: null,
189 + })
190 + );
191 + }
192 +
193 + const result = spawnSync('bun', ['run', 'src/bin.ts', ...args], {
194 + cwd: process.cwd(),
195 + encoding: 'utf8',
196 + env: {
197 + ...process.env,
198 + CI: '1',
199 + NO_COLOR: '1',
200 + COMPOSIO_CACHE_DIR: configDirectory,
201 + },
202 + });
203 +
204 + expect(result.status).toBe(1);
205 + expect(result.stdout).toBe('');
206 + expect(result.stderr).toContain(message);
207 + expect(result.stderr).not.toContain('CommandInputError');
208 + }
209 + );
210 +
211 it('reports a bare `composio run` as a usage error without a defect dump', () => {
212 const configDirectory = tempy.temporaryDirectory();
213
ts/packages/cli/test/src/commands/agent/claim/agent.claim.handler.test.ts
+1
@@ -87,6 +87,7 @@ describe('runAgentClaim', () => {
87
88 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
89 'No Composio agent identity is saved on this machine.',
90 + expect.stringMatching(/^Next steps:\n/),
91 ]);
92 expect(process.exitCode).toBe(1);
93 expect(fetchSpy).not.toHaveBeenCalled();
ts/packages/cli/test/src/commands/agent/inbox/agent.inbox.handler.test.ts
+1
@@ -63,6 +63,7 @@ describe('runAgentInbox', () => {
63
64 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
65 'This CLI is currently signed in to Composio as a regular user, not an agent.',
66 + expect.stringMatching(/^Next steps:\n/),
67 ]);
68 expect(process.exitCode).toBe(1);
69 expect(fetchSpy).not.toHaveBeenCalled();
ts/packages/cli/test/src/commands/agent/login/agent.login.handler.test.ts
+1
@@ -72,6 +72,7 @@ describe('runAgentLogin', () => {
72
73 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
74 'This CLI is currently signed in to Composio as a regular user, not an agent.',
75 + expect.stringMatching(/^Next steps:\n/),
76 ]);
77 expect(process.exitCode).toBe(1);
78 expect(fetchSpy).not.toHaveBeenCalled();
ts/packages/cli/test/src/commands/agent/signup/agent.signup.handler.test.ts
+1
@@ -203,6 +203,7 @@ describe('runAgentSignup', () => {
203
204 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
205 'This CLI is currently signed in to Composio as a regular user, not an agent.',
206 + expect.stringMatching(/^Next steps:\n/),
207 ]);
208 expect(process.exitCode).toBe(1);
209 expect(fetchSpy).not.toHaveBeenCalled();
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.handler.test.ts
+3 -3
@@ -126,9 +126,9 @@ describe('runAgentWhoami', () => {
126
127 yield* runAgentWhoami();
128
129 - const warnings = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
130 - expect(warnings).toEqual([message]);
131 - expect(yield* decoration).toContain('Next steps:');
129 + // Plain lines on stderr: a headless terminal drops `ui.log.*` decoration.
130 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
131 + expect(stderr).toEqual([message, expect.stringMatching(/^Next steps:\n/)]);
132 expect(process.exitCode).toBe(1);
133 expect(fetchSpy).not.toHaveBeenCalled();
134 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.cmd.test.ts
+11 -7
@@ -68,16 +68,20 @@ describe('CLI: composio dev connected-accounts info', () => {
68 );
69
70 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
71 - '[Given] no ID argument [Then] shows missing argument warning',
71 + '[Given] no ID argument [Then] fails with a usage error',
72 it => {
73 - it.effect('warns about missing argument', () =>
73 + it.effect('raises a CommandInputError naming <id>', () =>
74 Effect.gen(function* () {
75 - yield* cli(['dev', 'connected-accounts', 'info']);
76 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
77 - const output = lines.join('\n');
75 + const failure = yield* cli(['dev', 'connected-accounts', 'info']).pipe(Effect.flip);
76
79 - expect(output).toContain('Missing required argument');
80 - expect(output).toContain('composio dev connected-accounts info');
77 + expect(failure).toMatchObject({
78 + _tag: 'commands/CommandInputError',
79 + option: '<id>',
80 + message: expect.stringMatching(
81 + /^Missing required argument: <id>\n[^]*composio dev connected-accounts info /
82 + ),
83 + });
84 + expect(yield* MockConsole.getLines()).toEqual([]);
85 })
86 );
87 }
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.handler.test.ts
+13 -4
@@ -2,6 +2,7 @@ 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 { isUsageFailure } from 'src/commands/errors';
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';
@@ -104,13 +105,21 @@ describe('runConnectedAccountsInfo', () => {
105 }
106 );
107
107 - it.effect('[Given] no id [Then] warns with an example and fetches nothing', () => {
108 + it.effect('[Given] no id [Then] fails with a usage error before any request', () => {
109 const { layer, outputs, exitCodes } = infoTest();
110 return Effect.gen(function* () {
110 - yield* runConnectedAccountsInfo({ id: Option.none() });
111 + const failure = yield* runConnectedAccountsInfo({ id: Option.none() }).pipe(Effect.flip);
112
112 - expect(yield* stderrLines).toEqual([MISSING_ID_MESSAGE]);
113 - expect(yield* stdoutLines).toEqual([missingIdHint('info')]);
113 + expect(failure).toMatchObject({
114 + _tag: 'commands/CommandInputError',
115 + command: 'dev connected-accounts info',
116 + option: '<id>',
117 + message: `${MISSING_ID_MESSAGE}\n${missingIdHint('info')}`,
118 + });
119 + // `cli-main.ts` prints a usage failure on stderr and exits 1.
120 + expect(isUsageFailure(failure)).toBe(true);
121 + expect(yield* stderrLines).toEqual([]);
122 + expect(yield* stdoutLines).toEqual([]);
123 expect(outputs).toEqual([]);
124 expect(exitCodes).toEqual([]);
125 }).pipe(Effect.provide(layer));
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.cmd.test.ts
+39 -15
@@ -8,6 +8,7 @@ import type { TestLiveInput } from 'test/__utils__/services/test-layer';
8 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
9 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
10 import { ComposioUserContext } from 'src/services/user-context';
11 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
12 import open from 'open';
13 import { afterEach, vi } from 'vitest';
14
@@ -129,6 +130,7 @@ describe('CLI: composio dev connected-accounts link', () => {
130 afterEach(() => {
131 vi.restoreAllMocks();
132 vi.clearAllMocks();
133 + process.exitCode = undefined;
134 });
135
136 layer(
@@ -300,6 +302,29 @@ describe('CLI: composio dev connected-accounts link', () => {
302 expect(vi.mocked(open)).not.toHaveBeenCalled();
303 })
304 );
305 +
306 + // Logged as decoration, this mistake vanished whenever stderr was not a TTY and the
307 + // command exited 0; as a `CommandInputError` it reaches stderr and exits 1.
308 + it.effect('reports a toolkit passed together with --auth-config', () =>
309 + Effect.gen(function* () {
310 + const error = yield* cli([
311 + 'dev',
312 + 'connected-accounts',
313 + 'link',
314 + 'gmail',
315 + '--auth-config',
316 + 'ac_test',
317 + '--no-wait',
318 + ]).pipe(Effect.flip);
319 +
320 + expect(error).toMatchObject({
321 + _tag: 'commands/CommandInputError',
322 + command: 'dev connected-accounts link',
323 + option: '--auth-config',
324 + });
325 + expect(vi.mocked(open)).not.toHaveBeenCalled();
326 + })
327 + );
328 });
329
330 layer(
@@ -434,22 +459,21 @@ describe('CLI: composio dev connected-accounts link', () => {
459 }),
460 },
461 })
437 - )(
438 - '[Given] auth-config link returns an incomplete response [Then] logs an error and exits early',
439 - it => {
440 - it.effect('reports the incomplete response instead of waiting with empty values', () =>
441 - Effect.gen(function* () {
442 - yield* cli(['link', 'gmail']);
443 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
462 + )('[Given] auth-config link returns an incomplete response [Then] reports it and exits 1', it => {
463 + it.effect('reports the incomplete response instead of waiting with empty values', () =>
464 + Effect.gen(function* () {
465 + // Redirected streams, as under a script: only plain stderr lines and stdout data show.
466 + const terminal = redirectedTerminalUI();
467 + yield* cli(['link', 'gmail']).pipe(Effect.provide(terminal.layer));
468
445 - expect(lines).toEqual([
446 - 'Linking gmail...',
447 - 'The link response from the API is missing `connected_account_id` or `redirect_url`.',
448 - ]);
449 - })
450 - );
451 - }
452 - );
469 + expect(terminal.stderr()).toBe(
470 + 'The link response from the API is missing `connected_account_id` or `redirect_url`.\n'
471 + );
472 + expect(terminal.stdout()).toBe('');
473 + expect(process.exitCode).toBe(1);
474 + })
475 + );
476 + });
477
478 layer(
479 TestLive({
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+135 -71
@@ -17,6 +17,7 @@ import {
17 AUTH_CONFIG_SCOPE_MESSAGE,
18 BROWSE_AUTH_CONFIGS_HINT,
19 BROWSE_TOOLKITS_HINT,
20 + INCOMPLETE_LINK_RESPONSE_MESSAGE,
21 LIST_REQUIRES_TOOLKIT_MESSAGE,
22 LIST_WITH_AUTH_CONFIG_MESSAGE,
23 ROOT_AUTH_CONFIG_MESSAGE,
@@ -30,7 +31,7 @@ import type { ProjectKeys } from 'src/models/project-keys';
31 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
32 import { ComposioClientSingleton } from 'src/services/composio-clients';
33 import { NodeOs } from 'src/services/node-os';
33 -import { NodeProcess } from 'src/services/node-process';
34 +import type { TerminalUI } from 'src/services/terminal-ui';
35 import { ProjectContext } from 'src/services/project-context';
36 import { ComposioUserContext } from 'src/services/user-context';
37 import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
@@ -41,6 +42,8 @@ import {
42 } from 'test/__utils__/layers/connected-accounts';
43 import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
44 import { makeOrgProject } from 'test/__utils__/models/account';
45 +import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
46 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
47 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
48 import open from 'open';
49 import { afterEach, vi } from 'vitest';
@@ -115,6 +118,8 @@ interface LinkFixture {
118 readonly connectedAccountsListFails?: boolean;
119 /** Makes the first N `connectedAccounts.retrieve` calls fail, for the polling retries. */
120 readonly retrieveFailsFirst?: number;
121 + /** Replaces the headless test terminal, e.g. with `redirectedTerminalUI`. */
122 + readonly terminal?: Layer.Layer<TerminalUI>;
123 }
124
125 /** A request that creates a link, as the mock client saw it. */
@@ -159,7 +164,8 @@ const cliUserConfig = ComposioCliUserConfig.of({
164 /**
165 * What a link handler needs and nothing more: the account and connected-account families of
166 * the mock client (`test/__utils__/layers`), a Tool Router session that answers, and doubles
162 - * for the user, the directory, and the platform. `requests` records every link request.
167 + * for the user, the directory, and the platform. `requests` records every link request, and
168 + * `exitCode` the exit code a handler sets.
169 */
170 const linkHandlerTest = (fixture: LinkFixture = {}) => {
171 const requests: Array<LinkRequest> = [];
@@ -223,9 +229,10 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
229 }) as unknown as ComposioClientShape;
230
231 const dir = tempy.temporaryDirectory({ prefix: 'link-handler' });
232 + const proc = recordingNodeProcess(dir);
233 const layer = Layer.mergeAll(
234 Layer.effect(Console.Console, MockConsole.make),
228 - TerminalUITest,
235 + fixture.terminal ?? TerminalUITest,
236 fixture.surface ?? CommandSurface.root,
237 Layer.succeed(
238 ComposioUserContext,
@@ -264,20 +271,11 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
271 NodeOs,
272 NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' })
273 ),
267 - Layer.succeed(
268 - NodeProcess,
269 - NodeProcess.of({
270 - cwd: dir,
271 - execPath: `${dir}/composio`,
272 - platform: 'darwin',
273 - arch: 'arm64',
274 - setExitCode: () => Effect.void,
275 - })
276 - ),
274 + proc.layer,
275 Layer.succeed(ComposioCliUserConfig, cliUserConfig),
276 ConfigProvider.layer(hostOnlyEnvConfigProvider)
277 );
280 - return { layer, requests };
278 + return { layer, requests, exitCode: proc.exitCode };
279 };
280
281 const lines = MockConsole.getLines({ stripAnsi: true });
@@ -361,6 +359,7 @@ describe('connected-accounts link handler: runConnectedAccountsLink', () => {
359 input: { alias: Option.some(' '), authConfig: Option.some('ac_1') },
360 option: '--alias',
361 message: '`--alias` cannot be empty.',
362 + command: 'link',
363 },
364 {
365 name: '--auth-config on the root tree, which is consumer-only',
@@ -368,53 +367,46 @@ describe('connected-accounts link handler: runConnectedAccountsLink', () => {
367 input: { toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') },
368 option: '--auth-config',
369 message: ROOT_AUTH_CONFIG_MESSAGE,
370 + command: 'link',
371 },
372 - ])('[Given] $name [Then] fails with a CommandInputError and sends nothing', c =>
373 - Effect.gen(function* () {
374 - const { layer, requests } = linkHandlerTest({ surface: c.surface });
375 - const error = yield* runConnectedAccountsLink(params(c.input)).pipe(
376 - Effect.flip,
377 - Effect.provide(layer)
378 - );
379 -
380 - expect(error).toMatchObject({
381 - _tag: 'commands/CommandInputError',
382 - command: 'link',
383 - option: c.option,
384 - message: c.message,
385 - });
386 - expect(requests).toEqual([]);
387 - })
388 - );
389 -
390 - it.effect.each([
372 {
373 name: 'a toolkit and --auth-config under dev',
374 surface: devSurface(),
375 input: { toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') },
376 + option: '--auth-config',
377 message: TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
378 + command: 'dev connected-accounts link',
379 },
380 {
381 name: 'neither a toolkit nor --auth-config on the root tree',
382 surface: CommandSurface.root,
383 input: {},
384 + option: '<toolkit>',
385 message: missingArgumentMessage('root'),
386 + command: 'link',
387 },
388 {
389 name: 'neither a toolkit nor --auth-config under dev',
390 surface: devSurface(),
391 input: {},
392 + option: '<toolkit>',
393 message: missingArgumentMessage('dev'),
394 + command: 'dev connected-accounts link',
395 },
409 - ])('[Given] $name [Then] prints the usage message and exits 0', c =>
396 + ])('[Given] $name [Then] fails with a CommandInputError and sends nothing', c =>
397 Effect.gen(function* () {
398 const { layer, requests } = linkHandlerTest({ surface: c.surface });
412 - const output = yield* runConnectedAccountsLink(params(c.input)).pipe(
413 - Effect.andThen(lines),
399 + const error = yield* runConnectedAccountsLink(params(c.input)).pipe(
400 + Effect.flip,
401 Effect.provide(layer)
402 );
403
417 - expect(output).toEqual([c.message]);
404 + expect(error).toMatchObject({
405 + _tag: 'commands/CommandInputError',
406 + command: c.command,
407 + option: c.option,
408 + message: c.message,
409 + });
410 expect(requests).toEqual([]);
411 })
412 );
@@ -463,15 +455,21 @@ describe('connected-accounts link handler: handleListConnectedAccounts', () => {
455 input: { list: true, toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') },
456 message: LIST_WITH_AUTH_CONFIG_MESSAGE,
457 },
466 - ])('[Given] $name [Then] prints why --list cannot run', c =>
458 + ])('[Given] $name [Then] fails with a CommandInputError saying why --list cannot run', c =>
459 Effect.gen(function* () {
468 - const { layer } = linkHandlerTest();
469 - const output = yield* handleListConnectedAccounts(params(c.input)).pipe(
470 - Effect.andThen(lines),
460 + const { layer, requests } = linkHandlerTest();
461 + const error = yield* handleListConnectedAccounts(params(c.input)).pipe(
462 + Effect.flip,
463 Effect.provide(layer)
464 );
465
474 - expect(output).toEqual([c.message]);
466 + expect(error).toMatchObject({
467 + _tag: 'commands/CommandInputError',
468 + command: 'link',
469 + option: '--list',
470 + message: c.message,
471 + });
472 + expect(requests).toEqual([]);
473 })
474 );
475
@@ -604,6 +602,24 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
602 })
603 );
604
605 + it.effect('[Given] no --auth-config [Then] fails with a usage error and sends nothing', () =>
606 + Effect.gen(function* () {
607 + const { layer, requests } = linkHandlerTest({ surface: devSurface() });
608 + const error = yield* handleLegacyAuthConfigLink(params()).pipe(
609 + Effect.flip,
610 + Effect.provide(layer)
611 + );
612 +
613 + expect(error).toMatchObject({
614 + _tag: 'commands/CommandInputError',
615 + command: 'dev connected-accounts link',
616 + option: '--auth-config',
617 + message: missingArgumentMessage('dev'),
618 + });
619 + expect(requests).toEqual([]);
620 + })
621 + );
622 +
623 it.effect('[Given] no user anywhere [Then] fails pointing at dev init', () =>
624 Effect.gen(function* () {
625 const { layer } = linkHandlerTest({
@@ -622,23 +638,30 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
638 })
639 );
640
625 - it.effect('[Given] no developer project [Then] explains the scope and sends nothing', () =>
626 - Effect.gen(function* () {
627 - const { layer, requests } = linkHandlerTest({ surface: devSurface({ userId: 'user_1' }) });
628 - const output = yield* handleLegacyAuthConfigLink(
629 - params({ authConfig: Option.some('ac_gmail') })
630 - ).pipe(Effect.andThen(lines), Effect.provide(layer));
641 + it.effect(
642 + '[Given] no developer project [Then] fails with a CommandInputError explaining the scope and sends nothing',
643 + () =>
644 + Effect.gen(function* () {
645 + const { layer, requests } = linkHandlerTest({ surface: devSurface({ userId: 'user_1' }) });
646 + const error = yield* handleLegacyAuthConfigLink(
647 + params({ authConfig: Option.some('ac_gmail') })
648 + ).pipe(Effect.flip, Effect.provide(layer));
649
632 - expect(output).toEqual([AUTH_CONFIG_SCOPE_MESSAGE]);
633 - expect(requests).toEqual([]);
634 - })
650 + expect(error).toMatchObject({
651 + _tag: 'commands/CommandInputError',
652 + command: 'dev connected-accounts link',
653 + option: '--auth-config',
654 + message: AUTH_CONFIG_SCOPE_MESSAGE,
655 + });
656 + expect(requests).toEqual([]);
657 + })
658 );
659
660 it.effect(
638 - '[Given] the link request fails [Then] reports the message and the auth-config hint',
661 + '[Given] the link request fails [Then] reports the message and the auth-config hint, and exits 1',
662 () =>
663 Effect.gen(function* () {
641 - const { layer, requests } = linkHandlerTest({
664 + const { layer, requests, exitCode } = linkHandlerTest({
665 surface: devSurface({ userId: 'user_1' }),
666 directoryProject: directory(Option.none()),
667 legacyLinkCreate: () => Effect.fail(new Error('quota exhausted')),
@@ -648,6 +671,7 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
671 ).pipe(Effect.andThen(lines), Effect.provide(layer));
672
673 expect(output).toEqual(['quota exhausted', BROWSE_AUTH_CONFIGS_HINT]);
674 + expect(exitCode()).toBe(1);
675 expect(requests).toEqual([
676 {
677 operation: 'link.create',
@@ -658,10 +682,10 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
682 );
683
684 it.effect(
661 - '[Given] an alias already in use [Then] points at the dev commands and sends nothing',
685 + '[Given] an alias already in use [Then] points at the dev commands, sends nothing, and exits 1',
686 () =>
687 Effect.gen(function* () {
664 - const { layer, requests } = linkHandlerTest({
688 + const { layer, requests, exitCode } = linkHandlerTest({
689 surface: devSurface({ userId: 'user_1' }),
690 directoryProject: directory(Option.none()),
691 accounts: [account({ user_id: 'user_1', alias: 'Work' })],
@@ -674,6 +698,7 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
698 'Alias "work" is already in use by connected account "con_existing".',
699 "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list",
700 ]);
701 + expect(exitCode()).toBe(1);
702 expect(requests).toEqual([]);
703 })
704 );
@@ -684,7 +709,7 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
709 '[Given] the consumer project and --alias [Then] links with the alias and prints the pending link',
710 () =>
711 Effect.gen(function* () {
687 - const { layer, requests } = linkHandlerTest({ accounts: [account()] });
712 + const { layer, requests, exitCode } = linkHandlerTest({ accounts: [account()] });
713 const output = yield* handleToolRouterLink(
714 params({ toolkit: Option.some('gmail'), alias: Option.some(' work ') })
715 ).pipe(Effect.andThen(lines), Effect.provide(layer));
@@ -696,6 +721,7 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
721 },
722 ]);
723 expect(String(output.at(-1))).toBe(toolRouterPendingJson());
724 + expect(exitCode()).toBeUndefined();
725 })
726 );
727
@@ -758,16 +784,51 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
784
785 it.effect('[Given] the link request fails [Then] reports the cause and the browse hint', () =>
786 Effect.gen(function* () {
761 - const { layer } = linkHandlerTest({
787 + const terminal = redirectedTerminalUI();
788 + const { layer, exitCode } = linkHandlerTest({
789 toolRouterLink: () => Effect.fail(new Error('offline')),
790 + terminal: terminal.layer,
791 + });
792 + yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
793 + Effect.provide(layer)
794 + );
795 +
796 + // `failedWith` keeps the client error in `.cause`, and the message prefers it. Plain
797 + // lines, so a script, CI or an agent reading a redirected stderr sees them.
798 + expect(terminal.stderr()).toBe(`offline\n${BROWSE_TOOLKITS_HINT}\n`);
799 + expect(terminal.stdout()).toBe('');
800 + expect(exitCode()).toBe(1);
801 + })
802 + );
803 +
804 + it.effect('[Given] an incomplete link response [Then] reports it and exits 1', () =>
805 + Effect.gen(function* () {
806 + const { layer, exitCode } = linkHandlerTest({
807 + toolRouterLink: () =>
808 + Effect.succeed({ connected_account_id: 'con_new', link_token: 'lt', redirect_url: '' }),
809 });
810 const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
811 Effect.andThen(lines),
812 Effect.provide(layer)
813 );
814
769 - // `failedWith` keeps the client error in `.cause`, and the message prefers it.
770 - expect(output).toEqual(['offline', BROWSE_TOOLKITS_HINT]);
815 + expect(output).toEqual(['Linking gmail...', INCOMPLETE_LINK_RESPONSE_MESSAGE]);
816 + expect(exitCode()).toBe(1);
817 + })
818 + );
819 +
820 + it.effect('[Given] no toolkit [Then] fails with a usage error and sends nothing', () =>
821 + Effect.gen(function* () {
822 + const { layer, requests } = linkHandlerTest();
823 + const error = yield* handleToolRouterLink(params()).pipe(Effect.flip, Effect.provide(layer));
824 +
825 + expect(error).toMatchObject({
826 + _tag: 'commands/CommandInputError',
827 + command: 'link',
828 + option: '<toolkit>',
829 + message: missingArgumentMessage('root'),
830 + });
831 + expect(requests).toEqual([]);
832 })
833 );
834
@@ -873,18 +934,21 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
934 })
935 );
936
876 - it.effect('[Given] an active account and no --alias [Then] lists it and prints no link', () =>
877 - Effect.gen(function* () {
878 - const { layer } = linkHandlerTest({ accounts: [account({ alias: 'default' })] });
879 - const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
880 - Effect.andThen(lines),
881 - Effect.provide(layer)
882 - );
937 + it.effect(
938 + '[Given] an active account and no --alias [Then] lists it, prints no link, and exits 1',
939 + () =>
940 + Effect.gen(function* () {
941 + const { layer, exitCode } = linkHandlerTest({ accounts: [account({ alias: 'default' })] });
942 + const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
943 + Effect.andThen(lines),
944 + Effect.provide(layer)
945 + );
946
884 - expect(output.slice(-2)).toEqual([
885 - `A connected account already exists for user "${CONSUMER_USER_ID}" in toolkit "gmail". Pass --alias to create another one.`,
886 - '[Existing accounts] con_existing (default, castle)',
887 - ]);
888 - })
947 + expect(output.slice(-2)).toEqual([
948 + `A connected account already exists for user "${CONSUMER_USER_ID}" in toolkit "gmail". Pass --alias to create another one.`,
949 + '[Existing accounts] con_existing (default, castle)',
950 + ]);
951 + expect(exitCode()).toBe(1);
952 + })
953 );
954 });
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.cmd.test.ts
+11 -7
@@ -102,16 +102,20 @@ describe('CLI: composio dev connected-accounts whoami', () => {
102 );
103
104 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
105 - '[Given] no ID argument [Then] shows missing argument warning',
105 + '[Given] no ID argument [Then] fails with a usage error',
106 it => {
107 - it.effect('warns about missing argument', () =>
107 + it.effect('raises a CommandInputError naming <id>', () =>
108 Effect.gen(function* () {
109 - yield* cli(['dev', 'connected-accounts', 'whoami']);
110 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
111 - const output = lines.join('\n');
109 + const failure = yield* cli(['dev', 'connected-accounts', 'whoami']).pipe(Effect.flip);
110
113 - expect(output).toContain('Missing required argument');
114 - expect(output).toContain('composio dev connected-accounts whoami');
111 + expect(failure).toMatchObject({
112 + _tag: 'commands/CommandInputError',
113 + option: '<id>',
114 + message: expect.stringMatching(
115 + /^Missing required argument: <id>\n[^]*composio dev connected-accounts whoami /
116 + ),
117 + });
118 + expect(yield* MockConsole.getLines()).toEqual([]);
119 })
120 );
121 }
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.test.ts
+13 -4
@@ -3,6 +3,7 @@ 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 { isUsageFailure } from 'src/commands/errors';
7 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 import { NodeProcess } from 'src/services/node-process';
9 import { TerminalUI } from 'src/services/terminal-ui';
@@ -108,13 +109,21 @@ describe('runConnectedAccountsWhoami', () => {
109 }).pipe(Effect.provide(layer));
110 });
111
111 - it.effect('[Given] no id [Then] warns with an example and fetches nothing', () => {
112 + it.effect('[Given] no id [Then] fails with a usage error before any request', () => {
113 const { layer, outputs, exitCodes } = whoamiTest();
114 return Effect.gen(function* () {
114 - yield* runConnectedAccountsWhoami({ id: Option.none() });
115 + const failure = yield* runConnectedAccountsWhoami({ id: Option.none() }).pipe(Effect.flip);
116
116 - expect(yield* stderrLines).toEqual([MISSING_ID_MESSAGE]);
117 - expect(yield* stdoutLines).toEqual([missingIdHint('whoami')]);
117 + expect(failure).toMatchObject({
118 + _tag: 'commands/CommandInputError',
119 + command: 'dev connected-accounts whoami',
120 + option: '<id>',
121 + message: `${MISSING_ID_MESSAGE}\n${missingIdHint('whoami')}`,
122 + });
123 + // `cli-main.ts` prints a usage failure on stderr and exits 1.
124 + expect(isUsageFailure(failure)).toBe(true);
125 + expect(yield* stderrLines).toEqual([]);
126 + expect(yield* stdoutLines).toEqual([]);
127 expect(outputs).toEqual([]);
128 expect(exitCodes).toEqual([]);
129 }).pipe(Effect.provide(layer));
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
-169
@@ -76,48 +76,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
76 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
77 });
78
79 -const terminalUIWithConfirm = (confirmed: boolean) =>
80 - TerminalUI.of({
81 - capabilities: Effect.succeed(
82 - getTerminalCapabilities({
83 - stdin: { isTTY: true },
84 - stdout: { isTTY: true },
85 - stderr: { isTTY: true },
86 - })
87 - ),
88 - output: data => Console.log(data),
89 - error: data => Console.error(data),
90 - intro: title => Console.log(`-- ${title} --`),
91 - outro: message => Console.log(`-- ${message} --`),
92 - log: {
93 - info: message => Console.log(message),
94 - success: message => Console.log(message),
95 - warn: message => Console.warn(message),
96 - error: message => Console.error(message),
97 - step: message => Console.log(message),
98 - message: message => Console.log(message),
99 - },
100 - note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
101 - select: (_message, options) => Effect.succeed(options[0]!.value),
102 - confirm: () => Effect.succeed(confirmed),
103 - withSpinner: (message, effect, options) =>
104 - Effect.gen(function* () {
105 - const result = yield* effect;
106 - const successMsg =
107 - typeof options?.successMessage === 'function'
108 - ? options.successMessage(result)
109 - : (options?.successMessage ?? message);
110 - yield* Console.log(successMsg);
111 - return result;
112 - }),
113 - useMakeSpinner: (_message, use) =>
114 - use({
115 - message: (_msg: string) => Effect.void,
116 - stop: (msg?: string) => (msg ? Console.log(msg) : Effect.void),
117 - error: (msg?: string) => (msg ? Console.error(msg) : Effect.void),
118 - }),
119 - });
120 -
79 describe('CLI: composio connections list', () => {
80 layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(it => {
81 it.effect('[Given] no filter [Then] prints connection JSON with aliases for duplicates', () =>
@@ -230,130 +188,3 @@ describe('CLI: composio connections list', () => {
188 );
189 });
190 });
233 -
234 -describe('CLI: composio connections remove', () => {
235 - const confirmedDeleteCalls: string[] = [];
236 - layer(
237 - TestLive({
238 - baseConfigProvider: testConfigProvider,
239 - connectedAccountsData: {
240 - items: testConnections,
241 - onDelete: nanoid => confirmedDeleteCalls.push(nanoid),
242 - },
243 - terminalUI: terminalUIWithConfirm(true),
244 - })
245 - )(it => {
246 - it.effect('[Given] a unique toolkit selector and consent [Then] removes that connection', () =>
247 - Effect.gen(function* () {
248 - confirmedDeleteCalls.length = 0;
249 -
250 - const userContext = yield* ComposioUserContext;
251 - yield* userContext.login('test_api_key', 'org_test');
252 - yield* cli(['connections', 'remove', 'gmail']);
253 -
254 - expect(confirmedDeleteCalls).toEqual(['con_gmail_active']);
255 -
256 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
257 - expect(lines.join('\n')).toContain('Removed gmail connection.');
258 - })
259 - );
260 - });
261 -
262 - layer(
263 - TestLive({
264 - baseConfigProvider: testConfigProvider,
265 - terminalUI: terminalUIWithConfirm(true),
266 - })
267 - )(it => {
268 - it.effect('[Given] the API rejects the removal [Then] fails naming the connected account', () =>
269 - Effect.gen(function* () {
270 - const stub = stubClientResources(
271 - ['connectedAccounts'],
272 - routeRequests(
273 - [
274 - {
275 - method: 'DELETE',
276 - path: '/api/v3.1/connected_accounts/',
277 - respond: () =>
278 - Response.json(
279 - {
280 - error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 },
281 - },
282 - { status: 403 }
283 - ),
284 - },
285 - ],
286 - () => Response.json({ items: testConnections, next_cursor: null })
287 - )
288 - );
289 - const userContext = yield* ComposioUserContext;
290 - yield* userContext.login('test_api_key', 'org_test');
291 - const failure = yield* cli(['connections', 'remove', 'gmail']).pipe(
292 - Effect.provide(stub.layer),
293 - Effect.flip
294 - );
295 -
296 - expect(failure).toMatchObject({ _tag: 'commands/ConnectionsRemovalRequestError' });
297 - expect(extractErrorDetails(failure).message).toBe(
298 - 'Failed to remove connected account "con_gmail_active".\nCaused by: 403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}'
299 - );
300 - })
301 - );
302 - });
303 -
304 - const deniedDeleteCalls: string[] = [];
305 - layer(
306 - TestLive({
307 - baseConfigProvider: testConfigProvider,
308 - connectedAccountsData: {
309 - items: testConnections,
310 - onDelete: nanoid => deniedDeleteCalls.push(nanoid),
311 - },
312 - terminalUI: terminalUIWithConfirm(false),
313 - })
314 - )(it => {
315 - it.effect('[Given] consent is denied [Then] does not remove the connection', () =>
316 - Effect.gen(function* () {
317 - deniedDeleteCalls.length = 0;
318 -
319 - const userContext = yield* ComposioUserContext;
320 - yield* userContext.login('test_api_key', 'org_test');
321 - yield* cli(['connections', 'remove', 'work']);
322 -
323 - expect(deniedDeleteCalls).toEqual([]);
324 -
325 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
326 - expect(lines.join('\n')).toContain('No connection removed.');
327 - })
328 - );
329 - });
330 -
331 - const ambiguousDeleteCalls: string[] = [];
332 - layer(
333 - TestLive({
334 - baseConfigProvider: testConfigProvider,
335 - connectedAccountsData: {
336 - items: testConnections,
337 - onDelete: nanoid => ambiguousDeleteCalls.push(nanoid),
338 - },
339 - terminalUI: terminalUIWithConfirm(true),
340 - })
341 - )(it => {
342 - it.effect(
343 - '[Given] a selector matches multiple accounts [Then] asks for a unique selector',
344 - () =>
345 - Effect.gen(function* () {
346 - ambiguousDeleteCalls.length = 0;
347 -
348 - const userContext = yield* ComposioUserContext;
349 - yield* userContext.login('test_api_key', 'org_test');
350 - yield* cli(['connections', 'remove', 'github']);
351 -
352 - expect(ambiguousDeleteCalls).toEqual([]);
353 -
354 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
355 - expect(lines.join('\n')).toContain('Multiple connections matched "github"');
356 - })
357 - );
358 - });
359 -});
ts/packages/cli/test/src/commands/connections/remove/connections.remove.cmd.test.ts new
+311
@@ -0,0 +1,311 @@
1 +import { afterEach } from 'vitest';
2 +import { describe, expect, layer } from '@effect/vitest';
3 +import { ConfigProvider, Effect } from 'effect';
4 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
5 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 +import { ComposioUserContext } from 'src/services/user-context';
7 +import { cli, TestLive, MockConsole } from 'test/__utils__';
8 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
9 +import type { TestLiveInput } from 'test/__utils__/services/test-layer';
10 +import {
11 + terminalUIWithConfirm,
12 + terminalUIWithoutPrompt,
13 +} from 'test/__utils__/services/terminal-ui-test';
14 +
15 +const testConnections: ConnectedAccountItem[] = [
16 + {
17 + id: 'con_gmail_active',
18 + alias: null,
19 + word_id: null,
20 + status: 'ACTIVE',
21 + status_reason: null,
22 + is_disabled: false,
23 + user_id: 'consumer-user-org_test',
24 + toolkit: { slug: 'gmail' },
25 + auth_config: {
26 + id: 'ac_gmail_oauth',
27 + auth_scheme: 'OAUTH2',
28 + is_composio_managed: true,
29 + is_disabled: false,
30 + },
31 + created_at: '2026-01-01T00:00:00Z',
32 + updated_at: '2026-01-15T00:00:00Z',
33 + test_request_endpoint: '',
34 + },
35 + {
36 + id: 'con_github_work',
37 + alias: 'work',
38 + word_id: 'castle',
39 + status: 'ACTIVE',
40 + status_reason: null,
41 + is_disabled: false,
42 + user_id: 'consumer-user-org_test',
43 + toolkit: { slug: 'github' },
44 + auth_config: {
45 + id: 'ac_github_oauth',
46 + auth_scheme: 'OAUTH2',
47 + is_composio_managed: true,
48 + is_disabled: false,
49 + },
50 + created_at: '2026-02-01T00:00:00Z',
51 + updated_at: '2026-02-10T00:00:00Z',
52 + test_request_endpoint: '',
53 + },
54 + {
55 + id: 'con_github_personal',
56 + alias: 'personal',
57 + word_id: 'forest',
58 + status: 'FAILED',
59 + status_reason: 'Token expired',
60 + is_disabled: false,
61 + user_id: 'consumer-user-org_test',
62 + toolkit: { slug: 'github' },
63 + auth_config: {
64 + id: 'ac_github_oauth_2',
65 + auth_scheme: 'OAUTH2',
66 + is_composio_managed: true,
67 + is_disabled: false,
68 + },
69 + created_at: '2026-02-03T00:00:00Z',
70 + updated_at: '2026-02-12T00:00:00Z',
71 + test_request_endpoint: '',
72 + },
73 +];
74 +
75 +const connectedAccountsData = {
76 + items: testConnections,
77 +} satisfies TestLiveInput['connectedAccountsData'];
78 +
79 +const testConfigProvider = ConfigProvider.fromEnv({
80 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
81 +});
82 +
83 +describe('CLI: composio connections remove', () => {
84 + afterEach(() => {
85 + process.exitCode = undefined;
86 + });
87 +
88 + const confirmedDeleteCalls: string[] = [];
89 + layer(
90 + TestLive({
91 + baseConfigProvider: testConfigProvider,
92 + connectedAccountsData: {
93 + items: testConnections,
94 + onDelete: nanoid => confirmedDeleteCalls.push(nanoid),
95 + },
96 + terminalUI: terminalUIWithConfirm(true),
97 + })
98 + )(it => {
99 + it.effect('[Given] a unique toolkit selector and consent [Then] removes that connection', () =>
100 + Effect.gen(function* () {
101 + confirmedDeleteCalls.length = 0;
102 +
103 + const userContext = yield* ComposioUserContext;
104 + yield* userContext.login('test_api_key', 'org_test');
105 + yield* cli(['connections', 'remove', 'gmail']);
106 +
107 + expect(confirmedDeleteCalls).toEqual(['con_gmail_active']);
108 +
109 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
110 + expect(lines.join('\n')).toContain('Removed gmail connection.');
111 + })
112 + );
113 + });
114 +
115 + layer(
116 + TestLive({
117 + baseConfigProvider: testConfigProvider,
118 + terminalUI: terminalUIWithConfirm(true),
119 + })
120 + )(it => {
121 + it.effect('[Given] the API rejects the removal [Then] fails naming the connected account', () =>
122 + Effect.gen(function* () {
123 + const stub = stubClientResources(
124 + ['connectedAccounts'],
125 + routeRequests(
126 + [
127 + {
128 + method: 'DELETE',
129 + path: '/api/v3.1/connected_accounts/',
130 + respond: () =>
131 + Response.json(
132 + {
133 + error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 },
134 + },
135 + { status: 403 }
136 + ),
137 + },
138 + ],
139 + () => Response.json({ items: testConnections, next_cursor: null })
140 + )
141 + );
142 + const userContext = yield* ComposioUserContext;
143 + yield* userContext.login('test_api_key', 'org_test');
144 + const failure = yield* cli(['connections', 'remove', 'gmail']).pipe(
145 + Effect.provide(stub.layer),
146 + Effect.flip
147 + );
148 +
149 + expect(failure).toMatchObject({ _tag: 'commands/ConnectionsRemovalRequestError' });
150 + expect(extractErrorDetails(failure).message).toBe(
151 + 'Failed to remove connected account "con_gmail_active".\nCaused by: 403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}'
152 + );
153 + })
154 + );
155 + });
156 +
157 + const deniedDeleteCalls: string[] = [];
158 + layer(
159 + TestLive({
160 + baseConfigProvider: testConfigProvider,
161 + connectedAccountsData: {
162 + items: testConnections,
163 + onDelete: nanoid => deniedDeleteCalls.push(nanoid),
164 + },
165 + terminalUI: terminalUIWithConfirm(false),
166 + })
167 + )(it => {
168 + it.effect('[Given] consent is denied [Then] does not remove the connection', () =>
169 + Effect.gen(function* () {
170 + deniedDeleteCalls.length = 0;
171 +
172 + const userContext = yield* ComposioUserContext;
173 + yield* userContext.login('test_api_key', 'org_test');
174 + yield* cli(['connections', 'remove', 'work']);
175 +
176 + expect(deniedDeleteCalls).toEqual([]);
177 +
178 + // Declining is not a failure: the line says nothing changed, and the exit code stays 0.
179 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
180 + expect(lines.at(-1)).toBe('No connection removed.');
181 + expect(process.exitCode).toBeUndefined();
182 + })
183 + );
184 + });
185 +
186 + const ambiguousDeleteCalls: string[] = [];
187 + layer(
188 + TestLive({
189 + baseConfigProvider: testConfigProvider,
190 + connectedAccountsData: {
191 + items: testConnections,
192 + onDelete: nanoid => ambiguousDeleteCalls.push(nanoid),
193 + },
194 + terminalUI: terminalUIWithConfirm(true),
195 + })
196 + )(it => {
197 + it.effect(
198 + '[Given] a selector matches multiple accounts [Then] asks for a unique selector',
199 + () =>
200 + Effect.gen(function* () {
201 + ambiguousDeleteCalls.length = 0;
202 +
203 + const userContext = yield* ComposioUserContext;
204 + yield* userContext.login('test_api_key', 'org_test');
205 + const failure = yield* cli(['connections', 'remove', 'github']).pipe(Effect.flip);
206 +
207 + expect(ambiguousDeleteCalls).toEqual([]);
208 + expect(failure).toMatchObject({
209 + _tag: 'commands/CommandInputError',
210 + command: 'connections remove',
211 + option: '<account>',
212 + message: expect.stringContaining('Multiple connections matched "github"'),
213 + });
214 + })
215 + );
216 +
217 + it.effect('[Given] a selector matches no account [Then] fails with a usage error', () =>
218 + Effect.gen(function* () {
219 + ambiguousDeleteCalls.length = 0;
220 +
221 + const userContext = yield* ComposioUserContext;
222 + yield* userContext.login('test_api_key', 'org_test');
223 + const failure = yield* cli(['connections', 'remove', 'nothing-matches']).pipe(Effect.flip);
224 +
225 + expect(ambiguousDeleteCalls).toEqual([]);
226 + expect(failure).toMatchObject({
227 + _tag: 'commands/CommandInputError',
228 + command: 'connections remove',
229 + option: '<account>',
230 + message:
231 + 'No connection matched "nothing-matches". Run `composio connections list` to inspect available connections.',
232 + });
233 + })
234 + );
235 + });
236 +
237 + const headlessDeleteCalls: string[] = [];
238 + layer(
239 + TestLive({
240 + baseConfigProvider: testConfigProvider,
241 + connectedAccountsData: {
242 + items: testConnections,
243 + onDelete: nanoid => headlessDeleteCalls.push(nanoid),
244 + },
245 + })
246 + )(it => {
247 + it.effect(
248 + '[Given] no terminal and no --yes [Then] fails with a usage error before any request',
249 + () =>
250 + Effect.gen(function* () {
251 + headlessDeleteCalls.length = 0;
252 +
253 + const userContext = yield* ComposioUserContext;
254 + yield* userContext.login('test_api_key', 'org_test');
255 + const failure = yield* cli(['connections', 'remove', 'gmail']).pipe(Effect.flip);
256 +
257 + // `cli-main.ts` prints the message on stderr and exits 1.
258 + expect(failure).toMatchObject({
259 + _tag: 'commands/CommandInputError',
260 + command: 'connections remove',
261 + option: '--yes',
262 + message: '`composio connections remove` needs --yes when not running interactively.',
263 + });
264 + expect(headlessDeleteCalls).toEqual([]);
265 + // Not even the connection list is fetched.
266 + expect(yield* MockConsole.getLines()).toEqual([]);
267 + })
268 + );
269 +
270 + it.effect('[Given] no terminal and --yes [Then] removes the connection without asking', () =>
271 + Effect.gen(function* () {
272 + headlessDeleteCalls.length = 0;
273 +
274 + const userContext = yield* ComposioUserContext;
275 + yield* userContext.login('test_api_key', 'org_test');
276 + // The headless test terminal answers a prompt with its default, "no", so a removal
277 + // proves no prompt ran.
278 + yield* cli(['connections', 'remove', 'gmail', '--yes']);
279 +
280 + expect(headlessDeleteCalls).toEqual(['con_gmail_active']);
281 + expect(process.exitCode).toBeUndefined();
282 + })
283 + );
284 + });
285 +
286 + const interactiveYesDeleteCalls: string[] = [];
287 + layer(
288 + TestLive({
289 + baseConfigProvider: testConfigProvider,
290 + connectedAccountsData: {
291 + items: testConnections,
292 + onDelete: nanoid => interactiveYesDeleteCalls.push(nanoid),
293 + },
294 + terminalUI: terminalUIWithoutPrompt,
295 + })
296 + )(it => {
297 + it.effect('[Given] a terminal and -y [Then] removes the connection without asking', () =>
298 + Effect.gen(function* () {
299 + interactiveYesDeleteCalls.length = 0;
300 +
301 + const userContext = yield* ComposioUserContext;
302 + yield* userContext.login('test_api_key', 'org_test');
303 + yield* cli(['connections', 'remove', 'gmail', '-y']);
304 +
305 + expect(interactiveYesDeleteCalls).toEqual(['con_gmail_active']);
306 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
307 + expect(lines.at(-1)).toBe('Removed gmail connection.');
308 + })
309 + );
310 + });
311 +});
ts/packages/cli/test/src/commands/init.cmd.test.ts
+42
@@ -1,9 +1,15 @@
1 +import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { makeOrgProject } from 'test/__utils__/models/account';
6 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7
8 describe('CLI: composio dev init', () => {
9 + afterEach(() => {
10 + process.exitCode = undefined;
11 + });
12 +
13 describe('dev init --help', () => {
14 layer(TestLive({ fixture: 'typescript-project' }))(it => {
15 it.effect('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
@@ -20,6 +26,42 @@ describe('CLI: composio dev init', () => {
26 });
27 });
28
29 + describe('dev init without a usable login', () => {
30 + layer(TestLive({ fixture: 'user-config-example' }))(it => {
31 + it.effect('[Given] an API key but no org [Then] fails with a usage error', () =>
32 + Effect.gen(function* () {
33 + const failure = yield* cli(['dev', 'init', '--yes']).pipe(Effect.flip);
34 +
35 + // `cli-main.ts` prints the message on stderr and exits 1.
36 + expect(failure).toMatchObject({
37 + _tag: 'commands/CommandInputError',
38 + command: 'dev init',
39 + message: 'No global API key or org ID found. Please try `composio login` first.',
40 + });
41 + })
42 + );
43 + });
44 + });
45 +
46 + describe('dev init in an org without projects', () => {
47 + layer(TestLive({ fixture: 'user-config-with-global-context', accountData: { projects: [] } }))(
48 + it => {
49 + it.effect('[Given] no projects [Then] says so on a redirected stderr and exits 1', () =>
50 + Effect.gen(function* () {
51 + const terminal = redirectedTerminalUI();
52 + yield* cli(['dev', 'init', '--yes']).pipe(Effect.provide(terminal.layer));
53 +
54 + expect(terminal.stderr()).toBe(
55 + 'No projects found for your organization.\nCreate a project at https://platform.composio.dev, then run `composio dev init` again.\n'
56 + );
57 + expect(terminal.stdout()).toBe('');
58 + expect(process.exitCode).toBe(1);
59 + })
60 + );
61 + }
62 + );
63 + });
64 +
65 describe('dev init with the API unreachable', () => {
66 const projectGuidance =
67 'Create a project at https://platform.composio.dev, then run `composio dev init` again.';
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+125 -1
@@ -1,8 +1,13 @@
1 +import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
3 +import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
4 +import { TestClock } from 'effect/testing';
5 import { ListenCommandError } from 'src/commands/listen.cmd';
6 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
7 +import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
8 import { cli, MockConsole, TestLive } from 'test/__utils__';
9 +import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
10 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
11
12 const testConfigProvider = ConfigProvider.fromEnv({
13 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
@@ -18,7 +23,40 @@ const enableListen = Effect.gen(function* () {
23 });
24 });
25
26 +const failingRealtime = Layer.succeed(
27 + TriggersRealtime,
28 + TriggersRealtime.of({
29 + listen: () => Effect.fail(new TriggerRealtimeSubscriptionError({ message: 'socket closed' })),
30 + listenInProject: () =>
31 + Effect.fail(new TriggerRealtimeSubscriptionError({ message: 'socket closed' })),
32 + })
33 +);
34 +
35 describe('CLI: composio listen', () => {
36 + afterEach(() => {
37 + process.exitCode = undefined;
38 + });
39 +
40 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
41 + '[Given] the realtime subscription fails',
42 + it => {
43 + it.effect('[Then] reports it on a redirected stderr and exits 1', () =>
44 + Effect.gen(function* () {
45 + yield* enableListen;
46 + const terminal = redirectedTerminalUI();
47 + yield* cli(['listen', 'composio.connected_account.expired', '--max-events', '1']).pipe(
48 + Effect.provide(Layer.merge(failingRealtime, terminal.layer))
49 + );
50 +
51 + expect(terminal.stderr()).toContain(
52 + 'Could not subscribe to realtime trigger events: socket closed. Check your network connection or run `composio login`.\n'
53 + );
54 + expect(process.exitCode).toBe(1);
55 + })
56 + );
57 + }
58 + );
59 +
60 layer(
61 TestLive({
62 baseConfigProvider: testConfigProvider,
@@ -98,6 +136,92 @@ describe('CLI: composio listen', () => {
136 );
137 });
138
139 + layer(
140 + TestLive({
141 + baseConfigProvider: testConfigProvider,
142 + fixture: 'global-test-user-id',
143 + realtimeData: {
144 + events: [
145 + {
146 + id: 'evt_conn_expired_1',
147 + type: 'composio.connected_account.expired',
148 + timestamp: '2026-04-06T18:00:00.000Z',
149 + metadata: {
150 + project_id: 'consumer_project_id_test',
151 + org_id: 'org_test',
152 + },
153 + data: {
154 + id: 'con_expired_1',
155 + },
156 + },
157 + ],
158 + },
159 + })
160 + )('[Given] event payloads that cannot be written', it => {
161 + const payloadWritesFail = failingFileWrites(path => path.endsWith('-payload.json'));
162 +
163 + // The write failure logs its warn only after it was counted, so the latch is an ordered
164 + // count-is-set signal — no polling, no sleeps.
165 + const listenUntilWriteFails = (args: ReadonlyArray<string>) =>
166 + Effect.gen(function* () {
167 + const writeFailed = Latch.makeUnsafe(false);
168 + const terminal = redirectedTerminalUI({
169 + onWarn: message => {
170 + if (message.includes('-payload.json')) writeFailed.openUnsafe();
171 + },
172 + });
173 + const fiber = yield* Effect.forkChild(
174 + cli(['listen', 'composio.connected_account.expired', ...args]).pipe(
175 + Effect.provide(Layer.merge(payloadWritesFail, terminal.layer))
176 + )
177 + );
178 + yield* writeFailed.await;
179 + return { fiber, terminal };
180 + });
181 +
182 + // A failed write still counts toward --max-events, so the bounded run stops on its own.
183 + it.effect('[Then] stops at --max-events and sums the write failures up on stderr', () =>
184 + Effect.gen(function* () {
185 + yield* enableListen;
186 + const terminal = redirectedTerminalUI();
187 + yield* cli(['listen', 'composio.connected_account.expired', '--max-events', '1']).pipe(
188 + Effect.provide(Layer.merge(payloadWritesFail, terminal.layer))
189 + );
190 +
191 + expect(terminal.stderr()).toContain('1 event failed to write while listening.');
192 + expect(process.exitCode).toBeUndefined();
193 + })
194 + );
195 +
196 + it.effect('[Then] sums the write failures up on stderr when the timeout stops it', () =>
197 + Effect.gen(function* () {
198 + yield* enableListen;
199 + const { fiber, terminal } = yield* listenUntilWriteFails(['--timeout', '1s']);
200 +
201 + yield* TestClock.adjust('1 second');
202 + yield* Fiber.join(fiber);
203 +
204 + expect(terminal.stderr()).toContain('1 event failed to write while listening.');
205 + // Recovered per-event failures, not a failed command.
206 + expect(process.exitCode).toBeUndefined();
207 + })
208 + );
209 +
210 + // Ctrl+C/SIGTERM: runMain interrupts the listener fiber; the release hook must run the
211 + // summary anyway.
212 + it.effect('[Then] sums the write failures up even when the listener is interrupted', () =>
213 + Effect.gen(function* () {
214 + yield* enableListen;
215 + const { fiber, terminal } = yield* listenUntilWriteFails([]);
216 +
217 + yield* Fiber.interrupt(fiber);
218 +
219 + expect(terminal.stderr()).toContain('1 event failed to write while listening.');
220 + expect(process.exitCode).toBeUndefined();
221 + })
222 + );
223 + });
224 +
225 layer(
226 TestLive({
227 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+58 -16
@@ -1,3 +1,4 @@
1 +import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import * as FileSystem from 'effect/FileSystem';
4 import { ConfigProvider, Effect, Option } from 'effect';
@@ -6,24 +7,19 @@ import * as constants from 'src/constants';
7 import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { UserDataWithDefaults } from 'src/models/user-data';
9 import { writeStoredAgentIdentity } from 'src/services/agents';
9 -import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { cli, TestLive, MockConsole } from 'test/__utils__';
12 -import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
13 -
14 -// The confirm prompt is only reached from an interactive terminal.
15 -const terminalUIWithConfirm = (confirmed: boolean) =>
16 - TerminalUI.of({
17 - ...terminalUITestImpl,
18 - capabilities: Effect.succeed(
19 - getTerminalCapabilities({
20 - stdin: { isTTY: true },
21 - stdout: { isTTY: true },
22 - stderr: { isTTY: true },
23 - })
24 - ),
25 - confirm: () => Effect.succeed(confirmed),
26 - });
12 +import {
13 + terminalUIWithConfirm,
14 + terminalUIWithoutPrompt,
15 +} from 'test/__utils__/services/terminal-ui-test';
16 +
17 +/** Whether `~/.composio/agent.json` still holds the agent identity. */
18 +const agentConfigExists = Effect.gen(function* () {
19 + const fs = yield* FileSystem.FileSystem;
20 + const cacheDir = yield* setupCacheDir;
21 + return yield* fs.exists(path.join(cacheDir, 'agent.json'));
22 +});
23
24 const setupLoggedInAgent = Effect.gen(function* () {
25 const ctx = yield* ComposioUserContext;
@@ -43,6 +39,10 @@ const setupLoggedInAgent = Effect.gen(function* () {
39 });
40
41 describe('CLI: composio logout', () => {
42 + afterEach(() => {
43 + process.exitCode = undefined;
44 + });
45 +
46 describe('[When] logged out', () => {
47 layer(TestLive())(it => {
48 it.effect('[Then] it is idempotent', () =>
@@ -125,12 +125,54 @@ describe('CLI: composio logout', () => {
125 expect(output).toContain('Agent Logout Warning');
126 expect(output).toContain('composio_agent_key');
127 expect(output).toContain('Agent logout cancelled');
128 + // Declining is not a failure.
129 + expect(process.exitCode).toBeUndefined();
130 expect(ctx.isLoggedIn()).toBeTruthy();
131 expect(agentConfigExists).toBe(true);
132 })
133 );
134 });
135
136 + layer(TestLive())(it => {
137 + it.effect('[Then] without a terminal and --yes it fails and removes nothing', () =>
138 + Effect.gen(function* () {
139 + const ctx = yield* setupLoggedInAgent;
140 +
141 + const failure = yield* cli(['logout']).pipe(Effect.flip);
142 +
143 + // `cli-main.ts` prints the message on stderr and exits 1.
144 + expect(failure).toMatchObject({
145 + _tag: 'commands/CommandInputError',
146 + command: 'logout',
147 + option: '--yes',
148 + message:
149 + '`composio logout` needs --yes when not running interactively: it removes the stored Composio agent key.',
150 + });
151 + expect(yield* MockConsole.getLines()).toEqual([]);
152 + expect(ctx.isLoggedIn()).toBeTruthy();
153 + expect(yield* agentConfigExists).toBe(true);
154 + })
155 + );
156 + });
157 +
158 + layer(TestLive({ terminalUI: terminalUIWithoutPrompt }))(it => {
159 + it.effect.each([['--yes'], ['-y'], ['-f']])(
160 + '[Then] %s on a terminal logs out without asking',
161 + ([flag]) =>
162 + Effect.gen(function* () {
163 + const ctx = yield* setupLoggedInAgent;
164 +
165 + yield* cli(['logout', flag]);
166 +
167 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
168 + expect(output).not.toContain('Agent Logout Warning');
169 + expect(output).toContain('removed stored Composio agent key');
170 + expect(ctx.isLoggedIn()).toBeFalsy();
171 + expect(yield* agentConfigExists).toBe(false);
172 + })
173 + );
174 + });
175 +
176 layer(TestLive())(it => {
177 it.effect('[Then] --force removes user and agent credentials', () =>
178 Effect.gen(function* () {
ts/packages/cli/test/src/commands/projects/list/projects.list.cmd.test.ts
+21 -16
@@ -115,33 +115,38 @@ describe('CLI: composio dev projects list', () => {
115 accountData: { projects: PROJECTS, onRequest: request => noOrgRequests.push(request) },
116 })
117 )('[Given] no --org-id and no current org', it => {
118 - it.effect('[Then] warns with the `orgs switch` hint and sends no request', () =>
119 - Effect.gen(function* () {
120 - yield* cli(['dev', 'projects', 'list']);
121 -
122 - const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
123 - const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
124 - expect(noOrgRequests).toEqual([]);
125 - expect(stdout).toEqual([]);
126 - expect(stderr).toEqual([
127 - '-- composio dev projects list --',
128 - 'No current org is configured.',
129 - '-- Hint: run `composio orgs switch` first, or pass `--org-id`. --',
130 - ]);
131 - })
118 + it.effect(
119 + '[Then] fails with a usage error naming the `orgs switch` hint and sends no request',
120 + () =>
121 + Effect.gen(function* () {
122 + const failure = yield* cli(['dev', 'projects', 'list']).pipe(Effect.flip);
123 +
124 + expect(failure).toMatchObject({
125 + _tag: 'commands/CommandInputError',
126 + option: '--org-id',
127 + message:
128 + 'No current org is configured.\nHint: run `composio orgs switch` first, or pass `--org-id`.',
129 + });
130 + const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
131 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
132 + expect(noOrgRequests).toEqual([]);
133 + expect(stdout).toEqual([]);
134 + expect(stderr).toEqual(['-- composio dev projects list --']);
135 + })
136 );
137 });
138
139 layer(TestLive({ fixture: LOGGED_IN_FIXTURE, accountData: { projects: [] } }))(
140 '[Given] an org without projects',
141 it => {
138 - it.effect('[Then] warns, points at `dev init`, and prints no data', () =>
142 + it.effect('[Then] warns, points at `dev init`, and prints an empty list', () =>
143 Effect.gen(function* () {
144 yield* cli(['dev', 'projects', 'list']);
145
146 const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
147 const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
144 - expect(stdout).toEqual([]);
148 + // Piped callers get the parseable empty result, not silence.
149 + expect(stdout).toEqual(['[]']);
150 expect(stderr).toEqual([
151 '-- composio dev projects list --',
152 'Loaded 0 projects',
ts/packages/cli/test/src/commands/projects/list/projects.list.handler.test.ts
+16 -6
@@ -1,8 +1,10 @@
1 import { describe, expect, it } from '@effect/vitest';
2 import { Console, Effect, Layer, Option } from 'effect';
3 import { runProjectsList } from 'src/commands/projects/list/projects.list.handler';
4 +import { isUsageFailure } from 'src/commands/errors';
5 import {
6 NO_CURRENT_ORG_MESSAGE,
7 + NO_CURRENT_ORG_OUTRO,
8 NO_PROJECTS_MESSAGE,
9 } from 'src/commands/projects/list/projects.list.format';
10 import type { OrgProject } from 'src/services/composio-account';
@@ -113,14 +115,21 @@ describe('runProjectsList', () => {
115 { orgId: Option.none<string>(), current: Option.none<string>(), label: 'no org at all' },
116 { orgId: Option.some(''), current: Option.some('org_current'), label: 'an empty --org-id' },
117 { orgId: Option.none<string>(), current: Option.some(''), label: 'an empty current org' },
116 - ])('[Given] $label [Then] warns and sends no request', ({ orgId, current }) => {
118 + ])('[Given] $label [Then] fails with a usage error before any request', ({ orgId, current }) => {
119 const { layer, outputs, requests } = projectsListTest({ orgId: current });
120 return Effect.gen(function* () {
119 - yield* runProjectsList({ orgId, limit: 50 });
120 -
121 + const failure = yield* runProjectsList({ orgId, limit: 50 }).pipe(Effect.flip);
122 +
123 + expect(failure).toMatchObject({
124 + _tag: 'commands/CommandInputError',
125 + command: 'dev projects list',
126 + option: '--org-id',
127 + message: `${NO_CURRENT_ORG_MESSAGE}\n${NO_CURRENT_ORG_OUTRO}`,
128 + });
129 + // `cli-main.ts` prints a usage failure on stderr and exits 1.
130 + expect(isUsageFailure(failure)).toBe(true);
131 expect(requests).toEqual([]);
132 expect(outputs).toEqual([]);
123 - expect(yield* MockConsole.getLines({ stream: 'stderr' })).toContain(NO_CURRENT_ORG_MESSAGE);
133 }).pipe(Effect.provide(layer));
134 });
135
@@ -138,12 +147,13 @@ describe('runProjectsList', () => {
147 }).pipe(Effect.provide(layer));
148 });
149
141 - it.effect('[Given] no projects [Then] warns and outputs nothing', () => {
150 + it.effect('[Given] no projects [Then] warns and prints an empty list', () => {
151 const { layer, outputs } = projectsListTest({ projects: [] });
152 return Effect.gen(function* () {
153 yield* runProjectsList({ orgId: Option.none(), limit: 50 });
154
146 - expect(outputs).toEqual([]);
155 + // Piped callers get the parseable empty result, not silence.
156 + expect(outputs).toEqual(['[]']);
157 expect(yield* MockConsole.getLines({ stream: 'stderr' })).toEqual([NO_PROJECTS_MESSAGE]);
158 }).pipe(Effect.provide(layer));
159 });
ts/packages/cli/test/src/commands/request-failures.client.test.ts
+2 -1
@@ -79,7 +79,8 @@ const rejectedRequests: ReadonlyArray<{
79 },
80 {
81 command: 'connections remove',
82 - args: ['connections', 'remove', 'gmail'],
82 + // Without a terminal, removing needs --yes before any request is sent.
83 + args: ['connections', 'remove', 'gmail', '--yes'],
84 resources: ['connectedAccounts'],
85 tag: 'commands/ConnectionsRemovalRequestError',
86 message: 'Failed to list connections.',
ts/packages/cli/test/src/commands/toolkits/info/toolkits.info.cmd.test.ts
+53 -14
@@ -1,6 +1,9 @@
1 +import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, DateTime, Effect } from 'effect';
3 +import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
6 +import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
7 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
8 import type { Toolkits, ToolkitDetailed } from 'src/models/toolkits';
9
@@ -129,6 +132,10 @@ const testConfigProvider = ConfigProvider.fromEnv({
132 });
133
134 describe('CLI: composio dev toolkits info', () => {
135 + afterEach(() => {
136 + process.exitCode = undefined;
137 + });
138 +
139 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
140 '[Given] valid slug "gmail"',
141 it => {
@@ -215,13 +222,14 @@ describe('CLI: composio dev toolkits info', () => {
222 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
223 '[Given] invalid slug',
224 it => {
218 - it.effect('shows error', () =>
225 + it.effect('prints the error on a redirected stderr and exits 1', () =>
226 Effect.gen(function* () {
220 - yield* cli(['dev', 'toolkits', 'info', 'gmal']).pipe(Effect.result);
221 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
222 - const output = lines.join('\n');
227 + const terminal = redirectedTerminalUI();
228 + yield* cli(['dev', 'toolkits', 'info', 'gmal']).pipe(Effect.provide(terminal.layer));
229
224 - expect(output).toContain('Toolkit "gmal" not found');
230 + expect(terminal.stderr()).toContain('Toolkit "gmal" not found.\n');
231 + expect(terminal.stdout()).toBe('');
232 + expect(process.exitCode).toBe(1);
233 })
234 );
235 }
@@ -230,14 +238,15 @@ describe('CLI: composio dev toolkits info', () => {
238 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
239 '[Given] invalid slug with substring match',
240 it => {
233 - it.effect('shows error with hint', () =>
241 + it.effect('shows error with hint and exits 1', () =>
242 Effect.gen(function* () {
235 - yield* cli(['dev', 'toolkits', 'info', 'gma']).pipe(Effect.result);
243 + yield* cli(['dev', 'toolkits', 'info', 'gma']);
244 const lines = yield* MockConsole.getLines({ stripAnsi: true });
245 const output = lines.join('\n');
246
247 expect(output).toContain('Toolkit "gma" not found');
248 expect(output).toContain('composio dev toolkits info "gmail"');
249 + expect(process.exitCode).toBe(1);
250 })
251 );
252 }
@@ -246,14 +255,18 @@ describe('CLI: composio dev toolkits info', () => {
255 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
256 '[Given] no slug argument',
257 it => {
249 - it.effect('shows missing argument warning with tip', () =>
258 + it.effect('fails with a usage error naming <slug>, with a tip', () =>
259 Effect.gen(function* () {
251 - yield* cli(['dev', 'toolkits', 'info']);
252 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
253 - const output = lines.join('\n');
260 + const failure = yield* cli(['dev', 'toolkits', 'info']).pipe(Effect.flip);
261
255 - expect(output).toContain('Missing required argument');
256 - expect(output).toContain('composio dev toolkits info "gmail"');
262 + expect(failure).toMatchObject({
263 + _tag: 'commands/CommandInputError',
264 + command: 'dev toolkits info',
265 + option: '<slug>',
266 + message:
267 + 'Missing required argument: <slug>\nTry specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"',
268 + });
269 + expect(yield* MockConsole.getLines()).toEqual([]);
270 })
271 );
272 }
@@ -267,4 +280,30 @@ describe('CLI: composio dev toolkits info', () => {
280 })
281 );
282 });
283 +
284 + layer(
285 + TestLive({
286 + baseConfigProvider: testConfigProvider,
287 + toolkitsData,
288 + fixture: 'global-test-user-id',
289 + })
290 + )('[Given] the tool-router fetch fails', it => {
291 + it.effect('reports the failure on a redirected stderr and exits 1', () =>
292 + Effect.gen(function* () {
293 + const stub = stubClientResources(['toolRouter'], () =>
294 + Response.json({ error: { message: 'Tool Router is down' } }, { status: 500 })
295 + );
296 + const terminal = redirectedTerminalUI();
297 + yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(
298 + Effect.provide(Layer.mergeAll(stub.layer, terminal.layer))
299 + );
300 +
301 + expect(terminal.stderr()).toBe(
302 + 'Tool Router is down\nBrowse available toolkits:\n> composio dev toolkits list\n'
303 + );
304 + expect(terminal.stdout()).toBe('');
305 + expect(process.exitCode).toBe(1);
306 + })
307 + );
308 + });
309 });
ts/packages/cli/test/src/commands/toolkits/list/toolkits.list.cmd.test.ts
+6 -5
@@ -6,6 +6,7 @@ import type { Toolkits } from 'src/models/toolkits';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { notFoundError } from 'test/__utils__/layers/not-found';
8 import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
9 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
10 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
11 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
12
@@ -362,14 +363,14 @@ describe('CLI: composio dev toolkits list', () => {
363 searchToolkits: () => Effect.fail(notFoundError('Catalog unavailable')),
364 })
365 );
366 + // Redirected streams, as under a script: only plain stderr lines and stdout data show.
367 + const terminal = redirectedTerminalUI();
368 yield* cli(['dev', 'toolkits', 'list']).pipe(
366 - Effect.provide(Layer.merge(repository, proc.layer))
369 + Effect.provide(Layer.mergeAll(repository, proc.layer, terminal.layer))
370 );
368 - const stderr = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' });
369 - const stdout = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' });
371
371 - expect(stderr).toContain('Catalog unavailable');
372 - expect(stdout).toEqual(['[]']);
372 + expect(terminal.stderr()).toBe('Catalog unavailable\n');
373 + expect(terminal.stdout()).toBe('[]\n');
374 expect(proc.exitCode()).toBe(1);
375 })
376 );
ts/packages/cli/test/src/commands/toolkits/search/toolkits.search.cmd.test.ts
+6 -5
@@ -6,6 +6,7 @@ import type { Toolkits } from 'src/models/toolkits';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { notFoundError } from 'test/__utils__/layers/not-found';
8 import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
9 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
10 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
11
12 const testToolkits: Toolkits = [
@@ -153,14 +154,14 @@ describe('CLI: composio dev toolkits search', () => {
154 searchToolkits: () => Effect.fail(notFoundError('Search unavailable')),
155 })
156 );
157 + // Redirected streams, as under a script: only plain stderr lines and stdout data show.
158 + const terminal = redirectedTerminalUI();
159 yield* cli(['dev', 'toolkits', 'search', 'email']).pipe(
157 - Effect.provide(Layer.merge(repository, proc.layer))
160 + Effect.provide(Layer.mergeAll(repository, proc.layer, terminal.layer))
161 );
159 - const stderr = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' });
160 - const stdout = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' });
162
162 - expect(stderr).toContain('Search unavailable');
163 - expect(stdout).toEqual(['[]']);
163 + expect(terminal.stderr()).toBe('Search unavailable\n');
164 + expect(terminal.stdout()).toBe('[]\n');
165 expect(proc.exitCode()).toBe(1);
166 })
167 );
ts/packages/cli/test/src/commands/toolkits/version/toolkits.version.cmd.test.ts
+17 -6
@@ -1,6 +1,8 @@
1 +import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, DateTime, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 import type { Toolkits, ToolkitDetailed } from 'src/models/toolkits';
8
@@ -59,6 +61,10 @@ const testConfigProvider = ConfigProvider.fromEnv({
61 });
62
63 describe('CLI: composio dev toolkits version', () => {
64 + afterEach(() => {
65 + process.exitCode = undefined;
66 + });
67 +
68 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
69 '[Given] valid slug [Then] shows latest and last 20 versions',
70 it => {
@@ -85,14 +91,19 @@ describe('CLI: composio dev toolkits version', () => {
91 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
92 '[Given] invalid slug [Then] shows error and hint',
93 it => {
88 - it.effect('prints fetch failure and browse hint', () =>
94 + it.effect('prints fetch failure and browse hint on a redirected stderr and exits 1', () =>
95 Effect.gen(function* () {
90 - yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.result);
91 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
92 - const output = lines.join('\n');
96 + const terminal = redirectedTerminalUI();
97 + yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(
98 + Effect.provide(terminal.layer)
99 + );
100
94 - expect(output).toContain('Toolkit "unknown" not found');
95 - expect(output).toContain('composio dev toolkits list');
101 + expect(terminal.stderr()).toContain('Toolkit "unknown" not found');
102 + expect(terminal.stderr()).toContain(
103 + 'Browse available toolkits:\n> composio dev toolkits list\n'
104 + );
105 + expect(terminal.stdout()).toBe('');
106 + expect(process.exitCode).toBe(1);
107 })
108 );
109 }
ts/packages/cli/test/src/commands/triggers/disable/triggers.disable.cmd.test.ts
+15 -6
@@ -28,14 +28,23 @@ describe('CLI: composio dev triggers disable', () => {
28 });
29
30 layer(TestLive(dangerousDevConfig))(
31 - '[Given] missing ID for disable [Then] warns about missing argument',
31 + '[Given] missing ID for disable [Then] fails with a usage error',
32 it => {
33 - it.effect('shows missing id warning', () =>
33 + it.effect('raises a CommandInputError naming <id>', () =>
34 Effect.gen(function* () {
35 - yield* cli(['dev', 'triggers', 'disable', '--dangerously-allow']);
36 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
37 - const output = lines.join('\n');
38 - expect(output).toContain('Missing required argument');
35 + const failure = yield* cli(['dev', 'triggers', 'disable', '--dangerously-allow']).pipe(
36 + Effect.flip
37 + );
38 +
39 + expect(failure).toMatchObject({
40 + _tag: 'commands/CommandInputError',
41 + command: 'dev triggers disable',
42 + option: '<id>',
43 + message: expect.stringMatching(
44 + /^Missing required argument: <id>\nTry specifying a trigger ID, e\.g\.:\n> composio dev triggers disable "trg_123"/
45 + ),
46 + });
47 + expect(yield* MockConsole.getLines()).toEqual([]);
48 })
49 );
50 }
ts/packages/cli/test/src/commands/triggers/info/triggers.info.cmd.test.ts
+24 -9
@@ -99,15 +99,32 @@ describe('CLI: composio dev triggers info', () => {
99 );
100
101 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
102 - '[Given] no slug [Then] warns missing argument',
102 + '[Given] no slug [Then] fails with a usage error',
103 it => {
104 - it.effect('shows missing argument warning', () =>
104 + it.effect('raises a CommandInputError naming <slug>', () =>
105 Effect.gen(function* () {
106 - yield* cli(['dev', 'triggers', 'info']);
107 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
108 - const output = lines.join('\n');
106 + const failure = yield* cli(['dev', 'triggers', 'info']).pipe(Effect.flip);
107
110 - expect(output).toContain('Missing required argument');
108 + expect(failure).toMatchObject({
109 + _tag: 'commands/CommandInputError',
110 + command: 'dev triggers info',
111 + option: '<slug>',
112 + message:
113 + 'Missing required argument: <slug>\nTry specifying a trigger slug, e.g.:\n> composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"',
114 + });
115 + expect(yield* MockConsole.getLines()).toEqual([]);
116 + })
117 + );
118 +
119 + it.effect('names the root command on the root tree', () =>
120 + Effect.gen(function* () {
121 + const failure = yield* cli(['triggers', 'info']).pipe(Effect.flip);
122 +
123 + expect(failure).toMatchObject({
124 + _tag: 'commands/CommandInputError',
125 + command: 'triggers info',
126 + message: expect.stringContaining('> composio triggers info "GMAIL_NEW_GMAIL_MESSAGE"'),
127 + });
128 })
129 );
130 }
@@ -124,12 +141,10 @@ describe('CLI: composio dev triggers info', () => {
141
142 expect(output).toContain('not found');
143 expect(output).toContain('composio dev triggers list "<toolkit>"');
127 - // Once plainly for a captured stderr, once through the decorated log.
144 + // One plain stderr emission: the message, then the hint.
145 expect(lines).toEqual([
146 'Trigger "NONEXISTENT_TRIGGER" not found.',
147 'Browse available trigger types:\n> composio dev triggers list "<toolkit>"',
131 - 'Trigger "NONEXISTENT_TRIGGER" not found.',
132 - 'Browse available trigger types:\n> composio dev triggers list "<toolkit>"',
148 ]);
149 expect(process.exitCode).toBe(1);
150 })
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts new
+150
@@ -0,0 +1,150 @@
1 +import { afterEach } from 'vitest';
2 +import { describe, expect, layer } from '@effect/vitest';
3 +import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
4 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
5 +import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
6 +import { cli, TestLive } from 'test/__utils__';
7 +import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
8 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
9 +
10 +const testConfigProvider = ConfigProvider.fromEnv({
11 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
12 +});
13 +
14 +const enableListen = Effect.gen(function* () {
15 + const config = yield* ComposioCliUserConfig;
16 + yield* config.update({
17 + experimentalFeatures: {
18 + ...config.raw.experimentalFeatures,
19 + listen: true,
20 + },
21 + });
22 +});
23 +
24 +const failingRealtime = Layer.succeed(
25 + TriggersRealtime,
26 + TriggersRealtime.of({
27 + listen: () => Effect.fail(new TriggerRealtimeSubscriptionError({ message: 'socket closed' })),
28 + listenInProject: () =>
29 + Effect.fail(new TriggerRealtimeSubscriptionError({ message: 'socket closed' })),
30 + })
31 +);
32 +
33 +describe('CLI: composio dev listen', () => {
34 + afterEach(() => {
35 + process.exitCode = undefined;
36 + });
37 +
38 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
39 + '[Given] the realtime subscription fails',
40 + it => {
41 + it.effect('[Then] reports it on a redirected stderr and exits 1', () =>
42 + Effect.gen(function* () {
43 + yield* enableListen;
44 + const terminal = redirectedTerminalUI();
45 + yield* cli(['dev', 'listen', '--max-events', '1']).pipe(
46 + Effect.provide(Layer.merge(failingRealtime, terminal.layer))
47 + );
48 +
49 + expect(terminal.stderr()).toContain(
50 + 'Could not subscribe to realtime trigger events: socket closed. Check your network connection or run `composio login`.\n'
51 + );
52 + expect(process.exitCode).toBe(1);
53 + })
54 + );
55 + }
56 + );
57 +
58 + layer(
59 + TestLive({
60 + baseConfigProvider: testConfigProvider,
61 + fixture: 'global-test-user-id',
62 + realtimeData: {
63 + events: [
64 + {
65 + id: 'evt_conn_expired_1',
66 + type: 'composio.connected_account.expired',
67 + timestamp: '2026-04-06T18:00:00.000Z',
68 + metadata: {
69 + project_id: 'consumer_project_id_test',
70 + org_id: 'org_test',
71 + },
72 + data: {
73 + id: 'con_expired_1',
74 + },
75 + },
76 + ],
77 + },
78 + })
79 + )('[Given] a forwarding target that refuses events', it => {
80 + it.effect('[Then] sums the forwarding failures up on stderr when the listener stops', () =>
81 + Effect.gen(function* () {
82 + yield* enableListen;
83 + const terminal = redirectedTerminalUI();
84 + yield* cli([
85 + 'dev',
86 + 'listen',
87 + '--forward',
88 + 'http://127.0.0.1:9/composio',
89 + '--max-events',
90 + '1',
91 + ]).pipe(Effect.provide(terminal.layer));
92 +
93 + expect(terminal.stderr()).toContain(
94 + '1 event failed to forward to http://127.0.0.1:9/composio while listening.'
95 + );
96 + // Recovered per-event failures, not a failed command.
97 + expect(process.exitCode).toBeUndefined();
98 + })
99 + );
100 +
101 + it.effect('[Then] sums the output-file failures up on stderr when the listener stops', () =>
102 + Effect.gen(function* () {
103 + yield* enableListen;
104 + const outFile = '/tmp/composio-dev-listen-test-out.jsonl';
105 + const terminal = redirectedTerminalUI();
106 + yield* cli(['dev', 'listen', '--out', outFile, '--max-events', '1']).pipe(
107 + Effect.provide(
108 + Layer.merge(
109 + failingFileWrites(path => path === outFile),
110 + terminal.layer
111 + )
112 + )
113 + );
114 +
115 + expect(terminal.stderr()).toContain(
116 + `1 event failed to append to ${outFile} while listening.`
117 + );
118 + // Recovered per-event failures, not a failed command.
119 + expect(process.exitCode).toBeUndefined();
120 + })
121 + );
122 +
123 + // Ctrl+C/SIGTERM: runMain interrupts the listener fiber; the onExit finalizer must run the
124 + // summary anyway. The forwarding failure logs its warn only after the failure was counted,
125 + // so awaiting the latch is an ordered count-is-set signal — no polling, no sleeps.
126 + it.effect('[Then] sums the failures up even when the listener is interrupted mid-run', () =>
127 + Effect.gen(function* () {
128 + yield* enableListen;
129 + const forwardFailed = Latch.makeUnsafe(false);
130 + const terminal = redirectedTerminalUI({
131 + onWarn: message => {
132 + if (message.includes('Failed forwarding event to')) forwardFailed.openUnsafe();
133 + },
134 + });
135 + const fiber = yield* Effect.forkChild(
136 + cli(['dev', 'listen', '--forward', 'http://']).pipe(Effect.provide(terminal.layer))
137 + );
138 +
139 + yield* forwardFailed.await;
140 + yield* Fiber.interrupt(fiber);
141 +
142 + expect(terminal.stderr()).toContain(
143 + '1 event failed to forward to http:// while listening.'
144 + );
145 + // Recovered per-event failures, not a failed command.
146 + expect(process.exitCode).toBeUndefined();
147 + })
148 + );
149 + });
150 +});
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+15
@@ -4,6 +4,21 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
4 import { makeSessionInfo } from 'test/__utils__/models/account';
5
6 describe('CLI: composio whoami', () => {
7 + layer(TestLive())('without a login', it => {
8 + it.effect('[Given] no API key [Then] fails with NotLoggedInError and prints nothing', () =>
9 + Effect.gen(function* () {
10 + const failure = yield* cli(['whoami']).pipe(Effect.flip);
11 +
12 + // `cli-main.ts` prints the message on stderr and exits 1.
13 + expect(failure).toMatchObject({
14 + _tag: 'commands/NotLoggedInError',
15 + message: 'You are not logged in yet. Please run `composio login`.',
16 + });
17 + expect(yield* MockConsole.getLines()).toEqual([]);
18 + })
19 + );
20 + });
21 +
22 const testConfigProvider = ConfigProvider.fromEnv({
23 env: { COMPOSIO_USER_API_KEY: 'api_key_from_test_config_provider' },
24 });
ts/packages/cli/test/src/effects/handle-http-error.test.ts
+2 -9
@@ -81,10 +81,7 @@ describe('handleClientApiError', () => {
81 expect(result).toBe('fallback');
82 expect(lines).toStrictEqual([
83 'stderr: Auth config "ac_missing" was not found',
84 - 'stderr: Browse available auth configs:\n> composio dev auth-configs list',
85 - 'log.error: Auth config "ac_missing" was not found',
86 - 'log.step: Check the auth config id',
87 - 'log.step: Browse available auth configs:\n> composio dev auth-configs list',
84 + 'stderr: Check the auth config id\n\nBrowse available auth configs:\n> composio dev auth-configs list',
85 ]);
86 expect(exitCode()).toBe(1);
87 })
@@ -109,8 +106,6 @@ describe('handleClientApiError', () => {
106 expect(lines).toStrictEqual([
107 'stderr: Failed to fetch auth config "ac_missing".',
108 'stderr: Browse available auth configs:\n> composio dev auth-configs list',
112 - 'log.error: Failed to fetch auth config "ac_missing".',
113 - 'log.step: Browse available auth configs:\n> composio dev auth-configs list',
109 ]);
110 expect(exitCode()).toBe(1);
111 })
@@ -130,8 +125,6 @@ describe('handleClientApiError', () => {
125 expect(lines).toStrictEqual([
126 "stderr: The API response for 'authConfigs.retrieve' is not in the shape this version of the CLI expects (request id: req_decode).",
127 'stderr: Upgrade the CLI, then retry:\n> composio upgrade',
133 - "log.error: The API response for 'authConfigs.retrieve' is not in the shape this version of the CLI expects (request id: req_decode).",
134 - 'log.step: Upgrade the CLI, then retry:\n> composio upgrade',
128 ]);
129 expect(exitCode()).toBe(1);
130 })
@@ -150,7 +143,7 @@ describe('handleClientApiError', () => {
143 })(clientStatusError).pipe(provide);
144
145 expect(lines.at(-1)).toBe(
153 - 'log.step: Did you mean?\n ac_similar\n\n> composio dev auth-configs info "ac_similar"'
146 + 'stderr: Check the auth config id\n\nDid you mean?\n ac_similar\n\n> composio dev auth-configs info "ac_similar"'
147 );
148 })
149 );
ts/packages/cli/test/src/effects/report-failure.test.ts new
+77
@@ -0,0 +1,77 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { reportFailure } from 'src/effects/report-failure';
4 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
5 +import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
6 +import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
8 +
9 +// A TerminalUI whose stderr is a TTY, recording every line with the channel it went to.
10 +const decoratingUI = () => {
11 + const lines: Array<string> = [];
12 + const record = (channel: string) => (message: string) =>
13 + Effect.sync(() => {
14 + lines.push(`${channel}: ${message}`);
15 + });
16 + const ui = TerminalUI.of({
17 + ...terminalUITestImpl,
18 + capabilities: Effect.succeed(
19 + getTerminalCapabilities({
20 + stdin: { isTTY: true },
21 + stdout: { isTTY: true },
22 + stderr: { isTTY: true },
23 + })
24 + ),
25 + error: record('stderr'),
26 + log: { ...terminalUITestImpl.log, error: record('log.error'), step: record('log.step') },
27 + });
28 + return { ui, lines };
29 +};
30 +
31 +describe('reportFailure', () => {
32 + it.effect(
33 + '[Given] a redirected stderr [Then] prints the message and hint plainly and exits 1',
34 + () => {
35 + const terminal = redirectedTerminalUI();
36 + const proc = recordingNodeProcess();
37 + return Effect.gen(function* () {
38 + const ui = yield* TerminalUI;
39 +
40 + yield* reportFailure(ui, 'Failed to fetch toolkit "gmail".', 'Browse available toolkits');
41 +
42 + expect(terminal.stderr()).toBe(
43 + 'Failed to fetch toolkit "gmail".\nBrowse available toolkits\n'
44 + );
45 + expect(terminal.stdout()).toBe('');
46 + expect(proc.exitCode()).toBe(1);
47 + }).pipe(Effect.provide(terminal.layer), Effect.provide(proc.layer));
48 + }
49 + );
50 +
51 + it.effect('[Given] no hint [Then] prints only the message', () => {
52 + const terminal = redirectedTerminalUI();
53 + const proc = recordingNodeProcess();
54 + return Effect.gen(function* () {
55 + const ui = yield* TerminalUI;
56 +
57 + yield* reportFailure(ui, 'The link response is incomplete.');
58 +
59 + expect(terminal.stderr()).toBe('The link response is incomplete.\n');
60 + expect(proc.exitCode()).toBe(1);
61 + }).pipe(Effect.provide(terminal.layer), Effect.provide(proc.layer));
62 + });
63 +
64 + it.effect('[Given] a terminal [Then] renders a decorated error and step, once', () => {
65 + const { ui, lines } = decoratingUI();
66 + const proc = recordingNodeProcess();
67 + return Effect.gen(function* () {
68 + yield* reportFailure(ui, 'Failed to fetch toolkit "gmail".', 'Browse available toolkits');
69 +
70 + expect(lines).toEqual([
71 + 'log.error: Failed to fetch toolkit "gmail".',
72 + 'log.step: Browse available toolkits',
73 + ]);
74 + expect(proc.exitCode()).toBe(1);
75 + }).pipe(Effect.provide(proc.layer));
76 + });
77 +});
ts/packages/cli/test/src/services/composio-clients.test.ts
+6 -2
@@ -578,10 +578,12 @@ describe('composio-clients', () => {
578 expect(error).toMatchObject({ details: { message: 'Bad input', code: 1001 } });
579 assert(isClientApiError(error));
580
581 + const plain: string[] = [];
582 const errors: string[] = [];
583 const steps: string[] = [];
584 const ui = TerminalUI.of({
585 ...terminalUITestImpl,
586 + error: message => Effect.sync(() => void plain.push(message)),
587 log: {
588 ...terminalUITestImpl.log,
589 error: message => Effect.sync(() => void errors.push(message)),
@@ -595,8 +597,10 @@ describe('composio-clients', () => {
597 fallbackValue: undefined,
598 })(error).pipe(Effect.provide(proc.layer));
599
598 - expect(errors).toEqual(['Bad input']);
599 - expect(steps).toEqual(['hint']);
600 + // On a non-TTY the failure is two plain stderr lines: the message, then the hint.
601 + expect(plain).toEqual(['Bad input', 'hint']);
602 + expect(errors).toEqual([]);
603 + expect(steps).toEqual([]);
604 expect(proc.exitCode()).toBe(1);
605 }).pipe(Effect.provide(withRepository))
606 );