Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
test(cli): lint the test tree and enforce deterministic @effect/vitest suites (#3883)
Alberto Schiabel6010fc712c85
diff --git a/eslint.config.mjs b/eslint.config.mjsindex 06e0ac6d5..6907e8975 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -162,13 +162,12 @@ export default ['ts/examples/**/dist-worker/**','scripts/**','**/test/**',- // uncommented by the test-rules PR of this stack: the CLI test sources- // become linted (unlike other packages' tests) so the @effect/vitest- // guardrail below is actually enforced. Fixtures and the test/__utils__- // harness glue stay unlinted.- // '!ts/packages/cli/test/**',- // 'ts/packages/cli/test/__fixtures__/**',- // 'ts/packages/cli/test/__utils__/**',+ // The CLI test sources are linted (unlike other packages' tests) so the+ // @effect/vitest guardrail below is actually enforced. Fixtures and the+ // test/__utils__ harness glue stay unlinted.+ '!ts/packages/cli/test/**',+ 'ts/packages/cli/test/__fixtures__/**',+ 'ts/packages/cli/test/__utils__/**',],},{ files: ['ts/packages/**/*.ts', 'ts/examples/**/*.ts'] },@@ -225,34 +224,33 @@ export default [],},},- // uncommented by the test-rules PR of this stack.- // {- // // Tests exercise Effects through @effect/vitest (it.effect, it.scoped,- // // it.live) so failures surface as typed Exits instead of thrown- // // FiberFailures. The test/__utils__ harness glue (vitest setup files,- // // TestLayer runner) is intentionally outside this glob: it is the one- // // boundary allowed to run Effects directly.- // files: ['ts/packages/cli/test/src/**/*.{ts,tsx}'],- // rules: {- // // Vitest suites are one long describe() block by design, and mock- // // plumbing casts freely; the SUT's own types carry the safety.- // 'max-lines-per-function': 'off',- // '@typescript-eslint/no-explicit-any': 'off',- // 'no-restricted-syntax': [- // 'error',- // {- // selector: "MemberExpression[object.name='Effect'][property.name=/^run/]",- // message:- // 'Run Effects through @effect/vitest (it.effect, it.scoped, it.live) instead of Effect.run* in tests.',- // },- // {- // selector: "CallExpression[callee.object.name='Date'][callee.property.name='now']",- // message:- // 'Tests must be deterministic: pin time with vi.setSystemTime / TestClock-relative fixtures, use crypto.randomUUID() for unique names.',- // },- // ],- // },- // },+ {+ // Tests exercise Effects through @effect/vitest (it.effect, it.scoped,+ // it.live) so failures surface as typed Exits instead of thrown+ // FiberFailures. The test/__utils__ harness glue (vitest setup files,+ // TestLayer runner) is intentionally outside this glob: it is the one+ // boundary allowed to run Effects directly.+ files: ['ts/packages/cli/test/src/**/*.{ts,tsx}'],+ rules: {+ // Vitest suites are one long describe() block by design, and mock+ // plumbing casts freely; the SUT's own types carry the safety.+ 'max-lines-per-function': 'off',+ '@typescript-eslint/no-explicit-any': 'off',+ 'no-restricted-syntax': [+ 'error',+ {+ selector: "MemberExpression[object.name='Effect'][property.name=/^run/]",+ message:+ 'Run Effects through @effect/vitest (it.effect, it.scoped, it.live) instead of Effect.run* in tests.',+ },+ {+ selector: "CallExpression[callee.object.name='Date'][callee.property.name='now']",+ message:+ 'Tests must be deterministic: pin time with vi.setSystemTime / TestClock-relative fixtures, use crypto.randomUUID() for unique names.',+ },+ ],+ },+ },{// The one file allowed to touch @effect/cli's CommandDescriptor/Usage// modules (the Effect CLI v4 redesign seam).diff --git a/ts/packages/cli/test/__utils__/vitest.setup.ts b/ts/packages/cli/test/__utils__/vitest.setup.tsnew file mode 100644index 000000000..5f269218c--- /dev/null+++ b/ts/packages/cli/test/__utils__/vitest.setup.ts@@ -0,0 +1,36 @@+import { FileSystem } from '@effect/platform';+import { BunFileSystem } from '@effect/platform-bun';+import { Effect } from 'effect';+import { afterEach, beforeEach, vi } from 'vitest';++// Point every test at a fresh, empty config directory so nothing reads or+// writes the developer's real `~/.composio`. An empty directory holds no+// permission snapshot, so the tool-permission gate resolves to 'skip' instead+// of spawning the native approval dialog / browser prompt from the developer's+// real enhanced-controls state. Tests that need a specific directory stub+// COMPOSIO_CACHE_DIR themselves; stubs applied inside a test win over this one.+let testConfigDirectory: string | undefined;++const runFs = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>): Promise<A> =>+ Effect.runPromise(effect.pipe(Effect.provide(BunFileSystem.layer)));++beforeEach(async () => {+ testConfigDirectory = await runFs(+ Effect.flatMap(FileSystem.FileSystem, fs =>+ fs.makeTempDirectory({ prefix: 'composio-cli-test-config-' })+ )+ );+ vi.stubEnv('COMPOSIO_CACHE_DIR', testConfigDirectory);+});++afterEach(async () => {+ const directory = testConfigDirectory;+ testConfigDirectory = undefined;+ if (directory) {+ await runFs(+ Effect.flatMap(FileSystem.FileSystem, fs =>+ fs.remove(directory, { recursive: true, force: true })+ )+ );+ }+});diff --git a/ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.ts b/ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.tsnew file mode 100644index 000000000..33fa03c51--- /dev/null+++ b/ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.ts@@ -0,0 +1,134 @@+import { FileSystem, Path } from '@effect/platform';+import { BunFileSystem, BunPath } from '@effect/platform-bun';+import { ValidationError } from '@effect/cli';+import { describe, expect, it, layer } from '@effect/vitest';+import { Cause, Effect, Exit, Layer } from 'effect';+import * as tempy from 'tempy';+import { discoverSkillRoots } from 'src/effects/discover-skill-roots';+import { cli, MockConsole, TestLive } from 'test/__utils__';++const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);++const providePlatform = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) =>+ effect.pipe(Effect.provide(TestPlatform));++const expectRootsExactlyOnce = (actual: ReadonlyArray<string>, expected: ReadonlyArray<string>) => {+ expect(actual).toEqual(expected);+ expect(new Set(actual).size).toBe(actual.length);+};++describe('config experimental skill discovery', () => {+ it.effect('discovers only the canonical skill root', () =>+ providePlatform(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const home = tempy.temporaryDirectory();+ const canonicalRoot = path.join(home, '.agents', 'skills');+ yield* fs.makeDirectory(path.join(canonicalRoot, 'composio-cli'), { recursive: true });++ expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);+ })+ )+ );++ it.effect('discovers canonical and real Claude skill copies', () =>+ providePlatform(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const home = tempy.temporaryDirectory();+ const canonicalRoot = path.join(home, '.agents', 'skills');+ const claudeRoot = path.join(home, '.claude', 'skills');+ yield* fs.makeDirectory(path.join(canonicalRoot, 'composio-cli'), { recursive: true });+ yield* fs.makeDirectory(path.join(claudeRoot, 'composio-cli'), { recursive: true });++ expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot, claudeRoot]);+ })+ )+ );++ it.effect('deduplicates a Claude symlink to the canonical skill', () =>+ providePlatform(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const home = tempy.temporaryDirectory();+ const canonicalRoot = path.join(home, '.agents', 'skills');+ const canonicalSkill = path.join(canonicalRoot, 'composio-cli');+ const claudeSkill = path.join(home, '.claude', 'skills', 'composio-cli');+ yield* fs.makeDirectory(canonicalSkill, { recursive: true });+ yield* fs.makeDirectory(path.dirname(claudeSkill), { recursive: true });+ yield* fs.symlink(path.relative(path.dirname(claudeSkill), canonicalSkill), claudeSkill);++ expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);+ })+ )+ );++ it.effect('ignores a broken Claude symlink and keeps the canonical fallback', () =>+ providePlatform(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const home = tempy.temporaryDirectory();+ const canonicalRoot = path.join(home, '.agents', 'skills');+ const claudeSkill = path.join(home, '.claude', 'skills', 'composio-cli');+ yield* fs.makeDirectory(path.dirname(claudeSkill), { recursive: true });+ yield* fs.symlink('../missing-composio-cli', claudeSkill);++ expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);+ })+ )+ );++ it.effect('uses the canonical fallback when neither skill root exists', () =>+ providePlatform(+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const home = tempy.temporaryDirectory();+ const canonicalRoot = path.join(home, '.agents', 'skills');++ expectRootsExactlyOnce(yield* discoverSkillRoots(home), [canonicalRoot]);+ })+ )+ );++ it.effect('keeps an external symlink target and the canonical fallback once each', () =>+ providePlatform(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const home = tempy.temporaryDirectory();+ const canonicalRoot = path.join(home, '.agents', 'skills');+ const externalRoot = path.join(home, 'shared-skills');+ const externalSkill = path.join(externalRoot, 'composio-cli');+ const claudeSkill = path.join(home, '.claude', 'skills', 'composio-cli');+ yield* fs.makeDirectory(externalSkill, { recursive: true });+ yield* fs.makeDirectory(path.dirname(claudeSkill), { recursive: true });+ yield* fs.symlink(path.relative(path.dirname(claudeSkill), externalSkill), claudeSkill);++ expectRootsExactlyOnce(yield* discoverSkillRoots(home), [externalRoot, canonicalRoot]);+ })+ )+ );+});++layer(TestLive())('config experimental state validation', it => {+ it.scoped('reports an invalid state through Effect CLI validation', () =>+ Effect.gen(function* () {+ const exit = yield* Effect.exit(cli(['config', 'experimental', 'local_tools', 'sometimes']));++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(+ ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)+ ).toBe(true);+ }+ expect((yield* MockConsole.getLines()).join('\n')).toContain(+ 'Invalid state "sometimes". Use "on" or "off".'+ );+ })+ );+});diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.tsindex d1a4bfdd9..c04ecf4dc 100644--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts@@ -64,10 +64,6 @@ const connectedAccountsData = {items: testConnectedAccounts,} satisfies TestLiveInput['connectedAccountsData'];-const testConfigProvider = ConfigProvider.fromMap(- new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])-).pipe(extendConfigProvider);-const testDevConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key'],diff --git a/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts b/ts/packages/cli/test/src/commands/local-tools.cmd.test.tsindex e41046ffd..a3881e20e 100644--- a/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts@@ -11,7 +11,7 @@ const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>const previous = process.env.COMPOSIO_LOCAL_TOOLS_PATH;process.env.COMPOSIO_LOCAL_TOOLS_PATH = path.join(os.tmpdir(),- `composio-local-tools-${Date.now()}.json`+ `composio-local-tools-${crypto.randomUUID()}.json`);return previous;}),diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex 075f654d9..ed7990dc8 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -935,9 +935,9 @@ describe('CLI: composio execute', () => {expect(output.storedInFile).toBe(true);expect(output.logId).toBe('log_large_output');expect(output.tokenCount).toBeGreaterThan(10_000);- expect(output.outputFilePath).toMatch(- /composio\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/- );+ // Session artifacts fall back to COMPOSIO_CACHE_DIR, which the shared+ // vitest setup pins to a per-test temp directory.+ expect(output.outputFilePath).toMatch(/\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/);expect(fs.existsSync(output.outputFilePath)).toBe(true);const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');expect(storedJson).toContain('token token token');@@ -1123,7 +1123,7 @@ describe('CLI: composio execute', () => {it => {it.scoped('uploads local file paths before Tool Router execution', () =>Effect.gen(function* () {- const tempFile = path.join(os.tmpdir(), `composio-upload-${Date.now()}.txt`);+ const tempFile = path.join(os.tmpdir(), `composio-upload-${crypto.randomUUID()}.txt`);fs.writeFileSync(tempFile, 'hello from cli upload', 'utf8');const originalFetch = globalThis.fetch;@@ -1222,7 +1222,7 @@ describe('CLI: composio execute', () => {it => {it.scoped('injects into the single file_uploadable field before upload hydration', () =>Effect.gen(function* () {- const tempFile = path.join(os.tmpdir(), `composio-inject-${Date.now()}.png`);+ const tempFile = path.join(os.tmpdir(), `composio-inject-${crypto.randomUUID()}.png`);fs.writeFileSync(tempFile, 'png-binary-ish', 'utf8');const originalFetch = globalThis.fetch;@@ -1314,7 +1314,7 @@ describe('CLI: composio execute', () => {it => {it.scoped('treats property-bearing schema nodes as object-like during upload hydration', () =>Effect.gen(function* () {- const tempFile = path.join(os.tmpdir(), `composio-nested-${Date.now()}.png`);+ const tempFile = path.join(os.tmpdir(), `composio-nested-${crypto.randomUUID()}.png`);fs.writeFileSync(tempFile, 'nested-png-binary-ish', 'utf8');const originalFetch = globalThis.fetch;@@ -1403,7 +1403,10 @@ describe('CLI: composio execute', () => {it => {it.scoped('propagates upload failures from file hydration', () =>Effect.gen(function* () {- const tempFile = path.join(os.tmpdir(), `composio-upload-fail-${Date.now()}.txt`);+ const tempFile = path.join(+ os.tmpdir(),+ `composio-upload-fail-${crypto.randomUUID()}.txt`+ );fs.writeFileSync(tempFile, 'hello from failed cli upload', 'utf8');const originalFetch = globalThis.fetch;diff --git a/ts/packages/cli/test/src/effect-errors/cause-characterization.test.ts b/ts/packages/cli/test/src/effect-errors/cause-characterization.test.tsnew file mode 100644index 000000000..cb95e20ec--- /dev/null+++ b/ts/packages/cli/test/src/effect-errors/cause-characterization.test.ts@@ -0,0 +1,186 @@+import { describe, expect, it } from '@effect/vitest';+import { BunFileSystem, BunPath } from '@effect/platform-bun';+import { Cause, Data, Effect, FiberId } from 'effect';++import { captureErrors } from 'src/effect-errors/capture-errors';+import { captureErrorsFrom } from 'src/effect-errors/logic/errors/capture-errors-from-cause';+import { prettyPrintFromCapturedErrors } from 'src/effect-errors/pretty-print-from-captured-errors';++// Characterization tests pinning the v3 Cause traversal and rendering+// behavior, so the Effect v4 migration (flat failure list instead of the+// Empty/Fail/Die/Interrupt/Sequential/Parallel tree) has an executable+// equivalence oracle instead of eyeballing error output.++class DbError extends Data.TaggedError('DbError')<{+ readonly message: string;+}> {}++class HttpError extends Data.TaggedError('HttpError')<{+ readonly message: string;+}> {}++const stripAnsi = (value: string): string => value.replace(/\x1b\[[0-9;]*m/g, '');++const render = (captured: Effect.Effect.Success<ReturnType<typeof capture>>): string =>+ stripAnsi(+ prettyPrintFromCapturedErrors(captured, {+ enabled: true,+ stripCwd: true,+ hideStackTrace: true,+ })+ );++const capture = <E>(cause: Cause.Cause<E>) =>+ captureErrors(cause).pipe(Effect.provide([BunFileSystem.layer, BunPath.layer]));++describe('captureErrorsFrom (structural Cause traversal)', () => {+ it('returns no errors for an empty cause', () => {+ expect(captureErrorsFrom(Cause.empty)).toStrictEqual([]);+ });++ it('captures a tagged failure with its type and message', () => {+ const [error, ...rest] = captureErrorsFrom(Cause.fail(new DbError({ message: 'no db' })));++ expect(rest).toStrictEqual([]);+ expect(error?.errorType).toBe('DbError');+ expect(error?.message).toBe('no db');+ expect(error?.isPlainString).toBe(false);+ });++ it('captures a plain-string failure as a plain string', () => {+ const [error] = captureErrorsFrom(Cause.fail('boom'));++ expect(error?.isPlainString).toBe(true);+ expect(error?.message).toBe('boom');+ });++ it('captures a defect', () => {+ const [error, ...rest] = captureErrorsFrom(Cause.die(new Error('kaboom')));++ expect(rest).toStrictEqual([]);+ expect(error?.errorType).toBe('Error');+ expect(error?.message).toStrictEqual(['kaboom']);+ });++ it('captures nothing for an interruption', () => {+ expect(captureErrorsFrom(Cause.interrupt(FiberId.none))).toStrictEqual([]);+ });++ it('flattens a sequential cause left to right', () => {+ const cause = Cause.sequential(+ Cause.fail(new DbError({ message: 'first' })),+ Cause.die(new Error('second'))+ );++ const errors = captureErrorsFrom(cause);++ expect(errors.map(error => error.errorType)).toStrictEqual(['DbError', 'Error']);+ });++ it('flattens a parallel cause left to right', () => {+ const cause = Cause.parallel(+ Cause.fail(new DbError({ message: 'left' })),+ Cause.fail(new HttpError({ message: 'right' }))+ );++ const errors = captureErrorsFrom(cause);++ expect(errors.map(error => error.message)).toStrictEqual(['left', 'right']);+ });++ it('flattens nested parallel-in-sequential causes in traversal order', () => {+ const cause = Cause.sequential(+ Cause.parallel(+ Cause.fail(new DbError({ message: 'a' })),+ Cause.fail(new HttpError({ message: 'b' }))+ ),+ Cause.fail(new DbError({ message: 'c' }))+ );++ const errors = captureErrorsFrom(cause);++ expect(errors.map(error => error.message)).toStrictEqual(['a', 'b', 'c']);+ });++ it('ignores interruptions mixed with failures', () => {+ const cause = Cause.sequential(+ Cause.interrupt(FiberId.none),+ Cause.fail(new DbError({ message: 'still there' }))+ );++ const errors = captureErrorsFrom(cause);++ expect(errors.map(error => error.message)).toStrictEqual(['still there']);+ });++ it.effect('threads the ambient span from a runtime failure into the captured error', () =>+ Effect.gen(function* () {+ const cause = yield* Effect.fail(new DbError({ message: 'no db' })).pipe(+ Effect.withSpan('characterization-span'),+ Effect.sandbox,+ Effect.flip+ );++ const [error] = captureErrorsFrom(cause);++ expect(error?.span?.name).toBe('characterization-span');+ })+ );+});++describe('captureErrors + prettyPrintFromCapturedErrors (rendering)', () => {+ it.effect(+ 'reports interrupt-only causes as interrupted and renders the interruption message',+ () =>+ Effect.gen(function* () {+ const captured = yield* capture(Cause.interrupt(FiberId.none));++ expect(captured).toStrictEqual({ interrupted: true, errors: [] });+ expect(render(captured)).toBe('✅ All fibers interrupted without errors.');+ })+ );++ it.effect('renders a single failure without the multi-error header', () =>+ Effect.gen(function* () {+ const captured = yield* capture(Cause.fail(new DbError({ message: 'no db' })));+ const output = render(captured);++ expect(captured.interrupted).toBe(false);+ expect(output).toContain('💥 DbError • no db');+ expect(output).not.toContain('errors occurred');+ expect(output).not.toContain('#1 -');+ })+ );++ it.effect('renders a runtime failure with its span timeline', () =>+ Effect.gen(function* () {+ const cause = yield* Effect.fail(new HttpError({ message: 'request failed' })).pipe(+ Effect.withSpan('characterization-span'),+ Effect.sandbox,+ Effect.flip+ );++ const output = render(yield* capture(cause));++ expect(output).toContain('💥 HttpError • request failed');+ expect(output).toContain('◯');+ expect(output).toContain('characterization-span');+ })+ );++ it.effect('renders multiple failures with a count header and per-error indexes in order', () =>+ Effect.gen(function* () {+ const cause = Cause.parallel(+ Cause.fail(new DbError({ message: 'left' })),+ Cause.fail(new HttpError({ message: 'right' }))+ );++ const output = render(yield* capture(cause));++ expect(output).toContain('2 errors occurred');+ expect(output).toContain('💥 #1 - DbError • left');+ expect(output).toContain('💥 #2 - HttpError • right');+ expect(output.indexOf('DbError')).toBeLessThan(output.indexOf('HttpError'));+ })+ );+});diff --git a/ts/packages/cli/test/src/effects/compare-semver.test.ts b/ts/packages/cli/test/src/effects/compare-semver.test.tsindex eefc41dfb..82a218189 100644--- a/ts/packages/cli/test/src/effects/compare-semver.test.ts+++ b/ts/packages/cli/test/src/effects/compare-semver.test.ts@@ -281,19 +281,6 @@ describe('compare-semver.ts', () => {}}- // Verify that the comparator would sort correctly- const expectedOrder = ['1.0.0', '2.0.0', '3.0.0'];- const actualResult = [...versions].sort((a, b) => {- // Find the comparison result from our Effect calls- const comparison = comparisons.find(- c =>- (c.versions[0] === a && c.versions[1] === b) ||- (c.versions[0] === b && c.versions[1] === a)- );- if (!comparison) return 0;- return comparison.versions[0] === a ? comparison.result : -comparison.result;- });-// Since we can't actually use the Effect in Array.sort, just verify// the comparison results are consistent with sort expectationsexpect(comparisons.length).toBe(3); // 3 comparisons for 3 elementsdiff --git a/ts/packages/cli/test/src/effects/install-skill.test.ts b/ts/packages/cli/test/src/effects/install-skill.test.tsindex ad436c970..6cd0b53e5 100644--- a/ts/packages/cli/test/src/effects/install-skill.test.ts+++ b/ts/packages/cli/test/src/effects/install-skill.test.ts@@ -1,10 +1,10 @@+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';import { describe, expect, it, vi } from '@effect/vitest';import { Config, ConfigProvider, Effect, Exit, Layer } from 'effect';import { FetchHttpClient, FileSystem, HttpClient, Path } from '@effect/platform';import type * as PlatformError from '@effect/platform/Error';import { BunFileSystem, BunPath } from '@effect/platform-bun';import * as tempy from 'tempy';-import { withHttpServer } from 'test/__utils__/http-server';import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';import {inferSkillReleaseChannel,@@ -16,9 +16,9 @@ import {type SkillReleaseChannel,} from 'src/effects/install-skill';import { GITHUB_CONFIG } from 'src/effects/github-config';+import { CliReleaseResolutionError } from 'src/effects/resolve-cli-release';import { defaultNodeOs, NodeOs } from 'src/services/node-os';-const path = Effect.runSync(Effect.provide(Path.Path, Path.layer));const TEST_RELEASE_TAG = '@composio/[email protected]';const TEST_SKILL_ZIP = Uint8Array.from(atob(@@ -51,8 +51,43 @@ const makeInstallEffect = (home: string, apiBaseUrl: string) =>Effect.scoped);-const withSkillRelease = (skillZip: Uint8Array, run: (apiBaseUrl: string) => Promise<void>) =>- withHttpServer((req, res) => {+/**+ * Spin up a local HTTP server on an ephemeral port as a scoped resource and+ * return its base URL. Scope closure tears the server down.+ */+const startTestHttpServer = (handler: (req: IncomingMessage, res: ServerResponse) => void) =>+ Effect.map(+ Effect.acquireRelease(+ Effect.promise(+ () =>+ new Promise<Server>((resolve, reject) => {+ const server = createServer(handler);+ server.once('error', reject);+ server.listen({ port: 0, host: '127.0.0.1' }, () => {+ server.off('error', reject);+ resolve(server);+ });+ })+ ),+ server =>+ Effect.promise(+ () =>+ new Promise<void>((resolve, reject) => {+ server.close(error => (error ? reject(error) : resolve()));+ })+ )+ ),+ server => {+ const address = server.address();+ if (address === null || typeof address === 'string') {+ throw new Error('Failed to bind test server to an ephemeral port');+ }+ return `http://127.0.0.1:${address.port}`;+ }+ );++const startSkillReleaseServer = (skillZip: Uint8Array) =>+ startTestHttpServer((req, res) => {if (req.url === '/skill.zip') {res.writeHead(200, { 'content-type': 'application/zip' });res.end(skillZip);@@ -70,7 +105,17 @@ const withSkillRelease = (skillZip: Uint8Array, run: (apiBaseUrl: string) => Pro],}));- }, run);+ });++/** Scoped stub of Bun.which that misses, so release resolution takes the HTTP path. */+const stubBunWhichMiss = Effect.acquireRelease(+ Effect.sync(() => vi.stubGlobal('Bun', { which: vi.fn(() => null) })),+ () =>+ Effect.sync(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ })+);type TargetSetup = (fs: FileSystem.FileSystem,@@ -154,217 +199,240 @@ describe('install-skill', () => {expect(() => resolveInstalledSkillName('..')).toThrow(/Invalid skill name/);});- it('resolves the agent-specific skill path', () => {- expect(- resolveTargetSkillPath({- home: '/tmp/test-home',- path,- skillName: 'composio-cli',- target: 'claude',- })- ).toBe('/tmp/test-home/.claude/skills/composio-cli');- expect(- resolveTargetSkillPath({- home: '/tmp/test-home',- path,- skillName: 'composio-cli',- target: 'codex',- })- ).toBe('/tmp/test-home/.codex/skills/composio-cli');- expect(- resolveTargetSkillPath({- home: '/tmp/test-home',- path,- skillName: 'composio-cli',- target: 'openclaw',- })- ).toBe('/tmp/test-home/.openclaw/skills/composio-cli');- });+ it.effect('resolves the agent-specific skill path', () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ expect(+ resolveTargetSkillPath({+ home: '/tmp/test-home',+ path,+ skillName: 'composio-cli',+ target: 'claude',+ })+ ).toBe('/tmp/test-home/.claude/skills/composio-cli');+ expect(+ resolveTargetSkillPath({+ home: '/tmp/test-home',+ path,+ skillName: 'composio-cli',+ target: 'codex',+ })+ ).toBe('/tmp/test-home/.codex/skills/composio-cli');+ expect(+ resolveTargetSkillPath({+ home: '/tmp/test-home',+ path,+ skillName: 'composio-cli',+ target: 'openclaw',+ })+ ).toBe('/tmp/test-home/.openclaw/skills/composio-cli');+ }).pipe(Effect.provide(Path.layer))+ );- it('prefers an explicit running release tag over channel discovery', async () => {- const releaseTag = '@composio/[email protected]';- const tag = await makeResolveEffect([], {- channel: 'stable',- releaseTag,- }).pipe(Effect.runPromise);+ it.effect('prefers an explicit running release tag over channel discovery', () =>+ Effect.gen(function* () {+ const releaseTag = '@composio/[email protected]';+ const tag = yield* makeResolveEffect([], {+ channel: 'stable',+ releaseTag,+ });- expect(tag).toBe(releaseTag);- });+ expect(tag).toBe(releaseTag);+ })+ );++ it.scoped('fails with a typed decode error for malformed GitHub release lists', () =>+ Effect.gen(function* () {+ const apiBaseUrl = yield* startTestHttpServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ tag_name: '@composio/[email protected]' }));+ });++ const error = yield* Effect.flip(+ makeResolveEffect(+ [+ ['GITHUB_API_BASE_URL', apiBaseUrl],+ ['GITHUB_OWNER', 'test-owner'],+ ['GITHUB_REPO', 'test-repo'],+ ],+ { channel: 'stable' }+ )+ );++ expect(error).toBeInstanceOf(CliReleaseResolutionError);+ if (error instanceof CliReleaseResolutionError) {+ expect(error.reason).toBe('decode');+ expect(error.cause).toBeDefined();+ }+ })+ );- it.each(TARGET_SCENARIOS)('installs over %s target', async (_description, prepareTarget) => {- await withSkillRelease(TEST_SKILL_ZIP, async apiBaseUrl => {+ it.scoped('fails with a typed decode error for malformed skill release metadata', () =>+ Effect.gen(function* () {+ const apiBaseUrl = yield* startTestHttpServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ assets: [{ name: 'composio-skill.zip' }] }));+ });++ const home = tempy.temporaryDirectory();+ const error = yield* Effect.flip(makeInstallEffect(home, apiBaseUrl));++ // The install pipeline still fails with a plain Error until the+ // typed-error slice (PR 8 of this stack) introduces SkillInstallError.+ expect(error).toBeInstanceOf(Error);+ if (error instanceof Error) {+ expect(error.message).toContain('Failed to download skill');+ }+ })+ );++ it.scoped.each(TARGET_SCENARIOS)('installs over %s target', ([, prepareTarget]) =>+ Effect.gen(function* () {+ const apiBaseUrl = yield* startSkillReleaseServer(TEST_SKILL_ZIP);+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const home = tempy.temporaryDirectory();const target = path.join(home, '.claude', 'skills', 'composio-cli');const canonicalSkill = path.join(home, '.agents', 'skills', 'composio-cli');- await Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const platformPath = yield* Path.Path;- yield* prepareTarget(fs, platformPath, home, target);- }).pipe(Effect.provide(TestPlatform), Effect.runPromise);+ yield* prepareTarget(fs, path, home, target);- await makeInstallEffect(home, apiBaseUrl).pipe(Effect.runPromise);+ yield* makeInstallEffect(home, apiBaseUrl);- await Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const platformPath = yield* Path.Path;- expect(yield* fs.readFileString(platformPath.join(target, 'SKILL.md'))).toBe(- '# composio-cli\n'- );- expect(- yield* fs.readFileString(platformPath.join(canonicalSkill, SKILL_RELEASE_TAG_FILENAME))- ).toBe(`${TEST_RELEASE_TAG}\n`);- expect(yield* fs.readLink(target)).toBe(- platformPath.relative(platformPath.dirname(target), canonicalSkill)- );- expect(yield* fs.exists(platformPath.join(home, '.agents', '.tmp-skill-install'))).toBe(- false- );- }).pipe(Effect.provide(TestPlatform), Effect.runPromise);- });- });+ expect(yield* fs.readFileString(path.join(target, 'SKILL.md'))).toBe('# composio-cli\n');+ expect(yield* fs.readFileString(path.join(canonicalSkill, SKILL_RELEASE_TAG_FILENAME))).toBe(+ `${TEST_RELEASE_TAG}\n`+ );+ expect(yield* fs.readLink(target)).toBe(path.relative(path.dirname(target), canonicalSkill));+ expect(yield* fs.exists(path.join(home, '.agents', '.tmp-skill-install'))).toBe(false);+ }).pipe(Effect.provide(TestPlatform))+ );- it('removes the temporary install directory after extraction fails', async () => {- await withSkillRelease(new TextEncoder().encode('not a zip'), async apiBaseUrl => {+ it.scoped('removes the temporary install directory after extraction fails', () =>+ Effect.gen(function* () {+ const apiBaseUrl = yield* startSkillReleaseServer(new TextEncoder().encode('not a zip'));const home = tempy.temporaryDirectory();- const exit = await makeInstallEffect(home, apiBaseUrl).pipe(Effect.exit, Effect.runPromise);+ const exit = yield* Effect.exit(makeInstallEffect(home, apiBaseUrl));expect(Exit.isFailure(exit)).toBe(true);- expect(- await FileSystem.FileSystem.pipe(- Effect.flatMap(fs => fs.exists(path.join(home, '.agents', '.tmp-skill-install'))),- Effect.provide(TestPlatform),- Effect.runPromise- )- ).toBe(false);- });- });- it('resolves the latest stable release when the stable channel is requested', async () => {- vi.stubGlobal('Bun', { which: vi.fn(() => null) });-- try {- await withHttpServer(- (_req, res) => {- res.writeHead(200, { 'content-type': 'application/json' });- res.end(- JSON.stringify([- {- tag_name: '@composio/[email protected]',- draft: false,- prerelease: true,- assets: [- {- name: 'composio-skill.zip',- browser_download_url: 'http://127.0.0.1/beta-skill.zip',- },- ],- },- {- tag_name: '@composio/[email protected]',- draft: false,- prerelease: false,- assets: [- {- name: 'composio-skill.zip',- browser_download_url: 'http://127.0.0.1/stable-skill.zip',- },- ],- },- {- tag_name: '@composio/[email protected]',- draft: false,- prerelease: false,- assets: [- {- name: 'composio-linux-x64.zip',- browser_download_url: 'http://127.0.0.1/no-skill.zip',- },- ],- },- ])- );- },- async apiBaseUrl => {- const tag = await makeResolveEffect(- [- ['GITHUB_API_BASE_URL', apiBaseUrl],- ['GITHUB_OWNER', 'test-owner'],- ['GITHUB_REPO', 'test-repo'],- ],- { channel: 'stable' }- ).pipe(Effect.runPromise);-- expect(tag).toBe('@composio/[email protected]');- }+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ expect(yield* fs.exists(path.join(home, '.agents', '.tmp-skill-install'))).toBe(false);+ }).pipe(Effect.provide(TestPlatform))+ );++ it.scoped('resolves the latest stable release when the stable channel is requested', () =>+ Effect.gen(function* () {+ yield* stubBunWhichMiss;+ const apiBaseUrl = yield* startTestHttpServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(+ JSON.stringify([+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: true,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/beta-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: false,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/stable-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: false,+ assets: [+ {+ name: 'composio-linux-x64.zip',+ browser_download_url: 'http://127.0.0.1/no-skill.zip',+ },+ ],+ },+ ])+ );+ });++ const tag = yield* makeResolveEffect(+ [+ ['GITHUB_API_BASE_URL', apiBaseUrl],+ ['GITHUB_OWNER', 'test-owner'],+ ['GITHUB_REPO', 'test-repo'],+ ],+ { channel: 'stable' });- } finally {- vi.unstubAllGlobals();- vi.restoreAllMocks();- }- });- it('resolves the latest beta release when the beta channel is requested', async () => {- vi.stubGlobal('Bun', { which: vi.fn(() => null) });-- try {- await withHttpServer(- (_req, res) => {- res.writeHead(200, { 'content-type': 'application/json' });- res.end(- JSON.stringify([- {- tag_name: '@composio/[email protected]',- draft: false,- prerelease: true,- assets: [- {- name: 'composio-skill.zip',- browser_download_url: 'http://127.0.0.1/beta-1-skill.zip',- },- ],- },- {- tag_name: '@composio/[email protected]',- draft: false,- prerelease: true,- assets: [- {- name: 'composio-skill.zip',- browser_download_url: 'http://127.0.0.1/beta-3-skill.zip',- },- ],- },- {- tag_name: '@composio/[email protected]',- draft: false,- prerelease: false,- assets: [- {- name: 'composio-skill.zip',- browser_download_url: 'http://127.0.0.1/stable-skill.zip',- },- ],- },- ])- );- },- async apiBaseUrl => {- const tag = await makeResolveEffect(- [- ['GITHUB_API_BASE_URL', apiBaseUrl],- ['GITHUB_OWNER', 'test-owner'],- ['GITHUB_REPO', 'test-repo'],- ],- { channel: 'beta' }- ).pipe(Effect.runPromise);-- expect(tag).toBe('@composio/[email protected]');- }+ expect(tag).toBe('@composio/[email protected]');+ })+ );++ it.scoped('resolves the latest beta release when the beta channel is requested', () =>+ Effect.gen(function* () {+ yield* stubBunWhichMiss;+ const apiBaseUrl = yield* startTestHttpServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(+ JSON.stringify([+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: true,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/beta-1-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: true,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/beta-3-skill.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',+ draft: false,+ prerelease: false,+ assets: [+ {+ name: 'composio-skill.zip',+ browser_download_url: 'http://127.0.0.1/stable-skill.zip',+ },+ ],+ },+ ])+ );+ });++ const tag = yield* makeResolveEffect(+ [+ ['GITHUB_API_BASE_URL', apiBaseUrl],+ ['GITHUB_OWNER', 'test-owner'],+ ['GITHUB_REPO', 'test-repo'],+ ],+ { channel: 'beta' });- } finally {- vi.unstubAllGlobals();- vi.restoreAllMocks();- }- });++ expect(tag).toBe('@composio/[email protected]');+ })+ );});diff --git a/ts/packages/cli/test/src/models/project-keys.test.ts b/ts/packages/cli/test/src/models/project-keys.test.tsindex 65cff6563..b0c592f8f 100644--- a/ts/packages/cli/test/src/models/project-keys.test.ts+++ b/ts/packages/cli/test/src/models/project-keys.test.ts@@ -1,196 +1,231 @@-import { describe, it, expect } from 'vitest';-import { Effect, Option } from 'effect';+import { describe, it, expect } from '@effect/vitest';+import { Effect, Option, ParseResult } from 'effect';import { ProjectKeys, projectKeysFromJSON, projectKeysToJSON } from 'src/models/project-keys';describe('ProjectKeys', () => {describe('decode from JSON', () => {- it('decodes valid JSON with required fields only', () => {- const json = JSON.stringify({ org_id: 'abc', project_id: 'def' });-- const result = Effect.runSync(projectKeysFromJSON(json));-- expect(result.orgId).toBe('abc');- expect(result.projectId).toBe('def');- expect(Option.isNone(result.projectName)).toBe(true);- expect(Option.isNone(result.orgName)).toBe(true);- expect(Option.isNone(result.email)).toBe(true);- expect(Option.isNone(result.testUserId)).toBe(true);- });-- it('decodes valid JSON with all fields', () => {- const json = JSON.stringify({- org_id: 'abc',- project_id: 'def',- project_name: 'My Project',- org_name: 'My Org',- email: '[email protected]',- test_user_id: 'pg-test-user-123',- });-- const result = Effect.runSync(projectKeysFromJSON(json));-- expect(result.orgId).toBe('abc');- expect(result.projectId).toBe('def');- expect(Option.getOrUndefined(result.projectName)).toBe('My Project');- expect(Option.getOrUndefined(result.orgName)).toBe('My Org');- expect(Option.getOrUndefined(result.email)).toBe('[email protected]');- expect(Option.getOrUndefined(result.testUserId)).toBe('pg-test-user-123');- });-- it('decodes null optional fields as Option.none()', () => {- const json = JSON.stringify({- org_id: 'abc',- project_id: 'def',- project_name: null,- org_name: null,- email: null,- test_user_id: null,- });-- const result = Effect.runSync(projectKeysFromJSON(json));-- expect(result.orgId).toBe('abc');- expect(result.projectId).toBe('def');- expect(Option.isNone(result.projectName)).toBe(true);- expect(Option.isNone(result.orgName)).toBe(true);- expect(Option.isNone(result.email)).toBe(true);- expect(Option.isNone(result.testUserId)).toBe(true);- });-- it('ignores extra keys in decoded JSON', () => {- const json = JSON.stringify({- org_id: 'abc',- project_id: 'def',- future_field: 'unknown',- });-- // Should not throw -- onExcessProperty: 'ignore' silently drops extra keys- const result = Effect.runSync(projectKeysFromJSON(json));- expect(result.orgId).toBe('abc');- expect(result.projectId).toBe('def');- });-- it('fails on missing org_id', () => {- const json = JSON.stringify({ project_id: 'def' });- expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();- });-- it('fails on missing project_id', () => {- const json = JSON.stringify({ org_id: 'abc' });- expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();- });-- it('fails on non-string org_id', () => {- const json = JSON.stringify({ org_id: 123, project_id: 'def' });- expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();- });-- it('fails on non-string project_id', () => {- const json = JSON.stringify({ org_id: 'abc', project_id: true });- expect(() => Effect.runSync(projectKeysFromJSON(json))).toThrow();- });-- it('fails on invalid JSON', () => {- expect(() => Effect.runSync(projectKeysFromJSON('not json'))).toThrow();- });-- it('accepts empty strings for required fields', () => {- const json = JSON.stringify({ org_id: '', project_id: '' });- const result = Effect.runSync(projectKeysFromJSON(json));- expect(result.orgId).toBe('');- expect(result.projectId).toBe('');- });+ it.effect('decodes valid JSON with required fields only', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({ org_id: 'abc', project_id: 'def' });++ const result = yield* projectKeysFromJSON(json);++ expect(result.orgId).toBe('abc');+ expect(result.projectId).toBe('def');+ expect(Option.isNone(result.projectName)).toBe(true);+ expect(Option.isNone(result.orgName)).toBe(true);+ expect(Option.isNone(result.email)).toBe(true);+ expect(Option.isNone(result.testUserId)).toBe(true);+ })+ );++ it.effect('decodes valid JSON with all fields', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({+ org_id: 'abc',+ project_id: 'def',+ project_name: 'My Project',+ org_name: 'My Org',+ email: '[email protected]',+ test_user_id: 'pg-test-user-123',+ });++ const result = yield* projectKeysFromJSON(json);++ expect(result.orgId).toBe('abc');+ expect(result.projectId).toBe('def');+ expect(Option.getOrUndefined(result.projectName)).toBe('My Project');+ expect(Option.getOrUndefined(result.orgName)).toBe('My Org');+ expect(Option.getOrUndefined(result.email)).toBe('[email protected]');+ expect(Option.getOrUndefined(result.testUserId)).toBe('pg-test-user-123');+ })+ );++ it.effect('decodes null optional fields as Option.none()', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({+ org_id: 'abc',+ project_id: 'def',+ project_name: null,+ org_name: null,+ email: null,+ test_user_id: null,+ });++ const result = yield* projectKeysFromJSON(json);++ expect(result.orgId).toBe('abc');+ expect(result.projectId).toBe('def');+ expect(Option.isNone(result.projectName)).toBe(true);+ expect(Option.isNone(result.orgName)).toBe(true);+ expect(Option.isNone(result.email)).toBe(true);+ expect(Option.isNone(result.testUserId)).toBe(true);+ })+ );++ it.effect('ignores extra keys in decoded JSON', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({+ org_id: 'abc',+ project_id: 'def',+ future_field: 'unknown',+ });++ // Should not fail -- onExcessProperty: 'ignore' silently drops extra keys+ const result = yield* projectKeysFromJSON(json);+ expect(result.orgId).toBe('abc');+ expect(result.projectId).toBe('def');+ })+ );++ it.effect('fails on missing org_id', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({ project_id: 'def' });+ const error = yield* Effect.flip(projectKeysFromJSON(json));+ expect(error).toBeInstanceOf(ParseResult.ParseError);+ })+ );++ it.effect('fails on missing project_id', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({ org_id: 'abc' });+ const error = yield* Effect.flip(projectKeysFromJSON(json));+ expect(error).toBeInstanceOf(ParseResult.ParseError);+ })+ );++ it.effect('fails on non-string org_id', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({ org_id: 123, project_id: 'def' });+ const error = yield* Effect.flip(projectKeysFromJSON(json));+ expect(error).toBeInstanceOf(ParseResult.ParseError);+ })+ );++ it.effect('fails on non-string project_id', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({ org_id: 'abc', project_id: true });+ const error = yield* Effect.flip(projectKeysFromJSON(json));+ expect(error).toBeInstanceOf(ParseResult.ParseError);+ })+ );++ it.effect('fails on invalid JSON', () =>+ Effect.gen(function* () {+ const error = yield* Effect.flip(projectKeysFromJSON('not json'));+ expect(error).toBeInstanceOf(ParseResult.ParseError);+ })+ );++ it.effect('accepts empty strings for required fields', () =>+ Effect.gen(function* () {+ const json = JSON.stringify({ org_id: '', project_id: '' });+ const result = yield* projectKeysFromJSON(json);+ expect(result.orgId).toBe('');+ expect(result.projectId).toBe('');+ })+ );});describe('encode to JSON', () => {- it('encodes ProjectKeys with Some values', () => {- const keys: ProjectKeys = {- orgId: 'abc',- projectId: 'def',- projectName: Option.some('My Project'),- orgName: Option.some('My Org'),- email: Option.some('[email protected]'),- testUserId: Option.some('pg-test-user-123'),- };-- const json = Effect.runSync(projectKeysToJSON(keys));- const parsed = JSON.parse(json);-- expect(parsed.org_id).toBe('abc');- expect(parsed.project_id).toBe('def');- expect(parsed.project_name).toBe('My Project');- expect(parsed.org_name).toBe('My Org');- expect(parsed.email).toBe('[email protected]');- expect(parsed.test_user_id).toBe('pg-test-user-123');- });-- it('encodes None optional fields as null', () => {- const keys: ProjectKeys = {- orgId: 'abc',- projectId: 'def',- projectName: Option.none(),- orgName: Option.none(),- email: Option.none(),- testUserId: Option.none(),- };-- const json = Effect.runSync(projectKeysToJSON(keys));- const parsed = JSON.parse(json);-- expect(parsed.org_id).toBe('abc');- expect(parsed.project_id).toBe('def');- expect(parsed.project_name).toBeNull();- expect(parsed.org_name).toBeNull();- expect(parsed.email).toBeNull();- expect(parsed.test_user_id).toBeNull();- });+ it.effect('encodes ProjectKeys with Some values', () =>+ Effect.gen(function* () {+ const keys: ProjectKeys = {+ orgId: 'abc',+ projectId: 'def',+ projectName: Option.some('My Project'),+ orgName: Option.some('My Org'),+ email: Option.some('[email protected]'),+ testUserId: Option.some('pg-test-user-123'),+ };++ const json = yield* projectKeysToJSON(keys);+ const parsed = JSON.parse(json);++ expect(parsed.org_id).toBe('abc');+ expect(parsed.project_id).toBe('def');+ expect(parsed.project_name).toBe('My Project');+ expect(parsed.org_name).toBe('My Org');+ expect(parsed.email).toBe('[email protected]');+ expect(parsed.test_user_id).toBe('pg-test-user-123');+ })+ );++ it.effect('encodes None optional fields as null', () =>+ Effect.gen(function* () {+ const keys: ProjectKeys = {+ orgId: 'abc',+ projectId: 'def',+ projectName: Option.none(),+ orgName: Option.none(),+ email: Option.none(),+ testUserId: Option.none(),+ };++ const json = yield* projectKeysToJSON(keys);+ const parsed = JSON.parse(json);++ expect(parsed.org_id).toBe('abc');+ expect(parsed.project_id).toBe('def');+ expect(parsed.project_name).toBeNull();+ expect(parsed.org_name).toBeNull();+ expect(parsed.email).toBeNull();+ expect(parsed.test_user_id).toBeNull();+ })+ );});describe('round-trip', () => {- it('encode then decode preserves Some values', () => {- const original: ProjectKeys = {- orgId: 'org-123',- projectId: 'proj-456',- projectName: Option.some('Test Project'),- orgName: Option.some('Test Org'),- email: Option.some('[email protected]'),- testUserId: Option.some('pg-test-user-123'),- };-- const json = Effect.runSync(projectKeysToJSON(original));- const decoded = Effect.runSync(projectKeysFromJSON(json));-- expect(decoded.orgId).toBe(original.orgId);- expect(decoded.projectId).toBe(original.projectId);- expect(Option.getOrUndefined(decoded.projectName)).toBe(- Option.getOrUndefined(original.projectName)- );- expect(Option.getOrUndefined(decoded.orgName)).toBe(Option.getOrUndefined(original.orgName));- expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));- expect(Option.getOrUndefined(decoded.testUserId)).toBe(- Option.getOrUndefined(original.testUserId)- );- });-- it('encode then decode preserves None values', () => {- const original: ProjectKeys = {- orgId: 'org-123',- projectId: 'proj-456',- projectName: Option.none(),- orgName: Option.none(),- email: Option.none(),- testUserId: Option.none(),- };-- const json = Effect.runSync(projectKeysToJSON(original));- const decoded = Effect.runSync(projectKeysFromJSON(json));-- expect(decoded.orgId).toBe(original.orgId);- expect(decoded.projectId).toBe(original.projectId);- expect(Option.isNone(decoded.projectName)).toBe(true);- expect(Option.isNone(decoded.orgName)).toBe(true);- expect(Option.isNone(decoded.email)).toBe(true);- expect(Option.isNone(decoded.testUserId)).toBe(true);- });+ it.effect('encode then decode preserves Some values', () =>+ Effect.gen(function* () {+ const original: ProjectKeys = {+ orgId: 'org-123',+ projectId: 'proj-456',+ projectName: Option.some('Test Project'),+ orgName: Option.some('Test Org'),+ email: Option.some('[email protected]'),+ testUserId: Option.some('pg-test-user-123'),+ };++ const json = yield* projectKeysToJSON(original);+ const decoded = yield* projectKeysFromJSON(json);++ expect(decoded.orgId).toBe(original.orgId);+ expect(decoded.projectId).toBe(original.projectId);+ expect(Option.getOrUndefined(decoded.projectName)).toBe(+ Option.getOrUndefined(original.projectName)+ );+ expect(Option.getOrUndefined(decoded.orgName)).toBe(+ Option.getOrUndefined(original.orgName)+ );+ expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));+ expect(Option.getOrUndefined(decoded.testUserId)).toBe(+ Option.getOrUndefined(original.testUserId)+ );+ })+ );++ it.effect('encode then decode preserves None values', () =>+ Effect.gen(function* () {+ const original: ProjectKeys = {+ orgId: 'org-123',+ projectId: 'proj-456',+ projectName: Option.none(),+ orgName: Option.none(),+ email: Option.none(),+ testUserId: Option.none(),+ };++ const json = yield* projectKeysToJSON(original);+ const decoded = yield* projectKeysFromJSON(json);++ expect(decoded.orgId).toBe(original.orgId);+ expect(decoded.projectId).toBe(original.projectId);+ expect(Option.isNone(decoded.projectName)).toBe(true);+ expect(Option.isNone(decoded.orgName)).toBe(true);+ expect(Option.isNone(decoded.email)).toBe(true);+ expect(Option.isNone(decoded.testUserId)).toBe(true);+ })+ );});});diff --git a/ts/packages/cli/test/src/services/composio-clients.test.ts b/ts/packages/cli/test/src/services/composio-clients.test.tsindex 7290b3102..5d2a53359 100644--- a/ts/packages/cli/test/src/services/composio-clients.test.ts+++ b/ts/packages/cli/test/src/services/composio-clients.test.ts@@ -1,4 +1,5 @@-import { afterEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from '@effect/vitest';+import { afterEach, vi } from 'vitest';import { Effect } from 'effect';import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';@@ -15,36 +16,42 @@ describe('getSessionInfoByUserApiKey org context', () => {// The response body does not satisfy SessionInfoResponse, so decoding fails —// but the fetch call (whose headers we assert) has already happened by then.- const runIgnoringDecode = (params: { baseURL: string; userApiKey: string; orgId?: string }) =>- Effect.runPromise(getSessionInfoByUserApiKey(params).pipe(Effect.ignore));-- it('[Given] orgId [Then] forwards it as x-org-id so the backend honors the switched org', async () => {- const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());-- await runIgnoringDecode({- baseURL: 'https://backend.composio.dev',- userApiKey: 'uak_test',- orgId: 'ok_selected_org',- });-- const [url, init] = fetchSpy.mock.calls[0]!;- expect(String(url)).toContain('/api/v3/auth/session/info');- const headers = new Headers((init as RequestInit).headers);- expect(headers.get('x-user-api-key')).toBe('uak_test');- expect(headers.get('x-org-id')).toBe('ok_selected_org');- });-- it('[Given] no orgId [Then] omits x-org-id (login-time behavior is unchanged)', async () => {- const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());-- await runIgnoringDecode({- baseURL: 'https://backend.composio.dev',- userApiKey: 'uak_test',- });-- const [, init] = fetchSpy.mock.calls[0]!;- const headers = new Headers((init as RequestInit).headers);- expect(headers.get('x-user-api-key')).toBe('uak_test');- expect(headers.has('x-org-id')).toBe(false);- });+ const callIgnoringDecode = (params: { baseURL: string; userApiKey: string; orgId?: string }) =>+ getSessionInfoByUserApiKey(params).pipe(Effect.ignore);++ it.effect(+ '[Given] orgId [Then] forwards it as x-org-id so the backend honors the switched org',+ () =>+ Effect.gen(function* () {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());++ yield* callIgnoringDecode({+ baseURL: 'https://backend.composio.dev',+ userApiKey: 'uak_test',+ orgId: 'ok_selected_org',+ });++ const [url, init] = fetchSpy.mock.calls[0]!;+ expect(String(url)).toContain('/api/v3/auth/session/info');+ const headers = new Headers((init as RequestInit).headers);+ expect(headers.get('x-user-api-key')).toBe('uak_test');+ expect(headers.get('x-org-id')).toBe('ok_selected_org');+ })+ );++ it.effect('[Given] no orgId [Then] omits x-org-id (login-time behavior is unchanged)', () =>+ Effect.gen(function* () {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyOkResponse());++ yield* callIgnoringDecode({+ baseURL: 'https://backend.composio.dev',+ userApiKey: 'uak_test',+ });++ const [, init] = fetchSpy.mock.calls[0]!;+ const headers = new Headers((init as RequestInit).headers);+ expect(headers.get('x-user-api-key')).toBe('uak_test');+ expect(headers.has('x-org-id')).toBe(false);+ })+ );});diff --git a/ts/packages/cli/test/src/services/config.test.ts b/ts/packages/cli/test/src/services/config.test.tsindex a606c069c..4793e4f8e 100644--- a/ts/packages/cli/test/src/services/config.test.ts+++ b/ts/packages/cli/test/src/services/config.test.ts@@ -1,4 +1,4 @@-import { describe, it, vi } from '@effect/vitest';+import { beforeEach, describe, it, vi } from '@effect/vitest';import { assertEquals } from '@effect/vitest/utils';import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';@@ -13,314 +13,340 @@ describe('Config', () => {Effect.withConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)));describe('APP_CONFIG', () => {- it('[When] no map entry is set', () => {- const map = new Map([]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://backend.composio.dev',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- WEB_URL: 'https://dashboard.composio.dev/',+ it.effect('[When] no map entry is set', () =>+ Effect.gen(function* () {+ const map = new Map([]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ WEB_URL: 'https://dashboard.composio.dev/',+ })+ );+ })+ );++ it.effect('[When] map entries are set without `COMPOSIO_` prefix', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['USER_API_KEY', 'api_key'],+ ['BASE_URL', 'https://test.localhost'],+ ['CACHE_DIR', '~/.composio'],+ ['LOG_LEVEL', 'info'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ WEB_URL: 'https://dashboard.composio.dev/',+ })+ );+ })+ );++ it.effect('[When] env variables are set with `COMPOSIO_` prefix', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_USER_API_KEY', 'api_key'],+ ['COMPOSIO_BASE_URL', 'https://test.localhost'],+ ['COMPOSIO_WEB_URL', 'https://test.localhost'],+ ['COMPOSIO_CACHE_DIR', '~/.composio'],+ ['COMPOSIO_LOG_LEVEL', 'info'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.some('api_key'),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://test.localhost',+ WEB_URL: 'https://test.localhost',+ CACHE_DIR: Option.some('~/.composio'),+ LOG_LEVEL: Option.some(LogLevel.Info),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ WEB_URL: 'https://dashboard.composio.dev/',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: false,+ })+ );+ })+ );++ it.effect('[When] COMPOSIO_ENVIRONMENT is "production"', () =>+ Effect.gen(function* () {+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'production']]) satisfies Map<+ string,+ string+ >;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('production'),+ BASE_URL: constants.DEFAULT_BASE_URL,+ WEB_URL: constants.DEFAULT_WEB_URL,+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect('[When] COMPOSIO_ENVIRONMENT is "staging"', () =>+ Effect.gen(function* () {+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('staging'),+ BASE_URL: constants.STAGING_BASE_URL,+ WEB_URL: constants.STAGING_WEB_URL,+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect(+ '[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_BASE_URL is set',+ () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_ENVIRONMENT', 'staging'],+ ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('staging'),+ BASE_URL: 'https://custom-backend.localhost',+ WEB_URL: constants.STAGING_WEB_URL,+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );})- );- });-- it('[When] map entries are set without `COMPOSIO_` prefix', () => {- const map = new Map([- ['USER_API_KEY', 'api_key'],- ['BASE_URL', 'https://test.localhost'],- ['CACHE_DIR', '~/.composio'],- ['LOG_LEVEL', 'info'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://backend.composio.dev',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- WEB_URL: 'https://dashboard.composio.dev/',+ );++ it.effect(+ '[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_WEB_URL is set',+ () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_ENVIRONMENT', 'staging'],+ ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('staging'),+ BASE_URL: constants.STAGING_BASE_URL,+ WEB_URL: 'https://custom-web.localhost',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );})- );- });-- it('[When] env variables are set with `COMPOSIO_` prefix', () => {- const map = new Map([- ['COMPOSIO_USER_API_KEY', 'api_key'],- ['COMPOSIO_BASE_URL', 'https://test.localhost'],- ['COMPOSIO_WEB_URL', 'https://test.localhost'],- ['COMPOSIO_CACHE_DIR', '~/.composio'],- ['COMPOSIO_LOG_LEVEL', 'info'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.some('api_key'),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://test.localhost',- WEB_URL: 'https://test.localhost',- CACHE_DIR: Option.some('~/.composio'),- LOG_LEVEL: Option.some(LogLevel.Info),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () => {- const map = new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']]) satisfies Map<- string,- string- >;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://backend.composio.dev',- WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: false,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is "production"', () => {- const map = new Map([['COMPOSIO_ENVIRONMENT', 'production']]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('production'),- BASE_URL: constants.DEFAULT_BASE_URL,- WEB_URL: constants.DEFAULT_WEB_URL,- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {- const map = new Map([['COMPOSIO_ENVIRONMENT', 'staging']]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('staging'),- BASE_URL: constants.STAGING_BASE_URL,- WEB_URL: constants.STAGING_WEB_URL,- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_BASE_URL is set', () => {- const map = new Map([- ['COMPOSIO_ENVIRONMENT', 'staging'],- ['COMPOSIO_BASE_URL', 'https://custom-backend.localhost'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('staging'),- BASE_URL: 'https://custom-backend.localhost',- WEB_URL: constants.STAGING_WEB_URL,- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit COMPOSIO_WEB_URL is set', () => {- const map = new Map([- ['COMPOSIO_ENVIRONMENT', 'staging'],- ['COMPOSIO_WEB_URL', 'https://custom-web.localhost'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('staging'),- BASE_URL: constants.STAGING_BASE_URL,- WEB_URL: 'https://custom-web.localhost',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is an unknown value', () => {- const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('unknown'),- BASE_URL: constants.DEFAULT_BASE_URL,- WEB_URL: constants.DEFAULT_WEB_URL,- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });+ );++ it.effect('[When] COMPOSIO_ENVIRONMENT is an unknown value', () =>+ Effect.gen(function* () {+ const map = new Map([['COMPOSIO_ENVIRONMENT', 'unknown']]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('unknown'),+ BASE_URL: constants.DEFAULT_BASE_URL,+ WEB_URL: constants.DEFAULT_WEB_URL,+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );});describe('DEBUG_OVERRIDE_CONFIG', () => {- it('[When] no map entries variable is set', () => {- const map = new Map([]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(- Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))- )- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.none(),- VERSION: Option.none(),- })- );- });+ it.effect('[When] no map entries variable is set', () =>+ Effect.gen(function* () {+ const map = new Map([]) satisfies Map<string, string>;- it('[When] map entries are set without `DEBUG_OVERRIDE_` prefix', () => {- const map = new Map([- ['UPGRADE_TARGET', 'upgrade_target'],- ['VERSION', 'x.x.x'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(+ const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))- )- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.none(),- VERSION: Option.none(),- })- );- });-- it('[When] map entries are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix', () => {- const map = new Map([- ['COMPOSIO_UPGRADE_TARGET', 'upgrade_target'],- ['COMPOSIO_VERSION', 'x.x.x'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.none(),+ VERSION: Option.none(),+ })+ );+ })+ );++ it.effect('[When] map entries are set without `DEBUG_OVERRIDE_` prefix', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['UPGRADE_TARGET', 'upgrade_target'],+ ['VERSION', 'x.x.x'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))- )- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.none(),- VERSION: Option.none(),+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.none(),+ VERSION: Option.none(),+ })+ );+ })+ );++ it.effect(+ '[When] map entries are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix',+ () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_UPGRADE_TARGET', 'upgrade_target'],+ ['COMPOSIO_VERSION', 'x.x.x'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.none(),+ VERSION: Option.none(),+ })+ );})- );- });- it('[When] map entries are set with `DEBUG_OVERRIDE_` prefix', () => {- const map = new Map([- ['DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target'],- ['DEBUG_OVERRIDE_VERSION', 'x.x.x'],- ]) satisfies Map<string, string>;-- const actual = Effect.runSync(- withMapConfigProvider(map)(+ );+ it.effect('[When] map entries are set with `DEBUG_OVERRIDE_` prefix', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target'],+ ['DEBUG_OVERRIDE_VERSION', 'x.x.x'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))- )- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.some('upgrade_target'),- VERSION: Option.some('x.x.x'),- })- );- });+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.some('upgrade_target'),+ VERSION: Option.some('x.x.x'),+ })+ );+ })+ );});});@@ -329,218 +355,255 @@ describe('Config', () => {extendConfigProvider(ConfigProvider.fromEnv()));+ // These cases assert what the config resolves from a clean environment,+ // but the developer's shell (direnv) and the shared vitest setup both+ // export COMPOSIO_* variables. Neutralize every APP_CONFIG input.+ beforeEach(() => {+ vi.stubEnv('COMPOSIO_USER_API_KEY', undefined);+ vi.stubEnv('COMPOSIO_ENVIRONMENT', undefined);+ vi.stubEnv('COMPOSIO_BASE_URL', undefined);+ vi.stubEnv('COMPOSIO_WEB_URL', undefined);+ vi.stubEnv('COMPOSIO_CACHE_DIR', undefined);+ vi.stubEnv('COMPOSIO_LOG_LEVEL', undefined);+ vi.stubEnv('COMPOSIO_ORG_ID', undefined);+ vi.stubEnv('COMPOSIO_PROJECT_ID', undefined);+ vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', undefined);+ });+describe('APP_CONFIG', () => {- it('[When] no env variable is set', () => {- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://backend.composio.dev',- WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] env variables are set without `COMPOSIO_` prefix', () => {- vi.stubEnv('USER_API_KEY', 'api_key');- vi.stubEnv('BASE_URL', 'https://test.localhost');- vi.stubEnv('CACHE_DIR', '~/.composio');- vi.stubEnv('LOG_LEVEL', 'info');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://backend.composio.dev',- WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] env variables are set with `COMPOSIO_` prefix', () => {- vi.stubEnv('COMPOSIO_USER_API_KEY', 'api_key');- vi.stubEnv('COMPOSIO_BASE_URL', 'https://test.localhost');- vi.stubEnv('COMPOSIO_WEB_URL', 'https://test.localhost');- vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');- vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.some('api_key'),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://test.localhost',- WEB_URL: 'https://test.localhost',- CACHE_DIR: Option.some('~/.composio'),- LOG_LEVEL: Option.some(LogLevel.Info),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () => {- vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.none(),- BASE_URL: 'https://backend.composio.dev',- WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: false,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is "staging"', () => {- vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('staging'),- BASE_URL: constants.STAGING_BASE_URL,- WEB_URL: constants.STAGING_WEB_URL,- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });-- it('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit URLs override', () => {- vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');- vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');- vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- USER_API_KEY: Option.none(),- ENVIRONMENT: Option.some('staging'),- BASE_URL: 'https://custom.localhost',- WEB_URL: 'https://custom-web.localhost',- CACHE_DIR: Option.none(),- LOG_LEVEL: Option.none(),- ORG_ID: Option.none(),- PROJECT_ID: Option.none(),- DISABLE_CONNECTED_ACCOUNT_CACHE: true,- })- );- });+ it.effect('[When] no env variable is set', () =>+ Effect.gen(function* () {+ const actual = yield* withEnvConfigProvider(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ WEB_URL: 'https://dashboard.composio.dev/',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect('[When] env variables are set without `COMPOSIO_` prefix', () =>+ Effect.gen(function* () {+ vi.stubEnv('USER_API_KEY', 'api_key');+ vi.stubEnv('BASE_URL', 'https://test.localhost');+ vi.stubEnv('CACHE_DIR', '~/.composio');+ vi.stubEnv('LOG_LEVEL', 'info');++ const actual = yield* withEnvConfigProvider(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ WEB_URL: 'https://dashboard.composio.dev/',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect('[When] env variables are set with `COMPOSIO_` prefix', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_USER_API_KEY', 'api_key');+ vi.stubEnv('COMPOSIO_BASE_URL', 'https://test.localhost');+ vi.stubEnv('COMPOSIO_WEB_URL', 'https://test.localhost');+ vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');+ vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');++ const actual = yield* withEnvConfigProvider(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.some('api_key'),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://test.localhost',+ WEB_URL: 'https://test.localhost',+ CACHE_DIR: Option.some('~/.composio'),+ LOG_LEVEL: Option.some(LogLevel.Info),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false');++ const actual = yield* withEnvConfigProvider(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.none(),+ BASE_URL: 'https://backend.composio.dev',+ WEB_URL: 'https://dashboard.composio.dev/',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: false,+ })+ );+ })+ );++ it.effect('[When] COMPOSIO_ENVIRONMENT is "staging"', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');++ const actual = yield* withEnvConfigProvider(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('staging'),+ BASE_URL: constants.STAGING_BASE_URL,+ WEB_URL: constants.STAGING_WEB_URL,+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );++ it.effect('[When] COMPOSIO_ENVIRONMENT is "staging" but explicit URLs override', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_ENVIRONMENT', 'staging');+ vi.stubEnv('COMPOSIO_BASE_URL', 'https://custom.localhost');+ vi.stubEnv('COMPOSIO_WEB_URL', 'https://custom-web.localhost');++ const actual = yield* withEnvConfigProvider(+ Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ USER_API_KEY: Option.none(),+ ENVIRONMENT: Option.some('staging'),+ BASE_URL: 'https://custom.localhost',+ WEB_URL: 'https://custom-web.localhost',+ CACHE_DIR: Option.none(),+ LOG_LEVEL: Option.none(),+ ORG_ID: Option.none(),+ PROJECT_ID: Option.none(),+ DISABLE_CONNECTED_ACCOUNT_CACHE: true,+ })+ );+ })+ );});describe('DEBUG_OVERRIDE_CONFIG', () => {- it('[When] no env variable is set', () => {- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.none(),- VERSION: Option.none(),- })- );- });-- it('[When] env variables are set without `DEBUG_OVERRIDE_` prefix', () => {- vi.stubEnv('UPGRADE_TARGET', 'upgrade_target');- vi.stubEnv('VERSION', 'x.x.x');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.none(),- VERSION: Option.none(),- })- );- });-- it('[When] env variables are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix', () => {- vi.stubEnv('COMPOSIO_UPGRADE_TARGET', 'upgrade_target');- vi.stubEnv('COMPOSIO_VERSION', 'x.x.x');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.none(),- VERSION: Option.none(),- })- );- });-- it('[When] env variables are set with `DEBUG_OVERRIDE_` prefix', () => {- vi.stubEnv('DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target');- vi.stubEnv('DEBUG_OVERRIDE_VERSION', 'x.x.x');-- const actual = Effect.runSync(- withEnvConfigProvider(Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct)))- );-- assertEquals(- actual,- Data.struct({- UPGRADE_TARGET: Option.some('upgrade_target'),- VERSION: Option.some('x.x.x'),+ it.effect('[When] no env variable is set', () =>+ Effect.gen(function* () {+ const actual = yield* withEnvConfigProvider(+ Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.none(),+ VERSION: Option.none(),+ })+ );+ })+ );++ it.effect('[When] env variables are set without `DEBUG_OVERRIDE_` prefix', () =>+ Effect.gen(function* () {+ vi.stubEnv('UPGRADE_TARGET', 'upgrade_target');+ vi.stubEnv('VERSION', 'x.x.x');++ const actual = yield* withEnvConfigProvider(+ Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.none(),+ VERSION: Option.none(),+ })+ );+ })+ );++ it.effect(+ '[When] env variables are set without `DEBUG_OVERRIDE_` but with `COMPOSIO_` prefix',+ () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_UPGRADE_TARGET', 'upgrade_target');+ vi.stubEnv('COMPOSIO_VERSION', 'x.x.x');++ const actual = yield* withEnvConfigProvider(+ Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.none(),+ VERSION: Option.none(),+ })+ );})- );- });+ );++ it.effect('[When] env variables are set with `DEBUG_OVERRIDE_` prefix', () =>+ Effect.gen(function* () {+ vi.stubEnv('DEBUG_OVERRIDE_UPGRADE_TARGET', 'upgrade_target');+ vi.stubEnv('DEBUG_OVERRIDE_VERSION', 'x.x.x');++ const actual = yield* withEnvConfigProvider(+ Config.all(DEBUG_OVERRIDE_CONFIG).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ UPGRADE_TARGET: Option.some('upgrade_target'),+ VERSION: Option.some('x.x.x'),+ })+ );+ })+ );});});});diff --git a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.tsindex ceb082bed..e7a3ab5d7 100644--- a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts+++ b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts@@ -1,5 +1,5 @@import { describe, expect, layer } from '@effect/vitest';-import { vi, afterEach } from 'vitest';+import { vi, beforeEach, afterEach } from 'vitest';import { FileSystem } from '@effect/platform';import { ConfigProvider, Effect, Option } from 'effect';import path from 'node:path';@@ -29,8 +29,20 @@ const cacheEnabledTestConfigProvider = makeTestConfigProvider([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false'],]);+// Instant the wall clock is pinned to; fixture expiresAt values below are+// written relative to it so freshness checks in the SUT stay deterministic.+const PINNED_NOW = '2026-01-01T00:00:00.000Z';+const ONE_MINUTE_FROM_PINNED_NOW = '2026-01-01T00:01:00.000Z';+describe('consumer short-term cache', () => {+ beforeEach(() => {+ // Fake ONLY Date so real timers and promise scheduling keep working.+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date(PINNED_NOW));+ });+afterEach(() => {+ vi.useRealTimers();vi.restoreAllMocks();});@@ -181,6 +193,34 @@ describe('consumer short-term cache', () => {);});+ layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(+ '[Given] a malformed persisted cache [Then] cache reads fail closed',+ it => {+ it.scoped('ignores cache entries that do not match the persisted schema', () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ yield* fs.writeFileString(+ path.join(cacheDir, 'consumer-short-term-cache.json'),+ JSON.stringify({+ 'org_test:consumer-user-test': {+ toolkits: 'github',+ expiresAt: ONE_MINUTE_FROM_PINNED_NOW,+ },+ })+ );++ const cached = yield* getFreshConsumerConnectedToolkitsFromCache({+ orgId: 'org_test',+ consumerUserId: 'consumer-user-test',+ });++ expect(cached).toEqual(Option.none());+ })+ );+ }+ );+layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))('[Given] one corrupt entry among valid ones [Then] only the corrupt entry is dropped',it => {@@ -194,7 +234,7 @@ describe('consumer short-term cache', () => {'org_bad:consumer-user-bad': { toolkits: 'not-an-array', expiresAt: 42 },'org_test:consumer-user-test': {toolkits: ['github'],- expiresAt: new Date(Date.now() + 60_000).toISOString(),+ expiresAt: ONE_MINUTE_FROM_PINNED_NOW,},}));diff --git a/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts b/ts/packages/cli/test/src/services/native-ui-sidecar.test.tsindex d2ab51fdd..f9d75c0a1 100644--- a/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts+++ b/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts@@ -1,31 +1,94 @@import { describe, expect, it } from '@effect/vitest';-import { ConfigProvider, Effect } from 'effect';-import { interactivePermissionUiDisabledConfig } from 'src/services/native-ui-sidecar';--const loadFlag = (entries: Record<string, string>): boolean =>- Effect.runSync(- ConfigProvider.fromMap(new Map(Object.entries(entries))).load(- interactivePermissionUiDisabledConfig- )+import { CommandExecutor, Error as PlatformError } from '@effect/platform';+import { ConfigProvider, Effect, Layer } from 'effect';+import {+ detectNativeUiCallerAgentEffect,+ interactivePermissionUiDisabledConfig,+} from 'src/services/native-ui-sidecar';++const loadFlag = (entries: Record<string, string>) =>+ ConfigProvider.fromMap(new Map(Object.entries(entries))).load(+ interactivePermissionUiDisabledConfig);+const executorLayer = (start: Parameters<typeof CommandExecutor.makeExecutor>[0]) =>+ Layer.succeed(CommandExecutor.CommandExecutor, CommandExecutor.makeExecutor(start));++// Environment-based detection must resolve before `ps` is ever spawned.+const processTreeMustNotRun = executorLayer(() =>+ Effect.die(new Error('the process tree must not be consulted'))+);++// Spawn failures during the process-tree walk resolve to the default agent.+const processTreeUnavailable = executorLayer(() =>+ Effect.fail(+ new PlatformError.SystemError({ reason: 'NotFound', module: 'Command', method: 'spawn' })+ )+);++const detectAgent = (+ env: Record<string, string>,+ layer: Layer.Layer<CommandExecutor.CommandExecutor>+) => detectNativeUiCallerAgentEffect(env).pipe(Effect.provide(layer));+describe('native UI sidecar', () => {- it('disables interactive permission UI in CI and Vitest environments', () => {- expect(loadFlag({})).toBe(false);- expect(loadFlag({ CI: 'true' })).toBe(true);- expect(loadFlag({ CI: '1' })).toBe(true);- expect(loadFlag({ CI: 'woohoo' })).toBe(true);- expect(loadFlag({ CI: 'false' })).toBe(false);- expect(loadFlag({ CI: '' })).toBe(false);- expect(loadFlag({ VITEST: 'true' })).toBe(true);- });-- it('lets COMPOSIO_DISABLE_PERMISSION_UI override environment detection in both directions', () => {- expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '1' })).toBe(true);- expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: 'true' })).toBe(true);- expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '0', CI: 'true', VITEST: 'true' })).toBe(- false- );- expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '', CI: 'true' })).toBe(true);- });+ it.effect('disables interactive permission UI in CI and Vitest environments', () =>+ Effect.gen(function* () {+ expect(yield* loadFlag({})).toBe(false);+ expect(yield* loadFlag({ CI: 'true' })).toBe(true);+ expect(yield* loadFlag({ CI: '1' })).toBe(true);+ expect(yield* loadFlag({ CI: 'woohoo' })).toBe(true);+ expect(yield* loadFlag({ CI: 'false' })).toBe(false);+ expect(yield* loadFlag({ CI: '' })).toBe(false);+ expect(yield* loadFlag({ VITEST: 'true' })).toBe(true);+ })+ );++ it.effect(+ 'lets COMPOSIO_DISABLE_PERMISSION_UI override environment detection in both directions',+ () =>+ Effect.gen(function* () {+ expect(yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '1' })).toBe(true);+ expect(yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: 'true' })).toBe(true);+ expect(+ yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '0', CI: 'true', VITEST: 'true' })+ ).toBe(false);+ expect(yield* loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '', CI: 'true' })).toBe(true);+ })+ );++ it.effect('honours explicit caller-agent overrides without consulting the process tree', () =>+ Effect.gen(function* () {+ expect(yield* detectAgent({ COMPOSIO_CALLER_AGENT: 'Claude' }, processTreeMustNotRun)).toBe(+ 'claude'+ );+ expect(yield* detectAgent({ COMPOSIO_AGENT: 'open-claw' }, processTreeMustNotRun)).toBe(+ 'openclaw'+ );+ expect(+ yield* detectAgent(+ { COMPOSIO_CALLER_AGENT: 'codex', CLAUDE_CODE: '1' },+ processTreeMustNotRun+ )+ ).toBe('codex');+ })+ );++ it.effect('detects the caller agent from environment prefixes', () =>+ Effect.gen(function* () {+ expect(yield* detectAgent({ OPENCLAW_GATEWAY: '1' }, processTreeMustNotRun)).toBe('openclaw');+ expect(yield* detectAgent({ CLAUDE_CODE_ENTRYPOINT: 'cli' }, processTreeMustNotRun)).toBe(+ 'claude'+ );+ expect(yield* detectAgent({ CODEX_HOME: '/tmp/codex' }, processTreeMustNotRun)).toBe('codex');+ })+ );++ it.effect(+ 'falls back to composio when nothing matches and the process tree cannot be walked',+ () =>+ Effect.gen(function* () {+ expect(yield* detectAgent({}, processTreeUnavailable)).toBe('composio');+ })+ );});diff --git a/ts/packages/cli/test/src/services/test-layer.test.ts b/ts/packages/cli/test/src/services/test-layer.test.tsindex eb66aea2a..1dcb41cc4 100644--- a/ts/packages/cli/test/src/services/test-layer.test.ts+++ b/ts/packages/cli/test/src/services/test-layer.test.ts@@ -1,24 +1,28 @@-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it, vi } from '@effect/vitest';import { Effect } from 'effect';import { TestLive } from 'test/__utils__';describe('TestLayer', () => {- it('restores globalThis.fetch after the layer scope closes', async () => {- const originalFetch = globalThis.fetch;+ it.effect('restores globalThis.fetch after the layer scope closes', () =>+ Effect.gen(function* () {+ const originalFetch = globalThis.fetch;- await Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped, Effect.runPromise);+ yield* Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped);- expect(globalThis.fetch).toBe(originalFetch);- });+ expect(globalThis.fetch).toBe(originalFetch);+ })+ );- it('does not leak the fetch mock into later spy restore cycles', async () => {- const originalFetch = globalThis.fetch;+ it.effect('does not leak the fetch mock into later spy restore cycles', () =>+ Effect.gen(function* () {+ const originalFetch = globalThis.fetch;- await Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped, Effect.runPromise);+ yield* Effect.provide(Effect.void, TestLive()).pipe(Effect.scoped);- vi.spyOn(globalThis, 'fetch');- vi.restoreAllMocks();+ vi.spyOn(globalThis, 'fetch');+ vi.restoreAllMocks();- expect(globalThis.fetch).toBe(originalFetch);- });+ expect(globalThis.fetch).toBe(originalFetch);+ })+ );});diff --git a/ts/packages/cli/vitest.config.ts b/ts/packages/cli/vitest.config.tsindex 4dfa6a46c..1fb225d41 100644--- a/ts/packages/cli/vitest.config.ts+++ b/ts/packages/cli/vitest.config.ts@@ -23,7 +23,7 @@ export default defineConfig({),'@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),'@composio/cli-local-tools': path.join(cliLocalToolsDir, 'src/index.ts'),- 'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),+ 'effect-errors': path.resolve(__dirname, './src/effect-errors'),// @composio/core uses package.json "imports" (#config_defaults, #platform, etc.)// Vitest/Vite does not resolve these for workspace deps, so alias them explicitly'#config_defaults': path.join(coreDir, 'src/utils/config-defaults/ConfigDefaults.node.ts'),@@ -41,6 +41,7 @@ export default defineConfig({// When defined, Vitest will run all matched files with import.meta.vitest inside.includeSource: ['src/**/*.ts', 'test/__utils__/*-compiler.ts'],unstubEnvs: true,+ setupFiles: ['./test/__utils__/vitest.setup.ts'],globalSetup: './test/__utils__/vitest.global-setup.ts',},});