@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 646 lines 25.7 KB
Raw
1 import { describe, it } from '@effect/vitest';
2 import { assertEquals, deepStrictEqual } from '@effect/vitest/utils';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
6 import { ConfigProvider, Effect, Layer, Option } from 'effect';
7 import * as tempy from 'tempy';
8 import { ComposioUserContext, rawComposioUserContextLive } from 'src/services/user-context';
9 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
10 import { UserData, UserDataWithDefaults, userDataToJSON } from 'src/models/user-data';
11 import { CliUserConfig } from 'src/models/cli-user-config';
12 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
13 import { makeKeyringService, KeyringService } from '@composio/cli-keyring/effect';
14 import {
15 type CredentialStore,
16 type EntryModifiers,
17 KeyringError,
18 CredentialPersistence,
19 } from '@composio/cli-keyring';
20 import fs from 'node:fs';
21 import path from 'node:path';
22
23 const InMemoryKeyringLayer = (() => {
24 const items = new Map<string, Uint8Array>();
25 const key = (s: string, u: string) => `${s}\0${u}`;
26 const store: CredentialStore = {
27 id: 'memory',
28 vendor: 'test',
29 persistence: () => CredentialPersistence.ProcessOnly,
30 async setSecret(s: string, u: string, secret: Uint8Array, _m: EntryModifiers) {
31 items.set(key(s, u), new Uint8Array(secret));
32 },
33 async getSecret(s: string, u: string, _m: EntryModifiers) {
34 const v = items.get(key(s, u));
35 if (!v) throw new KeyringError({ kind: 'NoEntry' });
36 return v;
37 },
38 async deleteCredential(s: string, u: string, _m: EntryModifiers) {
39 if (!items.delete(key(s, u))) throw new KeyringError({ kind: 'NoEntry' });
40 },
41 };
42 return Layer.succeed(KeyringService, makeKeyringService(store));
43 })();
44
45 const MockCliUserConfigLayer = Layer.succeed(
46 ComposioCliUserConfig,
47 ComposioCliUserConfig.of({
48 data: {
49 channel: 'beta',
50 developerModeEnabled: true,
51 developerDangerousCommandsEnabled: false,
52 experimentalFeatures: {},
53 artifactDirectory: undefined,
54 security: 'auto',
55 },
56 raw: CliUserConfig.make({
57 developer: { enabled: true, destructiveActions: false },
58 experimentalFeatures: {},
59 artifactDirectory: Option.none(),
60 security: 'auto',
61 }),
62 channel: 'beta',
63 isDevModeEnabled: () => true,
64 areDeveloperDangerousCommandsEnabled: () => false,
65 isExperimentalFeatureEnabled: () => true,
66 update: () => Effect.void,
67 })
68 );
69
70 const ComposioUserContextLive = Layer.provide(
71 rawComposioUserContextLive,
72 Layer.mergeAll(InMemoryKeyringLayer, MockCliUserConfigLayer)
73 );
74
75 describe('ComposioUserContext', () => {
76 const withMapConfigProvider = (map: Map<string, string>) =>
77 Layer.succeed(
78 ConfigProvider.ConfigProvider,
79 ConfigProvider.fromEnv({ env: Object.fromEntries(map) })
80 );
81
82 describe('[When] no `~/.composio/user_data.json` config file exists', () => {
83 describe('[When] no dynamic `Config` is set', () => {
84 it.effect('[Then] it contains default user data', () => {
85 const cwd = tempy.temporaryDirectory();
86 const map = new Map([]) satisfies Map<string, string>;
87
88 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
89 const ComposioUserContextTest = Layer.provideMerge(
90 ComposioUserContextLive,
91 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
92 );
93
94 return Effect.gen(function* () {
95 const ctx = yield* ComposioUserContext;
96
97 const expectedUserData = UserDataWithDefaults.make({
98 apiKey: Option.none(),
99 baseURL: 'https://backend.composio.dev',
100 webURL: 'https://dashboard.composio.dev/',
101 orgId: Option.none(),
102 projectId: Option.none(),
103 testUserId: Option.none(),
104 });
105 deepStrictEqual(ctx.data, expectedUserData);
106 deepStrictEqual(ctx.isLoggedIn(), false);
107 }).pipe(Effect.provide(ComposioUserContextTest));
108 });
109 });
110
111 describe('[When] dynamic `APP_CONFIG` is set', () => {
112 it.effect('[Then] is logged in', () => {
113 const cwd = tempy.temporaryDirectory();
114 const map = new Map([
115 ['COMPOSIO_USER_API_KEY', 'api_key'],
116 ['COMPOSIO_BASE_URL', 'https://test.composio.localhost'],
117 ]) satisfies Map<string, string>;
118
119 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
120 const ComposioUserContextTest = Layer.provideMerge(
121 ComposioUserContextLive,
122 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
123 );
124
125 return Effect.gen(function* () {
126 const ctx = yield* ComposioUserContext;
127
128 const expectedUserData = UserDataWithDefaults.make({
129 apiKey: Option.some('api_key'),
130 baseURL: 'https://test.composio.localhost',
131 webURL: 'https://dashboard.composio.dev/',
132 orgId: Option.none(),
133 projectId: Option.none(),
134 testUserId: Option.none(),
135 });
136 deepStrictEqual(ctx.data, expectedUserData);
137 deepStrictEqual(ctx.isLoggedIn(), true);
138 }).pipe(Effect.provide(ComposioUserContextTest));
139 });
140
141 it.effect('[Then] COMPOSIO_API_KEY alone does not authenticate user context', () => {
142 const cwd = tempy.temporaryDirectory();
143 const map = new Map([['COMPOSIO_API_KEY', 'legacy_api_key']]) satisfies Map<string, string>;
144
145 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
146 const ComposioUserContextTest = Layer.provideMerge(
147 ComposioUserContextLive,
148 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
149 );
150
151 return Effect.gen(function* () {
152 const ctx = yield* ComposioUserContext;
153 deepStrictEqual(ctx.isLoggedIn(), false);
154 deepStrictEqual(Option.getOrUndefined(ctx.data.apiKey), undefined);
155 }).pipe(Effect.provide(ComposioUserContextTest));
156 });
157 });
158 });
159
160 describe('[When] `~/.composio/user_data.json` config file exists', () => {
161 describe('[When] no dynamic `Config` is set', () => {
162 // Note: this test only passes when using `it`, not `it.scoped`
163 it('[Then] it reflects the config file', () => {
164 const cwd = tempy.temporaryDirectory();
165 const map = new Map([]) satisfies Map<string, string>;
166
167 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
168 const ComposioUserContextTest = Layer.provideMerge(
169 ComposioUserContextLive,
170 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
171 );
172
173 return Effect.gen(function* () {
174 const expectedUserData = UserData.make({
175 apiKey: Option.some('api_key'),
176 baseURL: Option.some('https://test.composio.localhost'),
177 webURL: Option.some('https://dashboard.composio.dev/'),
178 orgId: Option.none(),
179 projectId: Option.none(),
180 testUserId: Option.none(),
181 });
182 const userDataAsJson = yield* userDataToJSON(expectedUserData);
183
184 const fs = yield* FileSystem.FileSystem;
185 const userDataPath = path.join(cwd, '.composio', 'user_data.json');
186 yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
187 yield* fs.writeFileString(userDataPath, userDataAsJson);
188 yield* fs.chmod(userDataPath, 0o644);
189 assertEquals((yield* fs.stat(userDataPath)).mode & 0o777, 0o644);
190
191 const ctx = yield* ComposioUserContext;
192 deepStrictEqual(ctx.data, {
193 ...expectedUserData,
194 baseURL: expectedUserData.baseURL.pipe(Option.getOrUndefined),
195 webURL: expectedUserData.webURL.pipe(Option.getOrUndefined),
196 });
197 deepStrictEqual(ctx.isLoggedIn(), true);
198 assertEquals(yield* fs.readFileString(userDataPath, 'utf8'), userDataAsJson);
199 assertEquals((yield* fs.stat(userDataPath)).mode & 0o777, 0o600);
200 }).pipe(Effect.provide(ComposioUserContextTest));
201 });
202 });
203
204 describe('[When] dynamic `APP_CONFIG` is set', () => {
205 it.effect('[Then] it overrides the config file', () => {
206 const cwd = tempy.temporaryDirectory();
207 const map = new Map([['COMPOSIO_USER_API_KEY', 'api_key']]) satisfies Map<string, string>;
208
209 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
210 const ComposioUserContextTest = Layer.provideMerge(
211 ComposioUserContextLive,
212 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
213 );
214
215 return Effect.gen(function* () {
216 const expectedUserData = UserData.make({
217 apiKey: Option.some('api_key'),
218 baseURL: Option.none(),
219 webURL: Option.some('https://dashboard.composio.dev/'),
220 orgId: Option.none(),
221 projectId: Option.none(),
222 testUserId: Option.none(),
223 });
224 const userDataAsJson = yield* userDataToJSON(expectedUserData);
225
226 const fs = yield* FileSystem.FileSystem;
227 yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
228 yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), userDataAsJson);
229
230 const ctx = yield* ComposioUserContext;
231
232 deepStrictEqual(ctx.data, {
233 ...expectedUserData,
234 baseURL: 'https://backend.composio.dev',
235 webURL: expectedUserData.webURL.pipe(Option.getOrUndefined),
236 });
237 deepStrictEqual(ctx.isLoggedIn(), true);
238 }).pipe(Effect.provide(ComposioUserContextTest));
239 });
240 });
241
242 it.effect('[Then] preserves unknown fields across read-modify-write updates', () => {
243 const cwd = tempy.temporaryDirectory();
244 const map = new Map([]) satisfies Map<string, string>;
245 const userDataPath = path.join(cwd, '.composio', 'user_data.json');
246 fs.mkdirSync(path.dirname(userDataPath), { recursive: true });
247 fs.writeFileSync(
248 userDataPath,
249 JSON.stringify({
250 api_key: 'old-api-key',
251 future_auth: {
252 provider: 'custom',
253 scopes: ['read', 'write'],
254 },
255 })
256 );
257
258 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
259 const ComposioUserContextTest = Layer.provideMerge(
260 ComposioUserContextLive,
261 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
262 );
263
264 return Effect.gen(function* () {
265 const fileSystem = yield* FileSystem.FileSystem;
266 const ctx = yield* ComposioUserContext;
267 yield* ctx.login('new-api-key');
268
269 const parsed = JSON.parse(yield* fileSystem.readFileString(userDataPath, 'utf8')) as {
270 api_key: string;
271 future_auth: { provider: string; scopes: Array<string> };
272 };
273 assertEquals(parsed.api_key, 'new-api-key');
274 assertEquals(parsed.future_auth, {
275 provider: 'custom',
276 scopes: ['read', 'write'],
277 });
278 }).pipe(Effect.provide(ComposioUserContextTest));
279 });
280
281 describe('[When] the file is empty', () => {
282 it('[Then] it falls back to defaults and overwrites the file', () => {
283 const cwd = tempy.temporaryDirectory();
284 const map = new Map([]) satisfies Map<string, string>;
285
286 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
287 const ComposioUserContextTest = Layer.provideMerge(
288 ComposioUserContextLive,
289 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
290 );
291
292 return Effect.gen(function* () {
293 const fs = yield* FileSystem.FileSystem;
294 yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
295 // Write an empty file
296 yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), '');
297
298 // Should NOT throw — should fall back to defaults
299 const ctx = yield* ComposioUserContext;
300
301 const expectedUserData = UserDataWithDefaults.make({
302 apiKey: Option.none(),
303 baseURL: 'https://backend.composio.dev',
304 webURL: 'https://dashboard.composio.dev/',
305 orgId: Option.none(),
306 projectId: Option.none(),
307 testUserId: Option.none(),
308 });
309 deepStrictEqual(ctx.data, expectedUserData);
310 deepStrictEqual(ctx.isLoggedIn(), false);
311
312 // The corrupted file should have been overwritten with valid defaults
313 const contents = yield* fs.readFileString(
314 path.join(cwd, '.composio', 'user_data.json'),
315 'utf8'
316 );
317 const parsed = JSON.parse(contents);
318 deepStrictEqual(parsed.api_key, null);
319 }).pipe(Effect.provide(ComposioUserContextTest));
320 });
321 });
322
323 describe('[When] the file contains invalid JSON', () => {
324 it('[Then] it falls back to defaults and overwrites the file', () => {
325 const cwd = tempy.temporaryDirectory();
326 const map = new Map([]) satisfies Map<string, string>;
327
328 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
329 const ComposioUserContextTest = Layer.provideMerge(
330 ComposioUserContextLive,
331 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
332 );
333
334 return Effect.gen(function* () {
335 const fs = yield* FileSystem.FileSystem;
336 yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
337 // Write corrupted JSON
338 yield* fs.writeFileString(
339 path.join(cwd, '.composio', 'user_data.json'),
340 '{not valid json!!!'
341 );
342
343 // Should NOT throw — should fall back to defaults
344 const ctx = yield* ComposioUserContext;
345
346 const expectedUserData = UserDataWithDefaults.make({
347 apiKey: Option.none(),
348 baseURL: 'https://backend.composio.dev',
349 webURL: 'https://dashboard.composio.dev/',
350 orgId: Option.none(),
351 projectId: Option.none(),
352 testUserId: Option.none(),
353 });
354 deepStrictEqual(ctx.data, expectedUserData);
355 deepStrictEqual(ctx.isLoggedIn(), false);
356 }).pipe(Effect.provide(ComposioUserContextTest));
357 });
358 });
359
360 describe('[When] the file contains valid JSON but wrong schema', () => {
361 it('[Then] it falls back to defaults and overwrites the file', () => {
362 const cwd = tempy.temporaryDirectory();
363 const map = new Map([]) satisfies Map<string, string>;
364
365 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
366 const ComposioUserContextTest = Layer.provideMerge(
367 ComposioUserContextLive,
368 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
369 );
370
371 return Effect.gen(function* () {
372 const fs = yield* FileSystem.FileSystem;
373 yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
374 // Write valid JSON but with wrong schema (api_key should be string|null, not number)
375 yield* fs.writeFileString(
376 path.join(cwd, '.composio', 'user_data.json'),
377 JSON.stringify({ api_key: 12345, unknown_field: true })
378 );
379
380 // Should NOT throw — should fall back to defaults
381 const ctx = yield* ComposioUserContext;
382
383 const expectedUserData = UserDataWithDefaults.make({
384 apiKey: Option.none(),
385 baseURL: 'https://backend.composio.dev',
386 webURL: 'https://dashboard.composio.dev/',
387 orgId: Option.none(),
388 projectId: Option.none(),
389 testUserId: Option.none(),
390 });
391 deepStrictEqual(ctx.data, expectedUserData);
392 deepStrictEqual(ctx.isLoggedIn(), false);
393 }).pipe(Effect.provide(ComposioUserContextTest));
394 });
395 });
396
397 describe('[When] the file is corrupted but env USER_API_KEY is set', () => {
398 it('[Then] it falls back to defaults but preserves env USER_API_KEY', () => {
399 const cwd = tempy.temporaryDirectory();
400 const map = new Map([
401 ['COMPOSIO_USER_API_KEY', 'env_api_key'],
402 ['COMPOSIO_API_KEY', 'legacy_api_key_should_be_ignored'],
403 ]) satisfies Map<string, string>;
404
405 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
406 const ComposioUserContextTest = Layer.provideMerge(
407 ComposioUserContextLive,
408 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
409 );
410
411 return Effect.gen(function* () {
412 const fs = yield* FileSystem.FileSystem;
413 yield* fs.makeDirectory(path.join(cwd, '.composio'), { recursive: true });
414 yield* fs.writeFileString(path.join(cwd, '.composio', 'user_data.json'), '');
415
416 const ctx = yield* ComposioUserContext;
417
418 // Despite corrupted file, env USER_API_KEY should still work
419 deepStrictEqual(ctx.isLoggedIn(), true);
420 deepStrictEqual(Option.getOrUndefined(ctx.data.apiKey), 'env_api_key');
421 }).pipe(Effect.provide(ComposioUserContextTest));
422 });
423 });
424 });
425
426 describe('[When] resolving the backend of a stored login', () => {
427 const STAGING = {
428 base_url: 'https://staging-backend.composio.dev',
429 web_url: 'https://staging-dashboard.composio.dev/',
430 };
431 const PRODUCTION = {
432 base_url: 'https://backend.composio.dev',
433 web_url: 'https://dashboard.composio.dev/',
434 };
435
436 /** Builds the context over a home whose user_data.json is `stored` (none when undefined). */
437 const withContext = <A, E>(
438 env: Record<string, string>,
439 stored: Record<string, unknown> | undefined,
440 use: (ctx: ComposioUserContext['Service'], userDataPath: string) => Effect.Effect<A, E>
441 ) => {
442 const home = tempy.temporaryDirectory();
443 const userDataPath = path.join(home, '.composio', 'user_data.json');
444 if (stored !== undefined) {
445 fs.mkdirSync(path.dirname(userDataPath), { recursive: true });
446 fs.writeFileSync(userDataPath, JSON.stringify(stored));
447 }
448 const layer = Layer.provideMerge(
449 ComposioUserContextLive,
450 Layer.mergeAll(
451 BunFileSystem.layer,
452 BunPath.layer,
453 Layer.succeed(NodeOs, defaultNodeOs({ homedir: home })),
454 withMapConfigProvider(new Map(Object.entries(env)))
455 )
456 );
457 return Effect.flatMap(ComposioUserContext, ctx => use(ctx, userDataPath)).pipe(
458 Effect.provide(layer)
459 );
460 };
461 const readStored = (userDataPath: string) =>
462 JSON.parse(fs.readFileSync(userDataPath, 'utf8')) as Record<string, unknown>;
463 const stagingLogin = { api_key: 'uak_staging', org_id: 'org_1', ...STAGING };
464
465 it.effect('[Given] a staging login and no env var [Then] it uses staging', () =>
466 withContext({}, stagingLogin, ctx =>
467 Effect.sync(() => {
468 assertEquals(ctx.data.baseURL, STAGING.base_url);
469 assertEquals(ctx.data.webURL, STAGING.web_url);
470 assertEquals(Option.isNone(ctx.backendMismatch), true);
471 })
472 )
473 );
474
475 it.effect(
476 '[Given] a staging login and COMPOSIO_BASE_URL [Then] the env var wins and the mismatch is reported',
477 () =>
478 withContext({ COMPOSIO_BASE_URL: PRODUCTION.base_url }, stagingLogin, ctx =>
479 Effect.sync(() => {
480 assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
481 assertEquals(ctx.data.webURL, PRODUCTION.web_url);
482 deepStrictEqual(
483 ctx.backendMismatch,
484 Option.some({
485 variable: 'COMPOSIO_BASE_URL' as const,
486 issuedBy: STAGING.base_url,
487 selected: PRODUCTION.base_url,
488 })
489 );
490 })
491 )
492 );
493
494 it.effect(
495 '[Given] a staging login and COMPOSIO_ENVIRONMENT=staging [Then] nothing is reported',
496 () =>
497 withContext({ COMPOSIO_ENVIRONMENT: 'staging' }, stagingLogin, ctx =>
498 Effect.sync(() => {
499 assertEquals(ctx.data.baseURL, STAGING.base_url);
500 assertEquals(Option.isNone(ctx.backendMismatch), true);
501 })
502 )
503 );
504
505 it.effect(
506 '[Given] COMPOSIO_USER_API_KEY and no env var [Then] it uses the default backend',
507 () =>
508 withContext({ COMPOSIO_USER_API_KEY: 'uak_env' }, stagingLogin, ctx =>
509 Effect.sync(() => {
510 assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
511 assertEquals(ctx.data.webURL, PRODUCTION.web_url);
512 assertEquals(Option.isNone(ctx.backendMismatch), true);
513 })
514 )
515 );
516
517 it.effect(
518 '[Given] a recorded backend but no stored key [Then] it uses the default backend',
519 () =>
520 withContext({}, { api_key: null, ...STAGING }, ctx =>
521 Effect.sync(() => {
522 assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
523 assertEquals(ctx.data.webURL, PRODUCTION.web_url);
524 })
525 )
526 );
527
528 it.effect(
529 '[Given] an env override [When] the user data is updated [Then] the stored backend is kept',
530 () =>
531 withContext(
532 { COMPOSIO_BASE_URL: 'http://127.0.0.1:9' },
533 stagingLogin,
534 (ctx, userDataPath) =>
535 Effect.gen(function* () {
536 yield* ctx.update({ orgId: Option.some('org_2') });
537 const stored = readStored(userDataPath);
538 assertEquals(stored.org_id, 'org_2');
539 assertEquals(stored.base_url, STAGING.base_url);
540 assertEquals(stored.web_url, STAGING.web_url);
541 })
542 )
543 );
544
545 it.effect(
546 '[Given] COMPOSIO_ENVIRONMENT=staging [When] logging in [Then] the staging backend is recorded',
547 () =>
548 withContext({ COMPOSIO_ENVIRONMENT: 'staging' }, undefined, (ctx, userDataPath) =>
549 Effect.gen(function* () {
550 yield* ctx.login('uak_new', 'org_1');
551 const stored = readStored(userDataPath);
552 assertEquals(stored.base_url, STAGING.base_url);
553 assertEquals(stored.web_url, STAGING.web_url);
554 })
555 )
556 );
557
558 it.effect(
559 '[Given] a staging login and no env var [When] logging in again [Then] staging stays recorded',
560 () =>
561 withContext({}, stagingLogin, (ctx, userDataPath) =>
562 Effect.gen(function* () {
563 yield* ctx.login('uak_again', 'org_1');
564 assertEquals(readStored(userDataPath).base_url, STAGING.base_url);
565 assertEquals(ctx.data.baseURL, STAGING.base_url);
566 })
567 )
568 );
569
570 it.effect(
571 '[Given] a staging login and COMPOSIO_USER_API_KEY [When] the user data is updated [Then] the stored key stays paired with its backend',
572 () =>
573 withContext(
574 { COMPOSIO_USER_API_KEY: 'uak_env_production' },
575 stagingLogin,
576 (ctx, userDataPath) =>
577 Effect.gen(function* () {
578 yield* ctx.update({ orgId: Option.some('org_2') });
579 const stored = readStored(userDataPath);
580 assertEquals(stored.org_id, 'org_2');
581 assertEquals(stored.api_key, 'uak_staging');
582 assertEquals(stored.base_url, STAGING.base_url);
583 // The env key still serves this run's requests.
584 assertEquals(Option.getOrUndefined(ctx.data.apiKey), 'uak_env_production');
585 })
586 )
587 );
588
589 it.effect(
590 '[Given] COMPOSIO_USER_API_KEY and no stored login [When] the user data is updated [Then] the env key is not written',
591 () =>
592 withContext({ COMPOSIO_USER_API_KEY: 'uak_env_only' }, undefined, (ctx, userDataPath) =>
593 Effect.gen(function* () {
594 yield* ctx.update({ orgId: Option.some('org_2') });
595 const stored = readStored(userDataPath);
596 assertEquals(stored.org_id, 'org_2');
597 assertEquals(stored.api_key ?? null, null);
598 })
599 )
600 );
601
602 it.effect(
603 '[Given] a login recorded against another backend [When] an agent identity logs in [Then] the env-selected backend is recorded',
604 () =>
605 withContext(
606 {},
607 { api_key: 'uak_old', base_url: 'https://proxy.example.test', web_url: null },
608 (ctx, userDataPath) =>
609 Effect.gen(function* () {
610 yield* ctx.login('uak_agent', 'org_agent', undefined, { issuer: 'environment' });
611 const stored = readStored(userDataPath);
612 assertEquals(stored.api_key, 'uak_agent');
613 assertEquals(stored.base_url, PRODUCTION.base_url);
614 assertEquals(stored.web_url, PRODUCTION.web_url);
615 assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
616 })
617 )
618 );
619
620 it.effect(
621 '[Given] COMPOSIO_ENVIRONMENT=staging and an older production login [When] an agent identity logs in [Then] staging is recorded',
622 () =>
623 withContext(
624 { COMPOSIO_ENVIRONMENT: 'staging' },
625 { api_key: 'uak_old', ...PRODUCTION },
626 (ctx, userDataPath) =>
627 Effect.gen(function* () {
628 yield* ctx.login('uak_agent', 'org_agent', undefined, { issuer: 'environment' });
629 assertEquals(readStored(userDataPath).base_url, STAGING.base_url);
630 })
631 )
632 );
633
634 it.effect('[When] logging out [Then] the recorded backend is forgotten', () =>
635 withContext({}, stagingLogin, (ctx, userDataPath) =>
636 Effect.gen(function* () {
637 yield* ctx.logout;
638 const stored = readStored(userDataPath);
639 assertEquals(stored.base_url, null);
640 assertEquals(stored.web_url, null);
641 assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
642 })
643 )
644 );
645 });
646 });