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

test(cli): lint the test tree and enforce deterministic @effect/vitest suites (#3883)

This PR: - un-ignores `ts/packages/cli/test` in the root ESLint config (fixtures and the `test/__utils__` harness glue stay unlinted) and activates the test rule group: no `Effect.run*` in suites (use `it.effect`/`it.scoped`/`it.live`) and no `Date.now()` - adds `test/__utils__/vitest.setup.ts`, pointing HOME and `COMPOSIO_CACHE_DIR` at per-run temp directories so suites never touch the developer's real `~/.composio` state - migrates the remaining suites onto @effect/vitest runners with layer-provided platforms, pins wall-clock reads via `vi.setSystemTime`/TestClock-relative fixtures, and uses `crypto.randomUUID()` for unique temp names - lands the v3 Cause characterization suite pinning `reduceWithContext` traversal over the six-constructor tree and rendered error output — the executable equivalence oracle for the effect v4 migration - tests arriving in later stack PRs must comply from birth --- **Stack** (re-slice of https://github.com/ComposioHQ/composio/pull/3859; each PR targets its parent and auto-retargets to `next` as parents merge): 1. https://github.com/ComposioHQ/composio/pull/3877 — guidelines + inert rule groups 2. https://github.com/ComposioHQ/composio/pull/3878 — `new Function()` eval security fix 3. https://github.com/ComposioHQ/composio/pull/3879 — behavioral fix pack 4. https://github.com/ComposioHQ/composio/pull/3880 — platform-imports rule + migration 5. https://github.com/ComposioHQ/composio/pull/3881 — terminal-streams rule + TerminalUI boundary 6. https://github.com/ComposioHQ/composio/pull/3882 — descriptor seam + zod→Schema 7. https://github.com/ComposioHQ/composio/pull/3883 — test-tree lint + deterministic suites ← **this PR** 8. https://github.com/ComposioHQ/composio/pull/3884 — typed error boundaries + v4 seams 9. https://github.com/ComposioHQ/composio/pull/3885 — try/catch+env ban + boundary ratchet On stacked bases CI runs lint/build and the CLI Docker e2e job; unit tests and typecheck are verified locally per PR and re-verified by full CI when each PR is retargeted to `next`.

Alberto Schiabel committed Jul 21, 2026 at 11:35 UTC 6010fc712c8580c127f20c7f22d4a87cd0201b0b
16 files changed +1647 -1026
eslint.config.mjs
+33 -35
@@ -162,13 +162,12 @@ export default [
162 'ts/examples/**/dist-worker/**',
163 'scripts/**',
164 '**/test/**',
165 - // uncommented by the test-rules PR of this stack: the CLI test sources
166 - // become linted (unlike other packages' tests) so the @effect/vitest
167 - // guardrail below is actually enforced. Fixtures and the test/__utils__
168 - // harness glue stay unlinted.
169 - // '!ts/packages/cli/test/**',
170 - // 'ts/packages/cli/test/__fixtures__/**',
171 - // 'ts/packages/cli/test/__utils__/**',
165 + // The CLI test sources are linted (unlike other packages' tests) so the
166 + // @effect/vitest guardrail below is actually enforced. Fixtures and the
167 + // test/__utils__ harness glue stay unlinted.
168 + '!ts/packages/cli/test/**',
169 + 'ts/packages/cli/test/__fixtures__/**',
170 + 'ts/packages/cli/test/__utils__/**',
171 ],
172 },
173 { files: ['ts/packages/**/*.ts', 'ts/examples/**/*.ts'] },
@@ -225,34 +224,33 @@ export default [
224 ],
225 },
226 },
228 - // uncommented by the test-rules PR of this stack.
229 - // {
230 - // // Tests exercise Effects through @effect/vitest (it.effect, it.scoped,
231 - // // it.live) so failures surface as typed Exits instead of thrown
232 - // // FiberFailures. The test/__utils__ harness glue (vitest setup files,
233 - // // TestLayer runner) is intentionally outside this glob: it is the one
234 - // // boundary allowed to run Effects directly.
235 - // files: ['ts/packages/cli/test/src/**/*.{ts,tsx}'],
236 - // rules: {
237 - // // Vitest suites are one long describe() block by design, and mock
238 - // // plumbing casts freely; the SUT's own types carry the safety.
239 - // 'max-lines-per-function': 'off',
240 - // '@typescript-eslint/no-explicit-any': 'off',
241 - // 'no-restricted-syntax': [
242 - // 'error',
243 - // {
244 - // selector: "MemberExpression[object.name='Effect'][property.name=/^run/]",
245 - // message:
246 - // 'Run Effects through @effect/vitest (it.effect, it.scoped, it.live) instead of Effect.run* in tests.',
247 - // },
248 - // {
249 - // selector: "CallExpression[callee.object.name='Date'][callee.property.name='now']",
250 - // message:
251 - // 'Tests must be deterministic: pin time with vi.setSystemTime / TestClock-relative fixtures, use crypto.randomUUID() for unique names.',
252 - // },
253 - // ],
254 - // },
255 - // },
227 + {
228 + // Tests exercise Effects through @effect/vitest (it.effect, it.scoped,
229 + // it.live) so failures surface as typed Exits instead of thrown
230 + // FiberFailures. The test/__utils__ harness glue (vitest setup files,
231 + // TestLayer runner) is intentionally outside this glob: it is the one
232 + // boundary allowed to run Effects directly.
233 + files: ['ts/packages/cli/test/src/**/*.{ts,tsx}'],
234 + rules: {
235 + // Vitest suites are one long describe() block by design, and mock
236 + // plumbing casts freely; the SUT's own types carry the safety.
237 + 'max-lines-per-function': 'off',
238 + '@typescript-eslint/no-explicit-any': 'off',
239 + 'no-restricted-syntax': [
240 + 'error',
241 + {
242 + selector: "MemberExpression[object.name='Effect'][property.name=/^run/]",
243 + message:
244 + 'Run Effects through @effect/vitest (it.effect, it.scoped, it.live) instead of Effect.run* in tests.',
245 + },
246 + {
247 + selector: "CallExpression[callee.object.name='Date'][callee.property.name='now']",
248 + message:
249 + 'Tests must be deterministic: pin time with vi.setSystemTime / TestClock-relative fixtures, use crypto.randomUUID() for unique names.',
250 + },
251 + ],
252 + },
253 + },
254 {
255 // The one file allowed to touch @effect/cli's CommandDescriptor/Usage
256 // modules (the Effect CLI v4 redesign seam).
ts/packages/cli/test/__utils__/vitest.setup.ts new
+36
@@ -0,0 +1,36 @@
1 +import { FileSystem } from '@effect/platform';
2 +import { BunFileSystem } from '@effect/platform-bun';
3 +import { Effect } from 'effect';
4 +import { afterEach, beforeEach, vi } from 'vitest';
5 +
6 +// Point every test at a fresh, empty config directory so nothing reads or
7 +// writes the developer's real `~/.composio`. An empty directory holds no
8 +// permission snapshot, so the tool-permission gate resolves to 'skip' instead
9 +// of spawning the native approval dialog / browser prompt from the developer's
10 +// real enhanced-controls state. Tests that need a specific directory stub
11 +// COMPOSIO_CACHE_DIR themselves; stubs applied inside a test win over this one.
12 +let testConfigDirectory: string | undefined;
13 +
14 +const runFs = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>): Promise<A> =>
15 + Effect.runPromise(effect.pipe(Effect.provide(BunFileSystem.layer)));
16 +
17 +beforeEach(async () => {
18 + testConfigDirectory = await runFs(
19 + Effect.flatMap(FileSystem.FileSystem, fs =>
20 + fs.makeTempDirectory({ prefix: 'composio-cli-test-config-' })
21 + )
22 + );
23 + vi.stubEnv('COMPOSIO_CACHE_DIR', testConfigDirectory);
24 +});
25 +
26 +afterEach(async () => {
27 + const directory = testConfigDirectory;
28 + testConfigDirectory = undefined;
29 + if (directory) {
30 + await runFs(
31 + Effect.flatMap(FileSystem.FileSystem, fs =>
32 + fs.remove(directory, { recursive: true, force: true })
33 + )
34 + );
35 + }
36 +});
ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.ts new
+134
@@ -0,0 +1,134 @@
1 +import { FileSystem, Path } from '@effect/platform';
2 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
3 +import { ValidationError } from '@effect/cli';
4 +import { describe, expect, it, layer } from '@effect/vitest';
5 +import { Cause, Effect, Exit, Layer } from 'effect';
6 +import * as tempy from 'tempy';
7 +import { discoverSkillRoots } from 'src/effects/discover-skill-roots';
8 +import { cli, MockConsole, TestLive } from 'test/__utils__';
9 +
10 +const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
11 +
12 +const providePlatform = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) =>
13 + effect.pipe(Effect.provide(TestPlatform));
14 +
15 +const expectRootsExactlyOnce = (actual: ReadonlyArray<string>, expected: ReadonlyArray<string>) => {
16 + expect(actual).toEqual(expected);
17 + expect(new Set(actual).size).toBe(actual.length);
18 +};
19 +
20 +describe('config experimental skill discovery', () => {
21 + it.effect('discovers only the canonical skill root', () =>
22 + providePlatform(
23 + Effect.gen(function* () {
24 + const fs = yield* FileSystem.FileSystem;
25 + const path = yield* Path.Path;
26 + const home = tempy.temporaryDirectory();
27 + const canonicalRoot = path.join(home, '.agents', 'skills');
28 + yield* fs.makeDirectory(path.join(canonicalRoot, 'composio-cli'), { recursive: true });
29 +
30 + expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);
31 + })
32 + )
33 + );
34 +
35 + it.effect('discovers canonical and real Claude skill copies', () =>
36 + providePlatform(
37 + Effect.gen(function* () {
38 + const fs = yield* FileSystem.FileSystem;
39 + const path = yield* Path.Path;
40 + const home = tempy.temporaryDirectory();
41 + const canonicalRoot = path.join(home, '.agents', 'skills');
42 + const claudeRoot = path.join(home, '.claude', 'skills');
43 + yield* fs.makeDirectory(path.join(canonicalRoot, 'composio-cli'), { recursive: true });
44 + yield* fs.makeDirectory(path.join(claudeRoot, 'composio-cli'), { recursive: true });
45 +
46 + expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot, claudeRoot]);
47 + })
48 + )
49 + );
50 +
51 + it.effect('deduplicates a Claude symlink to the canonical skill', () =>
52 + providePlatform(
53 + Effect.gen(function* () {
54 + const fs = yield* FileSystem.FileSystem;
55 + const path = yield* Path.Path;
56 + const home = tempy.temporaryDirectory();
57 + const canonicalRoot = path.join(home, '.agents', 'skills');
58 + const canonicalSkill = path.join(canonicalRoot, 'composio-cli');
59 + const claudeSkill = path.join(home, '.claude', 'skills', 'composio-cli');
60 + yield* fs.makeDirectory(canonicalSkill, { recursive: true });
61 + yield* fs.makeDirectory(path.dirname(claudeSkill), { recursive: true });
62 + yield* fs.symlink(path.relative(path.dirname(claudeSkill), canonicalSkill), claudeSkill);
63 +
64 + expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);
65 + })
66 + )
67 + );
68 +
69 + it.effect('ignores a broken Claude symlink and keeps the canonical fallback', () =>
70 + providePlatform(
71 + Effect.gen(function* () {
72 + const fs = yield* FileSystem.FileSystem;
73 + const path = yield* Path.Path;
74 + const home = tempy.temporaryDirectory();
75 + const canonicalRoot = path.join(home, '.agents', 'skills');
76 + const claudeSkill = path.join(home, '.claude', 'skills', 'composio-cli');
77 + yield* fs.makeDirectory(path.dirname(claudeSkill), { recursive: true });
78 + yield* fs.symlink('../missing-composio-cli', claudeSkill);
79 +
80 + expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);
81 + })
82 + )
83 + );
84 +
85 + it.effect('uses the canonical fallback when neither skill root exists', () =>
86 + providePlatform(
87 + Effect.gen(function* () {
88 + const path = yield* Path.Path;
89 + const home = tempy.temporaryDirectory();
90 + const canonicalRoot = path.join(home, '.agents', 'skills');
91 +
92 + expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);
93 + })
94 + )
95 + );
96 +
97 + it.effect('keeps an external symlink target and the canonical fallback once each', () =>
98 + providePlatform(
99 + Effect.gen(function* () {
100 + const fs = yield* FileSystem.FileSystem;
101 + const path = yield* Path.Path;
102 + const home = tempy.temporaryDirectory();
103 + const canonicalRoot = path.join(home, '.agents', 'skills');
104 + const externalRoot = path.join(home, 'shared-skills');
105 + const externalSkill = path.join(externalRoot, 'composio-cli');
106 + const claudeSkill = path.join(home, '.claude', 'skills', 'composio-cli');
107 + yield* fs.makeDirectory(externalSkill, { recursive: true });
108 + yield* fs.makeDirectory(path.dirname(claudeSkill), { recursive: true });
109 + yield* fs.symlink(path.relative(path.dirname(claudeSkill), externalSkill), claudeSkill);
110 +
111 + expectRootsExactlyOnce(yield* discoverSkillRoots(home), [externalRoot, canonicalRoot]);
112 + })
113 + )
114 + );
115 +});
116 +
117 +layer(TestLive())('config experimental state validation', it => {
118 + it.scoped('reports an invalid state through Effect CLI validation', () =>
119 + Effect.gen(function* () {
120 + const exit = yield* Effect.exit(cli(['config', 'experimental', 'local_tools', 'sometimes']));
121 +
122 + expect(Exit.isFailure(exit)).toBe(true);
123 + if (Exit.isFailure(exit)) {
124 + const failure = Cause.squash(exit.cause);
125 + expect(
126 + ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
127 + ).toBe(true);
128 + }
129 + expect((yield* MockConsole.getLines()).join('\n')).toContain(
130 + 'Invalid state "sometimes". Use "on" or "off".'
131 + );
132 + })
133 + );
134 +});
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts
-4
@@ -64,10 +64,6 @@ const connectedAccountsData = {
64 items: testConnectedAccounts,
65 } satisfies TestLiveInput['connectedAccountsData'];
66
67 -const testConfigProvider = ConfigProvider.fromMap(
68 - new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
69 -).pipe(extendConfigProvider);
70 -
67 const testDevConfigProvider = ConfigProvider.fromMap(
68 new Map([
69 ['COMPOSIO_USER_API_KEY', 'test_api_key'],
ts/packages/cli/test/src/commands/local-tools.cmd.test.ts
+1 -1
@@ -11,7 +11,7 @@ const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
11 const previous = process.env.COMPOSIO_LOCAL_TOOLS_PATH;
12 process.env.COMPOSIO_LOCAL_TOOLS_PATH = path.join(
13 os.tmpdir(),
14 - `composio-local-tools-${Date.now()}.json`
14 + `composio-local-tools-${crypto.randomUUID()}.json`
15 );
16 return previous;
17 }),
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+10 -7
@@ -935,9 +935,9 @@ describe('CLI: composio execute', () => {
935 expect(output.storedInFile).toBe(true);
936 expect(output.logId).toBe('log_large_output');
937 expect(output.tokenCount).toBeGreaterThan(10_000);
938 - expect(output.outputFilePath).toMatch(
939 - /composio\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/
940 - );
938 + // Session artifacts fall back to COMPOSIO_CACHE_DIR, which the shared
939 + // vitest setup pins to a per-test temp directory.
940 + expect(output.outputFilePath).toMatch(/\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/);
941 expect(fs.existsSync(output.outputFilePath)).toBe(true);
942 const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');
943 expect(storedJson).toContain('token token token');
@@ -1123,7 +1123,7 @@ describe('CLI: composio execute', () => {
1123 it => {
1124 it.scoped('uploads local file paths before Tool Router execution', () =>
1125 Effect.gen(function* () {
1126 - const tempFile = path.join(os.tmpdir(), `composio-upload-${Date.now()}.txt`);
1126 + const tempFile = path.join(os.tmpdir(), `composio-upload-${crypto.randomUUID()}.txt`);
1127 fs.writeFileSync(tempFile, 'hello from cli upload', 'utf8');
1128
1129 const originalFetch = globalThis.fetch;
@@ -1222,7 +1222,7 @@ describe('CLI: composio execute', () => {
1222 it => {
1223 it.scoped('injects into the single file_uploadable field before upload hydration', () =>
1224 Effect.gen(function* () {
1225 - const tempFile = path.join(os.tmpdir(), `composio-inject-${Date.now()}.png`);
1225 + const tempFile = path.join(os.tmpdir(), `composio-inject-${crypto.randomUUID()}.png`);
1226 fs.writeFileSync(tempFile, 'png-binary-ish', 'utf8');
1227
1228 const originalFetch = globalThis.fetch;
@@ -1314,7 +1314,7 @@ describe('CLI: composio execute', () => {
1314 it => {
1315 it.scoped('treats property-bearing schema nodes as object-like during upload hydration', () =>
1316 Effect.gen(function* () {
1317 - const tempFile = path.join(os.tmpdir(), `composio-nested-${Date.now()}.png`);
1317 + const tempFile = path.join(os.tmpdir(), `composio-nested-${crypto.randomUUID()}.png`);
1318 fs.writeFileSync(tempFile, 'nested-png-binary-ish', 'utf8');
1319
1320 const originalFetch = globalThis.fetch;
@@ -1403,7 +1403,10 @@ describe('CLI: composio execute', () => {
1403 it => {
1404 it.scoped('propagates upload failures from file hydration', () =>
1405 Effect.gen(function* () {
1406 - const tempFile = path.join(os.tmpdir(), `composio-upload-fail-${Date.now()}.txt`);
1406 + const tempFile = path.join(
1407 + os.tmpdir(),
1408 + `composio-upload-fail-${crypto.randomUUID()}.txt`
1409 + );
1410 fs.writeFileSync(tempFile, 'hello from failed cli upload', 'utf8');
1411
1412 const originalFetch = globalThis.fetch;
ts/packages/cli/test/src/effect-errors/cause-characterization.test.ts new
+186
@@ -0,0 +1,186 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
3 +import { Cause, Data, Effect, FiberId } from 'effect';
4 +
5 +import { captureErrors } from 'src/effect-errors/capture-errors';
6 +import { captureErrorsFrom } from 'src/effect-errors/logic/errors/capture-errors-from-cause';
7 +import { prettyPrintFromCapturedErrors } from 'src/effect-errors/pretty-print-from-captured-errors';
8 +
9 +// Characterization tests pinning the v3 Cause traversal and rendering
10 +// behavior, so the Effect v4 migration (flat failure list instead of the
11 +// Empty/Fail/Die/Interrupt/Sequential/Parallel tree) has an executable
12 +// equivalence oracle instead of eyeballing error output.
13 +
14 +class DbError extends Data.TaggedError('DbError')<{
15 + readonly message: string;
16 +}> {}
17 +
18 +class HttpError extends Data.TaggedError('HttpError')<{
19 + readonly message: string;
20 +}> {}
21 +
22 +const stripAnsi = (value: string): string => value.replace(/\x1b\[[0-9;]*m/g, '');
23 +
24 +const render = (captured: Effect.Effect.Success<ReturnType<typeof capture>>): string =>
25 + stripAnsi(
26 + prettyPrintFromCapturedErrors(captured, {
27 + enabled: true,
28 + stripCwd: true,
29 + hideStackTrace: true,
30 + })
31 + );
32 +
33 +const capture = <E>(cause: Cause.Cause<E>) =>
34 + captureErrors(cause).pipe(Effect.provide([BunFileSystem.layer, BunPath.layer]));
35 +
36 +describe('captureErrorsFrom (structural Cause traversal)', () => {
37 + it('returns no errors for an empty cause', () => {
38 + expect(captureErrorsFrom(Cause.empty)).toStrictEqual([]);
39 + });
40 +
41 + it('captures a tagged failure with its type and message', () => {
42 + const [error, ...rest] = captureErrorsFrom(Cause.fail(new DbError({ message: 'no db' })));
43 +
44 + expect(rest).toStrictEqual([]);
45 + expect(error?.errorType).toBe('DbError');
46 + expect(error?.message).toBe('no db');
47 + expect(error?.isPlainString).toBe(false);
48 + });
49 +
50 + it('captures a plain-string failure as a plain string', () => {
51 + const [error] = captureErrorsFrom(Cause.fail('boom'));
52 +
53 + expect(error?.isPlainString).toBe(true);
54 + expect(error?.message).toBe('boom');
55 + });
56 +
57 + it('captures a defect', () => {
58 + const [error, ...rest] = captureErrorsFrom(Cause.die(new Error('kaboom')));
59 +
60 + expect(rest).toStrictEqual([]);
61 + expect(error?.errorType).toBe('Error');
62 + expect(error?.message).toStrictEqual(['kaboom']);
63 + });
64 +
65 + it('captures nothing for an interruption', () => {
66 + expect(captureErrorsFrom(Cause.interrupt(FiberId.none))).toStrictEqual([]);
67 + });
68 +
69 + it('flattens a sequential cause left to right', () => {
70 + const cause = Cause.sequential(
71 + Cause.fail(new DbError({ message: 'first' })),
72 + Cause.die(new Error('second'))
73 + );
74 +
75 + const errors = captureErrorsFrom(cause);
76 +
77 + expect(errors.map(error => error.errorType)).toStrictEqual(['DbError', 'Error']);
78 + });
79 +
80 + it('flattens a parallel cause left to right', () => {
81 + const cause = Cause.parallel(
82 + Cause.fail(new DbError({ message: 'left' })),
83 + Cause.fail(new HttpError({ message: 'right' }))
84 + );
85 +
86 + const errors = captureErrorsFrom(cause);
87 +
88 + expect(errors.map(error => error.message)).toStrictEqual(['left', 'right']);
89 + });
90 +
91 + it('flattens nested parallel-in-sequential causes in traversal order', () => {
92 + const cause = Cause.sequential(
93 + Cause.parallel(
94 + Cause.fail(new DbError({ message: 'a' })),
95 + Cause.fail(new HttpError({ message: 'b' }))
96 + ),
97 + Cause.fail(new DbError({ message: 'c' }))
98 + );
99 +
100 + const errors = captureErrorsFrom(cause);
101 +
102 + expect(errors.map(error => error.message)).toStrictEqual(['a', 'b', 'c']);
103 + });
104 +
105 + it('ignores interruptions mixed with failures', () => {
106 + const cause = Cause.sequential(
107 + Cause.interrupt(FiberId.none),
108 + Cause.fail(new DbError({ message: 'still there' }))
109 + );
110 +
111 + const errors = captureErrorsFrom(cause);
112 +
113 + expect(errors.map(error => error.message)).toStrictEqual(['still there']);
114 + });
115 +
116 + it.effect('threads the ambient span from a runtime failure into the captured error', () =>
117 + Effect.gen(function* () {
118 + const cause = yield* Effect.fail(new DbError({ message: 'no db' })).pipe(
119 + Effect.withSpan('characterization-span'),
120 + Effect.sandbox,
121 + Effect.flip
122 + );
123 +
124 + const [error] = captureErrorsFrom(cause);
125 +
126 + expect(error?.span?.name).toBe('characterization-span');
127 + })
128 + );
129 +});
130 +
131 +describe('captureErrors + prettyPrintFromCapturedErrors (rendering)', () => {
132 + it.effect(
133 + 'reports interrupt-only causes as interrupted and renders the interruption message',
134 + () =>
135 + Effect.gen(function* () {
136 + const captured = yield* capture(Cause.interrupt(FiberId.none));
137 +
138 + expect(captured).toStrictEqual({ interrupted: true, errors: [] });
139 + expect(render(captured)).toBe('✅ All fibers interrupted without errors.');
140 + })
141 + );
142 +
143 + it.effect('renders a single failure without the multi-error header', () =>
144 + Effect.gen(function* () {
145 + const captured = yield* capture(Cause.fail(new DbError({ message: 'no db' })));
146 + const output = render(captured);
147 +
148 + expect(captured.interrupted).toBe(false);
149 + expect(output).toContain('💥 DbError • no db');
150 + expect(output).not.toContain('errors occurred');
151 + expect(output).not.toContain('#1 -');
152 + })
153 + );
154 +
155 + it.effect('renders a runtime failure with its span timeline', () =>
156 + Effect.gen(function* () {
157 + const cause = yield* Effect.fail(new HttpError({ message: 'request failed' })).pipe(
158 + Effect.withSpan('characterization-span'),
159 + Effect.sandbox,
160 + Effect.flip
161 + );
162 +
163 + const output = render(yield* capture(cause));
164 +
165 + expect(output).toContain('💥 HttpError • request failed');
166 + expect(output).toContain('◯');
167 + expect(output).toContain('characterization-span');
168 + })
169 + );
170 +
171 + it.effect('renders multiple failures with a count header and per-error indexes in order', () =>
172 + Effect.gen(function* () {
173 + const cause = Cause.parallel(
174 + Cause.fail(new DbError({ message: 'left' })),
175 + Cause.fail(new HttpError({ message: 'right' }))
176 + );
177 +
178 + const output = render(yield* capture(cause));
179 +
180 + expect(output).toContain('2 errors occurred');
181 + expect(output).toContain('💥 #1 - DbError • left');
182 + expect(output).toContain('💥 #2 - HttpError • right');
183 + expect(output.indexOf('DbError')).toBeLessThan(output.indexOf('HttpError'));
184 + })
185 + );
186 +});
ts/packages/cli/test/src/effects/compare-semver.test.ts
-13
@@ -281,19 +281,6 @@ describe('compare-semver.ts', () => {
281 }
282 }
283
284 - // Verify that the comparator would sort correctly
285 - const expectedOrder = ['1.0.0', '2.0.0', '3.0.0'];
286 - const actualResult = [...versions].sort((a, b) => {
287 - // Find the comparison result from our Effect calls
288 - const comparison = comparisons.find(
289 - c =>
290 - (c.versions[0] === a && c.versions[1] === b) ||
291 - (c.versions[0] === b && c.versions[1] === a)
292 - );
293 - if (!comparison) return 0;
294 - return comparison.versions[0] === a ? comparison.result : -comparison.result;
295 - });
296 -
284 // Since we can't actually use the Effect in Array.sort, just verify
285 // the comparison results are consistent with sort expectations
286 expect(comparisons.length).toBe(3); // 3 comparisons for 3 elements
ts/packages/cli/test/src/effects/install-skill.test.ts
+269 -201
@@ -1,10 +1,10 @@
1 +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2 import { describe, expect, it, vi } from '@effect/vitest';
3 import { Config, ConfigProvider, Effect, Exit, Layer } from 'effect';
4 import { FetchHttpClient, FileSystem, HttpClient, Path } from '@effect/platform';
5 import type * as PlatformError from '@effect/platform/Error';
6 import { BunFileSystem, BunPath } from '@effect/platform-bun';
7 import * as tempy from 'tempy';
7 -import { withHttpServer } from 'test/__utils__/http-server';
8 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
9 import {
10 inferSkillReleaseChannel,
@@ -16,9 +16,9 @@ import {
16 type SkillReleaseChannel,
17 } from 'src/effects/install-skill';
18 import { GITHUB_CONFIG } from 'src/effects/github-config';
19 +import { CliReleaseResolutionError } from 'src/effects/resolve-cli-release';
20 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
21
21 -const path = Effect.runSync(Effect.provide(Path.Path, Path.layer));
22 const TEST_RELEASE_TAG = '@composio/cli@0.3.0-test';
23 const TEST_SKILL_ZIP = Uint8Array.from(
24 atob(
@@ -51,8 +51,43 @@ const makeInstallEffect = (home: string, apiBaseUrl: string) =>
51 Effect.scoped
52 );
53
54 -const withSkillRelease = (skillZip: Uint8Array, run: (apiBaseUrl: string) => Promise<void>) =>
55 - withHttpServer((req, res) => {
54 +/**
55 + * Spin up a local HTTP server on an ephemeral port as a scoped resource and
56 + * return its base URL. Scope closure tears the server down.
57 + */
58 +const startTestHttpServer = (handler: (req: IncomingMessage, res: ServerResponse) => void) =>
59 + Effect.map(
60 + Effect.acquireRelease(
61 + Effect.promise(
62 + () =>
63 + new Promise<Server>((resolve, reject) => {
64 + const server = createServer(handler);
65 + server.once('error', reject);
66 + server.listen({ port: 0, host: '127.0.0.1' }, () => {
67 + server.off('error', reject);
68 + resolve(server);
69 + });
70 + })
71 + ),
72 + server =>
73 + Effect.promise(
74 + () =>
75 + new Promise<void>((resolve, reject) => {
76 + server.close(error => (error ? reject(error) : resolve()));
77 + })
78 + )
79 + ),
80 + server => {
81 + const address = server.address();
82 + if (address === null || typeof address === 'string') {
83 + throw new Error('Failed to bind test server to an ephemeral port');
84 + }
85 + return `http://127.0.0.1:${address.port}`;
86 + }
87 + );
88 +
89 +const startSkillReleaseServer = (skillZip: Uint8Array) =>
90 + startTestHttpServer((req, res) => {
91 if (req.url === '/skill.zip') {
92 res.writeHead(200, { 'content-type': 'application/zip' });
93 res.end(skillZip);
@@ -70,7 +105,17 @@ const withSkillRelease = (skillZip: Uint8Array, run: (apiBaseUrl: string) => Pro
105 ],
106 })
107 );
73 - }, run);
108 + });
109 +
110 +/** Scoped stub of Bun.which that misses, so release resolution takes the HTTP path. */
111 +const stubBunWhichMiss = Effect.acquireRelease(
112 + Effect.sync(() => vi.stubGlobal('Bun', { which: vi.fn(() => null) })),
113 + () =>
114 + Effect.sync(() => {
115 + vi.unstubAllGlobals();
116 + vi.restoreAllMocks();
117 + })
118 +);
119
120 type TargetSetup = (
121 fs: FileSystem.FileSystem,
@@ -154,217 +199,240 @@ describe('install-skill', () => {
199 expect(() => resolveInstalledSkillName('..')).toThrow(/Invalid skill name/);
200 });
201
157 - it('resolves the agent-specific skill path', () => {
158 - expect(
159 - resolveTargetSkillPath({
160 - home: '/tmp/test-home',
161 - path,
162 - skillName: 'composio-cli',
163 - target: 'claude',
164 - })
165 - ).toBe('/tmp/test-home/.claude/skills/composio-cli');
166 - expect(
167 - resolveTargetSkillPath({
168 - home: '/tmp/test-home',
169 - path,
170 - skillName: 'composio-cli',
171 - target: 'codex',
172 - })
173 - ).toBe('/tmp/test-home/.codex/skills/composio-cli');
174 - expect(
175 - resolveTargetSkillPath({
176 - home: '/tmp/test-home',
177 - path,
178 - skillName: 'composio-cli',
179 - target: 'openclaw',
180 - })
181 - ).toBe('/tmp/test-home/.openclaw/skills/composio-cli');
182 - });
202 + it.effect('resolves the agent-specific skill path', () =>
203 + Effect.gen(function* () {
204 + const path = yield* Path.Path;
205 + expect(
206 + resolveTargetSkillPath({
207 + home: '/tmp/test-home',
208 + path,
209 + skillName: 'composio-cli',
210 + target: 'claude',
211 + })
212 + ).toBe('/tmp/test-home/.claude/skills/composio-cli');
213 + expect(
214 + resolveTargetSkillPath({
215 + home: '/tmp/test-home',
216 + path,
217 + skillName: 'composio-cli',
218 + target: 'codex',
219 + })
220 + ).toBe('/tmp/test-home/.codex/skills/composio-cli');
221 + expect(
222 + resolveTargetSkillPath({
223 + home: '/tmp/test-home',
224 + path,
225 + skillName: 'composio-cli',
226 + target: 'openclaw',
227 + })
228 + ).toBe('/tmp/test-home/.openclaw/skills/composio-cli');
229 + }).pipe(Effect.provide(Path.layer))
230 + );
231
184 - it('prefers an explicit running release tag over channel discovery', async () => {
185 - const releaseTag = '@composio/cli@0.3.0-beta.123';
186 - const tag = await makeResolveEffect([], {
187 - channel: 'stable',
188 - releaseTag,
189 - }).pipe(Effect.runPromise);
232 + it.effect('prefers an explicit running release tag over channel discovery', () =>
233 + Effect.gen(function* () {
234 + const releaseTag = '@composio/cli@0.3.0-beta.123';
235 + const tag = yield* makeResolveEffect([], {
236 + channel: 'stable',
237 + releaseTag,
238 + });
239
191 - expect(tag).toBe(releaseTag);
192 - });
240 + expect(tag).toBe(releaseTag);
241 + })
242 + );
243 +
244 + it.scoped('fails with a typed decode error for malformed GitHub release lists', () =>
245 + Effect.gen(function* () {
246 + const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
247 + res.writeHead(200, { 'content-type': 'application/json' });
248 + res.end(JSON.stringify({ tag_name: '@composio/cli@0.3.0' }));
249 + });
250 +
251 + const error = yield* Effect.flip(
252 + makeResolveEffect(
253 + [
254 + ['GITHUB_API_BASE_URL', apiBaseUrl],
255 + ['GITHUB_OWNER', 'test-owner'],
256 + ['GITHUB_REPO', 'test-repo'],
257 + ],
258 + { channel: 'stable' }
259 + )
260 + );
261 +
262 + expect(error).toBeInstanceOf(CliReleaseResolutionError);
263 + if (error instanceof CliReleaseResolutionError) {
264 + expect(error.reason).toBe('decode');
265 + expect(error.cause).toBeDefined();
266 + }
267 + })
268 + );
269
194 - it.each(TARGET_SCENARIOS)('installs over %s target', async (_description, prepareTarget) => {
195 - await withSkillRelease(TEST_SKILL_ZIP, async apiBaseUrl => {
270 + it.scoped('fails with a typed decode error for malformed skill release metadata', () =>
271 + Effect.gen(function* () {
272 + const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
273 + res.writeHead(200, { 'content-type': 'application/json' });
274 + res.end(JSON.stringify({ assets: [{ name: 'composio-skill.zip' }] }));
275 + });
276 +
277 + const home = tempy.temporaryDirectory();
278 + const error = yield* Effect.flip(makeInstallEffect(home, apiBaseUrl));
279 +
280 + // The install pipeline still fails with a plain Error until the
281 + // typed-error slice (PR 8 of this stack) introduces SkillInstallError.
282 + expect(error).toBeInstanceOf(Error);
283 + if (error instanceof Error) {
284 + expect(error.message).toContain('Failed to download skill');
285 + }
286 + })
287 + );
288 +
289 + it.scoped.each(TARGET_SCENARIOS)('installs over %s target', ([, prepareTarget]) =>
290 + Effect.gen(function* () {
291 + const apiBaseUrl = yield* startSkillReleaseServer(TEST_SKILL_ZIP);
292 + const fs = yield* FileSystem.FileSystem;
293 + const path = yield* Path.Path;
294 const home = tempy.temporaryDirectory();
295 const target = path.join(home, '.claude', 'skills', 'composio-cli');
296 const canonicalSkill = path.join(home, '.agents', 'skills', 'composio-cli');
297
200 - await Effect.gen(function* () {
201 - const fs = yield* FileSystem.FileSystem;
202 - const platformPath = yield* Path.Path;
203 - yield* prepareTarget(fs, platformPath, home, target);
204 - }).pipe(Effect.provide(TestPlatform), Effect.runPromise);
298 + yield* prepareTarget(fs, path, home, target);
299
206 - await makeInstallEffect(home, apiBaseUrl).pipe(Effect.runPromise);
300 + yield* makeInstallEffect(home, apiBaseUrl);
301
208 - await Effect.gen(function* () {
209 - const fs = yield* FileSystem.FileSystem;
210 - const platformPath = yield* Path.Path;
211 - expect(yield* fs.readFileString(platformPath.join(target, 'SKILL.md'))).toBe(
212 - '# composio-cli\n'
213 - );
214 - expect(
215 - yield* fs.readFileString(platformPath.join(canonicalSkill, SKILL_RELEASE_TAG_FILENAME))
216 - ).toBe(`${TEST_RELEASE_TAG}\n`);
217 - expect(yield* fs.readLink(target)).toBe(
218 - platformPath.relative(platformPath.dirname(target), canonicalSkill)
219 - );
220 - expect(yield* fs.exists(platformPath.join(home, '.agents', '.tmp-skill-install'))).toBe(
221 - false
222 - );
223 - }).pipe(Effect.provide(TestPlatform), Effect.runPromise);
224 - });
225 - });
302 + expect(yield* fs.readFileString(path.join(target, 'SKILL.md'))).toBe('# composio-cli\n');
303 + expect(yield* fs.readFileString(path.join(canonicalSkill, SKILL_RELEASE_TAG_FILENAME))).toBe(
304 + `${TEST_RELEASE_TAG}\n`
305 + );
306 + expect(yield* fs.readLink(target)).toBe(path.relative(path.dirname(target), canonicalSkill));
307 + expect(yield* fs.exists(path.join(home, '.agents', '.tmp-skill-install'))).toBe(false);
308 + }).pipe(Effect.provide(TestPlatform))
309 + );
310
227 - it('removes the temporary install directory after extraction fails', async () => {
228 - await withSkillRelease(new TextEncoder().encode('not a zip'), async apiBaseUrl => {
311 + it.scoped('removes the temporary install directory after extraction fails', () =>
312 + Effect.gen(function* () {
313 + const apiBaseUrl = yield* startSkillReleaseServer(new TextEncoder().encode('not a zip'));
314 const home = tempy.temporaryDirectory();
230 - const exit = await makeInstallEffect(home, apiBaseUrl).pipe(Effect.exit, Effect.runPromise);
315 + const exit = yield* Effect.exit(makeInstallEffect(home, apiBaseUrl));
316
317 expect(Exit.isFailure(exit)).toBe(true);
233 - expect(
234 - await FileSystem.FileSystem.pipe(
235 - Effect.flatMap(fs => fs.exists(path.join(home, '.agents', '.tmp-skill-install'))),
236 - Effect.provide(TestPlatform),
237 - Effect.runPromise
238 - )
239 - ).toBe(false);
240 - });
241 - });
318
243 - it('resolves the latest stable release when the stable channel is requested', async () => {
244 - vi.stubGlobal('Bun', { which: vi.fn(() => null) });
245 -
246 - try {
247 - await withHttpServer(
248 - (_req, res) => {
249 - res.writeHead(200, { 'content-type': 'application/json' });
250 - res.end(
251 - JSON.stringify([
252 - {
253 - tag_name: '@composio/cli@0.2.20-beta.2',
254 - draft: false,
255 - prerelease: true,
256 - assets: [
257 - {
258 - name: 'composio-skill.zip',
259 - browser_download_url: 'http://127.0.0.1/beta-skill.zip',
260 - },
261 - ],
262 - },
263 - {
264 - tag_name: '@composio/cli@0.2.19',
265 - draft: false,
266 - prerelease: false,
267 - assets: [
268 - {
269 - name: 'composio-skill.zip',
270 - browser_download_url: 'http://127.0.0.1/stable-skill.zip',
271 - },
272 - ],
273 - },
274 - {
275 - tag_name: '@composio/cli@0.2.20',
276 - draft: false,
277 - prerelease: false,
278 - assets: [
279 - {
280 - name: 'composio-linux-x64.zip',
281 - browser_download_url: 'http://127.0.0.1/no-skill.zip',
282 - },
283 - ],
284 - },
285 - ])
286 - );
287 - },
288 - async apiBaseUrl => {
289 - const tag = await makeResolveEffect(
290 - [
291 - ['GITHUB_API_BASE_URL', apiBaseUrl],
292 - ['GITHUB_OWNER', 'test-owner'],
293 - ['GITHUB_REPO', 'test-repo'],
294 - ],
295 - { channel: 'stable' }
296 - ).pipe(Effect.runPromise);
297 -
298 - expect(tag).toBe('@composio/cli@0.2.19');
299 - }
319 + const fs = yield* FileSystem.FileSystem;
320 + const path = yield* Path.Path;
321 + expect(yield* fs.exists(path.join(home, '.agents', '.tmp-skill-install'))).toBe(false);
322 + }).pipe(Effect.provide(TestPlatform))
323 + );
324 +
325 + it.scoped('resolves the latest stable release when the stable channel is requested', () =>
326 + Effect.gen(function* () {
327 + yield* stubBunWhichMiss;
328 + const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
329 + res.writeHead(200, { 'content-type': 'application/json' });
330 + res.end(
331 + JSON.stringify([
332 + {
333 + tag_name: '@composio/cli@0.2.20-beta.2',
334 + draft: false,
335 + prerelease: true,
336 + assets: [
337 + {
338 + name: 'composio-skill.zip',
339 + browser_download_url: 'http://127.0.0.1/beta-skill.zip',
340 + },
341 + ],
342 + },
343 + {
344 + tag_name: '@composio/cli@0.2.19',
345 + draft: false,
346 + prerelease: false,
347 + assets: [
348 + {
349 + name: 'composio-skill.zip',
350 + browser_download_url: 'http://127.0.0.1/stable-skill.zip',
351 + },
352 + ],
353 + },
354 + {
355 + tag_name: '@composio/cli@0.2.20',
356 + draft: false,
357 + prerelease: false,
358 + assets: [
359 + {
360 + name: 'composio-linux-x64.zip',
361 + browser_download_url: 'http://127.0.0.1/no-skill.zip',
362 + },
363 + ],
364 + },
365 + ])
366 + );
367 + });
368 +
369 + const tag = yield* makeResolveEffect(
370 + [
371 + ['GITHUB_API_BASE_URL', apiBaseUrl],
372 + ['GITHUB_OWNER', 'test-owner'],
373 + ['GITHUB_REPO', 'test-repo'],
374 + ],
375 + { channel: 'stable' }
376 );
301 - } finally {
302 - vi.unstubAllGlobals();
303 - vi.restoreAllMocks();
304 - }
305 - });
377
307 - it('resolves the latest beta release when the beta channel is requested', async () => {
308 - vi.stubGlobal('Bun', { which: vi.fn(() => null) });
309 -
310 - try {
311 - await withHttpServer(
312 - (_req, res) => {
313 - res.writeHead(200, { 'content-type': 'application/json' });
314 - res.end(
315 - JSON.stringify([
316 - {
317 - tag_name: '@composio/cli@0.2.20-beta.1',
318 - draft: false,
319 - prerelease: true,
320 - assets: [
321 - {
322 - name: 'composio-skill.zip',
323 - browser_download_url: 'http://127.0.0.1/beta-1-skill.zip',
324 - },
325 - ],
326 - },
327 - {
328 - tag_name: '@composio/cli@0.2.20-beta.3',
329 - draft: false,
330 - prerelease: true,
331 - assets: [
332 - {
333 - name: 'composio-skill.zip',
334 - browser_download_url: 'http://127.0.0.1/beta-3-skill.zip',
335 - },
336 - ],
337 - },
338 - {
339 - tag_name: '@composio/cli@0.2.20',
340 - draft: false,
341 - prerelease: false,
342 - assets: [
343 - {
344 - name: 'composio-skill.zip',
345 - browser_download_url: 'http://127.0.0.1/stable-skill.zip',
346 - },
347 - ],
348 - },
349 - ])
350 - );
351 - },
352 - async apiBaseUrl => {
353 - const tag = await makeResolveEffect(
354 - [
355 - ['GITHUB_API_BASE_URL', apiBaseUrl],
356 - ['GITHUB_OWNER', 'test-owner'],
357 - ['GITHUB_REPO', 'test-repo'],
358 - ],
359 - { channel: 'beta' }
360 - ).pipe(Effect.runPromise);
361 -
362 - expect(tag).toBe('@composio/cli@0.2.20-beta.3');
363 - }
378 + expect(tag).toBe('@composio/cli@0.2.19');
379 + })
380 + );
381 +
382 + it.scoped('resolves the latest beta release when the beta channel is requested', () =>
383 + Effect.gen(function* () {
384 + yield* stubBunWhichMiss;
385 + const apiBaseUrl = yield* startTestHttpServer((_req, res) => {
386 + res.writeHead(200, { 'content-type': 'application/json' });
387 + res.end(
388 + JSON.stringify([
389 + {
390 + tag_name: '@composio/cli@0.2.20-beta.1',
391 + draft: false,
392 + prerelease: true,
393 + assets: [
394 + {
395 + name: 'composio-skill.zip',
396 + browser_download_url: 'http://127.0.0.1/beta-1-skill.zip',
397 + },
398 + ],
399 + },
400 + {
401 + tag_name: '@composio/cli@0.2.20-beta.3',
402 + draft: false,
403 + prerelease: true,
404 + assets: [
405 + {
406 + name: 'composio-skill.zip',
407 + browser_download_url: 'http://127.0.0.1/beta-3-skill.zip',
408 + },
409 + ],
410 + },
411 + {
412 + tag_name: '@composio/cli@0.2.20',
413 + draft: false,
414 + prerelease: false,
415 + assets: [
416 + {
417 + name: 'composio-skill.zip',
418 + browser_download_url: 'http://127.0.0.1/stable-skill.zip',
419 + },
420 + ],
421 + },
422 + ])
423 + );
424 + });
425 +
426 + const tag = yield* makeResolveEffect(
427 + [
428 + ['GITHUB_API_BASE_URL', apiBaseUrl],
429 + ['GITHUB_OWNER', 'test-owner'],
430 + ['GITHUB_REPO', 'test-repo'],
431 + ],
432 + { channel: 'beta' }
433 );
365 - } finally {
366 - vi.unstubAllGlobals();
367 - vi.restoreAllMocks();
368 - }
369 - });
434 +
435 + expect(tag).toBe('@composio/cli@0.2.20-beta.3');
436 + })
437 + );
438 });
ts/packages/cli/test/src/models/project-keys.test.ts
+219 -184
@@ -1,196 +1,231 @@
1 -import { describe, it, expect } from 'vitest';
2 -import { Effect, Option } from 'effect';
1 +import { describe, it, expect } from '@effect/vitest';
2 +import { Effect, Option, ParseResult } from 'effect';
3 import { ProjectKeys, projectKeysFromJSON, projectKeysToJSON } from 'src/models/project-keys';
4
5 describe('ProjectKeys', () => {
6 describe('decode from JSON', () => {
7 - it('decodes valid JSON with required fields only', () => {
8 - const json = JSON.stringify({ org_id: 'abc', project_id: 'def' });
9 -
10 - const result = Effect.runSync(projectKeysFromJSON(json));
11 -
12 - expect(result.orgId).toBe('abc');
13 - expect(result.projectId).toBe('def');
14 - expect(Option.isNone(result.projectName)).toBe(true);
15 - expect(Option.isNone(result.orgName)).toBe(true);
16 - expect(Option.isNone(result.email)).toBe(true);
17 - expect(Option.isNone(result.testUserId)).toBe(true);
18 - });
19 -
20 - it('decodes valid JSON with all fields', () => {
21 - const json = JSON.stringify({
22 - org_id: 'abc',
23 - project_id: 'def',
24 - project_name: 'My Project',
25 - org_name: 'My Org',
26 - email: 'test@test.com',
27 - test_user_id: 'pg-test-user-123',
28 - });
29 -
30 - const result = Effect.runSync(projectKeysFromJSON(json));
31 -
32 - expect(result.orgId).toBe('abc');
33 - expect(result.projectId).toBe('def');
34 - expect(Option.getOrUndefined(result.projectName)).toBe('My Project');
35 - expect(Option.getOrUndefined(result.orgName)).toBe('My Org');
36 - expect(Option.getOrUndefined(result.email)).toBe('test@test.com');
37 - expect(Option.getOrUndefined(result.testUserId)).toBe('pg-test-user-123');
38 - });
39 -
40 - it('decodes null optional fields as Option.none()', () => {
41 - const json = JSON.stringify({
42 - org_id: 'abc',
43 - project_id: 'def',
44 - project_name: null,
45 - org_name: null,
46 - email: null,
47 - test_user_id: null,
48 - });
49 -
50 - const result = Effect.runSync(projectKeysFromJSON(json));
51 -
52 - expect(result.orgId).toBe('abc');
53 - expect(result.projectId).toBe('def');
54 - expect(Option.isNone(result.projectName)).toBe(true);
55 - expect(Option.isNone(result.orgName)).toBe(true);
56 - expect(Option.isNone(result.email)).toBe(true);
57 - expect(Option.isNone(result.testUserId)).toBe(true);
58 - });
59 -
60 - it('ignores extra keys in decoded JSON', () => {
61 - const json = JSON.stringify({
62 - org_id: 'abc',
63 - project_id: 'def',
64 - future_field: 'unknown',
65 - });
66 -
67 - // Should not throw -- onExcessProperty: 'ignore' silently drops extra keys
68 - const result = Effect.runSync(projectKeysFromJSON(json));
69 - expect(result.orgId).toBe('abc');
70 - expect(result.projectId).toBe('def');
71 - });
72 -
73 - it('fails on missing org_id', () => {
74 - const json = JSON.stringify({ project_id: 'def' });
75 - expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
76 - });
77 -
78 - it('fails on missing project_id', () => {
79 - const json = JSON.stringify({ org_id: 'abc' });
80 - expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
81 - });
82 -
83 - it('fails on non-string org_id', () => {
84 - const json = JSON.stringify({ org_id: 123, project_id: 'def' });
85 - expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
86 - });
87 -
88 - it('fails on non-string project_id', () => {
89 - const json = JSON.stringify({ org_id: 'abc', project_id: true });
90 - expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();
91 - });
92 -
93 - it('fails on invalid JSON', () => {
94 - expect(() => Effect.runSync(projectKeysFromJSON('not json'))).toThrow();
95 - });
96 -
97 - it('accepts empty strings for required fields', () => {
98 - const json = JSON.stringify({ org_id: '', project_id: '' });
99 - const result = Effect.runSync(projectKeysFromJSON(json));
100 - expect(result.orgId).toBe('');
101 - expect(result.projectId).toBe('');
102 - });
7 + it.effect('decodes valid JSON with required fields only', () =>
8 + Effect.gen(function* () {
9 + const json = JSON.stringify({ org_id: 'abc', project_id: 'def' });
10 +
11 + const result = yield* projectKeysFromJSON(json);
12 +
13 + expect(result.orgId).toBe('abc');
14 + expect(result.projectId).toBe('def');
15 + expect(Option.isNone(result.projectName)).toBe(true);
16 + expect(Option.isNone(result.orgName)).toBe(true);
17 + expect(Option.isNone(result.email)).toBe(true);
18 + expect(Option.isNone(result.testUserId)).toBe(true);
19 + })
20 + );
21 +
22 + it.effect('decodes valid JSON with all fields', () =>
23 + Effect.gen(function* () {
24 + const json = JSON.stringify({
25 + org_id: 'abc',
26 + project_id: 'def',
27 + project_name: 'My Project',
28 + org_name: 'My Org',
29 + email: 'test@test.com',
30 + test_user_id: 'pg-test-user-123',
31 + });
32 +
33 + const result = yield* projectKeysFromJSON(json);
34 +
35 + expect(result.orgId).toBe('abc');
36 + expect(result.projectId).toBe('def');
37 + expect(Option.getOrUndefined(result.projectName)).toBe('My Project');
38 + expect(Option.getOrUndefined(result.orgName)).toBe('My Org');
39 + expect(Option.getOrUndefined(result.email)).toBe('test@test.com');
40 + expect(Option.getOrUndefined(result.testUserId)).toBe('pg-test-user-123');
41 + })
42 + );
43 +
44 + it.effect('decodes null optional fields as Option.none()', () =>
45 + Effect.gen(function* () {
46 + const json = JSON.stringify({
47 + org_id: 'abc',
48 + project_id: 'def',
49 + project_name: null,
50 + org_name: null,
51 + email: null,
52 + test_user_id: null,
53 + });
54 +
55 + const result = yield* projectKeysFromJSON(json);
56 +
57 + expect(result.orgId).toBe('abc');
58 + expect(result.projectId).toBe('def');
59 + expect(Option.isNone(result.projectName)).toBe(true);
60 + expect(Option.isNone(result.orgName)).toBe(true);
61 + expect(Option.isNone(result.email)).toBe(true);
62 + expect(Option.isNone(result.testUserId)).toBe(true);
63 + })
64 + );
65 +
66 + it.effect('ignores extra keys in decoded JSON', () =>
67 + Effect.gen(function* () {
68 + const json = JSON.stringify({
69 + org_id: 'abc',
70 + project_id: 'def',
71 + future_field: 'unknown',
72 + });
73 +
74 + // Should not fail -- onExcessProperty: 'ignore' silently drops extra keys
75 + const result = yield* projectKeysFromJSON(json);
76 + expect(result.orgId).toBe('abc');
77 + expect(result.projectId).toBe('def');
78 + })
79 + );
80 +
81 + it.effect('fails on missing org_id', () =>
82 + Effect.gen(function* () {
83 + const json = JSON.stringify({ project_id: 'def' });
84 + const error = yield* Effect.flip(projectKeysFromJSON(json));
85 + expect(error).toBeInstanceOf(ParseResult.ParseError);
86 + })
87 + );
88 +
89 + it.effect('fails on missing project_id', () =>
90 + Effect.gen(function* () {
91 + const json = JSON.stringify({ org_id: 'abc' });
92 + const error = yield* Effect.flip(projectKeysFromJSON(json));
93 + expect(error).toBeInstanceOf(ParseResult.ParseError);
94 + })
95 + );
96 +
97 + it.effect('fails on non-string org_id', () =>
98 + Effect.gen(function* () {
99 + const json = JSON.stringify({ org_id: 123, project_id: 'def' });
100 + const error = yield* Effect.flip(projectKeysFromJSON(json));
101 + expect(error).toBeInstanceOf(ParseResult.ParseError);
102 + })
103 + );
104 +
105 + it.effect('fails on non-string project_id', () =>
106 + Effect.gen(function* () {
107 + const json = JSON.stringify({ org_id: 'abc', project_id: true });
108 + const error = yield* Effect.flip(projectKeysFromJSON(json));
109 + expect(error).toBeInstanceOf(ParseResult.ParseError);
110 + })
111 + );
112 +
113 + it.effect('fails on invalid JSON', () =>
114 + Effect.gen(function* () {
115 + const error = yield* Effect.flip(projectKeysFromJSON('not json'));
116 + expect(error).toBeInstanceOf(ParseResult.ParseError);
117 + })
118 + );
119 +
120 + it.effect('accepts empty strings for required fields', () =>
121 + Effect.gen(function* () {
122 + const json = JSON.stringify({ org_id: '', project_id: '' });
123 + const result = yield* projectKeysFromJSON(json);
124 + expect(result.orgId).toBe('');
125 + expect(result.projectId).toBe('');
126 + })
127 + );
128 });
129
130 describe('encode to JSON', () => {
106 - it('encodes ProjectKeys with Some values', () => {
107 - const keys: ProjectKeys = {
108 - orgId: 'abc',
109 - projectId: 'def',
110 - projectName: Option.some('My Project'),
111 - orgName: Option.some('My Org'),
112 - email: Option.some('test@test.com'),
113 - testUserId: Option.some('pg-test-user-123'),
114 - };
115 -
116 - const json = Effect.runSync(projectKeysToJSON(keys));
117 - const parsed = JSON.parse(json);
118 -
119 - expect(parsed.org_id).toBe('abc');
120 - expect(parsed.project_id).toBe('def');
121 - expect(parsed.project_name).toBe('My Project');
122 - expect(parsed.org_name).toBe('My Org');
123 - expect(parsed.email).toBe('test@test.com');
124 - expect(parsed.test_user_id).toBe('pg-test-user-123');
125 - });
126 -
127 - it('encodes None optional fields as null', () => {
128 - const keys: ProjectKeys = {
129 - orgId: 'abc',
130 - projectId: 'def',
131 - projectName: Option.none(),
132 - orgName: Option.none(),
133 - email: Option.none(),
134 - testUserId: Option.none(),
135 - };
136 -
137 - const json = Effect.runSync(projectKeysToJSON(keys));
138 - const parsed = JSON.parse(json);
139 -
140 - expect(parsed.org_id).toBe('abc');
141 - expect(parsed.project_id).toBe('def');
142 - expect(parsed.project_name).toBeNull();
143 - expect(parsed.org_name).toBeNull();
144 - expect(parsed.email).toBeNull();
145 - expect(parsed.test_user_id).toBeNull();
146 - });
131 + it.effect('encodes ProjectKeys with Some values', () =>
132 + Effect.gen(function* () {
133 + const keys: ProjectKeys = {
134 + orgId: 'abc',
135 + projectId: 'def',
136 + projectName: Option.some('My Project'),
137 + orgName: Option.some('My Org'),
138 + email: Option.some('test@test.com'),
139 + testUserId: Option.some('pg-test-user-123'),
140 + };
141 +
142 + const json = yield* projectKeysToJSON(keys);
143 + const parsed = JSON.parse(json);
144 +
145 + expect(parsed.org_id).toBe('abc');
146 + expect(parsed.project_id).toBe('def');
147 + expect(parsed.project_name).toBe('My Project');
148 + expect(parsed.org_name).toBe('My Org');
149 + expect(parsed.email).toBe('test@test.com');
150 + expect(parsed.test_user_id).toBe('pg-test-user-123');
151 + })
152 + );
153 +
154 + it.effect('encodes None optional fields as null', () =>
155 + Effect.gen(function* () {
156 + const keys: ProjectKeys = {
157 + orgId: 'abc',
158 + projectId: 'def',
159 + projectName: Option.none(),
160 + orgName: Option.none(),
161 + email: Option.none(),
162 + testUserId: Option.none(),
163 + };
164 +
165 + const json = yield* projectKeysToJSON(keys);
166 + const parsed = JSON.parse(json);
167 +
168 + expect(parsed.org_id).toBe('abc');
169 + expect(parsed.project_id).toBe('def');
170 + expect(parsed.project_name).toBeNull();
171 + expect(parsed.org_name).toBeNull();
172 + expect(parsed.email).toBeNull();
173 + expect(parsed.test_user_id).toBeNull();
174 + })
175 + );
176 });
177
178 describe('round-trip', () => {
150 - it('encode then decode preserves Some values', () => {
151 - const original: ProjectKeys = {
152 - orgId: 'org-123',
153 - projectId: 'proj-456',
154 - projectName: Option.some('Test Project'),
155 - orgName: Option.some('Test Org'),
156 - email: Option.some('user@example.com'),
157 - testUserId: Option.some('pg-test-user-123'),
158 - };
159 -
160 - const json = Effect.runSync(projectKeysToJSON(original));
161 - const decoded = Effect.runSync(projectKeysFromJSON(json));
162 -
163 - expect(decoded.orgId).toBe(original.orgId);
164 - expect(decoded.projectId).toBe(original.projectId);
165 - expect(Option.getOrUndefined(decoded.projectName)).toBe(
166 - Option.getOrUndefined(original.projectName)
167 - );
168 - expect(Option.getOrUndefined(decoded.orgName)).toBe(Option.getOrUndefined(original.orgName));
169 - expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));
170 - expect(Option.getOrUndefined(decoded.testUserId)).toBe(
171 - Option.getOrUndefined(original.testUserId)
172 - );
173 - });
174 -
175 - it('encode then decode preserves None values', () => {
176 - const original: ProjectKeys = {
177 - orgId: 'org-123',
178 - projectId: 'proj-456',
179 - projectName: Option.none(),
180 - orgName: Option.none(),
181 - email: Option.none(),
182 - testUserId: Option.none(),
183 - };
184 -
185 - const json = Effect.runSync(projectKeysToJSON(original));
186 - const decoded = Effect.runSync(projectKeysFromJSON(json));
187 -
188 - expect(decoded.orgId).toBe(original.orgId);
189 - expect(decoded.projectId).toBe(original.projectId);
190 - expect(Option.isNone(decoded.projectName)).toBe(true);
191 - expect(Option.isNone(decoded.orgName)).toBe(true);
192 - expect(Option.isNone(decoded.email)).toBe(true);
193 - expect(Option.isNone(decoded.testUserId)).toBe(true);
194 - });
179 + it.effect('encode then decode preserves Some values', () =>
180 + Effect.gen(function* () {
181 + const original: ProjectKeys = {
182 + orgId: 'org-123',
183 + projectId: 'proj-456',
184 + projectName: Option.some('Test Project'),
185 + orgName: Option.some('Test Org'),
186 + email: Option.some('user@example.com'),
187 + testUserId: Option.some('pg-test-user-123'),
188 + };
189 +
190 + const json = yield* projectKeysToJSON(original);
191 + const decoded = yield* projectKeysFromJSON(json);
192 +
193 + expect(decoded.orgId).toBe(original.orgId);
194 + expect(decoded.projectId).toBe(original.projectId);
195 + expect(Option.getOrUndefined(decoded.projectName)).toBe(
196 + Option.getOrUndefined(original.projectName)
197 + );
198 + expect(Option.getOrUndefined(decoded.orgName)).toBe(
199 + Option.getOrUndefined(original.orgName)
200 + );
201 + expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));
202 + expect(Option.getOrUndefined(decoded.testUserId)).toBe(
203 + Option.getOrUndefined(original.testUserId)
204 + );
205 + })
206 + );
207 +
208 + it.effect('encode then decode preserves None values', () =>
209 + Effect.gen(function* () {
210 + const original: ProjectKeys = {
211 + orgId: 'org-123',
212 + projectId: 'proj-456',
213 + projectName: Option.none(),
214 + orgName: Option.none(),
215 + email: Option.none(),
216 + testUserId: Option.none(),
217 + };
218 +
219 + const json = yield* projectKeysToJSON(original);
220 + const decoded = yield* projectKeysFromJSON(json);
221 +
222 + expect(decoded.orgId).toBe(original.orgId);
223 + expect(decoded.projectId).toBe(original.projectId);
224 + expect(Option.isNone(decoded.projectName)).toBe(true);
225 + expect(Option.isNone(decoded.orgName)).toBe(true);
226 + expect(Option.isNone(decoded.email)).toBe(true);
227 + expect(Option.isNone(decoded.testUserId)).toBe(true);
228 + })
229 + );
230 });
231 });
ts/packages/cli/test/src/services/composio-clients.test.ts
+40 -33
@@ -1,4 +1,5 @@
1 -import { afterEach, describe, expect, it, vi } from 'vitest';
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { afterEach, vi } from 'vitest';
3 import { Effect } from 'effect';
4 import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
5
@@ -15,36 +16,42 @@ describe('getSessionInfoByUserApiKey org context', () => {
16
17 // The response body does not satisfy SessionInfoResponse, so decoding fails —
18 // but the fetch call (whose headers we assert) has already happened by then.
18 - const runIgnoringDecode = (params: { baseURL: string; userApiKey: string; orgId?: string }) =>
19 - Effect.runPromise(getSessionInfoByUserApiKey(params).pipe(Effect.ignore));
20 -
21 - it('[Given] orgId [Then] forwards it as x-org-id so the backend honors the switched org', async () => {
22 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());
23 -
24 - await runIgnoringDecode({
25 - baseURL: 'https://backend.composio.dev',
26 - userApiKey: 'uak_test',
27 - orgId: 'ok_selected_org',
28 - });
29 -
30 - const [url, init] = fetchSpy.mock.calls[0]!;
31 - expect(String(url)).toContain('/api/v3/auth/session/info');
32 - const headers = new Headers((init as RequestInit).headers);
33 - expect(headers.get('x-user-api-key')).toBe('uak_test');
34 - expect(headers.get('x-org-id')).toBe('ok_selected_org');
35 - });
36 -
37 - it('[Given] no orgId [Then] omits x-org-id (login-time behavior is unchanged)', async () => {
38 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());
39 -
40 - await runIgnoringDecode({
41 - baseURL: 'https://backend.composio.dev',
42 - userApiKey: 'uak_test',
43 - });
44 -
45 - const [, init] = fetchSpy.mock.calls[0]!;
46 - const headers = new Headers((init as RequestInit).headers);
47 - expect(headers.get('x-user-api-key')).toBe('uak_test');
48 - expect(headers.has('x-org-id')).toBe(false);
49 - });
19 + const callIgnoringDecode = (params: { baseURL: string; userApiKey: string; orgId?: string }) =>
20 + getSessionInfoByUserApiKey(params).pipe(Effect.ignore);
21 +
22 + it.effect(
23 + '[Given] orgId [Then] forwards it as x-org-id so the backend honors the switched org',
24 + () =>
25 + Effect.gen(function* () {
26 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());
27 +
28 + yield* callIgnoringDecode({
29 + baseURL: 'https://backend.composio.dev',
30 + userApiKey: 'uak_test',
31 + orgId: 'ok_selected_org',
32 + });
33 +
34 + const [url, init] = fetchSpy.mock.calls[0]!;
35 + expect(String(url)).toContain('/api/v3/auth/session/info');
36 + const headers = new Headers((init as RequestInit).headers);
37 + expect(headers.get('x-user-api-key')).toBe('uak_test');
38 + expect(headers.get('x-org-id')).toBe('ok_selected_org');
39 + })
40 + );
41 +
42 + it.effect('[Given] no orgId [Then] omits x-org-id (login-time behavior is unchanged)', () =>
43 + Effect.gen(function* () {
44 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());
45 +
46 + yield* callIgnoringDecode({
47 + baseURL: 'https://backend.composio.dev',
48 + userApiKey: 'uak_test',
49 + });
50 +
51 + const [, init] = fetchSpy.mock.calls[0]!;
52 + const headers = new Headers((init as RequestInit).headers);
53 + expect(headers.get('x-user-api-key')).toBe('uak_test');
54 + expect(headers.has('x-org-id')).toBe(false);
55 + })
56 + );
57 });
ts/packages/cli/test/src/services/config.test.ts
+569 -506
@@ -1,4 +1,4 @@
1 -import { describe, it, vi } from '@effect/vitest';
1 +import { beforeEach, describe, it, vi } from '@effect/vitest';
2 import { assertEquals } from '@effect/vitest/utils';
3
4 import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';
@@ -13,314 +13,340 @@ describe('Config', () => {
13 Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)));
14
15 describe('APP_CONFIG', () => {
16 - it('[When] no map entry is set', () => {
17 - const map = new Map([]) satisfies Map<string, string>;
18 -
19 - const actual = Effect.runSync(
20 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
21 - );
22 -
23 - assertEquals(
24 - actual,
25 - Data.struct({
26 - USER_API_KEY: Option.none(),
27 - ENVIRONMENT: Option.none(),
28 - BASE_URL: 'https://backend.composio.dev',
29 - CACHE_DIR: Option.none(),
30 - LOG_LEVEL: Option.none(),
31 - ORG_ID: Option.none(),
32 - PROJECT_ID: Option.none(),
33 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
34 - WEB_URL: 'https://dashboard.composio.dev/',
16 + it.effect('[When] no map entry is set', () =>
17 + Effect.gen(function* () {
18 + const map = new Map([]) satisfies Map<string, string>;
19 +
20 + const actual = yield* withMapConfigProvider(map)(
21 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
22 + );
23 +
24 + assertEquals(
25 + actual,
26 + Data.struct({
27 + USER_API_KEY: Option.none(),
28 + ENVIRONMENT: Option.none(),
29 + BASE_URL: 'https://backend.composio.dev',
30 + CACHE_DIR: Option.none(),
31 + LOG_LEVEL: Option.none(),
32 + ORG_ID: Option.none(),
33 + PROJECT_ID: Option.none(),
34 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
35 + WEB_URL: 'https://dashboard.composio.dev/',
36 + })
37 + );
38 + })
39 + );
40 +
41 + it.effect('[When] map entries are set without `COMPOSIO_` prefix', () =>
42 + Effect.gen(function* () {
43 + const map = new Map([
44 + ['USER_API_KEY', 'api_key'],
45 + ['BASE_URL', 'https://test.localhost'],
46 + ['CACHE_DIR', '~/.composio'],
47 + ['LOG_LEVEL', 'info'],
48 + ]) satisfies Map<string, string>;
49 +
50 + const actual = yield* withMapConfigProvider(map)(
51 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
52 + );
53 +
54 + assertEquals(
55 + actual,
56 + Data.struct({
57 + USER_API_KEY: Option.none(),
58 + ENVIRONMENT: Option.none(),
59 + BASE_URL: 'https://backend.composio.dev',
60 + CACHE_DIR: Option.none(),
61 + LOG_LEVEL: Option.none(),
62 + ORG_ID: Option.none(),
63 + PROJECT_ID: Option.none(),
64 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
65 + WEB_URL: 'https://dashboard.composio.dev/',
66 + })
67 + );
68 + })
69 + );
70 +
71 + it.effect('[When] env variables are set with `COMPOSIO_` prefix', () =>
72 + Effect.gen(function* () {
73 + const map = new Map([
74 + ['COMPOSIO_USER_API_KEY', 'api_key'],
75 + ['COMPOSIO_BASE_URL', 'https://test.localhost'],
76 + ['COMPOSIO_WEB_URL', 'https://test.localhost'],
77 + ['COMPOSIO_CACHE_DIR', '~/.composio'],
78 + ['COMPOSIO_LOG_LEVEL', 'info'],
79 + ]) satisfies Map<string, string>;
80 +
81 + const actual = yield* withMapConfigProvider(map)(
82 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
83 + );
84 +
85 + assertEquals(
86 + actual,
87 + Data.struct({
88 + USER_API_KEY: Option.some('api_key'),
89 + ENVIRONMENT: Option.none(),
90 + BASE_URL: 'https://test.localhost',
91 + WEB_URL: 'https://test.localhost',
92 + CACHE_DIR: Option.some('~/.composio'),
93 + LOG_LEVEL: Option.some(LogLevel.Info),
94 + ORG_ID: Option.none(),
95 + PROJECT_ID: Option.none(),
96 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
97 + })
98 + );
99 + })
100 + );
101 +
102 + it.effect('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () =>
103 + Effect.gen(function* () {
104 + const map = new Map([
105 + ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false'],
106 + ]) satisfies Map<string, string>;
107 +
108 + const actual = yield* withMapConfigProvider(map)(
109 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
110 + );
111 +
112 + assertEquals(
113 + actual,
114 + Data.struct({
115 + USER_API_KEY: Option.none(),
116 + ENVIRONMENT: Option.none(),
117 + BASE_URL: 'https://backend.composio.dev',
118 + WEB_URL: 'https://dashboard.composio.dev/',
119 + CACHE_DIR: Option.none(),
120 + LOG_LEVEL: Option.none(),
121 + ORG_ID: Option.none(),
122 + PROJECT_ID: Option.none(),
123 + DISABLE_CONNECTED_ACCOUNT_CACHE: false,
124 + })
125 + );
126 + })
127 + );
128 +
129 + it.effect('[When] COMPOSIO_ENVIRONMENT is "production"', () =>
130 + Effect.gen(function* () {
131 + const map = new Map([['COMPOSIO_ENVIRONMENT', 'production']]) satisfies Map<
132 + string,
133 + string
134 + >;
135 +
136 + const actual = yield* withMapConfigProvider(map)(
137 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
138 + );
139 +
140 + assertEquals(
141 + actual,
142 + Data.struct({
143 + USER_API_KEY: Option.none(),
144 + ENVIRONMENT: Option.some('production'),
145 + BASE_URL: constants.DEFAULT_BASE_URL,
146 + WEB_URL: constants.DEFAULT_WEB_URL,
147 + CACHE_DIR: Option.none(),
148 + LOG_LEVEL: Option.none(),
149 + ORG_ID: Option.none(),
150 + PROJECT_ID: Option.none(),
151 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
152 + })
153 + );
154 + })
155 + );
156 +
157 + it.effect('[When] COMPOSIO_ENVIRONMENT is "staging"', () =>
158 + Effect.gen(function* () {
159 + const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;
160 +
161 + const actual = yield* withMapConfigProvider(map)(
162 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
163 + );
164 +
165 + assertEquals(
166 + actual,
167 + Data.struct({
168 + USER_API_KEY: Option.none(),
169 + ENVIRONMENT: Option.some('staging'),
170 + BASE_URL: constants.STAGING_BASE_URL,
171 + WEB_URL: constants.STAGING_WEB_URL,
172 + CACHE_DIR: Option.none(),
173 + LOG_LEVEL: Option.none(),
174 + ORG_ID: Option.none(),
175 + PROJECT_ID: Option.none(),
176 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
177 + })
178 + );
179 + })
180 + );
181 +
182 + it.effect(
183 + '[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_BASE_URL is set',
184 + () =>
185 + Effect.gen(function* () {
186 + const map = new Map([
187 + ['COMPOSIO_ENVIRONMENT', 'staging'],
188 + ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],
189 + ]) satisfies Map<string, string>;
190 +
191 + const actual = yield* withMapConfigProvider(map)(
192 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
193 + );
194 +
195 + assertEquals(
196 + actual,
197 + Data.struct({
198 + USER_API_KEY: Option.none(),
199 + ENVIRONMENT: Option.some('staging'),
200 + BASE_URL: 'https://custom-backend.localhost',
201 + WEB_URL: constants.STAGING_WEB_URL,
202 + CACHE_DIR: Option.none(),
203 + LOG_LEVEL: Option.none(),
204 + ORG_ID: Option.none(),
205 + PROJECT_ID: Option.none(),
206 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
207 + })
208 + );
209 })
36 - );
37 - });
38 -
39 - it('[When] map entries are set without `COMPOSIO_` prefix', () => {
40 - const map = new Map([
41 - ['USER_API_KEY', 'api_key'],
42 - ['BASE_URL', 'https://test.localhost'],
43 - ['CACHE_DIR', '~/.composio'],
44 - ['LOG_LEVEL', 'info'],
45 - ]) satisfies Map<string, string>;
46 -
47 - const actual = Effect.runSync(
48 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
49 - );
50 -
51 - assertEquals(
52 - actual,
53 - Data.struct({
54 - USER_API_KEY: Option.none(),
55 - ENVIRONMENT: Option.none(),
56 - BASE_URL: 'https://backend.composio.dev',
57 - CACHE_DIR: Option.none(),
58 - LOG_LEVEL: Option.none(),
59 - ORG_ID: Option.none(),
60 - PROJECT_ID: Option.none(),
61 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
62 - WEB_URL: 'https://dashboard.composio.dev/',
210 + );
211 +
212 + it.effect(
213 + '[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_WEB_URL is set',
214 + () =>
215 + Effect.gen(function* () {
216 + const map = new Map([
217 + ['COMPOSIO_ENVIRONMENT', 'staging'],
218 + ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],
219 + ]) satisfies Map<string, string>;
220 +
221 + const actual = yield* withMapConfigProvider(map)(
222 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
223 + );
224 +
225 + assertEquals(
226 + actual,
227 + Data.struct({
228 + USER_API_KEY: Option.none(),
229 + ENVIRONMENT: Option.some('staging'),
230 + BASE_URL: constants.STAGING_BASE_URL,
231 + WEB_URL: 'https://custom-web.localhost',
232 + CACHE_DIR: Option.none(),
233 + LOG_LEVEL: Option.none(),
234 + ORG_ID: Option.none(),
235 + PROJECT_ID: Option.none(),
236 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
237 + })
238 + );
239 })
64 - );
65 - });
66 -
67 - it('[When] env variables are set with `COMPOSIO_` prefix', () => {
68 - const map = new Map([
69 - ['COMPOSIO_USER_API_KEY', 'api_key'],
70 - ['COMPOSIO_BASE_URL', 'https://test.localhost'],
71 - ['COMPOSIO_WEB_URL', 'https://test.localhost'],
72 - ['COMPOSIO_CACHE_DIR', '~/.composio'],
73 - ['COMPOSIO_LOG_LEVEL', 'info'],
74 - ]) satisfies Map<string, string>;
75 -
76 - const actual = Effect.runSync(
77 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
78 - );
79 -
80 - assertEquals(
81 - actual,
82 - Data.struct({
83 - USER_API_KEY: Option.some('api_key'),
84 - ENVIRONMENT: Option.none(),
85 - BASE_URL: 'https://test.localhost',
86 - WEB_URL: 'https://test.localhost',
87 - CACHE_DIR: Option.some('~/.composio'),
88 - LOG_LEVEL: Option.some(LogLevel.Info),
89 - ORG_ID: Option.none(),
90 - PROJECT_ID: Option.none(),
91 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
92 - })
93 - );
94 - });
95 -
96 - it('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () => {
97 - const map = new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']]) satisfies Map<
98 - string,
99 - string
100 - >;
101 -
102 - const actual = Effect.runSync(
103 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
104 - );
105 -
106 - assertEquals(
107 - actual,
108 - Data.struct({
109 - USER_API_KEY: Option.none(),
110 - ENVIRONMENT: Option.none(),
111 - BASE_URL: 'https://backend.composio.dev',
112 - WEB_URL: 'https://dashboard.composio.dev/',
113 - CACHE_DIR: Option.none(),
114 - LOG_LEVEL: Option.none(),
115 - ORG_ID: Option.none(),
116 - PROJECT_ID: Option.none(),
117 - DISABLE_CONNECTED_ACCOUNT_CACHE: false,
118 - })
119 - );
120 - });
121 -
122 - it('[When] COMPOSIO_ENVIRONMENT is "production"', () => {
123 - const map = new Map([['COMPOSIO_ENVIRONMENT', 'production']]) satisfies Map<string, string>;
124 -
125 - const actual = Effect.runSync(
126 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
127 - );
128 -
129 - assertEquals(
130 - actual,
131 - Data.struct({
132 - USER_API_KEY: Option.none(),
133 - ENVIRONMENT: Option.some('production'),
134 - BASE_URL: constants.DEFAULT_BASE_URL,
135 - WEB_URL: constants.DEFAULT_WEB_URL,
136 - CACHE_DIR: Option.none(),
137 - LOG_LEVEL: Option.none(),
138 - ORG_ID: Option.none(),
139 - PROJECT_ID: Option.none(),
140 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
141 - })
142 - );
143 - });
144 -
145 - it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {
146 - const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;
147 -
148 - const actual = Effect.runSync(
149 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
150 - );
151 -
152 - assertEquals(
153 - actual,
154 - Data.struct({
155 - USER_API_KEY: Option.none(),
156 - ENVIRONMENT: Option.some('staging'),
157 - BASE_URL: constants.STAGING_BASE_URL,
158 - WEB_URL: constants.STAGING_WEB_URL,
159 - CACHE_DIR: Option.none(),
160 - LOG_LEVEL: Option.none(),
161 - ORG_ID: Option.none(),
162 - PROJECT_ID: Option.none(),
163 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
164 - })
165 - );
166 - });
167 -
168 - it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_BASE_URL is set', () => {
169 - const map = new Map([
170 - ['COMPOSIO_ENVIRONMENT', 'staging'],
171 - ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],
172 - ]) satisfies Map<string, string>;
173 -
174 - const actual = Effect.runSync(
175 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
176 - );
177 -
178 - assertEquals(
179 - actual,
180 - Data.struct({
181 - USER_API_KEY: Option.none(),
182 - ENVIRONMENT: Option.some('staging'),
183 - BASE_URL: 'https://custom-backend.localhost',
184 - WEB_URL: constants.STAGING_WEB_URL,
185 - CACHE_DIR: Option.none(),
186 - LOG_LEVEL: Option.none(),
187 - ORG_ID: Option.none(),
188 - PROJECT_ID: Option.none(),
189 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
190 - })
191 - );
192 - });
193 -
194 - it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_WEB_URL is set', () => {
195 - const map = new Map([
196 - ['COMPOSIO_ENVIRONMENT', 'staging'],
197 - ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],
198 - ]) satisfies Map<string, string>;
199 -
200 - const actual = Effect.runSync(
201 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
202 - );
203 -
204 - assertEquals(
205 - actual,
206 - Data.struct({
207 - USER_API_KEY: Option.none(),
208 - ENVIRONMENT: Option.some('staging'),
209 - BASE_URL: constants.STAGING_BASE_URL,
210 - WEB_URL: 'https://custom-web.localhost',
211 - CACHE_DIR: Option.none(),
212 - LOG_LEVEL: Option.none(),
213 - ORG_ID: Option.none(),
214 - PROJECT_ID: Option.none(),
215 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
216 - })
217 - );
218 - });
219 -
220 - it('[When] COMPOSIO_ENVIRONMENT is an unknown value', () => {
221 - const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;
222 -
223 - const actual = Effect.runSync(
224 - withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
225 - );
226 -
227 - assertEquals(
228 - actual,
229 - Data.struct({
230 - USER_API_KEY: Option.none(),
231 - ENVIRONMENT: Option.some('unknown'),
232 - BASE_URL: constants.DEFAULT_BASE_URL,
233 - WEB_URL: constants.DEFAULT_WEB_URL,
234 - CACHE_DIR: Option.none(),
235 - LOG_LEVEL: Option.none(),
236 - ORG_ID: Option.none(),
237 - PROJECT_ID: Option.none(),
238 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
239 - })
240 - );
241 - });
240 + );
241 +
242 + it.effect('[When] COMPOSIO_ENVIRONMENT is an unknown value', () =>
243 + Effect.gen(function* () {
244 + const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;
245 +
246 + const actual = yield* withMapConfigProvider(map)(
247 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
248 + );
249 +
250 + assertEquals(
251 + actual,
252 + Data.struct({
253 + USER_API_KEY: Option.none(),
254 + ENVIRONMENT: Option.some('unknown'),
255 + BASE_URL: constants.DEFAULT_BASE_URL,
256 + WEB_URL: constants.DEFAULT_WEB_URL,
257 + CACHE_DIR: Option.none(),
258 + LOG_LEVEL: Option.none(),
259 + ORG_ID: Option.none(),
260 + PROJECT_ID: Option.none(),
261 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
262 + })
263 + );
264 + })
265 + );
266 });
267
268 describe('DEBUG_OVERRIDE_CONFIG', () => {
245 - it('[When] no map entries variable is set', () => {
246 - const map = new Map([]) satisfies Map<string, string>;
247 -
248 - const actual = Effect.runSync(
249 - withMapConfigProvider(map)(
250 - Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
251 - )
252 - );
253 -
254 - assertEquals(
255 - actual,
256 - Data.struct({
257 - UPGRADE_TARGET: Option.none(),
258 - VERSION: Option.none(),
259 - })
260 - );
261 - });
269 + it.effect('[When] no map entries variable is set', () =>
270 + Effect.gen(function* () {
271 + const map = new Map([]) satisfies Map<string, string>;
272
263 - it('[When] map entries are set without `DEBUG_OVERRIDE_` prefix', () => {
264 - const map = new Map([
265 - ['UPGRADE_TARGET', 'upgrade_target'],
266 - ['VERSION', 'x.x.x'],
267 - ]) satisfies Map<string, string>;
268 -
269 - const actual = Effect.runSync(
270 - withMapConfigProvider(map)(
273 + const actual = yield* withMapConfigProvider(map)(
274 Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
272 - )
273 - );
274 -
275 - assertEquals(
276 - actual,
277 - Data.struct({
278 - UPGRADE_TARGET: Option.none(),
279 - VERSION: Option.none(),
280 - })
281 - );
282 - });
283 -
284 - it('[When] map entries are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix', () => {
285 - const map = new Map([
286 - ['COMPOSIO_UPGRADE_TARGET', 'upgrade_target'],
287 - ['COMPOSIO_VERSION', 'x.x.x'],
288 - ]) satisfies Map<string, string>;
289 -
290 - const actual = Effect.runSync(
291 - withMapConfigProvider(map)(
275 + );
276 +
277 + assertEquals(
278 + actual,
279 + Data.struct({
280 + UPGRADE_TARGET: Option.none(),
281 + VERSION: Option.none(),
282 + })
283 + );
284 + })
285 + );
286 +
287 + it.effect('[When] map entries are set without `DEBUG_OVERRIDE_` prefix', () =>
288 + Effect.gen(function* () {
289 + const map = new Map([
290 + ['UPGRADE_TARGET', 'upgrade_target'],
291 + ['VERSION', 'x.x.x'],
292 + ]) satisfies Map<string, string>;
293 +
294 + const actual = yield* withMapConfigProvider(map)(
295 Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
293 - )
294 - );
295 -
296 - assertEquals(
297 - actual,
298 - Data.struct({
299 - UPGRADE_TARGET: Option.none(),
300 - VERSION: Option.none(),
296 + );
297 +
298 + assertEquals(
299 + actual,
300 + Data.struct({
301 + UPGRADE_TARGET: Option.none(),
302 + VERSION: Option.none(),
303 + })
304 + );
305 + })
306 + );
307 +
308 + it.effect(
309 + '[When] map entries are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix',
310 + () =>
311 + Effect.gen(function* () {
312 + const map = new Map([
313 + ['COMPOSIO_UPGRADE_TARGET', 'upgrade_target'],
314 + ['COMPOSIO_VERSION', 'x.x.x'],
315 + ]) satisfies Map<string, string>;
316 +
317 + const actual = yield* withMapConfigProvider(map)(
318 + Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
319 + );
320 +
321 + assertEquals(
322 + actual,
323 + Data.struct({
324 + UPGRADE_TARGET: Option.none(),
325 + VERSION: Option.none(),
326 + })
327 + );
328 })
302 - );
303 - });
304 - it('[When] map entries are set with `DEBUG_OVERRIDE_` prefix', () => {
305 - const map = new Map([
306 - ['DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target'],
307 - ['DEBUG_OVERRIDE_VERSION', 'x.x.x'],
308 - ]) satisfies Map<string, string>;
309 -
310 - const actual = Effect.runSync(
311 - withMapConfigProvider(map)(
329 + );
330 + it.effect('[When] map entries are set with `DEBUG_OVERRIDE_` prefix', () =>
331 + Effect.gen(function* () {
332 + const map = new Map([
333 + ['DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target'],
334 + ['DEBUG_OVERRIDE_VERSION', 'x.x.x'],
335 + ]) satisfies Map<string, string>;
336 +
337 + const actual = yield* withMapConfigProvider(map)(
338 Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
313 - )
314 - );
315 -
316 - assertEquals(
317 - actual,
318 - Data.struct({
319 - UPGRADE_TARGET: Option.some('upgrade_target'),
320 - VERSION: Option.some('x.x.x'),
321 - })
322 - );
323 - });
339 + );
340 +
341 + assertEquals(
342 + actual,
343 + Data.struct({
344 + UPGRADE_TARGET: Option.some('upgrade_target'),
345 + VERSION: Option.some('x.x.x'),
346 + })
347 + );
348 + })
349 + );
350 });
351 });
352
@@ -329,218 +355,255 @@ describe('Config', () => {
355 extendConfigProvider(ConfigProvider.fromEnv())
356 );
357
358 + // These cases assert what the config resolves from a clean environment,
359 + // but the developer's shell (direnv) and the shared vitest setup both
360 + // export COMPOSIO_* variables. Neutralize every APP_CONFIG input.
361 + beforeEach(() => {
362 + vi.stubEnv('COMPOSIO_USER_API_KEY', undefined);
363 + vi.stubEnv('COMPOSIO_ENVIRONMENT', undefined);
364 + vi.stubEnv('COMPOSIO_BASE_URL', undefined);
365 + vi.stubEnv('COMPOSIO_WEB_URL', undefined);
366 + vi.stubEnv('COMPOSIO_CACHE_DIR', undefined);
367 + vi.stubEnv('COMPOSIO_LOG_LEVEL', undefined);
368 + vi.stubEnv('COMPOSIO_ORG_ID', undefined);
369 + vi.stubEnv('COMPOSIO_PROJECT_ID', undefined);
370 + vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', undefined);
371 + });
372 +
373 describe('APP_CONFIG', () => {
333 - it('[When] no env variable is set', () => {
334 - const actual = Effect.runSync(
335 - withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
336 - );
337 -
338 - assertEquals(
339 - actual,
340 - Data.struct({
341 - USER_API_KEY: Option.none(),
342 - ENVIRONMENT: Option.none(),
343 - BASE_URL: 'https://backend.composio.dev',
344 - WEB_URL: 'https://dashboard.composio.dev/',
345 - CACHE_DIR: Option.none(),
346 - LOG_LEVEL: Option.none(),
347 - ORG_ID: Option.none(),
348 - PROJECT_ID: Option.none(),
349 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
350 - })
351 - );
352 - });
353 -
354 - it('[When] env variables are set without `COMPOSIO_` prefix', () => {
355 - vi.stubEnv('USER_API_KEY', 'api_key');
356 - vi.stubEnv('BASE_URL', 'https://test.localhost');
357 - vi.stubEnv('CACHE_DIR', '~/.composio');
358 - vi.stubEnv('LOG_LEVEL', 'info');
359 -
360 - const actual = Effect.runSync(
361 - withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
362 - );
363 -
364 - assertEquals(
365 - actual,
366 - Data.struct({
367 - USER_API_KEY: Option.none(),
368 - ENVIRONMENT: Option.none(),
369 - BASE_URL: 'https://backend.composio.dev',
370 - WEB_URL: 'https://dashboard.composio.dev/',
371 - CACHE_DIR: Option.none(),
372 - LOG_LEVEL: Option.none(),
373 - ORG_ID: Option.none(),
374 - PROJECT_ID: Option.none(),
375 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
376 - })
377 - );
378 - });
379 -
380 - it('[When] env variables are set with `COMPOSIO_` prefix', () => {
381 - vi.stubEnv('COMPOSIO_USER_API_KEY', 'api_key');
382 - vi.stubEnv('COMPOSIO_BASE_URL', 'https://test.localhost');
383 - vi.stubEnv('COMPOSIO_WEB_URL', 'https://test.localhost');
384 - vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');
385 - vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');
386 -
387 - const actual = Effect.runSync(
388 - withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
389 - );
390 -
391 - assertEquals(
392 - actual,
393 - Data.struct({
394 - USER_API_KEY: Option.some('api_key'),
395 - ENVIRONMENT: Option.none(),
396 - BASE_URL: 'https://test.localhost',
397 - WEB_URL: 'https://test.localhost',
398 - CACHE_DIR: Option.some('~/.composio'),
399 - LOG_LEVEL: Option.some(LogLevel.Info),
400 - ORG_ID: Option.none(),
401 - PROJECT_ID: Option.none(),
402 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
403 - })
404 - );
405 - });
406 -
407 - it('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () => {
408 - vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false');
409 -
410 - const actual = Effect.runSync(
411 - withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
412 - );
413 -
414 - assertEquals(
415 - actual,
416 - Data.struct({
417 - USER_API_KEY: Option.none(),
418 - ENVIRONMENT: Option.none(),
419 - BASE_URL: 'https://backend.composio.dev',
420 - WEB_URL: 'https://dashboard.composio.dev/',
421 - CACHE_DIR: Option.none(),
422 - LOG_LEVEL: Option.none(),
423 - ORG_ID: Option.none(),
424 - PROJECT_ID: Option.none(),
425 - DISABLE_CONNECTED_ACCOUNT_CACHE: false,
426 - })
427 - );
428 - });
429 -
430 - it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {
431 - vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
432 -
433 - const actual = Effect.runSync(
434 - withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
435 - );
436 -
437 - assertEquals(
438 - actual,
439 - Data.struct({
440 - USER_API_KEY: Option.none(),
441 - ENVIRONMENT: Option.some('staging'),
442 - BASE_URL: constants.STAGING_BASE_URL,
443 - WEB_URL: constants.STAGING_WEB_URL,
444 - CACHE_DIR: Option.none(),
445 - LOG_LEVEL: Option.none(),
446 - ORG_ID: Option.none(),
447 - PROJECT_ID: Option.none(),
448 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
449 - })
450 - );
451 - });
452 -
453 - it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit URLs override', () => {
454 - vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
455 - vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');
456 - vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');
457 -
458 - const actual = Effect.runSync(
459 - withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))
460 - );
461 -
462 - assertEquals(
463 - actual,
464 - Data.struct({
465 - USER_API_KEY: Option.none(),
466 - ENVIRONMENT: Option.some('staging'),
467 - BASE_URL: 'https://custom.localhost',
468 - WEB_URL: 'https://custom-web.localhost',
469 - CACHE_DIR: Option.none(),
470 - LOG_LEVEL: Option.none(),
471 - ORG_ID: Option.none(),
472 - PROJECT_ID: Option.none(),
473 - DISABLE_CONNECTED_ACCOUNT_CACHE: true,
474 - })
475 - );
476 - });
374 + it.effect('[When] no env variable is set', () =>
375 + Effect.gen(function* () {
376 + const actual = yield* withEnvConfigProvider(
377 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
378 + );
379 +
380 + assertEquals(
381 + actual,
382 + Data.struct({
383 + USER_API_KEY: Option.none(),
384 + ENVIRONMENT: Option.none(),
385 + BASE_URL: 'https://backend.composio.dev',
386 + WEB_URL: 'https://dashboard.composio.dev/',
387 + CACHE_DIR: Option.none(),
388 + LOG_LEVEL: Option.none(),
389 + ORG_ID: Option.none(),
390 + PROJECT_ID: Option.none(),
391 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
392 + })
393 + );
394 + })
395 + );
396 +
397 + it.effect('[When] env variables are set without `COMPOSIO_` prefix', () =>
398 + Effect.gen(function* () {
399 + vi.stubEnv('USER_API_KEY', 'api_key');
400 + vi.stubEnv('BASE_URL', 'https://test.localhost');
401 + vi.stubEnv('CACHE_DIR', '~/.composio');
402 + vi.stubEnv('LOG_LEVEL', 'info');
403 +
404 + const actual = yield* withEnvConfigProvider(
405 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
406 + );
407 +
408 + assertEquals(
409 + actual,
410 + Data.struct({
411 + USER_API_KEY: Option.none(),
412 + ENVIRONMENT: Option.none(),
413 + BASE_URL: 'https://backend.composio.dev',
414 + WEB_URL: 'https://dashboard.composio.dev/',
415 + CACHE_DIR: Option.none(),
416 + LOG_LEVEL: Option.none(),
417 + ORG_ID: Option.none(),
418 + PROJECT_ID: Option.none(),
419 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
420 + })
421 + );
422 + })
423 + );
424 +
425 + it.effect('[When] env variables are set with `COMPOSIO_` prefix', () =>
426 + Effect.gen(function* () {
427 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'api_key');
428 + vi.stubEnv('COMPOSIO_BASE_URL', 'https://test.localhost');
429 + vi.stubEnv('COMPOSIO_WEB_URL', 'https://test.localhost');
430 + vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');
431 + vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');
432 +
433 + const actual = yield* withEnvConfigProvider(
434 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
435 + );
436 +
437 + assertEquals(
438 + actual,
439 + Data.struct({
440 + USER_API_KEY: Option.some('api_key'),
441 + ENVIRONMENT: Option.none(),
442 + BASE_URL: 'https://test.localhost',
443 + WEB_URL: 'https://test.localhost',
444 + CACHE_DIR: Option.some('~/.composio'),
445 + LOG_LEVEL: Option.some(LogLevel.Info),
446 + ORG_ID: Option.none(),
447 + PROJECT_ID: Option.none(),
448 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
449 + })
450 + );
451 + })
452 + );
453 +
454 + it.effect('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () =>
455 + Effect.gen(function* () {
456 + vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false');
457 +
458 + const actual = yield* withEnvConfigProvider(
459 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
460 + );
461 +
462 + assertEquals(
463 + actual,
464 + Data.struct({
465 + USER_API_KEY: Option.none(),
466 + ENVIRONMENT: Option.none(),
467 + BASE_URL: 'https://backend.composio.dev',
468 + WEB_URL: 'https://dashboard.composio.dev/',
469 + CACHE_DIR: Option.none(),
470 + LOG_LEVEL: Option.none(),
471 + ORG_ID: Option.none(),
472 + PROJECT_ID: Option.none(),
473 + DISABLE_CONNECTED_ACCOUNT_CACHE: false,
474 + })
475 + );
476 + })
477 + );
478 +
479 + it.effect('[When] COMPOSIO_ENVIRONMENT is "staging"', () =>
480 + Effect.gen(function* () {
481 + vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
482 +
483 + const actual = yield* withEnvConfigProvider(
484 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
485 + );
486 +
487 + assertEquals(
488 + actual,
489 + Data.struct({
490 + USER_API_KEY: Option.none(),
491 + ENVIRONMENT: Option.some('staging'),
492 + BASE_URL: constants.STAGING_BASE_URL,
493 + WEB_URL: constants.STAGING_WEB_URL,
494 + CACHE_DIR: Option.none(),
495 + LOG_LEVEL: Option.none(),
496 + ORG_ID: Option.none(),
497 + PROJECT_ID: Option.none(),
498 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
499 + })
500 + );
501 + })
502 + );
503 +
504 + it.effect('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit URLs override', () =>
505 + Effect.gen(function* () {
506 + vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');
507 + vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');
508 + vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');
509 +
510 + const actual = yield* withEnvConfigProvider(
511 + Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
512 + );
513 +
514 + assertEquals(
515 + actual,
516 + Data.struct({
517 + USER_API_KEY: Option.none(),
518 + ENVIRONMENT: Option.some('staging'),
519 + BASE_URL: 'https://custom.localhost',
520 + WEB_URL: 'https://custom-web.localhost',
521 + CACHE_DIR: Option.none(),
522 + LOG_LEVEL: Option.none(),
523 + ORG_ID: Option.none(),
524 + PROJECT_ID: Option.none(),
525 + DISABLE_CONNECTED_ACCOUNT_CACHE: true,
526 + })
527 + );
528 + })
529 + );
530 });
531
532 describe('DEBUG_OVERRIDE_CONFIG', () => {
480 - it('[When] no env variable is set', () => {
481 - const actual = Effect.runSync(
482 - withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))
483 - );
484 -
485 - assertEquals(
486 - actual,
487 - Data.struct({
488 - UPGRADE_TARGET: Option.none(),
489 - VERSION: Option.none(),
490 - })
491 - );
492 - });
493 -
494 - it('[When] env variables are set without `DEBUG_OVERRIDE_` prefix', () => {
495 - vi.stubEnv('UPGRADE_TARGET', 'upgrade_target');
496 - vi.stubEnv('VERSION', 'x.x.x');
497 -
498 - const actual = Effect.runSync(
499 - withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))
500 - );
501 -
502 - assertEquals(
503 - actual,
504 - Data.struct({
505 - UPGRADE_TARGET: Option.none(),
506 - VERSION: Option.none(),
507 - })
508 - );
509 - });
510 -
511 - it('[When] env variables are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix', () => {
512 - vi.stubEnv('COMPOSIO_UPGRADE_TARGET', 'upgrade_target');
513 - vi.stubEnv('COMPOSIO_VERSION', 'x.x.x');
514 -
515 - const actual = Effect.runSync(
516 - withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))
517 - );
518 -
519 - assertEquals(
520 - actual,
521 - Data.struct({
522 - UPGRADE_TARGET: Option.none(),
523 - VERSION: Option.none(),
524 - })
525 - );
526 - });
527 -
528 - it('[When] env variables are set with `DEBUG_OVERRIDE_` prefix', () => {
529 - vi.stubEnv('DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target');
530 - vi.stubEnv('DEBUG_OVERRIDE_VERSION', 'x.x.x');
531 -
532 - const actual = Effect.runSync(
533 - withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))
534 - );
535 -
536 - assertEquals(
537 - actual,
538 - Data.struct({
539 - UPGRADE_TARGET: Option.some('upgrade_target'),
540 - VERSION: Option.some('x.x.x'),
533 + it.effect('[When] no env variable is set', () =>
534 + Effect.gen(function* () {
535 + const actual = yield* withEnvConfigProvider(
536 + Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
537 + );
538 +
539 + assertEquals(
540 + actual,
541 + Data.struct({
542 + UPGRADE_TARGET: Option.none(),
543 + VERSION: Option.none(),
544 + })
545 + );
546 + })
547 + );
548 +
549 + it.effect('[When] env variables are set without `DEBUG_OVERRIDE_` prefix', () =>
550 + Effect.gen(function* () {
551 + vi.stubEnv('UPGRADE_TARGET', 'upgrade_target');
552 + vi.stubEnv('VERSION', 'x.x.x');
553 +
554 + const actual = yield* withEnvConfigProvider(
555 + Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
556 + );
557 +
558 + assertEquals(
559 + actual,
560 + Data.struct({
561 + UPGRADE_TARGET: Option.none(),
562 + VERSION: Option.none(),
563 + })
564 + );
565 + })
566 + );
567 +
568 + it.effect(
569 + '[When] env variables are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix',
570 + () =>
571 + Effect.gen(function* () {
572 + vi.stubEnv('COMPOSIO_UPGRADE_TARGET', 'upgrade_target');
573 + vi.stubEnv('COMPOSIO_VERSION', 'x.x.x');
574 +
575 + const actual = yield* withEnvConfigProvider(
576 + Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
577 + );
578 +
579 + assertEquals(
580 + actual,
581 + Data.struct({
582 + UPGRADE_TARGET: Option.none(),
583 + VERSION: Option.none(),
584 + })
585 + );
586 })
542 - );
543 - });
587 + );
588 +
589 + it.effect('[When] env variables are set with `DEBUG_OVERRIDE_` prefix', () =>
590 + Effect.gen(function* () {
591 + vi.stubEnv('DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target');
592 + vi.stubEnv('DEBUG_OVERRIDE_VERSION', 'x.x.x');
593 +
594 + const actual = yield* withEnvConfigProvider(
595 + Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))
596 + );
597 +
598 + assertEquals(
599 + actual,
600 + Data.struct({
601 + UPGRADE_TARGET: Option.some('upgrade_target'),
602 + VERSION: Option.some('x.x.x'),
603 + })
604 + );
605 + })
606 + );
607 });
608 });
609 });
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+42 -2
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { vi, afterEach } from 'vitest';
2 +import { vi, beforeEach, afterEach } from 'vitest';
3 import { FileSystem } from '@effect/platform';
4 import { ConfigProvider, Effect, Option } from 'effect';
5 import path from 'node:path';
@@ -29,8 +29,20 @@ const cacheEnabledTestConfigProvider = makeTestConfigProvider([
29 ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false'],
30 ]);
31
32 +// Instant the wall clock is pinned to; fixture expiresAt values below are
33 +// written relative to it so freshness checks in the SUT stay deterministic.
34 +const PINNED_NOW = '2026-01-01T00:00:00.000Z';
35 +const ONE_MINUTE_FROM_PINNED_NOW = '2026-01-01T00:01:00.000Z';
36 +
37 describe('consumer short-term cache', () => {
38 + beforeEach(() => {
39 + // Fake ONLY Date so real timers and promise scheduling keep working.
40 + vi.useFakeTimers({ toFake: ['Date'] });
41 + vi.setSystemTime(new Date(PINNED_NOW));
42 + });
43 +
44 afterEach(() => {
45 + vi.useRealTimers();
46 vi.restoreAllMocks();
47 });
48
@@ -181,6 +193,34 @@ describe('consumer short-term cache', () => {
193 );
194 });
195
196 + layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
197 + '[Given] a malformed persisted cache [Then] cache reads fail closed',
198 + it => {
199 + it.scoped('ignores cache entries that do not match the persisted schema', () =>
200 + Effect.gen(function* () {
201 + const fs = yield* FileSystem.FileSystem;
202 + const cacheDir = yield* setupCacheDir;
203 + yield* fs.writeFileString(
204 + path.join(cacheDir, 'consumer-short-term-cache.json'),
205 + JSON.stringify({
206 + 'org_test:consumer-user-test': {
207 + toolkits: 'github',
208 + expiresAt: ONE_MINUTE_FROM_PINNED_NOW,
209 + },
210 + })
211 + );
212 +
213 + const cached = yield* getFreshConsumerConnectedToolkitsFromCache({
214 + orgId: 'org_test',
215 + consumerUserId: 'consumer-user-test',
216 + });
217 +
218 + expect(cached).toEqual(Option.none());
219 + })
220 + );
221 + }
222 + );
223 +
224 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
225 '[Given] one corrupt entry among valid ones [Then] only the corrupt entry is dropped',
226 it => {
@@ -194,7 +234,7 @@ describe('consumer short-term cache', () => {
234 'org_bad:consumer-user-bad': { toolkits: 'not-an-array', expiresAt: 42 },
235 'org_test:consumer-user-test': {
236 toolkits: ['github'],
197 - expiresAt: new Date(Date.now() + 60_000).toISOString(),
237 + expiresAt: ONE_MINUTE_FROM_PINNED_NOW,
238 },
239 })
240 );
ts/packages/cli/test/src/services/native-ui-sidecar.test.ts
+89 -26
@@ -1,31 +1,94 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
3 -import { interactivePermissionUiDisabledConfig } from 'src/services/native-ui-sidecar';
4 -
5 -const loadFlag = (entries: Record<string, string>): boolean =>
6 - Effect.runSync(
7 - ConfigProvider.fromMap(new Map(Object.entries(entries))).load(
8 - interactivePermissionUiDisabledConfig
9 - )
2 +import { CommandExecutor, Error as PlatformError } from '@effect/platform';
3 +import { ConfigProvider, Effect, Layer } from 'effect';
4 +import {
5 + detectNativeUiCallerAgentEffect,
6 + interactivePermissionUiDisabledConfig,
7 +} from 'src/services/native-ui-sidecar';
8 +
9 +const loadFlag = (entries: Record<string, string>) =>
10 + ConfigProvider.fromMap(new Map(Object.entries(entries))).load(
11 + interactivePermissionUiDisabledConfig
12 );
13
14 +const executorLayer = (start: Parameters<typeof CommandExecutor.makeExecutor>[0]) =>
15 + Layer.succeed(CommandExecutor.CommandExecutor, CommandExecutor.makeExecutor(start));
16 +
17 +// Environment-based detection must resolve before `ps` is ever spawned.
18 +const processTreeMustNotRun = executorLayer(() =>
19 + Effect.die(new Error('the process tree must not be consulted'))
20 +);
21 +
22 +// Spawn failures during the process-tree walk resolve to the default agent.
23 +const processTreeUnavailable = executorLayer(() =>
24 + Effect.fail(
25 + new PlatformError.SystemError({ reason: 'NotFound', module: 'Command', method: 'spawn' })
26 + )
27 +);
28 +
29 +const detectAgent = (
30 + env: Record<string, string>,
31 + layer: Layer.Layer<CommandExecutor.CommandExecutor>
32 +) => detectNativeUiCallerAgentEffect(env).pipe(Effect.provide(layer));
33 +
34 describe('native UI sidecar', () => {
13 - it('disables interactive permission UI in CI and Vitest environments', () => {
14 - expect(loadFlag({})).toBe(false);
15 - expect(loadFlag({ CI: 'true' })).toBe(true);
16 - expect(loadFlag({ CI: '1' })).toBe(true);
17 - expect(loadFlag({ CI: 'woohoo' })).toBe(true);
18 - expect(loadFlag({ CI: 'false' })).toBe(false);
19 - expect(loadFlag({ CI: '' })).toBe(false);
20 - expect(loadFlag({ VITEST: 'true' })).toBe(true);
21 - });
22 -
23 - it('lets COMPOSIO_DISABLE_PERMISSION_UI override environment detection in both directions', () => {
24 - expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '1' })).toBe(true);
25 - expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: 'true' })).toBe(true);
26 - expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '0', CI: 'true', VITEST: 'true' })).toBe(
27 - false
28 - );
29 - expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '', CI: 'true' })).toBe(true);
30 - });
35 + it.effect('disables interactive permission UI in CI and Vitest environments', () =>
36 + Effect.gen(function* () {
37 + expect(yield* loadFlag({})).toBe(false);
38 + expect(yield* loadFlag({ CI: 'true' })).toBe(true);
39 + expect(yield* loadFlag({ CI: '1' })).toBe(true);
40 + expect(yield* loadFlag({ CI: 'woohoo' })).toBe(true);
41 + expect(yield* loadFlag({ CI: 'false' })).toBe(false);
42 + expect(yield* loadFlag({ CI: '' })).toBe(false);
43 + expect(yield* loadFlag({ VITEST: 'true' })).toBe(true);
44 + })
45 + );
46 +
47 + it.effect(
48 + 'lets COMPOSIO_DISABLE_PERMISSION_UI override environment detection in both directions',
49 + () =>
50 + Effect.gen(function* () {
51 + expect(yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '1' })).toBe(true);
52 + expect(yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: 'true' })).toBe(true);
53 + expect(
54 + yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '0', CI: 'true', VITEST: 'true' })
55 + ).toBe(false);
56 + expect(yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '', CI: 'true' })).toBe(true);
57 + })
58 + );
59 +
60 + it.effect('honours explicit caller-agent overrides without consulting the process tree', () =>
61 + Effect.gen(function* () {
62 + expect(yield* detectAgent({ COMPOSIO_CALLER_AGENT: 'Claude' }, processTreeMustNotRun)).toBe(
63 + 'claude'
64 + );
65 + expect(yield* detectAgent({ COMPOSIO_AGENT: 'open-claw' }, processTreeMustNotRun)).toBe(
66 + 'openclaw'
67 + );
68 + expect(
69 + yield* detectAgent(
70 + { COMPOSIO_CALLER_AGENT: 'codex', CLAUDE_CODE: '1' },
71 + processTreeMustNotRun
72 + )
73 + ).toBe('codex');
74 + })
75 + );
76 +
77 + it.effect('detects the caller agent from environment prefixes', () =>
78 + Effect.gen(function* () {
79 + expect(yield* detectAgent({ OPENCLAW_GATEWAY: '1' }, processTreeMustNotRun)).toBe('openclaw');
80 + expect(yield* detectAgent({ CLAUDE_CODE_ENTRYPOINT: 'cli' }, processTreeMustNotRun)).toBe(
81 + 'claude'
82 + );
83 + expect(yield* detectAgent({ CODEX_HOME: '/tmp/codex' }, processTreeMustNotRun)).toBe('codex');
84 + })
85 + );
86 +
87 + it.effect(
88 + 'falls back to composio when nothing matches and the process tree cannot be walked',
89 + () =>
90 + Effect.gen(function* () {
91 + expect(yield* detectAgent({}, processTreeUnavailable)).toBe('composio');
92 + })
93 + );
94 });
ts/packages/cli/test/src/services/test-layer.test.ts
+17 -13
@@ -1,24 +1,28 @@
1 -import { describe, expect, it, vi } from 'vitest';
1 +import { describe, expect, it, vi } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { TestLive } from 'test/__utils__';
4
5 describe('TestLayer', () => {
6 - it('restores globalThis.fetch after the layer scope closes', async () => {
7 - const originalFetch = globalThis.fetch;
6 + it.effect('restores globalThis.fetch after the layer scope closes', () =>
7 + Effect.gen(function* () {
8 + const originalFetch = globalThis.fetch;
9
9 - await Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped, Effect.runPromise);
10 + yield* Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped);
11
11 - expect(globalThis.fetch).toBe(originalFetch);
12 - });
12 + expect(globalThis.fetch).toBe(originalFetch);
13 + })
14 + );
15
14 - it('does not leak the fetch mock into later spy restore cycles', async () => {
15 - const originalFetch = globalThis.fetch;
16 + it.effect('does not leak the fetch mock into later spy restore cycles', () =>
17 + Effect.gen(function* () {
18 + const originalFetch = globalThis.fetch;
19
17 - await Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped, Effect.runPromise);
20 + yield* Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped);
21
19 - vi.spyOn(globalThis, 'fetch');
20 - vi.restoreAllMocks();
22 + vi.spyOn(globalThis, 'fetch');
23 + vi.restoreAllMocks();
24
22 - expect(globalThis.fetch).toBe(originalFetch);
23 - });
25 + expect(globalThis.fetch).toBe(originalFetch);
26 + })
27 + );
28 });
ts/packages/cli/vitest.config.ts
+2 -1
@@ -23,7 +23,7 @@ export default defineConfig({
23 ),
24 '@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),
25 '@composio/cli-local-tools': path.join(cliLocalToolsDir, 'src/index.ts'),
26 - 'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),
26 + 'effect-errors': path.resolve(__dirname, './src/effect-errors'),
27 // @composio/core uses package.json "imports" (#config_defaults, #platform, etc.)
28 // Vitest/Vite does not resolve these for workspace deps, so alias them explicitly
29 '#config_defaults': path.join(coreDir, 'src/utils/config-defaults/ConfigDefaults.node.ts'),
@@ -41,6 +41,7 @@ export default defineConfig({
41 // When defined, Vitest will run all matched files with import.meta.vitest inside.
42 includeSource: ['src/**/*.ts', 'test/__utils__/*-compiler.ts'],
43 unstubEnvs: true,
44 + setupFiles: ['./test/__utils__/vitest.setup.ts'],
45 globalSetup: './test/__utils__/vitest.global-setup.ts',
46 },
47 });