1
+import { afterEach, describe, expect, it } from '@effect/vitest';
2
+import { vi } from 'vitest';
3
+import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4
+import * as BunPath from '@effect/platform-bun/BunPath';
5
+import { APIConnectionError } from '@composio/client/effect';
6
+import { ConfigProvider, Effect, Fiber, Layer, Option } from 'effect';
7
+import { TestClock } from 'effect/testing';
8
+import * as tempy from 'tempy';
9
+import { ProjectResolutionError, resolveCommandProject } from 'src/services/command-project';
10
+import { ComposioClientSingleton } from 'src/services/composio-clients';
11
+import { defaultNodeOs, NodeOs } from 'src/services/node-os';
12
+import { ProjectContext } from 'src/services/project-context';
13
+import { ComposioUserContext } from 'src/services/user-context';
14
+import { makeOrgProject } from 'test/__utils__/models/account';
15
+
16
+const BASE_URL = 'https://backend.composio.dev';
17
+
18
+const userContext = (orgId: Option.Option<string>) =>
19
+ Layer.succeed(
20
+ ComposioUserContext,
21
+ ComposioUserContext.of({
22
+ data: {
23
+ apiKey: Option.some('uak_test'),
24
+ baseURL: BASE_URL,
25
+ webURL: 'https://app.composio.dev',
26
+ orgId,
27
+ projectId: Option.none(),
28
+ testUserId: Option.none(),
29
+ },
30
+ isLoggedIn: () => true,
31
+ logout: Effect.void,
32
+ login: () => Effect.void,
33
+ update: () => Effect.void,
34
+ })
35
+ );
36
+
37
+const noLocalProject = Layer.succeed(
38
+ ProjectContext,
39
+ ProjectContext.of({ resolve: Effect.succeed(Option.none()) })
40
+);
41
+
42
+const singleton = Layer.provide(
43
+ ComposioClientSingleton.Default,
44
+ Layer.mergeAll(
45
+ BunFileSystem.layer,
46
+ BunPath.layer,
47
+ Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempy.temporaryDirectory() })),
48
+ Layer.succeed(
49
+ ConfigProvider.ConfigProvider,
50
+ ConfigProvider.fromEnv({
51
+ env: { COMPOSIO_USER_API_KEY: 'uak_test', COMPOSIO_BASE_URL: BASE_URL },
52
+ })
53
+ )
54
+ )
55
+);
56
+
57
+const testLayer = Layer.mergeAll(singleton, userContext(Option.some('org_1')), noLocalProject);
58
+
59
+const jsonResponse = (body: unknown, status = 200) =>
60
+ new Response(JSON.stringify(body), {
61
+ status,
62
+ headers: { 'Content-Type': 'application/json', 'x-should-retry': 'false' },
63
+ });
64
+
65
+const projectsPage = (names: ReadonlyArray<string>) =>
66
+ jsonResponse({
67
+ data: names.map((name, index) => makeOrgProject({ id: `p${index + 1}`, name })),
68
+ total_pages: 1,
69
+ current_page: 1,
70
+ total_items: names.length,
71
+ });
72
+
73
+describe('resolveCommandProject', () => {
74
+ afterEach(() => {
75
+ vi.restoreAllMocks();
76
+ });
77
+
78
+ it.effect('fails with missing_org before any request when no org is configured', () =>
79
+ Effect.gen(function* () {
80
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
81
+
82
+ const error = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.flip);
83
+
84
+ expect(error).toBeInstanceOf(ProjectResolutionError);
85
+ expect(error).toMatchObject({
86
+ reason: 'missing_org',
87
+ message: 'No current org configured. Run `composio login` or `composio dev orgs switch`.',
88
+ });
89
+ expect(fetchSpy).not.toHaveBeenCalled();
90
+ }).pipe(Effect.provide(Layer.mergeAll(singleton, userContext(Option.none()), noLocalProject)))
91
+ );
92
+
93
+ it.effect('fails with missing_developer_project when nothing binds the directory', () =>
94
+ Effect.gen(function* () {
95
+ const error = yield* resolveCommandProject({ mode: 'developer' }).pipe(Effect.flip);
96
+
97
+ expect(error).toMatchObject({
98
+ _tag: 'services/ProjectResolutionError',
99
+ reason: 'missing_developer_project',
100
+ message: 'No developer project configured for this directory. Run `composio dev init`.',
101
+ });
102
+ }).pipe(Effect.provide(testLayer))
103
+ );
104
+
105
+ it.effect('turns an unknown project name into project_not_found with the remedy', () =>
106
+ Effect.gen(function* () {
107
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(projectsPage(['Other']));
108
+
109
+ const error = yield* resolveCommandProject({
110
+ mode: 'developer',
111
+ projectName: 'Missing',
112
+ }).pipe(Effect.flip);
113
+
114
+ expect(error).toMatchObject({
115
+ _tag: 'services/ProjectResolutionError',
116
+ reason: 'project_not_found',
117
+ message:
118
+ 'Developer project "Missing" was not found in org "org_1". Run `composio dev init` or `composio dev projects list`.',
119
+ });
120
+ }).pipe(Effect.provide(testLayer))
121
+ );
122
+
123
+ it.effect('turns a name collision into ambiguous_project_name', () =>
124
+ Effect.gen(function* () {
125
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(projectsPage(['Shared', 'shared']));
126
+
127
+ const error = yield* resolveCommandProject({
128
+ mode: 'consumer',
129
+ projectName: 'SHARED',
130
+ }).pipe(Effect.flip);
131
+
132
+ expect(error).toMatchObject({
133
+ _tag: 'services/ProjectResolutionError',
134
+ reason: 'ambiguous_project_name',
135
+ message:
136
+ 'Developer project name "SHARED" is ambiguous in org "org_1". Use an exact unique project name.',
137
+ });
138
+ }).pipe(Effect.provide(testLayer))
139
+ );
140
+
141
+ it.effect('turns an API error into request_failed carrying the server message', () =>
142
+ Effect.gen(function* () {
143
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
144
+ jsonResponse(
145
+ { error: { slug: 'Forbidden', status: 403, code: 403, message: 'Org access revoked.' } },
146
+ 403
147
+ )
148
+ );
149
+
150
+ const error = yield* resolveCommandProject({
151
+ mode: 'developer',
152
+ projectName: 'Any',
153
+ }).pipe(Effect.flip);
154
+
155
+ expect(error).toBeInstanceOf(ProjectResolutionError);
156
+ expect(error).toMatchObject({ reason: 'request_failed', message: 'Org access revoked.' });
157
+ expect((error as ProjectResolutionError).cause).toMatchObject({ status: 403 });
158
+ }).pipe(Effect.provide(testLayer))
159
+ );
160
+
161
+ it.effect('passes a connection failure through with its own type', () =>
162
+ Effect.gen(function* () {
163
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('fetch failed'));
164
+
165
+ // The client retries a connection failure with a backoff on Effect's clock, so run the
166
+ // lookup on its own fiber and move the test clock past every retry before joining. The
167
+ // first backoff is armed only after client construction and a rejected fetch promise, so
168
+ // advance in bounded steps until the fiber has settled rather than assuming one yield
169
+ // reaches it.
170
+ const fiber = yield* resolveCommandProject({ mode: 'developer', projectName: 'Any' }).pipe(
171
+ Effect.flip,
172
+ Effect.forkChild
173
+ );
174
+ for (let step = 0; step < 100 && fiber.pollUnsafe() === undefined; step++) {
175
+ yield* Effect.yieldNow;
176
+ yield* TestClock.adjust('1 minute');
177
+ }
178
+ expect(fiber.pollUnsafe()).toBeDefined();
179
+ const error = yield* Fiber.join(fiber);
180
+
181
+ expect(error).not.toBeInstanceOf(ProjectResolutionError);
182
+ expect(error).toBeInstanceOf(APIConnectionError);
183
+ }).pipe(Effect.provide(testLayer))
184
+ );
185
+});