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

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

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

Synced Nov 21, 07:15 UTC

feat(cli): apply one acting-user rule across commands (#5130)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5127 (base of this PR); no Linear issue exists for it - makes `dev connected-accounts link <toolkit>` and `link --list` act on the developer project (directory or `--project-name`) as `--user-id` → directory test user → global test user. They used to act as the consumer user and silently ignore `--user-id`. The Tool Router link gains the directory step, and with `--auth-config` a missing project is reported before a missing user. `composio link` is unchanged (Minor in CHANGELOG) - treats an empty `consumer_user_id` as no user everywhere: `execute`, `search` and `link` now fail with the missing-user error, and `run` starts the script without the consumer user's context - gives each tree one missing-user message: root says to run `composio login` (root `execute`/`search`/`link` no longer say "Provide --user-id"), and dev points at `--user-id` / `composio dev init` - has `actingUser` / `actingUserOption` print the fallback notice (`Using [global ]test user id "…"`) whenever a test user stands in. This now includes `dev playground-execute`, which printed nothing before; `--parallel` resolves the user once, so the notice prints once - retires `MissingLinkUserIdError`, `MissingConnectionsConsumerUserIdError`, `MissingConnectionRemovalConsumerUserIdError`, `ProxyCommandError`, `ToolExecutionError`'s `missing_user_id` reason, search's `CommandInputError` and listen's `project_context` reason in favour of `MissingActingUserError` - telemetry: `error_name` for missing-user failures becomes `commands/MissingActingUserError`. The `missing_user_id` reason was an internal field and was never emitted, so no emitted failure reason changes - `connections list` / `remove` and `listen` printed a `💥` defect banner here before; they now print the message and exit 1 - deletes `resolveToolkitsListUser` and the whole `ActingUserOptions` interface (`legacy`, `missingUserMessage`), so both functions take no arguments; updates `AGENTS.md`, `GLOSSARY.md`, `README.md` and the `dev` `--user-id` help Tests that encoded the old behaviour changed only where intended: the dev `link --list` command test (it now lists the global test user's accounts on the developer project), the handler flow-selection test (dev tool-router `project_type` is now `DEVELOPER`), the `MissingLinkUserIdError` tags and the legacy message in the link handler tests, the empty-consumer-id and legacy-option cases in `surface.acting-user.test.ts`, the `proxy` row in `cli-main.test.ts`, `errors.test.ts`, the `--user-id` help string, and the base branch's call-site tests: their missing-user cases for `connections list` / `remove`, `listen`, `execute` (both trees), `search` and the Tool Router link now expect `MissingActingUserError`, and their empty-consumer-id cases for `execute`, `search` and the Tool Router link now expect rejection instead of acceptance. New coverage: spawned-CLI rows for the missing user on `execute`, `search`, `link`, `connections list` / `remove` and `listen`; notice-once checks for `playground-execute` (also `--parallel`) and dev `link`; dev link handler cases; the `error_name` telemetry. Verified with `pnpm typecheck`, `pnpm --filter @composio/cli run lint:effect` (0 errors), `pnpm --filter @composio/cli test` (210 files, 2514 passed, 1 skipped) and `./node_modules/.bin/oxlint ts/packages/cli` (no errors). --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 12:19 UTC 87c11a197085db9aed3ce1348cbd743e3da88da7
32 files changed +606 -675
ts/packages/cli/AGENTS.md
+1 -1
@@ -87,7 +87,7 @@ Rules:
87 - `<group>.<name>.cmd.ts` declares the surface and nothing else: flag and argument constants, `Command.withDescription`, `Command.withExamples`, and the three-argument `Command.make(name, flags, handler)` with the handler imported from the sibling `.handler.ts`. It yields no service and contains no branching. `Command.withHandler` is reserved for `src/commands/index.ts`, where the root handler is attached at assembly time.
88 - `<group>.<name>.handler.ts` exports the handler as a function of a plain params type it declares itself; the command proves it provides those params when it passes the handler to `Command.make`. Do not derive the params type from the `Command` value (no phantom commands, no `GetCmdParams`).
89 - A command that exists in both the root tree and the `dev` tree is defined once. The group supplies what differs between the two surfaces through `Command.withSharedFlags` and `Command.provide`, not through a second `Command.make` with a copied description. `--user-id` and `--project-name` are shared flags of the `dev` group (`dev.cmd.ts`), accepted before or after the subcommand name and documented once on every `dev` page; a handler reads them, and the tree it runs in, from `CommandSurface` (`surface.ts`) and never declares either flag itself, since `withSharedFlags` rejects a duplicate on a direct subcommand. A `dev` command that cannot honor one of them yet (it cannot target another project, or it does not act for a user) pipes `rejectsSharedFlags` (`surface.ts`), and the `dev` group's own `--mode` toggle calls `rejectSharedFlags`, so the flag fails with a `CommandInputError` instead of being ignored. `execute` and `playground-execute` keep two registrations because their names differ; they share one handler.
90 -- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`) or `actingUserOption` (for a command that also runs without one) in `surface.ts`; it never reads `--user-id` or a test user id to resolve one itself. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
90 +- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `actingUserOption` (for a command that also runs without one) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
91 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
92 - A command that needs a logged-in user pipes `requireLogin` (`src/effects/require-auth.ts`) on itself or on its group entry, after `Command.withSubcommands`. Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`.
93 - A group entry is recognised by its place in the tree: `<dir>/<dir>.cmd.ts` or `<dir>/root-<dir>.cmd.ts` with other `.cmd.ts` files below `<dir>/`. The same name with nothing below it (`logout/logout.cmd.ts`) is a top-level command. Every command needs a test; a group entry does not, though one with a default action (`generate`) still gets one.
ts/packages/cli/CHANGELOG.md
+49
@@ -4,6 +4,20 @@
4
5 ### Minor Changes
6
7 +- `composio dev connected-accounts link <toolkit>` (with or without `--list`)
8 + now acts on your developer project, like the other `composio dev` commands:
9 + the directory's project, or the one `--project-name` names. It links or lists
10 + accounts for `--user-id` when given, else the directory's test user id (for
11 + the directory's own project), else the global test user id. Without
12 + `--project-name` it used to act as your consumer user on your consumer
13 + project and silently ignore `--user-id`; outside a directory set up with
14 + `composio dev init` it now fails asking for one. With `--project-name`,
15 + linking a toolkit now also uses the directory's test user when the name is
16 + the directory's own project. `composio link` is unchanged. With
17 + `--auth-config`, a missing developer project is now reported before a
18 + missing user id. On the dev tree, the alias hints point at
19 + `composio dev playground-execute` and `composio dev connected-accounts list`.
20 +
21 - `composio listen`, `composio dev listen` and `composio dev triggers listen`
22 gain `--fail-fast`: the listener stops at the first event it fails to save,
23 forward, or append to `--out`, prints how many events failed on stderr, and
@@ -19,6 +33,41 @@
33
34 ### Patch Changes
35
36 +- `composio connections list`, `composio connections remove`, and
37 + `composio listen` without a consumer user now print the message on stderr
38 + and exit 1, like other expected errors. They used to print it under a `💥`
39 + banner with the error tag and a stack location. Telemetry: every missing-user
40 + failure now reports `error_name` `commands/MissingActingUserError` in
41 + `cli.command.failed` and the command-family failure events, replacing
42 + `ToolExecutionError` (execute), `commands/CommandInputError` (search),
43 + `commands/MissingLinkUserIdError` (link),
44 + `commands/MissingConnectionsConsumerUserIdError` (connections list),
45 + `commands/MissingConnectionRemovalConsumerUserIdError` (connections remove),
46 + `commands/ListenCommandError` (listen), and `commands/ProxyCommandError`
47 + (proxy). Other failures of those commands keep their names.
48 +
49 +- Every `composio dev` command that acts as a user now names the test user it
50 + falls back to on stderr (`Using test user id "…"` for the directory's,
51 + `Using global test user id "…"` for the global one) when you pass no
52 + `--user-id`. `composio dev playground-execute` printed nothing before; with
53 + `--parallel` it names the user once.
54 +
55 +- A missing user id now gets the same message on every command of a tree.
56 + Root commands (`composio execute`, `search`, `link`, `listen`, `proxy`,
57 + `connections`) report a missing consumer user id and point at
58 + `composio login`; root `execute`, `search`, and `link` no longer tell you to
59 + pass `--user-id`, which the root tree does not take, and `listen` and `proxy`
60 + no longer describe a missing "project context". `composio dev` commands point
61 + at `--user-id` or `composio dev init`, or at `--user-id` or `composio login`
62 + with `--project-name`.
63 +
64 +- An empty consumer user id now counts as no user on every command.
65 + `composio execute`, `composio search`, and `composio link` fail with the
66 + missing-user error and exit 1, as `composio connections`, `composio listen`,
67 + and `composio proxy` already did; they used to send requests for the user
68 + `""`. `composio run` starts the script without the consumer user's context,
69 + as it does when there is no consumer user.
70 +
71 - `composio execute` now exits 1 when an argument names a file on your machine
72 but the tool does not accept file uploads for that input, such as `file` in
73 `TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD`. It used to send the path text to
ts/packages/cli/GLOSSARY.md
+1 -1
@@ -40,7 +40,7 @@ A user id a developer acts as on a developer project: the directory test user (f
40 _Avoid_: playground user, default user
41
42 **Acting user**:
43 -The user a command acts as: the consumer user on the root tree; on the dev tree, `--user-id` when given, otherwise the test user.
43 +The user a command acts as: the consumer user on the root tree; on the dev tree, against the developer project, `--user-id` when given, otherwise the directory test user (only for the directory's own project), otherwise the global test user. A test user standing in is named on stderr; no user at all is a missing acting user, with one message per tree.
44 _Avoid_: current user, target user
45
46 **User filter**:
ts/packages/cli/README.md
+12 -6
@@ -59,12 +59,18 @@ For a project with 2FA enabled, pass the user who owns the connected account:
59 composio dev triggers create GMAIL_NEW_GMAIL_MESSAGE --connected-account-id ca_123 --user-id user_123
60 ```
61
62 -The shared `--user-id` flag works before or after the subcommand. When omitted,
63 -the command uses the resolved directory project's test user, then the global test
64 -user configured by `composio login`. Setting both `COMPOSIO_ORG_ID` and
65 -`COMPOSIO_PROJECT_ID` in the process environment overrides directory configuration,
66 -including its test user. If no test user is resolved, the request omits `user_id`
67 -and the server applies the project's ownership policy.
62 +Every `composio dev` command that acts as a user (`playground-execute`,
63 +`connected-accounts link`, `toolkits list` and `info`, `triggers create`) follows
64 +one rule. It acts on the developer project (this directory's, or the one
65 +`--project-name` names) as the shared `--user-id`, which works before or after
66 +the subcommand. When omitted, it uses the directory project's test user (only
67 +when acting on that same project), then the global test user configured by
68 +`composio login`, and names the one it used on stderr. Setting both
69 +`COMPOSIO_ORG_ID` and `COMPOSIO_PROJECT_ID` in the process environment overrides
70 +directory configuration, including its test user. If no test user is resolved,
71 +`triggers create` omits `user_id` and the server applies the project's ownership
72 +policy. Root commands such as `composio execute` and `composio link` always act as
73 +your own (consumer) user and take no `--user-id`.
74
75 ## Configuration
76
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.errors.ts
-9
@@ -12,15 +12,6 @@ export class ConnectionPollingError extends Data.TaggedError('commands/Connectio
12 }
13 }
14
15 -export class MissingLinkUserIdError extends Data.TaggedError('commands/MissingLinkUserIdError')<{
16 - readonly message: string;
17 - readonly flow: 'list' | 'legacy' | 'tool-router';
18 -}> {
19 - get [ExpectedFailure]() {
20 - return true;
21 - }
22 -}
23 -
15 export class ConnectedAccountsDecodeError extends Data.TaggedError(
16 'commands/ConnectedAccountsDecodeError'
17 )<{
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+21 -77
@@ -2,16 +2,7 @@ import { Effect, Match, Option, Schedule, pipe } from 'effect';
2 import type { ComposioClientShape } from '@composio/client/effect';
3 import open from 'open';
4 import { commandInputError } from 'src/commands/errors';
5 -import {
6 - actingUser,
7 - actingUserOption,
8 - CommandSurface,
9 - fallbackNotice,
10 - missingUserIdMessage,
11 - type ActingUserOptions,
12 - type CommandTree,
13 - type MissingActingUserError,
14 -} from 'src/commands/surface';
5 +import { actingUser, CommandSurface, type CommandTree } from 'src/commands/surface';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { TerminalUI } from 'src/services/terminal-ui';
8 import { failedWith } from 'src/effects/request-error';
@@ -22,7 +13,7 @@ import { ProjectContext } from 'src/services/project-context';
13 import { ComposioClientSingleton } from 'src/services/composio-clients';
14 import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
15 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
25 -import { resolveCommandProject, type ResolvedCommandProject } from 'src/services/command-project';
16 +import type { ResolvedCommandProject } from 'src/services/command-project';
17 import {
18 invalidateConsumerConnectedToolkitsCache,
19 writeConsumerConnectedToolkitsCache,
@@ -39,7 +30,6 @@ import {
30 ConnectedAccountsDecodeError,
31 ConnectedAccountsRequestError,
32 ConnectionPollingError,
42 - MissingLinkUserIdError,
33 } from './connected-accounts.link.errors';
34 import {
35 AUTH_CONFIG_SCOPE_MESSAGE,
@@ -107,25 +97,6 @@ const consumerScope = (project: ResolvedCommandProject) =>
97 }))
98 );
99
110 -/**
111 - * On the dev tree without `--project-name`, `link` and `link --list` act as the consumer user on
112 - * the consumer project and ignore `--user-id`, matching their behavior before `actingUser`.
113 - */
114 -const LINK_LEGACY = {
115 - legacy: {
116 - consumerWithoutProjectName: true,
117 - // As before `actingUser`, an empty consumer user id still counts as a user.
118 - acceptEmptyConsumerUserId: true,
119 - },
120 -} satisfies ActingUserOptions;
121 -
122 -/**
123 - * Re-fail with link's own `MissingLinkUserIdError`, so `cli.command.failed` keeps reporting it as
124 - * `error_name` and the handler tests keep matching its tag.
125 - */
126 -const missingLinkUserId = (flow: LinkFlow) => (error: MissingActingUserError) =>
127 - Effect.fail(new MissingLinkUserIdError({ message: error.message, flow }));
128 -
100 /** The directory's project keys, or none when the directory is not initialized or unreadable. */
101 const directoryProject = Effect.gen(function* () {
102 const projectContext = yield* ProjectContext;
@@ -402,9 +373,8 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo
373 // --- the three flows --------------------------------------------------------------------------
374
375 /**
405 - * `link <toolkit> --list`: the user's active accounts in the toolkit, as a table on stderr and
406 - * JSON on stdout. Resolves the consumer project on both trees; `dev --project-name` names a
407 - * developer project instead, whose user comes from `--user-id` or a test user id.
376 + * `link <toolkit> --list`: the acting user's active accounts in the toolkit, as a table on
377 + * stderr and JSON on stdout.
378 */
379 export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams) =>
380 Effect.gen(function* () {
@@ -423,15 +393,7 @@ export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams)
393 const toolkitSlug = params.toolkit.value;
394
395 const clientSingleton = yield* ComposioClientSingleton;
426 - const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser({
427 - ...LINK_LEGACY,
428 - // Keep the command's own missing-user message rather than the tree's default.
429 - missingUserMessage: projectName =>
430 - missingUserIdMessage(
431 - projectName,
432 - 'Missing user id. Provide --user-id, or run composio dev init or composio login first.'
433 - ),
434 - }).pipe(Effect.catchTag('commands/MissingActingUserError', missingLinkUserId('list')));
396 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser();
397 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
398
399 const accounts = yield* ui.withSpinner(
@@ -485,8 +447,8 @@ export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams)
447
448 /**
449 * `dev connected-accounts link --auth-config <id>`: the legacy flow against a developer
488 - * project, without the Tool Router. The project is `--project-name` or the directory's; the
489 - * user is `--user-id`, then the directory's test user, then the global one.
450 + * project, without the Tool Router, as the acting user. A missing project is reported before a
451 + * missing user.
452 */
453 export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams) =>
454 Effect.gen(function* () {
@@ -501,34 +463,14 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
463 const authConfigId = params.authConfig.value;
464
465 const clientSingleton = yield* ComposioClientSingleton;
504 - // The user is checked before the directory's project, so a missing user wins over a
505 - // missing project; `actingUserOption` resolves only the --project-name project.
506 - const acting = yield* actingUserOption();
507 - if (Option.isNone(acting)) {
508 - // `actingUserOption` does not fail, so this flow raises link's own error and message.
509 - return yield* new MissingLinkUserIdError({
510 - message: missingUserIdMessage(
511 - projectName,
512 - 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
513 - ),
514 - flow: 'legacy',
515 - });
516 - }
517 - const { userId: resolvedUserId, project: namedResolvedProject } = acting.value;
466 if (Option.isNone(projectName) && Option.isNone(yield* directoryProject)) {
467 return yield* Effect.fail(
468 invalidOptionValueFor(tree)(AUTH_CONFIG_SCOPE_MESSAGE, '--auth-config')
469 );
470 }
523 - // The acting-user helpers leave the test-user notice to the command, so print it here.
524 - yield* Effect.transposeOption(
525 - Option.map(fallbackNotice(acting.value), notice => ui.log.warn(notice))
526 - );
471 + const acting = yield* actingUser();
472 + const { userId: resolvedUserId, project: resolvedProject } = acting;
473
528 - const resolvedProject = yield* Option.match(namedResolvedProject, {
529 - onSome: Effect.succeed,
530 - onNone: () => resolveCommandProject({ mode: 'developer' }),
531 - });
474 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
475 const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
476 const existingAccounts = yield* existingAccountsForHints({
@@ -593,8 +535,8 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
535 });
536
537 /**
596 - * `link <toolkit>`: the Tool Router flow against the consumer project (or the developer
597 - * project `dev --project-name` names). Records the link in the session history.
538 + * `link <toolkit>`: the Tool Router flow as the acting user, against the consumer project on the
539 + * root tree and the developer project on the dev tree. Records the link in the session history.
540 */
541 export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
542 Effect.gen(function* () {
@@ -610,12 +552,7 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
552
553 const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
554 const clientSingleton = yield* ComposioClientSingleton;
613 - const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser({
614 - // Ignores the directory test user and keeps its own message, as before `actingUser`.
615 - legacy: { ...LINK_LEGACY.legacy, skipDirectoryTestUser: true },
616 - missingUserMessage: () =>
617 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
618 - }).pipe(Effect.catchTag('commands/MissingActingUserError', missingLinkUserId('tool-router')));
555 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser();
556 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
557 const existingAccounts = yield* existingAccountsForHints({
558 client,
@@ -626,8 +563,15 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
563 ui,
564 alias: normalizedAlias,
565 existingAccounts,
629 - executeCommand: 'composio execute',
630 - listCommand: `composio connections list --toolkit ${toolkitSlug}`,
566 + ...(tree === 'dev'
567 + ? {
568 + executeCommand: 'composio dev playground-execute',
569 + listCommand: `composio dev connected-accounts list --toolkits ${toolkitSlug}`,
570 + }
571 + : {
572 + executeCommand: 'composio execute',
573 + listCommand: `composio connections list --toolkit ${toolkitSlug}`,
574 + }),
575 });
576 if (!aliasAvailable) return;
577
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+2 -14
@@ -1,4 +1,4 @@
1 -import { Data, Effect, Option } from 'effect';
1 +import { Effect, Option } from 'effect';
2 import { Command, Flag } from 'effect/cli';
3 import {
4 CONNECTED_ACCOUNTS_SHAPE_MESSAGE,
@@ -15,12 +15,6 @@ import {
15 } from 'src/services/tool-permissions';
16 import { idempotent } from 'src/services/composio-request';
17
18 -class MissingConnectionsConsumerUserIdError extends Data.TaggedError(
19 - 'commands/MissingConnectionsConsumerUserIdError'
20 -)<{
21 - readonly message: string;
22 -}> {}
23 -
18 class ConnectionsListRequestError extends requestError('commands/ConnectionsListRequestError') {}
19
20 const toolkit = Flag.String('toolkit').pipe(
@@ -78,13 +72,7 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
72 const ui = yield* TerminalUI;
73 const clientSingleton = yield* ComposioClientSingleton;
74 const toolkitSlug = Option.getOrUndefined(toolkit);
81 - const { userId: consumerUserId, project: resolvedProject } = yield* actingUser().pipe(
82 - // Re-fail with the command's own error, not the expected `MissingActingUserError`: it has
83 - // always failed with it as a defect, and `cli.command.failed` keeps its `error_name`.
84 - Effect.catchTag('commands/MissingActingUserError', error =>
85 - Effect.fail(new MissingConnectionsConsumerUserIdError({ message: error.message }))
86 - )
87 - );
75 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser();
76
77 const client = yield* clientSingleton.getFor({
78 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/connections/remove/connections.remove.errors.ts
-7
@@ -1,12 +1,5 @@
1 -import { Data } from 'effect';
1 import { requestError } from 'src/effects/request-error';
2
4 -export class MissingConnectionRemovalConsumerUserIdError extends Data.TaggedError(
5 - 'commands/MissingConnectionRemovalConsumerUserIdError'
6 -)<{
7 - readonly message: string;
8 -}> {}
9 -
3 export class ConnectionsRemovalRequestError extends requestError(
4 'commands/ConnectionsRemovalRequestError'
5 ) {}
ts/packages/cli/src/commands/connections/remove/connections.remove.handler.ts
+2 -11
@@ -12,10 +12,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold } from 'src/ui/colors';
13 import { redact } from 'src/ui/redact';
14 import { idempotent } from 'src/services/composio-request';
15 -import {
16 - ConnectionsRemovalRequestError,
17 - MissingConnectionRemovalConsumerUserIdError,
18 -} from './connections.remove.errors';
15 +import { ConnectionsRemovalRequestError } from './connections.remove.errors';
16
17 /** The flags of `composio connections remove`. */
18 export type ConnectionsRemoveParams = {
@@ -105,13 +102,7 @@ export const runConnectionsRemove = ({ account, yes }: ConnectionsRemoveParams)
102 return yield* invalidInput(NEEDS_YES_MESSAGE, '--yes');
103 }
104 const clientSingleton = yield* ComposioClientSingleton;
108 - const { userId: consumerUserId, project: resolvedProject } = yield* actingUser().pipe(
109 - // Re-fail with the command's own error, not the expected `MissingActingUserError`: it has
110 - // always failed with it as a defect, and `cli.command.failed` keeps its `error_name`.
111 - Effect.catchTag('commands/MissingActingUserError', error =>
112 - Effect.fail(new MissingConnectionRemovalConsumerUserIdError({ message: error.message }))
113 - )
114 - );
105 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser();
106
107 const client = yield* clientSingleton.getFor({
108 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/dev.cmd.ts
+1 -1
@@ -30,7 +30,7 @@ const devMode = Flag.Literals('mode', ['on', 'off'] as const).pipe(
30 const userId = Flag.String('user-id').pipe(
31 Flag.optional,
32 Flag.withDescription(
33 - 'User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one.'
33 + 'User id to act as or filter by. Without it, commands that act as a user use the test user id of this directory (for its own project), then the global one, and name it on stderr.'
34 )
35 );
36
ts/packages/cli/src/commands/listen.cmd.ts
+1 -17
@@ -29,7 +29,6 @@ type TriggerCreateParams = NonNullable<
29
30 export class ListenCommandError extends Data.TaggedError('commands/ListenCommandError')<{
31 readonly reason:
32 - | 'project_context'
32 | 'connected_account_not_found'
33 | 'unknown_trigger'
34 | 'create_trigger'
@@ -461,21 +460,6 @@ const resolveListenSetup = (params: {
460 };
461 });
462
464 -/** The consumer user `listen` subscribes as, with the consumer project. */
465 -const listenActingUser = (slug: string) =>
466 - actingUser({
467 - // Keep the command's own missing-user message rather than the tree's default.
468 - missingUserMessage: () => 'No consumer user is available in the current project context.',
469 - }).pipe(
470 - // Re-fail with the command's own error, not the expected `MissingActingUserError`: it has
471 - // always failed with it as a defect, and `cli.command.failed` keeps its `error_name`.
472 - Effect.catchTag('commands/MissingActingUserError', error =>
473 - Effect.fail(
474 - new ListenCommandError({ reason: 'project_context', message: error.message, slug })
475 - )
476 - )
477 - );
478 -
463 export const listenCmd = Command.make(
464 'listen',
465 { slug, params, maxEvents, timeout, stream, account, failFast, debug },
@@ -487,7 +471,7 @@ export const listenCmd = Command.make(
471 const clientSingleton = yield* ComposioClientSingleton;
472 const realtime = yield* TriggersRealtime;
473
490 - const { userId: actingUserId, project: resolvedProject } = yield* listenActingUser(slug);
474 + const { userId: actingUserId, project: resolvedProject } = yield* actingUser();
475
476 const client = yield* clientSingleton.getFor({
477 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/proxy.cmd.ts
+1 -24
@@ -5,7 +5,6 @@ import type {
5 SessionProxyExecuteParams,
6 SessionProxyExecuteResponse,
7 } from '@composio/client/resources/tool-router/session';
8 -import { ExpectedFailure } from 'src/effects/expected-failure';
8 import { requestError } from 'src/effects/request-error';
9 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
10 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
@@ -79,18 +78,6 @@ const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = [
78 'PATCH',
79 ];
80
82 -/**
83 - * `composio proxy` has no consumer user to send the request as. An expected failure:
84 - * `cli-main.ts` prints the message and exits 1.
85 - */
86 -export class ProxyCommandError extends Data.TaggedError('commands/ProxyCommandError')<{
87 - readonly message: string;
88 -}> {
89 - get [ExpectedFailure]() {
90 - return true;
91 - }
92 -}
93 -
81 /**
82 * A proxy call refused before sending it because the toolkit is not connected, already reported
83 * on stderr and as `{ "successful": false, ... }` on stdout. `cli-main.ts` prints nothing more
@@ -304,17 +291,7 @@ export const proxyCmd = Command.make('proxy', {
291 const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = options;
292 const ui = yield* TerminalUI;
293 const clientSingleton = yield* ComposioClientSingleton;
307 - const { userId: consumerUserId, project: resolvedProject } = yield* actingUser({
308 - // Keep the command's own missing-user message rather than the tree's default.
309 - missingUserMessage: () =>
310 - 'No consumer project user is available for proxy execution in this context.',
311 - }).pipe(
312 - // Re-fail with the `ProxyCommandError` the command has always failed with, so
313 - // `cli.command.failed` keeps reporting it as `error_name`.
314 - Effect.catchTag('commands/MissingActingUserError', error =>
315 - Effect.fail(new ProxyCommandError({ message: error.message }))
316 - )
317 - );
294 + const { userId: consumerUserId, project: resolvedProject } = yield* actingUser();
295 const normalizedToolkit = toolkit.toLowerCase();
296
297 yield* runProxyConnectedToolkitFailFast({
ts/packages/cli/src/commands/run.cmd.ts
+1 -4
@@ -285,10 +285,7 @@ const resolveRunHelperContext = () =>
285 }
286
287 // Without a consumer user the script runs with the base context alone.
288 - const consumer = yield* actingUser({
289 - // As before `actingUser`, an empty consumer user id still counts as a user.
290 - legacy: { acceptEmptyConsumerUserId: true },
291 - }).pipe(Effect.option);
288 + const consumer = yield* actingUser().pipe(Effect.option);
289 if (Option.isNone(consumer)) {
290 return baseContext;
291 }
ts/packages/cli/src/commands/surface.ts
+49 -72
@@ -8,6 +8,7 @@ import {
8 type ResolvedCommandProject,
9 } from 'src/services/command-project';
10 import { ProjectContext } from 'src/services/project-context';
11 +import { TerminalUI } from 'src/services/terminal-ui';
12 import { ComposioUserContext } from 'src/services/user-context';
13
14 /** The command tree a command was invoked from. */
@@ -82,43 +83,19 @@ export class MissingActingUserError extends Data.TaggedError('commands/MissingAc
83 }
84
85 /**
85 - * The missing-user message for a command, given its `--project-name`. With the flag the
86 - * directory's test user does not carry over to another project, so the message points at
87 - * `--user-id` and `composio login` instead of `composio dev init`.
86 + * The missing-user message for the tree. On the dev tree with `--project-name` the directory's
87 + * test user does not carry over to another project, so it points at `--user-id` and
88 + * `composio login` instead of `composio dev init`.
89 */
89 -export const missingUserIdMessage = (projectName: Option.Option<string>, otherwise: string) =>
90 - Option.match(projectName, {
91 - onNone: () => otherwise,
92 - onSome: () =>
93 - 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
94 - });
95 -
96 -const defaultMissingUserMessage =
97 - (tree: CommandTree) =>
98 - (projectName: Option.Option<string>): string =>
99 - tree === 'root'
100 - ? 'Missing consumer user id. Run `composio login` and try again.'
101 - : missingUserIdMessage(
102 - projectName,
103 - 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
104 - );
105 -
106 -export interface ActingUserOptions {
107 - /** The `MissingActingUserError` message, given `--project-name`; defaults to the tree's. Only `actingUser` reads it: `actingUserOption` never fails with a missing user. */
108 - readonly missingUserMessage?: (projectName: Option.Option<string>) => string;
109 - /** Departures from the rule that some commands keep, as they behaved before `actingUser`. */
110 - readonly legacy?: {
111 - /**
112 - * Accept an empty consumer user id as the consumer user, as `execute`, `search`, `link` and
113 - * `run` do; without it an empty id counts as none, as `connections`, `listen` and `proxy` do.
114 - */
115 - readonly acceptEmptyConsumerUserId?: boolean;
116 - /** On the dev tree without `--project-name`, act as the consumer user, ignoring `--user-id`. */
117 - readonly consumerWithoutProjectName?: boolean;
118 - /** Skip the directory test user on the dev tree. */
119 - readonly skipDirectoryTestUser?: boolean;
120 - };
121 -}
90 +const missingUserMessage = (tree: CommandTree, projectName: Option.Option<string>): string =>
91 + tree === 'root'
92 + ? 'Missing consumer user id. Run `composio login` and try again.'
93 + : Option.match(projectName, {
94 + onNone: () =>
95 + 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
96 + onSome: () =>
97 + 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
98 + });
99
100 /**
101 * The test user the directory configures (`.composio/project.json`), for a command that runs
@@ -142,7 +119,7 @@ const directoryTestUserId = (
119 );
120
121 /** The dev tree's rule over its candidates: `--user-id`, the directory test user, the global one. */
145 -export const devActingUser = (candidates: {
122 +const devActingUser = (candidates: {
123 readonly flag: Option.Option<string>;
124 readonly directoryTestUserId: Option.Option<string>;
125 readonly globalTestUserId: Option.Option<string>;
@@ -170,25 +147,33 @@ const noticeBySource: Record<ActingUserSource, (userId: string) => Option.Option
147 export const fallbackNotice = (user: Omit<ActingUser, 'project'>): Option.Option<string> =>
148 noticeBySource[user.source](user.userId);
149
173 -/** The consumer user of a consumer project; an empty id counts as none unless `legacy` accepts it. */
174 -const consumerUser = (project: ResolvedCommandProject, options: ActingUserOptions) =>
150 +/** Prints `fallbackNotice` on stderr when a test user stands in. */
151 +const announceFallback = (user: Option.Option<Omit<ActingUser, 'project'>>) =>
152 + Effect.gen(function* () {
153 + const ui = yield* TerminalUI;
154 + yield* Effect.transposeOption(
155 + Option.map(Option.flatMap(user, fallbackNotice), notice => ui.log.warn(notice))
156 + );
157 + });
158 +
159 +/** The consumer user of a consumer project; an empty id counts as none. */
160 +const consumerUser = (project: ResolvedCommandProject) =>
161 pipe(
162 Option.fromNullishOr(project.consumerUserId),
177 - Option.filter(
178 - userId => userId.length > 0 || options.legacy?.acceptEmptyConsumerUserId === true
179 - ),
163 + Option.filter(userId => userId.length > 0),
164 Option.map(userId => ({ userId, source: 'consumer' as const }))
165 );
166
167 /** The dev tree's user for a project, `namedProjectId` being the `--project-name` project's id. */
184 -const devUser = (namedProjectId: Option.Option<string>, options: ActingUserOptions) =>
168 +const devUser = (namedProjectId: Option.Option<string>) =>
169 Effect.gen(function* () {
170 const surface = yield* CommandSurface;
171 const userContext = yield* ComposioUserContext;
172 const projectContext = yield* ProjectContext;
189 - const directoryProject = options.legacy?.skipDirectoryTestUser
190 - ? Option.none()
191 - : yield* projectContext.resolve.pipe(Effect.option, Effect.map(Option.flatten));
173 + const directoryProject = yield* projectContext.resolve.pipe(
174 + Effect.option,
175 + Effect.map(Option.flatten)
176 + );
177 return devActingUser({
178 flag: surface.userId,
179 directoryTestUserId: directoryTestUserId(directoryProject, namedProjectId),
@@ -196,40 +181,33 @@ const devUser = (namedProjectId: Option.Option<string>, options: ActingUserOptio
181 });
182 });
183
199 -/** The tree whose rule applies: the surface's, unless a legacy option says otherwise. */
200 -const ruleTree = (surface: CommandSurfaceShape, options: ActingUserOptions): CommandTree =>
201 - surface.tree === 'dev' &&
202 - !(options.legacy?.consumerWithoutProjectName && Option.isNone(surface.projectName))
203 - ? 'dev'
204 - : 'root';
205 -
184 /**
185 * The acting user, resolved against the project the command runs in. On the root tree, the
186 * consumer user of the consumer project. On the dev tree, against the developer project
187 * (`--project-name`, else the directory's): `--user-id`, then the directory test user (only
210 - * for the directory's own project), then the global test user. Fails with
188 + * for the directory's own project), then the global test user; a test user standing in is
189 + * named on stderr (`fallbackNotice`). Fails with
190 * `ProjectResolutionError` when the project cannot be resolved and `MissingActingUserError`
191 * when no step finds a user.
192 */
214 -export const actingUser = (options: ActingUserOptions = {}) =>
193 +export const actingUser = () =>
194 Effect.gen(function* () {
216 - const surface = yield* CommandSurface;
217 - const tree = ruleTree(surface, options);
195 + const { tree, projectName } = yield* CommandSurface;
196 const project = yield* resolveCommandProject(
197 tree === 'root'
198 ? { mode: 'consumer' }
221 - : { mode: 'developer', projectName: Option.getOrUndefined(surface.projectName) }
199 + : { mode: 'developer', projectName: Option.getOrUndefined(projectName) }
200 );
201 const user =
202 tree === 'root'
225 - ? consumerUser(project, options)
226 - : yield* devUser(Option.as(surface.projectName, project.projectId), options);
203 + ? consumerUser(project)
204 + : yield* devUser(Option.as(projectName, project.projectId));
205 + yield* announceFallback(user);
206 if (Option.isNone(user)) {
228 - const message = options.missingUserMessage ?? defaultMissingUserMessage(tree);
207 return yield* new MissingActingUserError({
230 - tree: surface.tree,
231 - projectName: surface.projectName,
232 - message: message(surface.projectName),
208 + tree,
209 + projectName,
210 + message: missingUserMessage(tree, projectName),
211 });
212 }
213 return { ...user.value, project } satisfies ActingUser;
@@ -239,15 +217,16 @@ export const actingUser = (options: ActingUserOptions = {}) =>
217 * The acting user for a command that also runs without one, by the same rule as `actingUser`.
218 * On the dev tree it resolves only the project `--project-name` names, so `project` is none when
219 * the command runs against the directory's project through the default client; on the root
242 - * tree it is the consumer project. Fails only when that project cannot be resolved.
220 + * tree it is the consumer project. Names a test user standing in on stderr, as `actingUser`
221 + * does. Fails only when that project cannot be resolved.
222 */
244 -export const actingUserOption = (options: Omit<ActingUserOptions, 'missingUserMessage'> = {}) =>
223 +export const actingUserOption = () =>
224 Effect.gen(function* () {
225 const surface = yield* CommandSurface;
247 - if (ruleTree(surface, options) === 'root') {
226 + if (surface.tree === 'root') {
227 const project = yield* resolveCommandProject({ mode: 'consumer' });
228 return Option.map(
250 - consumerUser(project, options),
229 + consumerUser(project),
230 (user): ActingUser<Option.Option<ResolvedCommandProject>> => ({
231 ...user,
232 project: Option.some(project),
@@ -259,10 +238,8 @@ export const actingUserOption = (options: Omit<ActingUserOptions, 'missingUserMe
238 resolveCommandProject({ mode: 'developer', projectName })
239 )
240 );
262 - const user = yield* devUser(
263 - Option.map(namedProject, project => project.projectId),
264 - options
265 - );
241 + const user = yield* devUser(Option.map(namedProject, project => project.projectId));
242 + yield* announceFallback(user);
243 return Option.map(user, (found): ActingUser<Option.Option<ResolvedCommandProject>> => ({
244 ...found,
245 project: namedProject,
ts/packages/cli/src/commands/toolkits/info/toolkits.info.handler.ts
+6 -8
@@ -7,7 +7,7 @@ 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 { actingUserOption, fallbackNotice } from 'src/commands/surface';
10 +import { actingUserOption } from 'src/commands/surface';
11 import { BROWSE_TOOLKITS_HINT, formatToolkitInfo, formatToolkitInfoJson } from '../format';
12 import { ToolkitsInfoRequestError } from './toolkits.info.errors';
13
@@ -49,13 +49,11 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
49 );
50 const resolvedUserId = Option.map(acting, found => found.userId);
51
52 - // The acting-user helpers leave the test-user notice to the command, so print it here.
53 - yield* Option.match(acting, {
54 - onSome: found =>
55 - Effect.transposeOption(Option.map(fallbackNotice(found), notice => ui.log.warn(notice))),
56 - onNone: () =>
57 - ui.log.info('No test user id found; showing toolkit details without connection status.'),
58 - });
52 + if (Option.isNone(acting)) {
53 + yield* ui.log.info(
54 + 'No test user id found; showing toolkit details without connection status.'
55 + );
56 + }
57
58 const resultOpt = yield* ui
59 .withSpinner(
ts/packages/cli/src/commands/toolkits/list/toolkits.list.handler.ts
+6 -43
@@ -1,11 +1,6 @@
1 import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';
2 import { Array as Arr, Effect, Option } from 'effect';
3 -import {
4 - actingUserOption,
5 - devActingUser,
6 - fallbackNotice,
7 - type ActingUser,
8 -} from 'src/commands/surface';
3 +import { actingUserOption, fallbackNotice } from 'src/commands/surface';
4 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';
@@ -28,35 +23,6 @@ export type ToolkitsListParams = {
23
24 type SessionToolkitItem = SessionToolkitsResponse['items'][number];
25
31 -/** The user whose connection status the list shows, and the notice printed when it is a fallback. */
32 -export type ToolkitsListUser = {
33 - readonly id: string;
34 - readonly fallbackNotice: Option.Option<string>;
35 -};
36 -
37 -const toolkitsListUser = (user: Omit<ActingUser, 'project'>): ToolkitsListUser => ({
38 - id: user.userId,
39 - fallbackNotice: fallbackNotice(user),
40 -});
41 -
42 -/**
43 - * The `dev` group's `--user-id`, then the directory's test user id, then the global one: the
44 - * acting-user rule (`devActingUser`) over given candidates.
45 - */
46 -export const resolveToolkitsListUser = (candidates: {
47 - readonly flag: Option.Option<string>;
48 - readonly projectTestUserId: Option.Option<string>;
49 - readonly globalTestUserId: Option.Option<string>;
50 -}): Option.Option<ToolkitsListUser> =>
51 - Option.map(
52 - devActingUser({
53 - flag: candidates.flag,
54 - directoryTestUserId: candidates.projectTestUserId,
55 - globalTestUserId: candidates.globalTestUserId,
56 - }),
57 - toolkitsListUser
58 - );
59 -
26 /**
27 * Applies `--connected` to the merged rows. The filter needs the session's connection data; when a
28 * user was resolved but the session returned nothing, the rows are kept and the filter is reported
@@ -88,20 +54,17 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
54
55 const clampedLimit = clampLimit(limit);
56 // Resolved outside the session lookup, whose failures only drop the connection status.
91 - const acting = yield* actingUserOption();
92 - const user = Option.map(acting, toolkitsListUser);
57 + const user = yield* actingUserOption();
58 // The client of the project --project-name names; none keeps the default client.
59 const namedClient = yield* Effect.transposeOption(
60 Option.map(
96 - Option.flatMap(acting, found => found.project),
61 + Option.flatMap(user, found => found.project),
62 project => clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId })
63 )
64 );
65
101 - // The acting-user helpers leave the test-user notice to the command, so print it here.
102 - const notice = Option.flatMap(user, resolved => resolved.fallbackNotice);
103 - if (Option.isSome(notice)) {
104 - yield* ui.log.warn(notice.value);
66 + // `actingUserOption` named the test user standing in; say how to pick another.
67 + if (Option.isSome(Option.flatMap(user, fallbackNotice))) {
68 yield* ui.log.message('To show status for a specific user, use `--user-id`.');
69 }
70
@@ -126,7 +89,7 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
89 onSome: Effect.succeed,
90 onNone: () => clientSingleton.get(),
91 });
129 - const { sessionId } = yield* resolveToolRouterSession(client, resolved.id);
92 + const { sessionId } = yield* resolveToolRouterSession(client, resolved.userId);
93 return Option.some({ client, sessionId });
94 }).pipe(
95 Effect.catch(error =>
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+29 -41
@@ -136,12 +136,12 @@ const invalidArguments = commandInputError('execute');
136 // union from scattered constructor calls, so a new reason is added here next to its first use.
137
138 /**
139 - * `composio execute` cannot run the tool as invoked: a `--file` the tool cannot take, no user
140 - * id to run it for, or (with `--parallel`) a toolkit the user has not connected. An expected
139 + * `composio execute` cannot run the tool as invoked: a `--file` the tool cannot take, or (with
140 + * `--parallel`) a toolkit the user has not connected. An expected
141 * failure: `cli-main.ts` prints the message and exits 1.
142 */
143 export class ToolExecutionError extends Data.TaggedError('ToolExecutionError')<{
144 - readonly reason: 'file_input' | 'missing_user_id' | 'connection_check';
144 + readonly reason: 'file_input' | 'connection_check';
145 readonly message: string;
146 readonly toolSlug?: string;
147 }> {
@@ -862,7 +862,11 @@ const emitCachedSchema = (
862 );
863 });
864
865 -const resolveExecuteContext = (params: RunToolsExecuteParams) =>
865 +const resolveExecuteContext = (
866 + params: RunToolsExecuteParams,
867 + /** The acting user; `--parallel` resolves it once for all its tools. */
868 + user: ReturnType<typeof actingUser> = actingUser()
869 +) =>
870 Effect.gen(function* () {
871 const ui = yield* TerminalUI;
872 const executor = yield* ToolsExecutor;
@@ -870,29 +874,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
874 const parsedArgs = yield* parseArguments(input);
875 const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
876
873 - const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser(
874 - params.surface === 'root'
875 - ? {
876 - // As before `actingUser`, an empty consumer user id still counts as a user.
877 - legacy: { acceptEmptyConsumerUserId: true },
878 - // Keep the earlier message, which mentions --user-id, over the root tree's default.
879 - missingUserMessage: () =>
880 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
881 - }
882 - : {}
883 - ).pipe(
884 - // Re-fail with the `ToolExecutionError` the command has always failed with, so
885 - // `cli.command.failed` keeps reporting it as `error_name`.
886 - Effect.catchTag('commands/MissingActingUserError', error =>
887 - Effect.fail(
888 - new ToolExecutionError({
889 - reason: 'missing_user_id',
890 - toolSlug: params.slug,
891 - message: error.message,
892 - })
893 - )
894 - )
895 - );
877 + const { userId: resolvedUserId, project: resolvedProject } = yield* user;
878 const clientSingleton = yield* ComposioClientSingleton;
879 const client = yield* clientSingleton.getFor({
880 orgId: resolvedProject.orgId,
@@ -1702,23 +1684,29 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1684 return yield* runParallelSchemaFetchFromParsed(params);
1685 }
1686
1687 + // Resolved once, so a test user's notice prints once; each tool still fails on its own
1688 + // input before it fails on a missing user.
1689 + const user = Effect.fromResult(yield* Effect.result(actingUser()));
1690 const contexts = yield* Effect.forEach(
1691 params.specs,
1692 spec =>
1708 - resolveExecuteContext({
1709 - slug: spec.slug,
1710 - data: spec.data,
1711 - file: Option.none(),
1712 - account: spec.account,
1713 - projectName: params.projectName,
1714 - surface: params.surface,
1715 - projectMode: params.projectMode,
1716 - getSchema: params.getSchema,
1717 - dryRun: params.dryRun,
1718 - skipConnectionCheck: params.skipConnectionCheck,
1719 - skipToolParamsCheck: params.skipToolParamsCheck,
1720 - skipChecks: params.skipChecks,
1721 - }),
1693 + resolveExecuteContext(
1694 + {
1695 + slug: spec.slug,
1696 + data: spec.data,
1697 + file: Option.none(),
1698 + account: spec.account,
1699 + projectName: params.projectName,
1700 + surface: params.surface,
1701 + projectMode: params.projectMode,
1702 + getSchema: params.getSchema,
1703 + dryRun: params.dryRun,
1704 + skipConnectionCheck: params.skipConnectionCheck,
1705 + skipToolParamsCheck: params.skipToolParamsCheck,
1706 + skipChecks: params.skipChecks,
1707 + },
1708 + user
1709 + ),
1710 { concurrency: 'unbounded' }
1711 );
1712 const entries = contexts.map((context, index) => ({
ts/packages/cli/src/commands/tools/search/tools.search.handler.ts
+1 -13
@@ -125,19 +125,7 @@ export const runToolsSearch = (params: ToolsSearchParams) =>
125 : undefined;
126
127 const runSearchRequest = Effect.gen(function* () {
128 - const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser({
129 - // As before `actingUser`, an empty consumer user id still counts as a user.
130 - legacy: { acceptEmptyConsumerUserId: true },
131 - // Keep the earlier message, which mentions --user-id, over the root tree's default.
132 - missingUserMessage: () =>
133 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
134 - }).pipe(
135 - // Re-fail with the `CommandInputError` the command has always failed with, so
136 - // `cli.command.failed` keeps reporting it as `error_name`.
137 - Effect.catchTag('commands/MissingActingUserError', error =>
138 - Effect.fail(invalidSearchInput(error.message, '--user-id'))
139 - )
140 - );
128 + const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser();
129 const clientSingleton = yield* ComposioClientSingleton;
130 const client = yield* clientSingleton.getFor({
131 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/triggers/create/triggers.create.handler.ts
+3 -8
@@ -1,6 +1,6 @@
1 import { Effect, Match, Option, Result } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 -import { actingUserOption, fallbackNotice } from 'src/commands/surface';
3 +import { actingUserOption } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
@@ -72,16 +72,11 @@ export const runTriggersCreate = ({
72 return yield* invalidTriggerConfig(parsedTriggerConfig.failure);
73 }
74
75 - // The group rejects --project-name, so this is the directory's project.
75 + // The group rejects --project-name, so this is the directory's project. A defaulted user id
76 + // must own the connected account on a 2FA project; `actingUserOption` names it on stderr.
77 const acting = yield* actingUserOption();
78 const resolvedUserId = Option.map(acting, found => found.userId);
79
79 - // A defaulted user id must own the connected account on a 2FA project, so name it.
80 - // The acting-user helpers leave the test-user notice to the command, so print it here.
81 - yield* Effect.transposeOption(
82 - Option.map(Option.flatMap(acting, fallbackNotice), notice => ui.log.warn(notice))
83 - );
84 -
80 const createdOpt = yield* ui
81 .withSpinner(
82 `Creating trigger "${triggerName.value}"...`,
ts/packages/cli/test/src/analytics.events.test.ts
+24 -1
@@ -6,7 +6,7 @@ import { it } from '@effect/vitest';
6 import { afterEach, describe, expect, vi } from 'vitest';
7 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import * as BunPath from '@effect/platform-bun/BunPath';
9 -import { Effect, Layer } from 'effect';
9 +import { Effect, Layer, Option } from 'effect';
10 import { createCliCodactFailureBody } from 'src/analytics/dispatch';
11 import {
12 CLI_ANALYTICS_EVENTS,
@@ -29,6 +29,7 @@ import {
29 isMaybeToolNotFoundError,
30 isMaybeToolValidationError,
31 } from 'src/analytics/events';
32 +import { MissingActingUserError } from 'src/commands/surface';
33 import { APP_VERSION } from 'src/constants';
34 import { inferSkillReleaseChannel } from 'src/effects/install-skill';
35 import { CLI_RELEASE_CHANNELS } from 'src/experimental-features';
@@ -388,6 +389,28 @@ describe('CLI analytics setup runtime-context events', () => {
389 });
390 });
391
392 + // Execute, search, link, connections, listen and proxy each used to report their own class.
393 + it.each(['execute', 'search', 'link', 'connections list', 'listen', 'proxy'])(
394 + 'reports a missing user on `%s` as MissingActingUserError',
395 + command => {
396 + const context = createCliCommandTelemetryContext(
397 + ['bun', 'composio', ...command.split(' ')],
398 + APP_VERSION,
399 + { stdoutIsTTY: false, stderrIsTTY: false },
400 + CLI_INVOCATION
401 + );
402 + const error = new MissingActingUserError({
403 + tree: 'root',
404 + projectName: Option.none(),
405 + message: 'Missing consumer user id. Run `composio login` and try again.',
406 + });
407 +
408 + expect(getPrimaryLifecycleFailedEvent(context, error)?.properties).toMatchObject({
409 + error_name: 'commands/MissingActingUserError',
410 + });
411 + }
412 + );
413 +
414 it('records the setup failure reason code carried by SetupCommandError', () => {
415 const context = createCliCommandTelemetryContext(
416 ['bun', 'composio', 'setup'],
ts/packages/cli/test/src/cli-main.test.ts
+56 -2
@@ -638,6 +638,9 @@ describe('expected failures without the crash banner', () => {
638 })
639 : fakeComposio(req, res);
640
641 + /** Every root-tree command without a consumer user says this. */
642 + const ROOT_MISSING_USER = 'Missing consumer user id. Run `composio login` and try again.';
643 +
644 const notConnected = (toolkit: string) =>
645 `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
646
@@ -669,8 +672,59 @@ describe('expected failures without the crash banner', () => {
672 ],
673 setup: {},
674 server: withoutConsumerUser,
672 - tag: 'ProxyCommandError',
673 - message: 'No consumer project user is available for proxy execution in this context.',
675 + tag: 'MissingActingUserError',
676 + message: ROOT_MISSING_USER,
677 + },
678 + // An empty consumer user id is no user; these commands used to act as the user "", and
679 + // told a consumer to pass --user-id, which the root tree does not take.
680 + {
681 + name: '`execute` without a consumer user',
682 + args: ['execute', 'GMAIL_FETCH_EMAILS', '-d', '{}'],
683 + setup: {},
684 + server: withoutConsumerUser,
685 + tag: 'MissingActingUserError',
686 + message: ROOT_MISSING_USER,
687 + },
688 + {
689 + name: '`search` without a consumer user',
690 + args: ['search', 'send an email'],
691 + setup: {},
692 + server: withoutConsumerUser,
693 + tag: 'MissingActingUserError',
694 + message: ROOT_MISSING_USER,
695 + },
696 + {
697 + name: '`link` without a consumer user',
698 + args: ['link', 'gmail', '--no-wait'],
699 + setup: {},
700 + server: withoutConsumerUser,
701 + tag: 'MissingActingUserError',
702 + message: ROOT_MISSING_USER,
703 + },
704 + // These printed the defect banner for a missing consumer user.
705 + {
706 + name: '`connections list` without a consumer user',
707 + args: ['connections', 'list'],
708 + setup: {},
709 + server: withoutConsumerUser,
710 + tag: 'MissingActingUserError',
711 + message: ROOT_MISSING_USER,
712 + },
713 + {
714 + name: '`connections remove` without a consumer user',
715 + args: ['connections', 'remove', 'gmail', '--yes'],
716 + setup: {},
717 + server: withoutConsumerUser,
718 + tag: 'MissingActingUserError',
719 + message: ROOT_MISSING_USER,
720 + },
721 + {
722 + name: '`listen` without a consumer user',
723 + args: ['listen', 'GMAIL_NEW_GMAIL_MESSAGE'],
724 + setup: {},
725 + server: withoutConsumerUser,
726 + tag: 'MissingActingUserError',
727 + message: ROOT_MISSING_USER,
728 },
729 ])(
730 '[Given] $name [Then] prints the message without the banner and exits 1',
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.cmd.test.ts
+15 -7
@@ -204,21 +204,29 @@ describe('CLI: composio dev connected-accounts link', () => {
204 layer(
205 TestLive({
206 baseConfigProvider: testConfigProvider,
207 - connectedAccountsData: makeConnectedAccountsData(),
207 + connectedAccountsData: makeConnectedAccountsData({
208 + items: [
209 + makeConnectedAccount(),
210 + makeConnectedAccount({ id: 'con_global', alias: 'global', user_id: 'global-default' }),
211 + ],
212 + }),
213 fixture: 'global-test-user-id',
214 })
215 )(
211 - '[Given] dev connected-accounts link --list without developer project context [Then] it still uses consumer resolution',
216 + '[Given] dev connected-accounts link --list in a developer project directory [Then] it lists the test user’s accounts',
217 it => {
213 - it.effect('lists connected accounts instead of requiring a developer project', () =>
218 + // `link` on the dev tree acts on the developer project; it used to list the consumer
219 + // user's accounts in the consumer project.
220 + it.effect('lists the global test user’s accounts, not the consumer user’s', () =>
221 Effect.gen(function* () {
222 yield* cli(['dev', 'connected-accounts', 'link', 'gmail', '--list']);
223 const lines = yield* MockConsole.getLines({ stripAnsi: true });
217 - const output = lines.join('\n');
224
219 - expect(output).toContain('default');
220 - expect(output).toContain('castle');
221 - expect(output).not.toContain('MissingDeveloperProjectError');
225 + expect(lines).toContain('Using global test user id "global-default"');
226 + expect(parseLastLine(lines)).toMatchObject({
227 + total: 1,
228 + items: [{ id: 'con_global', user_id: 'global-default' }],
229 + });
230 })
231 );
232 }
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+160 -46
@@ -24,8 +24,7 @@ import {
24 TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
25 missingArgumentMessage,
26 } from 'src/commands/connected-accounts/link/connected-accounts.link.format';
27 -import { CommandSurface } from 'src/commands/surface';
28 -import { MissingLinkUserIdError } from 'src/commands/connected-accounts/link/connected-accounts.link.errors';
27 +import { CommandSurface, MissingActingUserError } from 'src/commands/surface';
28 import { CliUserConfig } from 'src/models/cli-user-config';
29 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
30 import type { ProjectKeys } from 'src/models/project-keys';
@@ -172,6 +171,8 @@ const cliUserConfig = ComposioCliUserConfig.of({
171 */
172 const linkHandlerTest = (fixture: LinkFixture = {}) => {
173 const requests: Array<LinkRequest> = [];
174 + /** The `user_id` of every Tool Router session the handler created. */
175 + const sessionUsers: Array<string> = [];
176 const connectedAccounts = mockConnectedAccountResources(
177 resolveConnectedAccountsTestData({ items: [...(fixture.accounts ?? [])] })
178 );
@@ -217,7 +218,10 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
218 ...baseClient.toolRouter,
219 session: {
220 ...baseClient.toolRouter.session,
220 - create: () => Effect.succeed({ session_id: 'trs_handler_test' }),
221 + create: (sessionParams: { user_id: string }) =>
222 + Effect.sync(() => sessionUsers.push(sessionParams.user_id)).pipe(
223 + Effect.as({ session_id: 'trs_handler_test' })
224 + ),
225 link: (sessionId: string, linkParams: { toolkit: string; alias?: string }) =>
226 record('toolRouter.session.link', { sessionId, ...linkParams }).pipe(
227 Effect.andThen(
@@ -281,7 +285,7 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
285 Layer.succeed(ComposioCliUserConfig, cliUserConfig),
286 ConfigProvider.layer(hostOnlyEnvConfigProvider)
287 );
284 - return { layer, requests, exitCode: proc.exitCode };
288 + return { layer, requests, sessionUsers, exitCode: proc.exitCode };
289 };
290
291 const lines = MockConsole.getLines({ stripAnsi: true });
@@ -315,14 +319,14 @@ const legacyPendingJson = () =>
319 });
320
321 /** The pending payload of a Tool Router link, byte for byte. */
318 -const toolRouterPendingJson = () =>
322 +const toolRouterPendingJson = (projectType: 'CONSUMER' | 'DEVELOPER' = 'CONSUMER') =>
323 toJson({
324 status: 'pending',
325 message: 'Complete authorization by opening the URL',
326 connected_account_id: TOOL_ROUTER_LINK_TARGET.connected_account_id,
327 redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url,
328 toolkit: 'gmail',
325 - project_type: 'CONSUMER',
329 + project_type: projectType,
330 });
331
332 /** The payload once polling saw `con_new` ACTIVE, byte for byte. */
@@ -423,7 +427,8 @@ describe('connected-accounts link handler: runConnectedAccountsLink', () => {
427 { flow: 'tool-router', input: { toolkit: Option.some('gmail') } },
428 ])('[Given] the flags select the $flow flow [Then] it runs that flow', c =>
429 Effect.gen(function* () {
426 - const fixtureAccount = account({ alias: 'work' });
430 + // On the dev tree every flow acts as --user-id on the directory's developer project.
431 + const fixtureAccount = account({ alias: 'work', user_id: 'user_1' });
432 const { layer } = linkHandlerTest({
433 surface: devSurface({ userId: 'user_1' }),
434 accounts: [fixtureAccount],
@@ -443,7 +448,7 @@ describe('connected-accounts link handler: runConnectedAccountsLink', () => {
448 ? toJson({ toolkit: 'gmail', total: 1, items: [fixtureAccount] })
449 : c.flow === 'legacy'
450 ? legacyPendingJson()
446 - : toolRouterPendingJson()
451 + : toolRouterPendingJson('DEVELOPER')
452 );
453 })
454 );
@@ -551,6 +556,47 @@ describe('connected-accounts link handler: handleListConnectedAccounts', () => {
556 })
557 );
558
559 + it.effect.each([
560 + { name: '--user-id', userId: 'user_flag', expectedUser: 'user_flag' },
561 + { name: 'the directory’s test user', userId: undefined, expectedUser: 'user_directory' },
562 + ])(
563 + '[Given] dev without --project-name and $name [Then] lists that user’s accounts in the directory’s project',
564 + c =>
565 + Effect.gen(function* () {
566 + const { layer } = linkHandlerTest({
567 + surface: devSurface({ userId: c.userId }),
568 + directoryProject: directory(Option.some('user_directory')),
569 + accounts: [CONSUMER_USER_ID, 'user_flag', 'user_directory'].map(userId =>
570 + account({ id: `con_${userId}`, user_id: userId })
571 + ),
572 + });
573 + const result = yield* handleListConnectedAccounts(
574 + params({ toolkit: Option.some('gmail'), list: true })
575 + ).pipe(Effect.andThen(lastJson), Effect.provide(layer));
576 +
577 + expect(result).toMatchObject({ total: 1, items: [{ user_id: c.expectedUser }] });
578 + })
579 + );
580 +
581 + it.effect(
582 + '[Given] dev without --project-name outside a developer project [Then] fails with ProjectResolutionError',
583 + () =>
584 + Effect.gen(function* () {
585 + const { layer, requests } = linkHandlerTest({
586 + surface: devSurface({ userId: 'user_flag' }),
587 + });
588 + const error = yield* handleListConnectedAccounts(
589 + params({ toolkit: Option.some('gmail'), list: true })
590 + ).pipe(Effect.flip, Effect.provide(layer));
591 +
592 + expect(error).toMatchObject({
593 + _tag: 'services/ProjectResolutionError',
594 + reason: 'missing_developer_project',
595 + });
596 + expect(requests).toEqual([]);
597 + })
598 + );
599 +
600 it.effect('[Given] the list request fails [Then] fails with the request error', () =>
601 Effect.gen(function* () {
602 const { layer } = linkHandlerTest({ connectedAccountsListFails: true });
@@ -565,6 +611,34 @@ describe('connected-accounts link handler: handleListConnectedAccounts', () => {
611 })
612 );
613
614 + it.effect.each([
615 + {
616 + tree: 'root',
617 + surface: CommandSurface.root,
618 + message: 'Missing consumer user id. Run `composio login` and try again.',
619 + },
620 + {
621 + tree: 'dev',
622 + surface: devSurface(),
623 + message:
624 + 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
625 + },
626 + ])('[Given] no user on the $tree tree [Then] fails with that tree’s message', c =>
627 + Effect.gen(function* () {
628 + const { layer } = linkHandlerTest({
629 + surface: c.surface,
630 + directoryProject: directory(Option.none()),
631 + consumerUserId: '',
632 + });
633 + const error = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
634 + Effect.flip,
635 + Effect.provide(layer)
636 + );
637 +
638 + expect(error).toMatchObject({ message: c.message });
639 + })
640 + );
641 +
642 it.effect(
643 '[Given] dev --project-name and no user anywhere [Then] fails pointing at --user-id',
644 () =>
@@ -575,8 +649,7 @@ describe('connected-accounts link handler: handleListConnectedAccounts', () => {
649 ).pipe(Effect.flip, Effect.provide(layer));
650
651 expect(error).toMatchObject({
578 - _tag: 'commands/MissingLinkUserIdError',
579 - flow: 'list',
652 + _tag: 'commands/MissingActingUserError',
653 message:
654 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
655 });
@@ -637,13 +710,31 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
710 ).pipe(Effect.flip, Effect.provide(layer));
711
712 expect(error).toMatchObject({
640 - _tag: 'commands/MissingLinkUserIdError',
641 - flow: 'legacy',
642 - message: 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.',
713 + _tag: 'commands/MissingActingUserError',
714 + message:
715 + 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
716 });
717 })
718 );
719
720 + it.effect(
721 + '[Given] no developer project and no user [Then] reports the missing project first',
722 + () =>
723 + Effect.gen(function* () {
724 + const { layer, requests } = linkHandlerTest({ surface: devSurface() });
725 + const error = yield* handleLegacyAuthConfigLink(
726 + params({ authConfig: Option.some('ac_gmail') })
727 + ).pipe(Effect.flip, Effect.provide(layer));
728 +
729 + expect(error).toMatchObject({
730 + _tag: 'commands/CommandInputError',
731 + option: '--auth-config',
732 + message: AUTH_CONFIG_SCOPE_MESSAGE,
733 + });
734 + expect(requests).toEqual([]);
735 + })
736 + );
737 +
738 it.effect(
739 '[Given] no developer project [Then] fails with a CommandInputError explaining the scope and sends nothing',
740 () =>
@@ -711,6 +802,49 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
802 });
803
804 describe('connected-accounts link handler: handleToolRouterLink', () => {
805 + it.effect.each([
806 + { name: '--user-id', userId: 'user_flag', expectedUser: 'user_flag' },
807 + { name: 'the directory’s test user', userId: undefined, expectedUser: 'user_directory' },
808 + ])(
809 + '[Given] dev without --project-name and $name [Then] links that user in the directory’s project',
810 + c =>
811 + Effect.gen(function* () {
812 + const { layer, sessionUsers } = linkHandlerTest({
813 + surface: devSurface({ userId: c.userId }),
814 + directoryProject: directory(Option.some('user_directory')),
815 + globalTestUserId: Option.some('user_global'),
816 + });
817 + const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
818 + Effect.andThen(lines),
819 + Effect.provide(layer)
820 + );
821 +
822 + expect(sessionUsers).toEqual([c.expectedUser]);
823 + expect(String(output.at(-1))).toBe(toolRouterPendingJson('DEVELOPER'));
824 + })
825 + );
826 +
827 + it.effect(
828 + '[Given] dev and an alias already in use [Then] points at the dev commands and sends nothing',
829 + () =>
830 + Effect.gen(function* () {
831 + const { layer, requests } = linkHandlerTest({
832 + surface: devSurface({ userId: 'user_1' }),
833 + directoryProject: directory(Option.none()),
834 + accounts: [account({ user_id: 'user_1', alias: 'Work' })],
835 + });
836 + const output = yield* handleToolRouterLink(
837 + params({ toolkit: Option.some('gmail'), alias: Option.some('work') })
838 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
839 +
840 + expect(output).toEqual([
841 + 'Alias "work" is already in use by connected account "con_existing".',
842 + "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list --toolkits gmail",
843 + ]);
844 + expect(requests).toEqual([]);
845 + })
846 + );
847 +
848 it.effect(
849 '[Given] the consumer project and --alias [Then] links with the alias and prints the pending link',
850 () =>
@@ -838,43 +972,23 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
972 })
973 );
974
841 - it.effect(
842 - '[Given] no consumer user and no test user [Then] fails with the tool-router missing-user error',
843 - () =>
844 - Effect.gen(function* () {
845 - const { layer, requests } = linkHandlerTest({ consumerUserId: null });
846 - const failure = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
847 - Effect.flip,
848 - Effect.provide(layer)
849 - );
850 -
851 - // The flow re-fails `actingUser`'s expected failure as its own expected error, so
852 - // `cli.command.failed` keeps reporting `commands/MissingLinkUserIdError`.
853 - expect(failure).toBeInstanceOf(MissingLinkUserIdError);
854 - expect(failure).toMatchObject({
855 - flow: 'tool-router',
856 - message:
857 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
858 - });
859 - expect(requests).toEqual([]);
860 - })
861 - );
862 -
863 - it.effect('[Given] an empty consumer user id [Then] the flow still acts as it and links', () =>
975 + it.effect.each([
976 + { case: 'no consumer user id at all', consumerUserId: null },
977 + { case: 'an empty consumer user id', consumerUserId: '' },
978 + ])('[Given] $case and no test user [Then] fails before any link request', c =>
979 Effect.gen(function* () {
865 - const { layer, requests } = linkHandlerTest({ consumerUserId: '' });
866 - yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
867 - Effect.andThen(lines),
980 + const { layer, requests } = linkHandlerTest({ consumerUserId: c.consumerUserId });
981 + const failure = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
982 + Effect.flip,
983 Effect.provide(layer)
984 );
985
871 - // As before `actingUser`, the flow's legacy options accept the empty id as the user.
872 - expect(requests).toEqual([
873 - {
874 - operation: 'toolRouter.session.link',
875 - params: { sessionId: 'trs_handler_test', toolkit: 'gmail' },
876 - },
877 - ]);
986 + // An empty id counts as no user, so both shapes fail with the shared missing-user error.
987 + expect(failure).toBeInstanceOf(MissingActingUserError);
988 + expect(failure).toMatchObject({
989 + message: 'Missing consumer user id. Run `composio login` and try again.',
990 + });
991 + expect(requests).toEqual([]);
992 })
993 );
994
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+3 -4
@@ -336,17 +336,16 @@ describe('CLI: composio connections list account identity', () => {
336 })
337 )(it => {
338 it.effect(
339 - '[Given] an empty consumer user id [Then] fails with the command defect and its message',
339 + '[Given] an empty consumer user id [Then] fails with the missing-user error and its message',
340 () =>
341 Effect.gen(function* () {
342 const userContext = yield* ComposioUserContext;
343 yield* userContext.login('test_api_key', 'org_test');
344 const failure = yield* cli(['connections', 'list']).pipe(Effect.flip);
345
346 - // The command has always failed with this class as a defect, so `actingUser`'s
347 - // expected failure is re-tagged; the tag and the message are both load-bearing.
346 + // An empty id counts as no user; the tag is what `cli.command.failed` reports.
347 expect(failure).toMatchObject({
349 - _tag: 'commands/MissingConnectionsConsumerUserIdError',
348 + _tag: 'commands/MissingActingUserError',
349 message: 'Missing consumer user id. Run `composio login` and try again.',
350 });
351 })
ts/packages/cli/test/src/commands/connections/remove/connections.remove.cmd.test.ts
+4 -5
@@ -3,7 +3,7 @@ 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 { MissingConnectionRemovalConsumerUserIdError } from 'src/commands/connections/remove/connections.remove.errors';
6 +import { MissingActingUserError } from 'src/commands/surface';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { cli, TestLive, MockConsole } from 'test/__utils__';
9 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
@@ -370,16 +370,15 @@ describe('CLI: composio connections remove', () => {
370 })
371 )(it => {
372 it.effect(
373 - '[Given] an empty consumer user id [Then] fails with the command defect and its message',
373 + '[Given] an empty consumer user id [Then] fails with the missing-user error and its message',
374 () =>
375 Effect.gen(function* () {
376 const userContext = yield* ComposioUserContext;
377 yield* userContext.login('test_api_key', 'org_test');
378 const failure = yield* cli(['connections', 'remove', 'gmail', '--yes']).pipe(Effect.flip);
379
380 - // The removal has always failed with this class as a defect, so `actingUser`'s
381 - // expected failure is re-tagged; the tag and the message are both load-bearing.
382 - expect(failure).toBeInstanceOf(MissingConnectionRemovalConsumerUserIdError);
380 + // An empty id counts as no user, so the removal fails before resolving any account.
381 + expect(failure).toBeInstanceOf(MissingActingUserError);
382 expect(failure).toMatchObject({
383 message: 'Missing consumer user id. Run `composio login` and try again.',
384 });
ts/packages/cli/test/src/commands/errors.test.ts
+11 -16
@@ -1,12 +1,10 @@
1 -import { Predicate } from 'effect';
1 +import { Option, Predicate } from 'effect';
2 import { describe, expect, it } from 'vitest';
3 -import {
4 - ConnectionPollingError,
5 - MissingLinkUserIdError,
6 -} from 'src/commands/connected-accounts/link/connected-accounts.link.errors';
3 +import { ConnectionPollingError } from 'src/commands/connected-accounts/link/connected-accounts.link.errors';
4 import { commandInputError, isUsageFailure, notLoggedIn } from 'src/commands/errors';
5 import { InvalidOrganizationError } from 'src/commands/login/login.errors';
9 -import { ProxyCommandError, ReportedProxyCommandError } from 'src/commands/proxy.cmd';
6 +import { ReportedProxyCommandError } from 'src/commands/proxy.cmd';
7 +import { MissingActingUserError } from 'src/commands/surface';
8 import {
9 ReportedToolExecutionError,
10 ToolExecutionError,
@@ -35,8 +33,13 @@ const expected = [
33 error: new ConnectedAccountResolutionError({ message: 'No match.', toolkitSlug: 'gmail' }),
34 },
35 {
38 - name: 'execute without a user id',
39 - error: new ToolExecutionError({ reason: 'missing_user_id', message: 'Missing user id.' }),
36 + // Every command without a user to act as: execute, search, link, connections, listen, proxy.
37 + name: 'a command without a user to act as',
38 + error: new MissingActingUserError({
39 + tree: 'root',
40 + projectName: Option.none(),
41 + message: 'Missing consumer user id.',
42 + }),
43 },
44 {
45 name: 'execute with a --file the tool cannot take',
@@ -46,14 +49,6 @@ const expected = [
49 name: 'execute with a toolkit that is not connected',
50 error: new ToolExecutionError({ reason: 'connection_check', message: 'Not connected.' }),
51 },
49 - {
50 - name: 'proxy without a consumer user',
51 - error: new ProxyCommandError({ message: 'No user.' }),
52 - },
53 - {
54 - name: 'link without a user id',
55 - error: new MissingLinkUserIdError({ message: 'Missing user id.', flow: 'list' }),
56 - },
52 {
53 name: 'link with an authorization not finished in time',
54 error: new ConnectionPollingError({
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+5 -6
@@ -5,6 +5,7 @@ import { TestClock } from 'effect/testing';
5 import { ListenCommandError } from 'src/commands/listen.cmd';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7 import { ConnectedAccountResolutionError } from 'src/services/connected-account-selection';
8 +import { MissingActingUserError } from 'src/commands/surface';
9 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
@@ -578,7 +579,7 @@ describe('CLI: composio listen', () => {
579 layer(TestLive({ baseConfigProvider: testConfigProvider, accountData: { consumerUserId: '' } }))(
580 '[Given] no consumer user in the project context',
581 it => {
581 - it.effect('[Then] fails before subscribing with the preserved message', () =>
582 + it.effect('[Then] fails before subscribing with the missing-user error', () =>
583 Effect.gen(function* () {
584 const userContext = yield* ComposioUserContext;
585 yield* userContext.login('test_api_key', 'org_test');
@@ -590,12 +591,10 @@ describe('CLI: composio listen', () => {
591 '1',
592 ]).pipe(Effect.flip);
593
593 - // The command has always failed with this class as a defect, so `actingUser`'s
594 - // expected failure is re-tagged; the reason and the message are both load-bearing.
595 - expect(failure).toBeInstanceOf(ListenCommandError);
594 + // An empty id counts as no user, so listen fails with the shared missing-user error.
595 + expect(failure).toBeInstanceOf(MissingActingUserError);
596 expect(failure).toMatchObject({
597 - reason: 'project_context',
598 - message: 'No consumer user is available in the current project context.',
597 + message: 'Missing consumer user id. Run `composio login` and try again.',
598 });
599 })
600 );
ts/packages/cli/test/src/commands/surface.acting-user.test.ts
+45 -106
@@ -7,16 +7,17 @@ import {
7 CommandSurface,
8 fallbackNotice,
9 MissingActingUserError,
10 - type ActingUserOptions,
10 type ActingUserSource,
11 type CommandTree,
12 } from 'src/commands/surface';
13 import type { ProjectKeys } from 'src/models/project-keys';
14 import { ComposioClientSingleton } from 'src/services/composio-clients';
15 import { ProjectContext } from 'src/services/project-context';
16 +import { TerminalUI } from 'src/services/terminal-ui';
17 import { ComposioUserContext } from 'src/services/user-context';
18 import { mockAccountResources } from 'test/__utils__/layers/accounts';
19 import { makeOrgProject } from 'test/__utils__/models/account';
20 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
21
22 const ORG_ID = 'org_test';
23 const CONSUMER_USER_ID = `consumer-user-${ORG_ID}`;
@@ -50,7 +51,8 @@ const PROJECT_NAMES: Record<ProjectName, Option.Option<string>> = {
51 other: Option.some('other'),
52 };
53
53 -const actingUserLayer = (fixture: Fixture) => {
54 +/** `warnings` collects what the code under test warns on stderr. */
55 +const actingUserLayer = (fixture: Fixture, warnings: Array<string>) => {
56 const has = (candidate: Exclude<Candidates, 'none'>) =>
57 CANDIDATE_ORDER.indexOf(candidate) >= CANDIDATE_ORDER.indexOf(fixture.candidates);
58 const directory: ProjectKeys = {
@@ -86,6 +88,16 @@ const actingUserLayer = (fixture: Fixture) => {
88 } as unknown as ComposioClientShape;
89
90 return Layer.mergeAll(
91 + Layer.succeed(
92 + TerminalUI,
93 + TerminalUI.of({
94 + ...terminalUITestImpl,
95 + log: {
96 + ...terminalUITestImpl.log,
97 + warn: message => Effect.sync(() => warnings.push(message)),
98 + },
99 + })
100 + ),
101 Layer.succeed(
102 CommandSurface,
103 CommandSurface.of({
@@ -171,18 +183,27 @@ const cases = TREES.flatMap(tree =>
183 const run = <
184 A,
185 E,
174 - R extends CommandSurface | ComposioUserContext | ProjectContext | ComposioClientSingleton,
186 + R extends
187 + CommandSurface | ComposioUserContext | ProjectContext | ComposioClientSingleton | TerminalUI,
188 >(
189 effect: Effect.Effect<A, E, R>,
177 - fixture: Fixture
178 -) => effect.pipe(Effect.provide(actingUserLayer(fixture)));
190 + fixture: Fixture,
191 + warnings: Array<string> = []
192 +) => effect.pipe(Effect.provide(actingUserLayer(fixture, warnings)));
193 +
194 +/** The notice printed for the rule's user: one line for a test user standing in, else none. */
195 +const expectedNotices = (fixture: Fixture) =>
196 + Option.toArray(Option.flatMap(expectedUser(fixture), fallbackNotice));
197
198 describe('actingUser', () => {
199 it.effect.each(cases)('[Given] $name [Then] acts as the rule’s user', fixture =>
200 Effect.gen(function* () {
183 - const result = yield* run(Effect.result(actingUser()), fixture);
201 + const warnings: Array<string> = [];
202 + const result = yield* run(Effect.result(actingUser()), fixture, warnings);
203 const expected = expectedUser(fixture);
204
205 + expect(warnings).toEqual(expectedNotices(fixture));
206 +
207 if (Option.isNone(expected)) {
208 expect(result).toMatchObject({ failure: { _tag: 'commands/MissingActingUserError' } });
209 return;
@@ -226,124 +247,42 @@ describe('actingUser', () => {
247 expect(error).toMatchObject({ tree, projectName: PROJECT_NAMES[projectName], message });
248 })
249 );
229 -
230 - it.effect('[Given] a command’s own message [Then] fails with it, given --project-name', () =>
231 - Effect.gen(function* () {
232 - const error = yield* run(
233 - Effect.flip(
234 - actingUser({
235 - missingUserMessage: name => `No user for ${Option.getOrElse(name, () => 'none')}.`,
236 - })
237 - ),
238 - { tree: 'dev', projectName: 'other', candidates: 'none' }
239 - );
240 -
241 - expect(error).toMatchObject({ message: 'No user for other.' });
242 - })
243 - );
244 -
245 - it.effect.each([
246 - {
247 - name: 'the consumer project without --project-name ignores --user-id',
248 - options: { legacy: { consumerWithoutProjectName: true } },
249 - fixture: { tree: 'dev', candidates: 'flag', projectName: 'absent' },
250 - expected: { userId: CONSUMER_USER_ID, source: 'consumer', projectId: CONSUMER_PROJECT_ID },
251 - },
252 - {
253 - name: 'the consumer project still yields to --project-name',
254 - options: { legacy: { consumerWithoutProjectName: true } },
255 - fixture: { tree: 'dev', candidates: 'directory', projectName: 'same' },
256 - expected: {
257 - userId: 'directory-user',
258 - source: 'directory-test-user',
259 - projectId: DIRECTORY_PROJECT_ID,
260 - },
261 - },
262 - {
263 - name: 'skipping the directory test user falls back to the global one',
264 - options: { legacy: { skipDirectoryTestUser: true } },
265 - fixture: { tree: 'dev', candidates: 'directory', projectName: 'same' },
266 - expected: {
267 - userId: 'global-user',
268 - source: 'global-test-user',
269 - projectId: DIRECTORY_PROJECT_ID,
270 - },
271 - },
272 - ] satisfies ReadonlyArray<{
273 - name: string;
274 - options: ActingUserOptions;
275 - fixture: Fixture;
276 - expected: { userId: string; source: ActingUserSource; projectId: string };
277 - }>)('[Given] legacy: $name', ({ options, fixture, expected }) =>
278 - Effect.gen(function* () {
279 - const user = yield* run(actingUser(options), fixture);
280 -
281 - expect(user).toMatchObject({
282 - userId: expected.userId,
283 - source: expected.source,
284 - project: { projectId: expected.projectId },
285 - });
286 - })
287 - );
250 });
251
290 -// Commands passing `acceptEmptyConsumerUserId` count an empty consumer user id as a user.
252 +// `execute`, `search`, `link` and `run` used to accept an empty consumer user id as the user.
253 describe('an empty consumer user id', () => {
292 - const ACCEPT_EMPTY = { legacy: { acceptEmptyConsumerUserId: true } } satisfies ActingUserOptions;
293 - const sites = [
294 - { sites: 'execute, search, link, run', options: ACCEPT_EMPTY, tree: 'root', accepted: true },
295 - {
296 - sites: 'link on the dev tree without --project-name',
297 - options: { legacy: { ...ACCEPT_EMPTY.legacy, consumerWithoutProjectName: true } },
298 - tree: 'dev',
299 - accepted: true,
300 - },
301 - { sites: 'connections list/remove, listen, proxy', options: {}, tree: 'root', accepted: false },
302 - ] satisfies ReadonlyArray<{
303 - sites: string;
304 - options: ActingUserOptions;
305 - tree: CommandTree;
306 - accepted: boolean;
307 - }>;
308 - const fixture = (tree: CommandTree): Fixture => ({
309 - tree,
254 + const fixture: Fixture = {
255 + tree: 'root',
256 candidates: 'flag',
257 projectName: 'absent',
258 consumerUserId: '',
313 - });
259 + };
260
315 - it.effect.each(sites)(
316 - '[Given] $sites [Then] actingUser accepts it: $accepted',
317 - ({ options, tree, accepted }) =>
318 - Effect.gen(function* () {
319 - const result = yield* run(Effect.result(actingUser(options)), fixture(tree));
261 + it.effect('[Given] an empty consumer user id [Then] actingUser fails as missing', () =>
262 + Effect.gen(function* () {
263 + const error = yield* run(Effect.flip(actingUser()), fixture);
264
321 - expect(result).toMatchObject(
322 - accepted
323 - ? { success: { userId: '', source: 'consumer' } }
324 - : { failure: { _tag: 'commands/MissingActingUserError' } }
325 - );
326 - })
265 + expect(error).toBeInstanceOf(MissingActingUserError);
266 + })
267 );
268
329 - it.effect.each(sites)(
330 - '[Given] $sites [Then] actingUserOption finds it: $accepted',
331 - ({ options, tree, accepted }) =>
332 - Effect.gen(function* () {
333 - const user = yield* run(actingUserOption(options), fixture(tree));
269 + it.effect('[Given] an empty consumer user id [Then] actingUserOption finds none', () =>
270 + Effect.gen(function* () {
271 + const user = yield* run(actingUserOption(), fixture);
272
335 - expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
336 - accepted ? Option.some({ userId: '', source: 'consumer' }) : Option.none()
337 - );
338 - })
273 + expect(user).toEqual(Option.none());
274 + })
275 );
276 });
277
278 describe('actingUserOption', () => {
279 it.effect.each(cases)('[Given] $name [Then] finds the rule’s user, or none', fixture =>
280 Effect.gen(function* () {
345 - const user = yield* run(actingUserOption(), fixture);
281 + const warnings: Array<string> = [];
282 + const user = yield* run(actingUserOption(), fixture, warnings);
283 const expected = expectedUser(fixture);
284 +
285 + expect(warnings).toEqual(expectedNotices(fixture));
286 // Only the project --project-name names is resolved on the dev tree.
287 const project =
288 fixture.tree === 'dev' && fixture.projectName === 'absent'
ts/packages/cli/test/src/commands/surface.test.ts
+67 -48
@@ -13,7 +13,7 @@ import { makeOrgProject } from 'test/__utils__/models/account';
13 const SHARED_PROJECT_DESCRIPTION =
14 'Developer project to use instead of the one configured in this directory';
15 const SHARED_USER_DESCRIPTION =
16 - 'User id to act as or filter by. Commands that act as a user default to the project test user id, then the global one.';
16 + 'User id to act as or filter by. Without it, commands that act as a user use the test user id of this directory (for its own project), then the global one, and name it on stderr.';
17 // `dev logs tools|triggers` declare a comma-separated `--user-id` filter of their own, which
18 // `withSharedFlags` accepts below a group entry and the help page shows in place of the shared row.
19 const OWN_USER_ID_PAGES = ['dev logs tools', 'dev logs triggers'];
@@ -422,13 +422,15 @@ describe('CommandSurface: a named project does not borrow the directory test use
422 );
423 });
424
425 + /** The users the command opened sessions as, and the fallback notices it printed. */
426 const sessionUser = (args: ReadonlyArray<string>) =>
427 Effect.gen(function* () {
428 const userIds: Array<string> = [];
428 - yield* Effect.gen(function* () {
429 + const lines = yield* Effect.gen(function* () {
430 yield* writeDirectoryProject;
431 yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
432 yield* Effect.exit(cli(args));
433 + return yield* MockConsole.getLines({ stripAnsi: true });
434 }).pipe(
435 Effect.provide(
436 TestLive({
@@ -460,7 +462,10 @@ describe('CommandSurface: a named project does not borrow the directory test use
462 ),
463 Effect.scoped
464 );
463 - return [...new Set(userIds)];
465 + return {
466 + users: [...new Set(userIds)],
467 + notices: lines.filter(line => /^Using (global )?test user id/u.test(line)),
468 + };
469 });
470
471 const projects = [
@@ -474,24 +479,52 @@ describe('CommandSurface: a named project does not borrow the directory test use
479 command: 'playground-execute',
480 args: ['dev', 'playground-execute', 'GMAIL_SEND_EMAIL', '-d', '{}', '--skip-checks'],
481 },
482 + {
483 + command: 'playground-execute --parallel',
484 + args: [
485 + 'dev',
486 + 'playground-execute',
487 + '--parallel',
488 + 'GMAIL_SEND_EMAIL',
489 + '-d',
490 + '{}',
491 + 'GMAIL_FETCH_EMAILS',
492 + '-d',
493 + '{}',
494 + '--skip-checks',
495 + ],
496 + },
497 + {
498 + command: 'connected-accounts link',
499 + args: ['dev', 'connected-accounts', 'link', 'gmail', '--no-wait'],
500 + },
501 ];
502 const projectCases = [
479 - { project: ['--project-name', 'other-project'], expected: 'global_user' },
480 - { project: ['--project-name', 'dir-project'], expected: 'directory_user' },
481 - { project: [], expected: 'directory_user' },
503 + {
504 + project: ['--project-name', 'other-project'],
505 + expected: 'global_user',
506 + notice: 'Using global test user id "global_user"',
507 + },
508 + {
509 + project: ['--project-name', 'dir-project'],
510 + expected: 'directory_user',
511 + notice: 'Using test user id "directory_user"',
512 + },
513 + { project: [], expected: 'directory_user', notice: 'Using test user id "directory_user"' },
514 ];
515
516 it.effect.each(
517 sessionCommands.flatMap(({ command, args }) =>
486 - projectCases.map(({ project, expected }) => ({
518 + projectCases.map(({ project, expected, notice }) => ({
519 args: [...args, ...project],
520 expected,
521 + notice,
522 name: `${command} ${project.join(' ') || 'without --project-name'}`,
523 }))
524 )
492 - )('`$name` opens its session as $expected', ({ args, expected }) =>
525 + )('`$name` opens its session as $expected and says so once', ({ args, expected, notice }) =>
526 Effect.gen(function* () {
494 - expect(yield* sessionUser(args)).toEqual([expected]);
527 + expect(yield* sessionUser(args)).toEqual({ users: [expected], notices: [notice] });
528 })
529 );
530
@@ -515,46 +548,32 @@ describe('CommandSurface: a named project does not borrow the directory test use
548 test_request_endpoint: '',
549 });
550
518 - // `link --list` without --project-name resolves the consumer project and its own user, so only
519 - // the named cases apply.
551 it.effect.each([
521 - { project: 'other-project', expected: 'ca_global', other: 'ca_dir' },
522 - { project: 'dir-project', expected: 'ca_dir', other: 'ca_global' },
523 - ])(
524 - '`connected-accounts link --list --project-name $project` lists $expected',
525 - ({ project, expected, other }) =>
526 - Effect.gen(function* () {
527 - yield* writeDirectoryProject;
528 - yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
529 - yield* cli([
530 - 'dev',
531 - 'connected-accounts',
532 - 'link',
533 - 'gmail',
534 - '--list',
535 - '--project-name',
536 - project,
537 - ]);
538 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
539 - expect(output).toContain(expected);
540 - expect(output).not.toContain(other);
541 - }).pipe(
542 - Effect.provide(
543 - TestLive({
544 - baseConfigProvider: ConfigProvider.fromEnv({
545 - env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
546 - }),
547 - accountData: { projects },
548 - connectedAccountsData: {
549 - items: [
550 - accountFor('global_user', 'ca_global'),
551 - accountFor('directory_user', 'ca_dir'),
552 - ],
553 - },
554 - })
555 - ),
556 - Effect.scoped
557 - )
552 + { project: ['--project-name', 'other-project'], expected: 'ca_global', other: 'ca_dir' },
553 + { project: ['--project-name', 'dir-project'], expected: 'ca_dir', other: 'ca_global' },
554 + { project: [], expected: 'ca_dir', other: 'ca_global' },
555 + ])('`connected-accounts link --list $project` lists $expected', ({ project, expected, other }) =>
556 + Effect.gen(function* () {
557 + yield* writeDirectoryProject;
558 + yield* (yield* ComposioUserContext).login('test_api_key', 'org_test', 'global_user');
559 + yield* cli(['dev', 'connected-accounts', 'link', 'gmail', '--list', ...project]);
560 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
561 + expect(output).toContain(expected);
562 + expect(output).not.toContain(other);
563 + }).pipe(
564 + Effect.provide(
565 + TestLive({
566 + baseConfigProvider: ConfigProvider.fromEnv({
567 + env: { COMPOSIO_USER_API_KEY: 'test_api_key', COMPOSIO_ORG_ID: 'org_test' },
568 + }),
569 + accountData: { projects },
570 + connectedAccountsData: {
571 + items: [accountFor('global_user', 'ca_global'), accountFor('directory_user', 'ca_dir')],
572 + },
573 + })
574 + ),
575 + Effect.scoped
576 + )
577 );
578
579 it.effect.each([
ts/packages/cli/test/src/commands/toolkits/list/toolkits.list.handler.test.ts
+1 -50
@@ -1,55 +1,6 @@
1 import { describe, expect, it } from 'vitest';
2 -import { Option } from 'effect';
2 import type { UnifiedToolkit } from 'src/commands/toolkits/format';
4 -import {
5 - applyConnectedFilter,
6 - resolveToolkitsListUser,
7 -} from 'src/commands/toolkits/list/toolkits.list.handler';
8 -
9 -describe('toolkits list handler: resolveToolkitsListUser', () => {
10 - // `--user-id` wins, then the directory's test user, then the global one; only a fallback is announced.
11 - it.each([
12 - {
13 - name: '--user-id and both test users',
14 - flag: Option.some('alice'),
15 - projectTestUserId: Option.some('project-user'),
16 - globalTestUserId: Option.some('global-user'),
17 - expected: Option.some({ id: 'alice', fallbackNotice: Option.none() }),
18 - },
19 - {
20 - name: 'the directory and the global test user',
21 - flag: Option.none(),
22 - projectTestUserId: Option.some('project-user'),
23 - globalTestUserId: Option.some('global-user'),
24 - expected: Option.some({
25 - id: 'project-user',
26 - fallbackNotice: Option.some('Using test user id "project-user"'),
27 - }),
28 - },
29 - {
30 - name: 'only the global test user',
31 - flag: Option.none(),
32 - projectTestUserId: Option.none(),
33 - globalTestUserId: Option.some('global-user'),
34 - expected: Option.some({
35 - id: 'global-user',
36 - fallbackNotice: Option.some('Using global test user id "global-user"'),
37 - }),
38 - },
39 - {
40 - name: 'no user anywhere',
41 - flag: Option.none(),
42 - projectTestUserId: Option.none(),
43 - globalTestUserId: Option.none(),
44 - expected: Option.none(),
45 - },
46 - ])(
47 - '[Given] $name [Then] resolves the expected user',
48 - ({ name: _name, expected, ...candidates }) => {
49 - expect(resolveToolkitsListUser(candidates)).toEqual(expected);
50 - }
51 - );
52 -});
3 +import { applyConnectedFilter } from 'src/commands/toolkits/list/toolkits.list.handler';
4
5 const row = (slug: string, status: string | null): UnifiedToolkit => ({
6 name: slug,
ts/packages/cli/test/src/commands/tools/search/tools.search.cmd.test.ts
+15 -13
@@ -8,6 +8,7 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
8 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
9 import type { Tools } from 'src/models/tools';
10 import { CommandInputError } from 'src/commands/errors';
11 +import { MissingActingUserError } from 'src/commands/surface';
12
13 const testTools: Tools = [
14 {
@@ -837,20 +838,17 @@ describe('CLI: composio search', () => {
838 layer(
839 TestLive({
840 ...testLiveOptions,
840 - // The empty id is accepted (legacy); a response without the field at all is the only
841 - // way no consumer user resolves.
841 + // A response without the field at all, which only a mock can answer.
842 accountData: { consumerUserId: null },
843 })
844 - )('[Given] no consumer user id [Then] the search fails as a usage error', it => {
845 - it.effect('[Then] the preserved message names --user-id', () =>
844 + )('[Given] no consumer user id [Then] the search fails with the missing-user error', it => {
845 + it.effect('[Then] the message points at composio login', () =>
846 Effect.gen(function* () {
847 const failure = yield* cli(['search', 'send']).pipe(Effect.flip);
848
849 - expect(failure).toBeInstanceOf(CommandInputError);
849 + expect(failure).toBeInstanceOf(MissingActingUserError);
850 expect(failure).toMatchObject({
851 - option: '--user-id',
852 - message:
853 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
851 + message: 'Missing consumer user id. Run `composio login` and try again.',
852 });
853 })
854 );
@@ -859,16 +857,20 @@ describe('CLI: composio search', () => {
857 layer(
858 TestLive({
859 ...testLiveOptions,
862 - // As before `actingUser`, the search accepts the empty id as the user.
860 + // The backend's "logged in, but no consumer user" shape counts as no user.
861 accountData: { consumerUserId: '' },
862 })
865 - )('[Given] an empty consumer user id [Then] the search still runs', it => {
866 - it.effect('[Then] results come back for the accepted user', () =>
863 + )('[Given] an empty consumer user id [Then] the search fails with the missing-user error', it => {
864 + it.effect('[Then] no results are printed', () =>
865 Effect.gen(function* () {
868 - yield* cli(['search', 'send']);
866 + const failure = yield* cli(['search', 'send']).pipe(Effect.flip);
867 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
868
871 - expect(output).toContain('GMAIL_SEND_EMAIL');
869 + expect(failure).toBeInstanceOf(MissingActingUserError);
870 + expect(failure).toMatchObject({
871 + message: 'Missing consumer user id. Run `composio login` and try again.',
872 + });
873 + expect(output).not.toContain('GMAIL_SEND_EMAIL');
874 })
875 );
876 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+14 -14
@@ -12,6 +12,7 @@ import { clearInProcessMemos } from 'src/utils/memoize-in-process';
12 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
13 import * as composioAccount from 'src/services/composio-account';
14 import type { ToolkitProjectScope } from 'src/services/composio-clients';
15 +import { MissingActingUserError } from 'src/commands/surface';
16 import { ComposioUserContext } from 'src/services/user-context';
17 import * as toolPermissions from 'src/services/tool-permissions';
18 import * as redactModule from 'src/ui/redact';
@@ -3458,15 +3459,13 @@ describe('CLI: composio execute without a resolvable acting user', () => {
3459 accountData: { consumerUserId: null },
3460 })
3461 )('[Given] the consumer project has no user id at all [Then] the root tree fails', it => {
3461 - it.effect('[Then] the missing_user_id failure carries the root message', () =>
3462 + it.effect('[Then] the missing-user error carries the root message', () =>
3463 Effect.gen(function* () {
3464 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{}']).pipe(Effect.flip);
3465
3466 + expect(failure).toBeInstanceOf(MissingActingUserError);
3467 expect(failure).toMatchObject({
3466 - _tag: 'ToolExecutionError',
3467 - reason: 'missing_user_id',
3468 - message:
3469 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
3468 + message: 'Missing consumer user id. Run `composio login` and try again.',
3469 });
3470 })
3471 );
@@ -3484,7 +3483,7 @@ describe('CLI: composio execute without a resolvable acting user', () => {
3483 stdin: { isTTY: true, data: '' },
3484 })
3485 )('[Given] a directory project and no user candidates [Then] the dev tree fails', it => {
3487 - it.effect('[Then] the missing_user_id failure carries the dev message', () =>
3486 + it.effect('[Then] the missing-user error carries the dev message', () =>
3487 Effect.gen(function* () {
3488 const userContext = yield* ComposioUserContext;
3489 yield* userContext.login('test_api_key', 'org_test');
@@ -3496,9 +3495,8 @@ describe('CLI: composio execute without a resolvable acting user', () => {
3495 '{}',
3496 ]).pipe(Effect.flip);
3497
3498 + expect(failure).toBeInstanceOf(MissingActingUserError);
3499 expect(failure).toMatchObject({
3500 - _tag: 'ToolExecutionError',
3501 - reason: 'missing_user_id',
3500 message:
3501 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
3502 });
@@ -3513,19 +3511,21 @@ describe('CLI: composio execute without a resolvable acting user', () => {
3511 stdin: { isTTY: true, data: '' },
3512 accountData: { consumerUserId: '' },
3513 })
3516 - )('[Given] an empty consumer user id [Then] the root tree accepts it as the user', it => {
3517 - it.effect('[Then] the execution runs and reports success', () =>
3514 + )('[Given] an empty consumer user id [Then] the root tree treats it as no user', it => {
3515 + it.effect('[Then] the execution fails with the missing-user error', () =>
3516 Effect.gen(function* () {
3519 - yield* cli([
3517 + const failure = yield* cli([
3518 'execute',
3519 'GMAIL_SEND_EMAIL',
3520 '--skip-connection-check',
3521 '-d',
3522 '{"recipient":"a"}',
3525 - ]);
3526 - const output = parseLastJson(yield* MockConsole.getLines({ stripAnsi: true }));
3523 + ]).pipe(Effect.flip);
3524
3528 - expect(output.successful).toBe(true);
3525 + expect(failure).toBeInstanceOf(MissingActingUserError);
3526 + expect(failure).toMatchObject({
3527 + message: 'Missing consumer user id. Run `composio login` and try again.',
3528 + });
3529 })
3530 );
3531 });