1
+import type { ComposioClientShape } from '@composio/client/effect';
2
+import { describe, expect, it } from '@effect/vitest';
3
+import { Effect, Layer, Option } from 'effect';
4
+import {
5
+ actingUser,
6
+ actingUserOption,
7
+ CommandSurface,
8
+ fallbackNotice,
9
+ MissingActingUserError,
10
+ type ActingUserOptions,
11
+ type ActingUserSource,
12
+ type CommandTree,
13
+} from 'src/commands/surface';
14
+import type { ProjectKeys } from 'src/models/project-keys';
15
+import { ComposioClientSingleton } from 'src/services/composio-clients';
16
+import { ProjectContext } from 'src/services/project-context';
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
+
21
+const ORG_ID = 'org_test';
22
+const CONSUMER_USER_ID = `consumer-user-${ORG_ID}`;
23
+const CONSUMER_PROJECT_ID = 'consumer_project_test';
24
+const DIRECTORY_PROJECT_ID = 'proj_directory';
25
+const OTHER_PROJECT_ID = 'proj_other';
26
+
27
+const projects = [
28
+ makeOrgProject({ id: DIRECTORY_PROJECT_ID, name: 'directory', orgId: ORG_ID }),
29
+ makeOrgProject({ id: OTHER_PROJECT_ID, name: 'other', orgId: ORG_ID }),
30
+];
31
+
32
+/** The candidates present, named after the one the dev tree's rule picks first. */
33
+type Candidates = 'flag' | 'directory' | 'global' | 'none';
34
+/** `--project-name`: absent, the directory's own project, or another one. */
35
+type ProjectName = 'absent' | 'same' | 'other';
36
+
37
+interface Fixture {
38
+ readonly tree: CommandTree;
39
+ readonly candidates: Candidates;
40
+ readonly projectName: ProjectName;
41
+ /** The consumer user id the consumer project resolves with. */
42
+ readonly consumerUserId?: string;
43
+}
44
+
45
+const CANDIDATE_ORDER: ReadonlyArray<Candidates> = ['flag', 'directory', 'global', 'none'];
46
+
47
+const PROJECT_NAMES: Record<ProjectName, Option.Option<string>> = {
48
+ absent: Option.none(),
49
+ same: Option.some('directory'),
50
+ other: Option.some('other'),
51
+};
52
+
53
+const actingUserLayer = (fixture: Fixture) => {
54
+ const has = (candidate: Exclude<Candidates, 'none'>) =>
55
+ CANDIDATE_ORDER.indexOf(candidate) >= CANDIDATE_ORDER.indexOf(fixture.candidates);
56
+ const directory: ProjectKeys = {
57
+ orgId: ORG_ID,
58
+ projectId: DIRECTORY_PROJECT_ID,
59
+ projectName: Option.some('directory'),
60
+ orgName: Option.none(),
61
+ email: Option.none(),
62
+ testUserId: has('directory') ? Option.some('directory-user') : Option.none(),
63
+ };
64
+ const resources = mockAccountResources({ projects }, {});
65
+ // The account resources answer only the fields `resolveCommandProject` reads.
66
+ const client = {
67
+ ...resources,
68
+ _internal: {
69
+ org: {
70
+ consumer: {
71
+ ...resources._internal.org.consumer,
72
+ project: {
73
+ resolve: (
74
+ ...args: Parameters<typeof resources._internal.org.consumer.project.resolve>
75
+ ) =>
76
+ resources._internal.org.consumer.project.resolve(...args).pipe(
77
+ Effect.map(project => ({
78
+ ...project,
79
+ consumer_user_id: fixture.consumerUserId ?? project.consumer_user_id,
80
+ }))
81
+ ),
82
+ },
83
+ },
84
+ },
85
+ },
86
+ } as unknown as ComposioClientShape;
87
+
88
+ return Layer.mergeAll(
89
+ Layer.succeed(
90
+ CommandSurface,
91
+ CommandSurface.of({
92
+ tree: fixture.tree,
93
+ userId: has('flag') ? Option.some('flag-user') : Option.none(),
94
+ projectName: PROJECT_NAMES[fixture.projectName],
95
+ })
96
+ ),
97
+ Layer.succeed(
98
+ ComposioUserContext,
99
+ ComposioUserContext.of({
100
+ data: {
101
+ apiKey: Option.some('uak_test'),
102
+ baseURL: 'https://mock.invalid',
103
+ webURL: 'https://platform.mock.invalid',
104
+ orgId: Option.some(ORG_ID),
105
+ projectId: Option.none(),
106
+ testUserId: has('global') ? Option.some('global-user') : Option.none(),
107
+ },
108
+ backendMismatch: Option.none(),
109
+ isLoggedIn: () => true,
110
+ logout: Effect.void,
111
+ login: () => Effect.void,
112
+ update: () => Effect.void,
113
+ })
114
+ ),
115
+ Layer.succeed(ProjectContext, ProjectContext.of({ resolve: Effect.succeedSome(directory) })),
116
+ Layer.succeed(
117
+ ComposioClientSingleton,
118
+ ComposioClientSingleton.of({
119
+ get: () => Effect.succeed(client),
120
+ getFor: () => Effect.succeed(client),
121
+ getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
122
+ })
123
+ )
124
+ );
125
+};
126
+
127
+/** The acting user the glossary's rule names, or none when it names no one. */
128
+const expectedUser = ({
129
+ tree,
130
+ candidates,
131
+ projectName,
132
+}: Fixture): Option.Option<{ readonly userId: string; readonly source: ActingUserSource }> => {
133
+ if (tree === 'root') {
134
+ return Option.some({ userId: CONSUMER_USER_ID, source: 'consumer' });
135
+ }
136
+ if (candidates === 'flag') {
137
+ return Option.some({ userId: 'flag-user', source: 'flag' });
138
+ }
139
+ // The directory test user stands in only for the directory's own project.
140
+ if (candidates === 'directory' && projectName !== 'other') {
141
+ return Option.some({ userId: 'directory-user', source: 'directory-test-user' });
142
+ }
143
+ return candidates === 'none'
144
+ ? Option.none()
145
+ : Option.some({ userId: 'global-user', source: 'global-test-user' });
146
+};
147
+
148
+/** The id of the project the user is resolved against. */
149
+const expectedProjectId = ({ tree, projectName }: Fixture) =>
150
+ tree === 'root'
151
+ ? CONSUMER_PROJECT_ID
152
+ : projectName === 'other'
153
+ ? OTHER_PROJECT_ID
154
+ : DIRECTORY_PROJECT_ID;
155
+
156
+const TREES: ReadonlyArray<CommandTree> = ['root', 'dev'];
157
+const PROJECT_NAME_CASES: ReadonlyArray<ProjectName> = ['absent', 'same', 'other'];
158
+
159
+// Every combination of the three axes.
160
+const cases = TREES.flatMap(tree =>
161
+ CANDIDATE_ORDER.flatMap(candidates =>
162
+ PROJECT_NAME_CASES.map(projectName => ({
163
+ tree,
164
+ candidates,
165
+ projectName,
166
+ name: `${tree}, ${candidates} first, --project-name ${projectName}`,
167
+ }))
168
+ )
169
+);
170
+
171
+const run = <
172
+ A,
173
+ E,
174
+ R extends CommandSurface | ComposioUserContext | ProjectContext | ComposioClientSingleton,
175
+>(
176
+ effect: Effect.Effect<A, E, R>,
177
+ fixture: Fixture
178
+) => effect.pipe(Effect.provide(actingUserLayer(fixture)));
179
+
180
+describe('actingUser', () => {
181
+ it.effect.each(cases)('[Given] $name [Then] acts as the rule’s user', fixture =>
182
+ Effect.gen(function* () {
183
+ const result = yield* run(Effect.result(actingUser()), fixture);
184
+ const expected = expectedUser(fixture);
185
+
186
+ if (Option.isNone(expected)) {
187
+ expect(result).toMatchObject({ failure: { _tag: 'commands/MissingActingUserError' } });
188
+ return;
189
+ }
190
+ expect(result).toMatchObject({
191
+ success: { ...expected.value, project: { projectId: expectedProjectId(fixture) } },
192
+ });
193
+ })
194
+ );
195
+
196
+ it.effect.each([
197
+ {
198
+ tree: 'root',
199
+ projectName: 'absent',
200
+ message: 'Missing consumer user id. Run `composio login` and try again.',
201
+ },
202
+ {
203
+ tree: 'dev',
204
+ projectName: 'absent',
205
+ message:
206
+ 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
207
+ },
208
+ {
209
+ tree: 'dev',
210
+ projectName: 'other',
211
+ message:
212
+ 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
213
+ },
214
+ ] as const)(
215
+ '[Given] no user on the $tree tree, --project-name $projectName [Then] fails with the tree’s message',
216
+ ({ tree, projectName, message }) =>
217
+ Effect.gen(function* () {
218
+ const error = yield* run(Effect.flip(actingUser()), {
219
+ tree,
220
+ projectName,
221
+ candidates: 'none',
222
+ consumerUserId: '',
223
+ });
224
+
225
+ expect(error).toBeInstanceOf(MissingActingUserError);
226
+ expect(error).toMatchObject({ tree, projectName: PROJECT_NAMES[projectName], message });
227
+ })
228
+ );
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
+ );
288
+});
289
+
290
+// Commands passing `acceptEmptyConsumerUserId` count an empty consumer user id as a user.
291
+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,
310
+ candidates: 'flag',
311
+ projectName: 'absent',
312
+ consumerUserId: '',
313
+ });
314
+
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));
320
+
321
+ expect(result).toMatchObject(
322
+ accepted
323
+ ? { success: { userId: '', source: 'consumer' } }
324
+ : { failure: { _tag: 'commands/MissingActingUserError' } }
325
+ );
326
+ })
327
+ );
328
+
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));
334
+
335
+ expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
336
+ accepted ? Option.some({ userId: '', source: 'consumer' }) : Option.none()
337
+ );
338
+ })
339
+ );
340
+});
341
+
342
+describe('actingUserOption', () => {
343
+ it.effect.each(cases)('[Given] $name [Then] finds the rule’s user, or none', fixture =>
344
+ Effect.gen(function* () {
345
+ const user = yield* run(actingUserOption(), fixture);
346
+ const expected = expectedUser(fixture);
347
+ // Only the project --project-name names is resolved on the dev tree.
348
+ const project =
349
+ fixture.tree === 'dev' && fixture.projectName === 'absent'
350
+ ? Option.none()
351
+ : Option.some(expectedProjectId(fixture));
352
+
353
+ expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(expected);
354
+ expect(
355
+ Option.map(user, found => Option.map(found.project, resolved => resolved.projectId))
356
+ ).toEqual(Option.map(expected, () => project));
357
+ })
358
+ );
359
+});
360
+
361
+describe('fallbackNotice', () => {
362
+ it.each([
363
+ { source: 'consumer', expected: Option.none() },
364
+ { source: 'flag', expected: Option.none() },
365
+ { source: 'directory-test-user', expected: Option.some('Using test user id "u"') },
366
+ { source: 'global-test-user', expected: Option.some('Using global test user id "u"') },
367
+ ] as const)(
368
+ '[Given] a $source user [Then] announces only a test user',
369
+ ({ source, expected }) => {
370
+ expect(fallbackNotice({ userId: 'u', source })).toEqual(expected);
371
+ }
372
+ );
373
+});