@devries-cameron20 / composio-1 / commits / fc135da35
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.

fix(cli): forward user ID when creating development triggers (#4982)

## Summary Refs #4964: fixes its main report, `dev triggers create` on 2FA projects. The issue stays open for its two related reports (connected accounts landing in the consumer project, and the toolkit CLI docs). A 2FA-enabled project requires `user_id` when validating a trigger's connected-account owner, but `composio dev triggers create` currently rejects the shared `--user-id` flag and sends no user ID. ```text shared --user-id -> resolved directory project test user -> global test user -> omit user_id when none is configured ``` ## Changes - Accept the existing shared `--user-id` before or after the subcommand and forward the selected user to trigger upsert. - Keep `--project-name` rejected until this command supports named-project routing. - Move create into the required cmd/handler directory layout, add its mirrored tests, and remove its command-test exemption. - Update the CLI README and changelog, including the existing process-environment override of directory configuration. The create-command move overlaps #4970, which is currently open. ## Type of change - [x] Bug fix ## Evidence / How Has This Been Tested? - **Before:** 4 failures and 1 pass in the five user-selection regression cases: explicit IDs are rejected and defaults do not reach the request. - **After:** 13 trigger tests pass, covering explicit IDs in both positions, directory/global defaults, absent defaults, creation output, JSON validation, and existing enable/disable behavior. - 30 selected shared-flag guard tests pass, including create's continued rejection of `--project-name`; other surface tests were filtered. - `pnpm typecheck`: 14/14 tasks passed. - `pnpm --filter @composio/cli run lint:effect`: no errors or warnings. - CLI build, changed-file Prettier/Oxlint, `validate:command-tests`, and `git diff --check`: passed. Windows validation limitations: - Focused tests use an untracked Vitest configuration with correct file URL conversion. The standard configuration/global setup currently generate a duplicated drive prefix on Windows. Tracked test configuration is unchanged. - Recorded full-suite comparison using the same path corrections: baseline 1,795 passed / 151 failed / 1 skipped; patched 1,798 passed / 152 failed / 1 skipped. Two patch-only timing failures passed on isolated rerun; one baseline-only analytics race passed in the patched run. The full suite is not green. - The root agent-guidance validator encounters an existing Windows symlink separator mismatch. - No real 2FA project or Trello account was used for hosted API validation. ## Merge Danger **Door:** Two-way; request parameter selection and command wiring. **Blast Radius:** Development trigger creation. User ownership continues to be checked by the API, and the existing project-context resolver supplies any directory default. ## Checklist - [x] Read the contribution policy, Code of Conduct, and complete diff. - [x] Added regression tests and updated README/changelog. - [x] Ran required checks and documented validation limitations. - [x] Confirmed that `@composio/cli` is excluded from Changesets. ## Additional context This addresses the trigger-creation user-ID conflict in #4964. The connected-account project-routing and toolkit-documentation reports in that issue are outside this patch. --------- Co-authored-by: shenmuegit <29520926+shenmuegit@users.noreply.github.com> Co-authored-by: jkomyno <alberto@composio.dev> Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com>

meolord committed Oct 22, 2026 at 22:43 UTC fc135da3568ef59041567d38211ca777b109db13
6 files changed +163 -4
ts/packages/cli/CHANGELOG.md
+9
@@ -4,6 +4,15 @@
4
5 ### Patch Changes
6
7 +- `composio dev triggers create` now accepts `--user-id` and sends it with the
8 + request, so it works on projects with 2FA enabled, which require the user who
9 + owns the connected account. It used to reject `--user-id` and send no user,
10 + so creating a trigger on those projects always failed. Without `--user-id`
11 + it sends the project's test user id, else the global test user id, and names
12 + the one it used on stderr; with neither configured it sends no user, as
13 + before. Given a user and no `--connected-account-id`, the API picks that
14 + user's first active connection for the trigger's toolkit.
15 +
16 - More expected errors now print as a plain message on stderr and exit 1, like
17 other usage errors. They used to print under a `💥` banner with the error tag
18 and a stack location, as if the CLI had crashed. The message itself is
ts/packages/cli/README.md
+15
@@ -51,6 +51,21 @@ composio [--log-level All|Trace|Debug|Info|Warn|Error|Fatal|None]
51 Use `composio execute <slug> --get-schema` to print a tool's input schema as JSON.
52 `composio execute <slug> --help` now shows command options and examples.
53
54 +### Creating development triggers
55 +
56 +For a project with 2FA enabled, pass the user who owns the connected account:
57 +
58 +```bash
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.
68 +
69 ## Configuration
70
71 The Composio CLI supports configuration via environment variables. It stores authenticated user context in `user_data.json` and general CLI settings in `config.json`.
ts/packages/cli/src/commands/triggers/create/triggers.create.handler.ts
+24 -1
@@ -1,9 +1,12 @@
1 import { Effect, Match, Option, Result } from 'effect';
2 import { commandInputError } from 'src/commands/errors';
3 +import { CommandSurface } from 'src/commands/surface';
4 import { handleClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 +import { ProjectContext } from 'src/services/project-context';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 import { parseJsonRecord, type JsonParsingError } from 'src/utils/parse-json';
11
12 export type TriggersCreateParams = {
@@ -40,7 +43,8 @@ const invalidTriggerConfig = (error: JsonParsingError) =>
43 );
44
45 /**
43 - * Create a trigger instance. A missing `<trigger-name>` or an invalid `--trigger-config` fails
46 + * Create a trigger instance as the `dev` group's `--user-id`, else the directory project's test
47 + * user, else the global test user; without any, the request omits `user_id`. A missing `<trigger-name>` or an invalid `--trigger-config` fails
48 * with a `CommandInputError` before any request; an API failure is reported with a hint and
49 * exits 1.
50 *
@@ -57,6 +61,9 @@ export const runTriggersCreate = ({
61 Effect.gen(function* () {
62 const ui = yield* TerminalUI;
63 const repo = yield* ComposioToolkitsRepository;
64 + const { userId } = yield* CommandSurface;
65 + const projectContext = yield* ProjectContext;
66 + const userContext = yield* ComposioUserContext;
67
68 if (Option.isNone(triggerName)) {
69 return yield* invalidInput(
@@ -70,12 +77,28 @@ export const runTriggersCreate = ({
77 return yield* invalidTriggerConfig(parsedTriggerConfig.failure);
78 }
79
80 + const project = yield* projectContext.resolve;
81 + const projectTestUserId = Option.flatMap(project, keys => keys.testUserId);
82 + const globalTestUserId = userContext.data.testUserId;
83 + const resolvedUserId = userId.pipe(
84 + Option.orElse(() => projectTestUserId),
85 + Option.orElse(() => globalTestUserId)
86 + );
87 +
88 + // A defaulted user id must own the connected account on a 2FA project, so name it.
89 + if (Option.isNone(userId) && Option.isSome(projectTestUserId)) {
90 + yield* ui.log.warn(`Using test user id "${projectTestUserId.value}"`);
91 + } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
92 + yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
93 + }
94 +
95 const createdOpt = yield* ui
96 .withSpinner(
97 `Creating trigger "${triggerName.value}"...`,
98 repo.createTrigger(triggerName.value, {
99 connected_account_id: Option.getOrUndefined(connectedAccountId),
100 trigger_config: parsedTriggerConfig.success,
101 + user_id: Option.getOrUndefined(resolvedUserId),
102 })
103 )
104 .pipe(
ts/packages/cli/src/commands/triggers/triggers.cmd.ts
+1 -1
@@ -24,7 +24,7 @@ export const triggersCmd = Command.make('triggers').pipe(
24 triggersCmd$List.pipe(rejectsSharedFlags('dev triggers list')),
25 triggersCmd$Info.pipe(rejectsSharedFlags('dev triggers info')),
26 triggersCmd$Status.pipe(rejectsSharedFlags('dev triggers status')),
27 - triggersCmd$Create.pipe(rejectsSharedFlags('dev triggers create')),
27 + triggersCmd$Create.pipe(rejectsSharedFlags('dev triggers create', ['--project-name'])),
28 triggersCmd$Enable.pipe(rejectsSharedFlags('dev triggers enable')),
29 triggersCmd$Disable.pipe(rejectsSharedFlags('dev triggers disable')),
30 ]),
ts/packages/cli/test/src/commands/surface.test.ts
+1 -1
@@ -357,7 +357,7 @@ const rejectingCommands = [
357 { path: ['triggers', 'status'], flags: ['--project-name', '--user-id'] },
358 {
359 path: ['triggers', 'create', 'GMAIL_NEW_GMAIL_MESSAGE'],
360 - flags: ['--project-name', '--user-id'],
360 + flags: ['--project-name'],
361 },
362 { path: ['triggers', 'enable', 'ti_1'], flags: ['--project-name', '--user-id'] },
363 { path: ['triggers', 'disable', 'ti_1'], flags: ['--project-name', '--user-id'] },
ts/packages/cli/test/src/commands/triggers/create/triggers.create.cmd.test.ts
+113 -1
@@ -1,8 +1,11 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect, Layer } from 'effect';
2 +import { ConfigProvider, Effect, Layer, Option } from 'effect';
3 import type { TriggerInstanceUpsertParams } from '@composio/client/resources/trigger-instances';
4 import { isUsageFailure } from 'src/commands/errors';
5 +import { projectKeysFromJSON } from 'src/models/project-keys';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 +import { ProjectContext } from 'src/services/project-context';
8 +import { ComposioUserContext } from 'src/services/user-context';
9 import { cli, MockConsole, TestLive } from 'test/__utils__';
10 import { notFoundError } from 'test/__utils__/layers/not-found';
11 import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
@@ -17,7 +20,116 @@ const dangerousDevConfig = {
20 cliUserConfig: { developerDangerousCommandsEnabled: true },
21 } as const;
22
23 +const createArgs = [
24 + 'triggers',
25 + 'create',
26 + 'GMAIL_NEW_GMAIL_MESSAGE',
27 + '--connected-account-id',
28 + 'con_123',
29 + '--trigger-config',
30 + '{"label":"inbox"}',
31 +];
32 +
33 +const userCases = [
34 + {
35 + name: '--user-id before the subcommand overrides both defaults',
36 + args: ['dev', '--user-id', 'alice', ...createArgs],
37 + projectUserId: 'project-user',
38 + globalUserId: 'global-user',
39 + expectedUserId: 'alice',
40 + expectedLog: undefined,
41 + },
42 + {
43 + name: '--user-id after the subcommand overrides both defaults',
44 + args: ['dev', ...createArgs, '--user-id', 'alice'],
45 + projectUserId: 'project-user',
46 + globalUserId: 'global-user',
47 + expectedUserId: 'alice',
48 + expectedLog: undefined,
49 + },
50 + {
51 + name: 'the project test user takes precedence over the global one',
52 + args: ['dev', ...createArgs],
53 + projectUserId: 'project-user',
54 + globalUserId: 'global-user',
55 + expectedUserId: 'project-user',
56 + expectedLog: 'Using test user id "project-user"',
57 + },
58 + {
59 + name: 'the global test user is used without a project test user',
60 + args: ['dev', ...createArgs],
61 + projectUserId: undefined,
62 + globalUserId: 'global-user',
63 + expectedUserId: 'global-user',
64 + expectedLog: 'Using global test user id "global-user"',
65 + },
66 + {
67 + name: 'a connection can still be used without a configured test user',
68 + args: ['dev', ...createArgs],
69 + projectUserId: undefined,
70 + globalUserId: undefined,
71 + expectedUserId: undefined,
72 + expectedLog: undefined,
73 + },
74 +];
75 +
76 describe('CLI: composio dev triggers create', () => {
77 + layer(TestLive(dangerousDevConfig))(
78 + '[Given] a user id source [Then] sends the selected user id',
79 + it => {
80 + it.effect.each(userCases)(
81 + '$name',
82 + ({ args, projectUserId, globalUserId, expectedUserId, expectedLog }) =>
83 + Effect.gen(function* () {
84 + const previousLines = (yield* MockConsole.getLines()).length;
85 + const userContext = yield* ComposioUserContext;
86 + yield* userContext.login('test_api_key', 'org_test', globalUserId);
87 + const project = yield* projectKeysFromJSON(
88 + JSON.stringify({
89 + org_id: 'org_test',
90 + project_id: 'proj_test',
91 + test_user_id: projectUserId,
92 + })
93 + );
94 + const calls: Array<{ slug: string; params?: TriggerInstanceUpsertParams }> = [];
95 + const repository = Layer.succeed(
96 + ComposioToolkitsRepository,
97 + makeToolkitsRepositoryStub({
98 + createTrigger: (slug, params) =>
99 + Effect.sync(() => {
100 + calls.push({ slug, params });
101 + return { trigger_id: 'trg_new' };
102 + }),
103 + })
104 + );
105 + const projectContext = Layer.succeed(
106 + ProjectContext,
107 + ProjectContext.of({ resolve: Effect.succeed(Option.some(project)) })
108 + );
109 +
110 + yield* cli(args).pipe(Effect.provide(Layer.merge(repository, projectContext)));
111 +
112 + expect(calls).toEqual([
113 + {
114 + slug: 'GMAIL_NEW_GMAIL_MESSAGE',
115 + params: {
116 + connected_account_id: 'con_123',
117 + trigger_config: { label: 'inbox' },
118 + user_id: expectedUserId,
119 + },
120 + },
121 + ]);
122 + const logs = (yield* MockConsole.getLines({ stripAnsi: true }))
123 + .slice(previousLines)
124 + .filter(line => line.includes('test user id'));
125 + expect(logs).toEqual(
126 + expectedLog === undefined ? [] : [expect.stringContaining(expectedLog)]
127 + );
128 + })
129 + );
130 + }
131 + );
132 +
133 layer(TestLive(dangerousDevConfig))(
134 '[Given] create with valid args [Then] creates trigger',
135 it => {