1
+/**
2
+ * Identity: which project and which user a command acts on.
3
+ *
4
+ * The root tree acts on the consumer project as the consumer user; the dev
5
+ * tree acts on a developer project as a test user. Each claim below is checked
6
+ * against what the fake backend received, not against what the CLI printed.
7
+ */
8
+
9
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
10
+import {
11
+ CONSUMER_PROJECT,
12
+ CONSUMER_USER_ID,
13
+ DEVELOPER_PROJECT,
14
+ GLOBAL_TEST_USER_ID,
15
+ OTHER_DEVELOPER_PROJECT,
16
+ ORG,
17
+} from '@e2e-tests/cli-fake-backend';
18
+import { startCliRig, type CliRig } from '@e2e-tests/cli-fake-backend/rig';
19
+import {
20
+ clean,
21
+ commandRequests,
22
+ DEV_DIRECTORY,
23
+ EXECUTE_SLACK,
24
+ ExecutionResult,
25
+ initDeveloperDirectory,
26
+ PLAYGROUND_EXECUTE_SLACK,
27
+ RIG_TIMEOUT_MS,
28
+ routesOf,
29
+ SLACK_ARGUMENTS,
30
+ stdoutJson,
31
+ TEST_TIMEOUT_MS,
32
+ writeDebugLog,
33
+} from './support';
34
+
35
+const inDevDirectory = (command: string) => `cd ${DEV_DIRECTORY} && ${command}`;
36
+
37
+/** A row of the help printed with the error: the name indented, then its description or type. */
38
+const helpRow = (name: string) =>
39
+ new RegExp(`^\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s`, 'm');
40
+
41
+describe('identity: the two command trees', () => {
42
+ let rig: CliRig;
43
+
44
+ beforeAll(async () => {
45
+ rig = await startCliRig({ label: 'identity' });
46
+ await rig.login();
47
+ await initDeveloperDirectory(rig);
48
+ }, RIG_TIMEOUT_MS);
49
+
50
+ afterAll(async () => {
51
+ await writeDebugLog(rig, import.meta.dir, 'identity');
52
+ await rig.stop();
53
+ });
54
+
55
+ describe('the same tool on each tree', () => {
56
+ it(
57
+ 'root `execute` acts on the consumer project as the consumer user',
58
+ async () => {
59
+ rig.fake.world.connect(CONSUMER_PROJECT.label, CONSUMER_USER_ID, 'slack');
60
+ const result = await rig.run(inDevDirectory(EXECUTE_SLACK));
61
+
62
+ expect(result.exitCode).toBe(0);
63
+ expect(stdoutJson(result, ExecutionResult).successful).toBe(true);
64
+
65
+ const execution = result.requests.filter(entry => entry.route === 'dashboard.execute');
66
+ expect(execution).toHaveLength(1);
67
+ expect(execution[0]).toMatchObject({
68
+ role: 'dashboard',
69
+ keyClass: 'user',
70
+ orgId: ORG.id,
71
+ project: CONSUMER_PROJECT.label,
72
+ userId: CONSUMER_USER_ID,
73
+ });
74
+ // Run from an initialized developer directory on purpose: the
75
+ // directory's project must not leak into a root-tree command.
76
+ const projects = commandRequests(result).map(entry => entry.project);
77
+ expect(projects).not.toContain(DEVELOPER_PROJECT.label);
78
+ expect(routesOf(result)).not.toContain('toolRouter.session.execute');
79
+ },
80
+ TEST_TIMEOUT_MS
81
+ );
82
+
83
+ it(
84
+ 'dev `playground-execute` acts on the developer project as the global test user',
85
+ async () => {
86
+ rig.fake.world.connect(DEVELOPER_PROJECT.label, GLOBAL_TEST_USER_ID, 'slack');
87
+ const result = await rig.run(inDevDirectory(PLAYGROUND_EXECUTE_SLACK));
88
+
89
+ expect(result.exitCode).toBe(0);
90
+ expect(stdoutJson(result, ExecutionResult).successful).toBe(true);
91
+
92
+ const execution = result.requests.filter(
93
+ entry => entry.route === 'toolRouter.session.execute'
94
+ );
95
+ expect(execution).toHaveLength(1);
96
+ expect(execution[0]).toMatchObject({
97
+ role: 'backend',
98
+ keyClass: 'user',
99
+ project: DEVELOPER_PROJECT.label,
100
+ userId: GLOBAL_TEST_USER_ID,
101
+ });
102
+ expect(routesOf(result)).not.toContain('dashboard.execute');
103
+ expect(commandRequests(result).map(entry => entry.project)).not.toContain(
104
+ CONSUMER_PROJECT.label
105
+ );
106
+ },
107
+ TEST_TIMEOUT_MS
108
+ );
109
+
110
+ it(
111
+ 'dev `--user-id` replaces the test user',
112
+ async () => {
113
+ rig.fake.world.connect(DEVELOPER_PROJECT.label, 'alice', 'slack');
114
+ const result = await rig.run(inDevDirectory(`${PLAYGROUND_EXECUTE_SLACK} --user-id alice`));
115
+
116
+ expect(result.exitCode).toBe(0);
117
+ const execution = result.requests.find(
118
+ entry => entry.route === 'toolRouter.session.execute'
119
+ );
120
+ expect(execution).toMatchObject({ project: DEVELOPER_PROJECT.label, userId: 'alice' });
121
+ },
122
+ TEST_TIMEOUT_MS
123
+ );
124
+
125
+ it(
126
+ 'dev `--project-name` targets the named developer project',
127
+ async () => {
128
+ rig.fake.world.connect(OTHER_DEVELOPER_PROJECT.label, GLOBAL_TEST_USER_ID, 'slack');
129
+ const result = await rig.run(
130
+ inDevDirectory(
131
+ `${PLAYGROUND_EXECUTE_SLACK} --project-name ${OTHER_DEVELOPER_PROJECT.name}`
132
+ )
133
+ );
134
+
135
+ expect(result.exitCode).toBe(0);
136
+ const execution = result.requests.find(
137
+ entry => entry.route === 'toolRouter.session.execute'
138
+ );
139
+ expect(execution).toMatchObject({
140
+ project: OTHER_DEVELOPER_PROJECT.label,
141
+ userId: GLOBAL_TEST_USER_ID,
142
+ });
143
+ },
144
+ TEST_TIMEOUT_MS
145
+ );
146
+ });
147
+
148
+ describe('connections do not cross trees', () => {
149
+ it(
150
+ 'an account linked on the root tree is not connected on the dev tree',
151
+ async () => {
152
+ const link = await rig.run(inDevDirectory('composio link github'));
153
+ expect(link.exitCode).toBe(0);
154
+ expect(
155
+ link.requests.find(entry => entry.route === 'toolRouter.session.link')
156
+ ).toMatchObject({ project: CONSUMER_PROJECT.label, userId: CONSUMER_USER_ID });
157
+
158
+ const execution = await rig.run(
159
+ inDevDirectory(
160
+ `composio dev playground-execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'`
161
+ )
162
+ );
163
+ expect(execution.exitCode).toBe(1);
164
+ expect(stdoutJson(execution, ExecutionResult)).toMatchObject({
165
+ successful: false,
166
+ slug: 'ToolRouterV2_NoActiveConnection',
167
+ });
168
+ },
169
+ TEST_TIMEOUT_MS
170
+ );
171
+
172
+ it(
173
+ 'an account linked on the dev tree is not connected on the root tree',
174
+ async () => {
175
+ const link = await rig.run(inDevDirectory('composio dev connected-accounts link gmail'));
176
+ expect(link.exitCode).toBe(0);
177
+ expect(
178
+ link.requests.find(entry => entry.route === 'toolRouter.session.link')
179
+ ).toMatchObject({ project: DEVELOPER_PROJECT.label, userId: GLOBAL_TEST_USER_ID });
180
+
181
+ const execution = await rig.run(
182
+ `composio execute GMAIL_SEND_EMAIL -d '{"recipient_email":"a@b.test"}'`
183
+ );
184
+ expect(execution.exitCode).toBe(1);
185
+ expect(stdoutJson(execution, ExecutionResult)).toMatchObject({
186
+ successful: false,
187
+ slug: 'ToolRouterV2_NoActiveConnection',
188
+ });
189
+ },
190
+ TEST_TIMEOUT_MS
191
+ );
192
+
193
+ it(
194
+ 'root `execute` without a connection names the root command that fixes it',
195
+ async () => {
196
+ const result = await rig.run(
197
+ `composio execute GMAIL_SEND_EMAIL -d '{"recipient_email":"a@b.test"}'`
198
+ );
199
+ expect(result.exitCode).toBe(1);
200
+ expect(stdoutJson(result, ExecutionResult).error).toContain('composio link gmail');
201
+ },
202
+ TEST_TIMEOUT_MS
203
+ );
204
+
205
+ it(
206
+ 'dev `playground-execute` without a connection names a dev-tree command that fixes it',
207
+ async () => {
208
+ const result = await rig.run(
209
+ inDevDirectory(
210
+ `composio dev playground-execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'`
211
+ )
212
+ );
213
+ const { error } = stdoutJson(result, ExecutionResult);
214
+ expect(error).toContain('composio dev connected-accounts link github');
215
+ expect(error).not.toContain('composio link github');
216
+ },
217
+ TEST_TIMEOUT_MS
218
+ );
219
+ });
220
+
221
+ describe('the developer project of the directory', () => {
222
+ const OTHER_DIRECTORY = '/work/other-app';
223
+ const listInOtherDirectory = async () => {
224
+ await rig.journey.writeFile(
225
+ `${OTHER_DIRECTORY}/.composio/project.json`,
226
+ JSON.stringify({
227
+ org_id: ORG.id,
228
+ project_id: OTHER_DEVELOPER_PROJECT.nanoId,
229
+ project_name: OTHER_DEVELOPER_PROJECT.name,
230
+ })
231
+ );
232
+ const result = await rig.run(`cd ${OTHER_DIRECTORY} && composio dev auth-configs list`);
233
+ return { result, listing: result.requests.find(entry => entry.route === 'authConfigs.list') };
234
+ };
235
+
236
+ it(
237
+ "today: `dev auth-configs list` in another project's directory sends no scope and gets the key's default project",
238
+ async () => {
239
+ const { result, listing } = await listInOtherDirectory();
240
+ expect(result.exitCode).toBe(0);
241
+ expect(listing).toMatchObject({
242
+ project: DEVELOPER_PROJECT.label,
243
+ projectFrom: 'key-default',
244
+ });
245
+ },
246
+ TEST_TIMEOUT_MS
247
+ );
248
+
249
+ // CLI defect: commands on the shared backend client send the user key with no org or project scope, so the backend picks the project.
250
+ it.failing(
251
+ '`dev auth-configs list` is scoped to the project the directory is set up for',
252
+ async () => {
253
+ const { listing } = await listInOtherDirectory();
254
+ expect(listing?.projectFrom).toBe('scope-headers');
255
+ },
256
+ TEST_TIMEOUT_MS
257
+ );
258
+ });
259
+
260
+ describe('a command from the wrong tree', () => {
261
+ const cases = [
262
+ {
263
+ command: `composio dev execute SLACK_SEND_MESSAGE -d ${SLACK_ARGUMENTS}`,
264
+ message: 'Unknown subcommand "execute" for "composio dev"',
265
+ listed: 'playground-execute',
266
+ },
267
+ {
268
+ command: 'composio dev link slack',
269
+ message: 'Unknown subcommand "link" for "composio dev"',
270
+ listed: 'connected-accounts',
271
+ },
272
+ {
273
+ command: `composio playground-execute SLACK_SEND_MESSAGE -d ${SLACK_ARGUMENTS}`,
274
+ message: 'Unknown subcommand "playground-execute" for "composio"',
275
+ listed: 'execute',
276
+ },
277
+ {
278
+ command: 'composio auth-configs list',
279
+ message: 'Unknown subcommand "auth-configs" for "composio"',
280
+ listed: 'dev',
281
+ },
282
+ {
283
+ command: `${EXECUTE_SLACK} --user-id alice`,
284
+ message: 'Unrecognized flag: --user-id in command composio execute',
285
+ listed: '--account',
286
+ },
287
+ ] as const;
288
+
289
+ for (const { command, message, listed } of cases) {
290
+ it(
291
+ `\`${command.split(' -d ')[0]}\` fails before any request, naming what was wrong`,
292
+ async () => {
293
+ const result = await rig.run(command);
294
+ expect(result.exitCode).toBe(1);
295
+ expect(result.stdout).toBe('');
296
+ const stderr = clean(result.stderr);
297
+ expect(stderr).toContain(message);
298
+ // The help printed with the error is what lets an agent find the real command.
299
+ expect(stderr).toMatch(helpRow(listed));
300
+ expect(commandRequests(result)).toEqual([]);
301
+ },
302
+ TEST_TIMEOUT_MS
303
+ );
304
+ }
305
+
306
+ // The two tests below pin what the CLI does today, not what it should do.
307
+ // Nothing in the repo says what a wrong-tree command should answer, so they
308
+ // are listed as known gaps in the README instead of as expected failures.
309
+ it(
310
+ 'today: `composio dev link --help` prints the `dev` help and exits 0, as if the command existed',
311
+ async () => {
312
+ const result = await rig.run('composio dev link --help');
313
+ expect(result.exitCode).toBe(0);
314
+ expect(`${result.stdout}${clean(result.stderr)}`).toContain('connected-accounts');
315
+ },
316
+ TEST_TIMEOUT_MS
317
+ );
318
+
319
+ it(
320
+ 'today: `composio dev link` lists `connected-accounts` but never names `connected-accounts link`',
321
+ async () => {
322
+ const result = await rig.run('composio dev link slack');
323
+ expect(clean(result.stderr)).not.toContain('composio dev connected-accounts link');
324
+ },
325
+ TEST_TIMEOUT_MS
326
+ );
327
+ });
328
+
329
+ describe('a help page teaches its own tree', () => {
330
+ // One `link` definition serves both trees, so its examples must follow the page they are on.
331
+ const examplesOf = (help: string) =>
332
+ (help.split('EXAMPLES')[1] ?? '')
333
+ .split('\n')
334
+ .map(line => line.trim())
335
+ .filter(line => line.startsWith('composio '));
336
+
337
+ for (const page of ['composio link', 'composio dev connected-accounts link']) {
338
+ it(
339
+ `\`${page} --help\` shows examples of \`${page}\` only`,
340
+ async () => {
341
+ const result = await rig.run(`${page} --help`);
342
+ expect(result.exitCode).toBe(0);
343
+ const examples = examplesOf(clean(`${result.stdout}${result.stderr}`));
344
+ expect(examples.length).toBeGreaterThan(0);
345
+ expect(examples.filter(example => !example.startsWith(`${page} `))).toEqual([]);
346
+ expect(commandRequests(result)).toEqual([]);
347
+ },
348
+ TEST_TIMEOUT_MS
349
+ );
350
+ }
351
+ });
352
+
353
+ // Last, so it covers every command above: links, auth configs, both executions.
354
+ it(
355
+ 'never sends the project API key `dev init` minted',
356
+ async () => {
357
+ expect(rig.fake.world.mintedProjectKeys).toHaveLength(1);
358
+ const classes = new Set(
359
+ rig.fake.journal
360
+ .entries()
361
+ .filter(entry => entry.role === 'backend' || entry.role === 'dashboard')
362
+ .map(entry => entry.keyClass)
363
+ );
364
+ expect([...classes]).toEqual(['user']);
365
+ },
366
+ TEST_TIMEOUT_MS
367
+ );
368
+});
369
+
370
+describe('identity: a missing acting user', () => {
371
+ let rig: CliRig;
372
+
373
+ beforeAll(async () => {
374
+ rig = await startCliRig({ label: 'acting-user' });
375
+ await rig.login();
376
+ }, RIG_TIMEOUT_MS);
377
+
378
+ afterAll(async () => {
379
+ await writeDebugLog(rig, import.meta.dir, 'acting-user');
380
+ await rig.stop();
381
+ });
382
+
383
+ it(
384
+ 'root tree: an empty consumer user id fails with the consumer message',
385
+ async () => {
386
+ const disarm = rig.fake.faults.inject({
387
+ route: '_internal.org.consumer.project.resolve',
388
+ fault: {
389
+ kind: 'schema-drift',
390
+ transform: body => ({ ...(body as Record<string, unknown>), consumer_user_id: '' }),
391
+ },
392
+ });
393
+ const result = await rig.run(EXECUTE_SLACK);
394
+ disarm();
395
+
396
+ expect(result.exitCode).toBe(1);
397
+ expect(result.stdout).toBe('');
398
+ expect(clean(result.stderr)).toBe(
399
+ 'Missing consumer user id. Run `composio login` and try again.'
400
+ );
401
+ expect(routesOf(result)).not.toContain('dashboard.execute');
402
+ },
403
+ TEST_TIMEOUT_MS
404
+ );
405
+
406
+ it(
407
+ 'dev tree: no developer project for the directory fails with the dev message',
408
+ async () => {
409
+ const result = await rig.run(PLAYGROUND_EXECUTE_SLACK);
410
+ expect(result.exitCode).toBe(1);
411
+ expect(result.stdout).toBe('');
412
+ expect(clean(result.stderr)).toBe(
413
+ 'No developer project configured for this directory. Run `composio dev init`.'
414
+ );
415
+ expect(commandRequests(result)).toEqual([]);
416
+ },
417
+ TEST_TIMEOUT_MS
418
+ );
419
+
420
+ it(
421
+ 'dev tree: `--project-name` without any test user fails with the dev message',
422
+ async () => {
423
+ await rig.run(
424
+ `sed -i 's/"test_user_id":"[^"]*"/"test_user_id":null/' ~/.composio/user_data.json`
425
+ );
426
+ const result = await rig.run(
427
+ `${PLAYGROUND_EXECUTE_SLACK} --project-name ${DEVELOPER_PROJECT.name}`
428
+ );
429
+ expect(result.exitCode).toBe(1);
430
+ expect(result.stdout).toBe('');
431
+ expect(clean(result.stderr)).toBe(
432
+ 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.'
433
+ );
434
+ expect(routesOf(result)).not.toContain('toolRouter.session.execute');
435
+ },
436
+ TEST_TIMEOUT_MS
437
+ );
438
+});