@devries-cameron20 / composio Mirror · read-only
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, 04:45 UTC

next
ts 495 lines 17 KB
Raw
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 CommandSurface,
7 devActingUserOption,
8 fallbackNotice,
9 MissingActingUserError,
10 resolveSurfaceProject,
11 resolveDeveloperResourceProject,
12 resolveSurfaceProjectAndUserOption,
13 type ActingUserSource,
14 type CommandTree,
15 } from 'src/commands/surface';
16 import type { ProjectKeys } from 'src/models/project-keys';
17 import { ProjectResolutionError } from 'src/services/command-project';
18 import { ComposioClientSingleton } from 'src/services/composio-clients';
19 import { ProjectContext } from 'src/services/project-context';
20 import { TerminalUI } from 'src/services/terminal-ui';
21 import { ComposioUserContext } from 'src/services/user-context';
22 import { mockAccountResources } from 'test/__utils__/layers/accounts';
23 import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
24 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
25
26 const ORG_ID = 'org_test';
27 const CONSUMER_USER_ID = `consumer-user-${ORG_ID}`;
28 const CONSUMER_PROJECT_ID = 'consumer_project_test';
29 const DIRECTORY_PROJECT_ID = 'proj_directory';
30 const OTHER_PROJECT_ID = 'proj_other';
31 /** The developer project the backend acts on for a request that names none. */
32 const DEFAULT_PROJECT_ID = 'proj_newest';
33
34 const projects = [
35 makeOrgProject({ id: DIRECTORY_PROJECT_ID, name: 'directory', orgId: ORG_ID }),
36 makeOrgProject({ id: OTHER_PROJECT_ID, name: 'other', orgId: ORG_ID }),
37 ];
38
39 /** The candidates present, named after the one the dev tree's rule picks first. */
40 type Candidates = 'flag' | 'directory' | 'global' | 'none';
41 /** `--project-name`: absent, the directory's own project, or another one. */
42 type ProjectName = 'absent' | 'same' | 'other';
43
44 interface Fixture {
45 readonly tree: CommandTree;
46 readonly candidates: Candidates;
47 readonly projectName: ProjectName;
48 /** The consumer user id the consumer project resolves with. */
49 readonly consumerUserId?: string;
50 }
51
52 const CANDIDATE_ORDER: ReadonlyArray<Candidates> = ['flag', 'directory', 'global', 'none'];
53
54 const PROJECT_NAMES: Record<ProjectName, Option.Option<string>> = {
55 absent: Option.none(),
56 same: Option.some('directory'),
57 other: Option.some('other'),
58 };
59
60 /** `warnings` collects what the code under test warns on stderr. */
61 const actingUserLayer = (fixture: Fixture, warnings: Array<string>) => {
62 const has = (candidate: Exclude<Candidates, 'none'>) =>
63 CANDIDATE_ORDER.indexOf(candidate) >= CANDIDATE_ORDER.indexOf(fixture.candidates);
64 const directory: ProjectKeys = {
65 orgId: ORG_ID,
66 projectId: DIRECTORY_PROJECT_ID,
67 projectName: Option.some('directory'),
68 orgName: Option.none(),
69 email: Option.none(),
70 testUserId: has('directory') ? Option.some('directory-user') : Option.none(),
71 };
72 const resources = mockAccountResources(
73 {
74 projects,
75 sessionInfo: makeSessionInfo({
76 orgId: ORG_ID,
77 projectNanoId: DEFAULT_PROJECT_ID,
78 projectName: 'newest',
79 }),
80 },
81 {}
82 );
83 // The account resources answer only the fields `resolveCommandProject` reads.
84 const client = {
85 ...resources,
86 _internal: {
87 org: {
88 consumer: {
89 ...resources._internal.org.consumer,
90 project: {
91 resolve: (
92 ...args: Parameters<typeof resources._internal.org.consumer.project.resolve>
93 ) =>
94 resources._internal.org.consumer.project.resolve(...args).pipe(
95 Effect.map(project => ({
96 ...project,
97 consumer_user_id: fixture.consumerUserId ?? project.consumer_user_id,
98 }))
99 ),
100 },
101 },
102 },
103 },
104 } as unknown as ComposioClientShape;
105
106 return Layer.mergeAll(
107 Layer.succeed(
108 TerminalUI,
109 TerminalUI.of({
110 ...terminalUITestImpl,
111 log: {
112 ...terminalUITestImpl.log,
113 warn: message => Effect.sync(() => warnings.push(message)),
114 },
115 // Off a terminal a warning that must still show is a plain stderr line.
116 error: message => Effect.sync(() => warnings.push(message)),
117 })
118 ),
119 Layer.succeed(
120 CommandSurface,
121 CommandSurface.of({
122 tree: fixture.tree,
123 userId: has('flag') ? Option.some('flag-user') : Option.none(),
124 projectName: PROJECT_NAMES[fixture.projectName],
125 })
126 ),
127 Layer.succeed(
128 ComposioUserContext,
129 ComposioUserContext.of({
130 data: {
131 apiKey: Option.some('uak_test'),
132 baseURL: 'https://mock.invalid',
133 webURL: 'https://platform.mock.invalid',
134 orgId: Option.some(ORG_ID),
135 projectId: Option.none(),
136 testUserId: has('global') ? Option.some('global-user') : Option.none(),
137 },
138 backendMismatch: Option.none(),
139 isLoggedIn: () => true,
140 logout: Effect.void,
141 login: () => Effect.void,
142 update: () => Effect.void,
143 })
144 ),
145 Layer.succeed(ProjectContext, ProjectContext.of({ resolve: Effect.succeedSome(directory) })),
146 Layer.succeed(
147 ComposioClientSingleton,
148 ComposioClientSingleton.of({
149 get: () => Effect.succeed(client),
150 getFor: () => Effect.succeed(client),
151 getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
152 })
153 )
154 );
155 };
156
157 /** The acting user the glossary's rule names, or none when it names no one. */
158 const expectedUser = ({
159 tree,
160 candidates,
161 projectName,
162 }: Fixture): Option.Option<{ readonly userId: string; readonly source: ActingUserSource }> => {
163 if (tree === 'root') {
164 return Option.some({ userId: CONSUMER_USER_ID, source: 'consumer' });
165 }
166 if (candidates === 'flag') {
167 return Option.some({ userId: 'flag-user', source: 'flag' });
168 }
169 // The directory test user stands in only for the directory's own project.
170 if (candidates === 'directory' && projectName !== 'other') {
171 return Option.some({ userId: 'directory-user', source: 'directory-test-user' });
172 }
173 return candidates === 'none'
174 ? Option.none()
175 : Option.some({ userId: 'global-user', source: 'global-test-user' });
176 };
177
178 /** The id of the project the user is resolved against. */
179 const expectedProjectId = ({ tree, projectName }: Fixture) =>
180 tree === 'root'
181 ? CONSUMER_PROJECT_ID
182 : projectName === 'other'
183 ? OTHER_PROJECT_ID
184 : DIRECTORY_PROJECT_ID;
185
186 const TREES: ReadonlyArray<CommandTree> = ['root', 'dev'];
187 const PROJECT_NAME_CASES: ReadonlyArray<ProjectName> = ['absent', 'same', 'other'];
188
189 // Every combination of the three axes.
190 const cases = TREES.flatMap(tree =>
191 CANDIDATE_ORDER.flatMap(candidates =>
192 PROJECT_NAME_CASES.map(projectName => ({
193 tree,
194 candidates,
195 projectName,
196 name: `${tree}, ${candidates} first, --project-name ${projectName}`,
197 }))
198 )
199 );
200
201 const run = <
202 A,
203 E,
204 R extends
205 CommandSurface | ComposioUserContext | ProjectContext | ComposioClientSingleton | TerminalUI,
206 >(
207 effect: Effect.Effect<A, E, R>,
208 fixture: Fixture,
209 warnings: Array<string> = []
210 ) => effect.pipe(Effect.provide(actingUserLayer(fixture, warnings)));
211
212 /** The notice printed for the rule's user: one line for a test user standing in, else none. */
213 const expectedNotices = (fixture: Fixture) =>
214 Option.toArray(Option.flatMap(expectedUser(fixture), fallbackNotice));
215
216 describe('actingUser', () => {
217 it.effect.each(cases)('[Given] $name [Then] acts as the rule’s user', fixture =>
218 Effect.gen(function* () {
219 const warnings: Array<string> = [];
220 const result = yield* run(Effect.result(actingUser()), fixture, warnings);
221 const expected = expectedUser(fixture);
222
223 expect(warnings).toEqual(expectedNotices(fixture));
224
225 if (Option.isNone(expected)) {
226 expect(result).toMatchObject({ failure: { _tag: 'commands/MissingActingUserError' } });
227 return;
228 }
229 expect(result).toMatchObject({
230 success: { ...expected.value, project: { projectId: expectedProjectId(fixture) } },
231 });
232 })
233 );
234
235 it.effect.each([
236 {
237 tree: 'root',
238 projectName: 'absent',
239 message: 'Missing consumer user id. Run `composio login` and try again.',
240 },
241 {
242 tree: 'dev',
243 projectName: 'absent',
244 message:
245 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.',
246 },
247 {
248 tree: 'dev',
249 projectName: 'other',
250 message:
251 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
252 },
253 ] as const)(
254 '[Given] no user on the $tree tree, --project-name $projectName [Then] fails with the tree’s message',
255 ({ tree, projectName, message }) =>
256 Effect.gen(function* () {
257 const error = yield* run(Effect.flip(actingUser()), {
258 tree,
259 projectName,
260 candidates: 'none',
261 consumerUserId: '',
262 });
263
264 expect(error).toBeInstanceOf(MissingActingUserError);
265 expect(error).toMatchObject({ tree, projectName: PROJECT_NAMES[projectName], message });
266 })
267 );
268 });
269
270 // `execute`, `search`, `link` and `run` used to accept an empty consumer user id as the user.
271 describe('an empty consumer user id', () => {
272 const fixture: Fixture = {
273 tree: 'root',
274 candidates: 'flag',
275 projectName: 'absent',
276 consumerUserId: '',
277 };
278
279 it.effect('[Given] an empty consumer user id [Then] actingUser fails as missing', () =>
280 Effect.gen(function* () {
281 const error = yield* run(Effect.flip(actingUser()), fixture);
282
283 expect(error).toBeInstanceOf(MissingActingUserError);
284 })
285 );
286 });
287
288 describe('devActingUserOption', () => {
289 it.effect.each(cases.filter(({ tree }) => tree === 'dev'))(
290 '[Given] $name [Then] finds the rule’s user for the resolved project, or none',
291 fixture =>
292 Effect.gen(function* () {
293 const warnings: Array<string> = [];
294 const user = yield* run(
295 Effect.flatMap(resolveSurfaceProject('developer'), devActingUserOption),
296 fixture,
297 warnings
298 );
299 const expected = expectedUser(fixture);
300
301 expect(warnings).toEqual(expectedNotices(fixture));
302 expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(expected);
303 expect(Option.map(user, found => found.project.projectId)).toEqual(
304 Option.map(expected, () => expectedProjectId(fixture))
305 );
306 })
307 );
308 });
309
310 const withoutDirectoryProject = Layer.succeed(
311 ProjectContext,
312 ProjectContext.of({ resolve: Effect.succeedNone })
313 );
314
315 /** A directory set up, by someone else, for a project in an org the user is not logged in to. */
316 const directoryProjectElsewhere = Layer.succeed(
317 ProjectContext,
318 ProjectContext.of({
319 resolve: Effect.succeedSome({
320 orgId: 'org_elsewhere',
321 projectId: 'proj_elsewhere',
322 projectName: Option.some('elsewhere'),
323 orgName: Option.none(),
324 email: Option.none(),
325 testUserId: Option.some('elsewhere-user'),
326 }),
327 })
328 );
329
330 const NO_DIRECTORY_PROJECT_NOTICE =
331 'Warning: No developer project is set up for this directory; using "newest" (proj_newest), the newest developer project in the org you are logged in to, instead. Run `composio dev init` to choose one, or pass --project-name.';
332
333 const DIRECTORY_PROJECT_ELSEWHERE_NOTICE =
334 'Warning: This directory\'s developer project is in org "org_elsewhere", not the org you are logged in to ("org_test"); using "newest" (proj_newest), the newest developer project in the org you are logged in to, instead. Run `composio orgs switch` to use the directory\'s org, or `composio dev init` to set this directory up in yours.';
335
336 describe('resolveDeveloperResourceProject', () => {
337 it.effect.each([
338 { projectName: 'absent', expected: DIRECTORY_PROJECT_ID },
339 { projectName: 'other', expected: OTHER_PROJECT_ID },
340 ] as const)(
341 '[Given] --project-name $projectName [Then] resolves that project with no notice',
342 ({ projectName, expected }) =>
343 Effect.gen(function* () {
344 const warnings: Array<string> = [];
345 const project = yield* run(
346 resolveDeveloperResourceProject,
347 { tree: 'dev', candidates: 'none', projectName },
348 warnings
349 );
350
351 expect(project.projectId).toBe(expected);
352 expect(warnings).toEqual([]);
353 })
354 );
355
356 it.effect.each([
357 {
358 given: 'no directory project',
359 layer: withoutDirectoryProject,
360 notice: NO_DIRECTORY_PROJECT_NOTICE,
361 },
362 {
363 given: 'a directory project in another org',
364 layer: directoryProjectElsewhere,
365 notice: DIRECTORY_PROJECT_ELSEWHERE_NOTICE,
366 },
367 ])(
368 '[Given] $given [Then] uses the default developer project and says so on stderr',
369 ({ layer, notice }) =>
370 Effect.gen(function* () {
371 const warnings: Array<string> = [];
372 const project = yield* run(
373 resolveDeveloperResourceProject.pipe(Effect.provide(layer)),
374 { tree: 'dev', candidates: 'none', projectName: 'absent' },
375 warnings
376 );
377
378 expect(project).toMatchObject({
379 orgId: ORG_ID,
380 projectId: DEFAULT_PROJECT_ID,
381 source: 'developer-default',
382 });
383 expect(warnings).toEqual([notice]);
384 })
385 );
386
387 it.effect('[Given] a --project-name the org does not hold [Then] fails', () =>
388 Effect.gen(function* () {
389 const error = yield* run(
390 Effect.flip(
391 resolveDeveloperResourceProject.pipe(
392 Effect.provide(
393 CommandSurface.dev({ userId: Option.none(), projectName: Option.some('missing') })
394 )
395 )
396 ),
397 { tree: 'dev', candidates: 'none', projectName: 'absent' }
398 );
399
400 expect(error).toBeInstanceOf(ProjectResolutionError);
401 expect(error).toMatchObject({ reason: 'project_not_found' });
402 })
403 );
404
405 it.effect(
406 '[Given] the default project stands in for another org’s directory project [Then] its test user does not',
407 () =>
408 Effect.gen(function* () {
409 const warnings: Array<string> = [];
410 const user = yield* run(
411 Effect.flatMap(resolveDeveloperResourceProject, devActingUserOption).pipe(
412 Effect.provide(directoryProjectElsewhere)
413 ),
414 { tree: 'dev', candidates: 'global', projectName: 'absent' },
415 warnings
416 );
417
418 expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
419 Option.some({ userId: 'global-user', source: 'global-test-user' })
420 );
421 })
422 );
423 });
424
425 describe('resolveSurfaceProjectAndUserOption', () => {
426 it.effect('[Given] a directory project and its test user [Then] finds both', () =>
427 Effect.gen(function* () {
428 const { project, user } = yield* run(resolveSurfaceProjectAndUserOption, {
429 tree: 'dev',
430 candidates: 'directory',
431 projectName: 'absent',
432 });
433
434 expect(Option.map(project, found => found.projectId)).toEqual(
435 Option.some(DIRECTORY_PROJECT_ID)
436 );
437 expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
438 Option.some({ userId: 'directory-user', source: 'directory-test-user' })
439 );
440 })
441 );
442
443 it.effect.each([
444 { candidates: 'flag', userId: 'flag-user' },
445 { candidates: 'global', userId: 'global-user' },
446 ] as const)(
447 '[Given] no directory project and a $candidates user [Then] uses the default project, saying so',
448 ({ candidates, userId }) =>
449 Effect.gen(function* () {
450 const warnings: Array<string> = [];
451 const { project, user } = yield* run(
452 resolveSurfaceProjectAndUserOption.pipe(Effect.provide(withoutDirectoryProject)),
453 { tree: 'dev', candidates, projectName: 'absent' },
454 warnings
455 );
456
457 expect(Option.map(project, found => found.projectId)).toEqual(
458 Option.some(DEFAULT_PROJECT_ID)
459 );
460 expect(Option.map(user, found => found.userId)).toEqual(Option.some(userId));
461 expect(warnings[0]).toBe(NO_DIRECTORY_PROJECT_NOTICE);
462 })
463 );
464
465 it.effect.each([
466 { given: 'no directory project', layer: withoutDirectoryProject },
467 { given: 'a directory project in another org', layer: directoryProjectElsewhere },
468 ])('[Given] $given and no user but the directory’s [Then] finds neither, quietly', ({ layer }) =>
469 Effect.gen(function* () {
470 const warnings: Array<string> = [];
471 const result = yield* run(
472 resolveSurfaceProjectAndUserOption.pipe(Effect.provide(layer)),
473 { tree: 'dev', candidates: 'none', projectName: 'absent' },
474 warnings
475 );
476
477 expect(result).toEqual({ project: Option.none(), user: Option.none() });
478 expect(warnings).toEqual([]);
479 })
480 );
481 });
482
483 describe('fallbackNotice', () => {
484 it.each([
485 { source: 'consumer', expected: Option.none() },
486 { source: 'flag', expected: Option.none() },
487 { source: 'directory-test-user', expected: Option.some('Using test user id "u"') },
488 { source: 'global-test-user', expected: Option.some('Using global test user id "u"') },
489 ] as const)(
490 '[Given] a $source user [Then] announces only a test user',
491 ({ source, expected }) => {
492 expect(fallbackNotice({ userId: 'u', source })).toEqual(expected);
493 }
494 );
495 });