1
+import { describe, expect, layer } from '@effect/vitest';
2
+import { ConfigProvider, Effect, Fiber } from 'effect';
3
+import { TestClock } from 'effect/testing';
4
+import type { ComposioClientShape } from '@composio/client/effect';
5
+import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
6
+import { cli, MockConsole, TestLive } from 'test/__utils__';
7
+import {
8
+ routeRequests,
9
+ stubClientResources,
10
+ type StubRequest,
11
+} from 'test/__utils__/services/stub-composio-client';
12
+
13
+const testLayer = () =>
14
+ TestLive({
15
+ baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
16
+ fixture: 'global-test-user-id',
17
+ });
18
+
19
+const forbidden = () =>
20
+ Response.json(
21
+ { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
22
+ { status: 403 }
23
+ );
24
+const FORBIDDEN_DETAIL =
25
+ '403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}';
26
+
27
+const session = () =>
28
+ Response.json({
29
+ session_id: 'trs_stub_session',
30
+ config: { user_id: 'consumer-user-org_test' },
31
+ mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
32
+ tool_router_tools: [],
33
+ });
34
+
35
+const failureOf = (
36
+ args: ReadonlyArray<string>,
37
+ resources: ReadonlyArray<keyof ComposioClientShape>,
38
+ respond: (request: StubRequest) => Response = forbidden
39
+) =>
40
+ Effect.gen(function* () {
41
+ const stub = stubClientResources(resources, respond);
42
+ return yield* cli(args).pipe(Effect.provide(stub.layer), Effect.flip);
43
+ });
44
+
45
+const rejectedRequests: ReadonlyArray<{
46
+ readonly command: string;
47
+ readonly args: ReadonlyArray<string>;
48
+ readonly resources: ReadonlyArray<keyof ComposioClientShape>;
49
+ readonly tag: string;
50
+ readonly message: string;
51
+}> = [
52
+ {
53
+ command: 'dev logs tools <id>',
54
+ args: ['dev', 'logs', 'tools', 'log_1'],
55
+ resources: ['logs'],
56
+ tag: 'commands/ToolLogsRequestError',
57
+ message: 'Failed to fetch tool log "log_1".',
58
+ },
59
+ {
60
+ command: 'dev logs triggers',
61
+ args: ['dev', 'logs', 'triggers'],
62
+ resources: ['logs'],
63
+ tag: 'commands/TriggerLogsRequestError',
64
+ message: 'Failed to fetch trigger logs.',
65
+ },
66
+ {
67
+ command: 'dev logs triggers <id>',
68
+ args: ['dev', 'logs', 'triggers', 'log_1'],
69
+ resources: ['logs'],
70
+ tag: 'commands/TriggerLogsRequestError',
71
+ message: 'Failed to fetch trigger log "log_1".',
72
+ },
73
+ {
74
+ command: 'connections list',
75
+ args: ['connections', 'list'],
76
+ resources: ['connectedAccounts'],
77
+ tag: 'commands/ConnectionsListRequestError',
78
+ message: 'Failed to list connections.',
79
+ },
80
+ {
81
+ command: 'connections remove',
82
+ args: ['connections', 'remove', 'gmail'],
83
+ resources: ['connectedAccounts'],
84
+ tag: 'commands/ConnectionsRemovalRequestError',
85
+ message: 'Failed to list connections.',
86
+ },
87
+ {
88
+ command: 'dev connected-accounts list',
89
+ args: ['dev', 'connected-accounts', 'list'],
90
+ resources: ['connectedAccounts'],
91
+ tag: 'commands/ConnectedAccountsListRequestError',
92
+ message: 'Failed to list connected accounts.',
93
+ },
94
+ {
95
+ command: 'link <toolkit> --list',
96
+ args: ['link', 'gmail', '--list'],
97
+ resources: ['connectedAccounts'],
98
+ tag: 'commands/ConnectedAccountsRequestError',
99
+ message: 'Failed to list connected accounts for "gmail".',
100
+ },
101
+];
102
+
103
+describe('CLI: a request the API rejects', () => {
104
+ describe.each(rejectedRequests)(
105
+ '[Given] composio $command',
106
+ ({ args, resources, tag, message }) => {
107
+ layer(testLayer())(it => {
108
+ it.effect(
109
+ '[Then] the command fails with its own message and the response as the cause',
110
+ () =>
111
+ Effect.gen(function* () {
112
+ const failure = yield* failureOf(args, resources);
113
+
114
+ expect(failure).toMatchObject({ _tag: tag, message });
115
+ expect(extractErrorDetails(failure).message).toBe(
116
+ `${message}\nCaused by: ${FORBIDDEN_DETAIL}`
117
+ );
118
+ })
119
+ );
120
+ });
121
+ }
122
+ );
123
+
124
+ layer(testLayer())('[Given] composio link while the new account cannot be fetched', it => {
125
+ it.effect('[Then] the wait fails with the fetch message once its retries run out', () =>
126
+ Effect.gen(function* () {
127
+ const stub = stubClientResources(
128
+ ['connectedAccounts'],
129
+ routeRequests(
130
+ [
131
+ {
132
+ method: 'GET',
133
+ path: '/api/v3.1/connected_accounts/con_test_link',
134
+ respond: forbidden,
135
+ },
136
+ ],
137
+ () => Response.json({ items: [], total_pages: 1, current_page: 1, total_items: 0 })
138
+ )
139
+ );
140
+ const fiber = yield* cli(['link', 'gmail', '--no-browser']).pipe(
141
+ Effect.provide(stub.layer),
142
+ Effect.flip,
143
+ Effect.forkChild
144
+ );
145
+ // Each retry waits on the test clock and then on the stub transport's promise.
146
+ yield* TestClock.adjust('2 hours').pipe(
147
+ Effect.andThen(TestClock.withLive(Effect.sleep('5 millis'))),
148
+ Effect.repeat({ times: 40 })
149
+ );
150
+ const failure = yield* Fiber.join(fiber);
151
+
152
+ expect(failure).toMatchObject({ _tag: 'commands/ConnectedAccountsRequestError' });
153
+ expect(extractErrorDetails(failure).message).toBe(
154
+ `Failed to fetch connected account "con_test_link".\nCaused by: ${FORBIDDEN_DETAIL}`
155
+ );
156
+ })
157
+ );
158
+ });
159
+});
160
+
161
+describe('CLI: a rejected request the command recovers from', () => {
162
+ const SESSION_TOOLKITS = '/api/v3.1/tool_router/session/trs_stub_session/toolkits?toolkits=gmail';
163
+ const toolkitsInfo = (toolkits: () => Response) =>
164
+ Effect.gen(function* () {
165
+ const stub = stubClientResources(
166
+ ['toolRouter'],
167
+ routeRequests([{ method: 'GET', path: SESSION_TOOLKITS, respond: toolkits }], session)
168
+ );
169
+ yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.provide(stub.layer));
170
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
171
+ return { lines, lastPath: stub.requests.at(-1)?.path };
172
+ });
173
+
174
+ layer(testLayer())('[Given] composio dev toolkits info and rejected session toolkits', it => {
175
+ it.effect('[Then] the API message and the browse hint are printed', () =>
176
+ Effect.gen(function* () {
177
+ const { lines, lastPath } = yield* toolkitsInfo(forbidden);
178
+
179
+ expect(lines).toEqual([
180
+ 'Using global test user id "global-default"',
181
+ 'Not allowed',
182
+ 'Browse available toolkits:\n> composio dev toolkits list',
183
+ ]);
184
+ expect(lastPath).toBe(SESSION_TOOLKITS);
185
+ })
186
+ );
187
+ });
188
+
189
+ const LISTING = '/api/v3.1/connected_accounts?';
190
+ const withoutExistingAccounts = () => stubClientResources(['connectedAccounts'], forbidden);
191
+ const redirect = [
192
+ 'Open this URL in your browser to authorize',
193
+ '[Redirect URL] https://app.composio.dev/link?token=lt_test_token',
194
+ ];
195
+ const pending = (fields: Record<string, string>) =>
196
+ JSON.stringify(
197
+ {
198
+ status: 'pending',
199
+ message: 'Complete authorization by opening the URL',
200
+ connected_account_id: 'con_test_link',
201
+ redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
202
+ ...fields,
203
+ },
204
+ null,
205
+ 2
206
+ );
207
+
208
+ layer(testLayer())('[Given] composio link <toolkit> and a rejected account listing', it => {
209
+ it.effect('[Then] the link is created as if the user had no account yet', () =>
210
+ Effect.gen(function* () {
211
+ const stub = withoutExistingAccounts();
212
+ yield* cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer));
213
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
214
+
215
+ expect(lines).toEqual([
216
+ 'Linking gmail...',
217
+ ...redirect,
218
+ pending({ toolkit: 'gmail', project_type: 'CONSUMER' }),
219
+ ]);
220
+ expect(stub.requests.map(request => request.path)).toEqual([
221
+ `${LISTING}user_ids=consumer-user-org_test&toolkit_slugs=gmail&statuses=ACTIVE&limit=100`,
222
+ `${LISTING}user_ids=consumer-user-org_test&statuses=ACTIVE&limit=1000`,
223
+ ]);
224
+ })
225
+ );
226
+ });
227
+
228
+ layer(testLayer())('[Given] composio link --auth-config and a rejected account listing', it => {
229
+ it.effect('[Then] the link is created as if the user had no account yet', () =>
230
+ Effect.gen(function* () {
231
+ const stub = withoutExistingAccounts();
232
+ yield* cli([
233
+ 'dev',
234
+ 'connected-accounts',
235
+ 'link',
236
+ '--auth-config',
237
+ 'ac_1',
238
+ '--user-id',
239
+ 'user_1',
240
+ '--no-wait',
241
+ ]).pipe(Effect.provide(stub.layer));
242
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
243
+
244
+ expect(lines).toEqual([
245
+ 'Creating link session...',
246
+ ...redirect,
247
+ pending({ project_type: 'DEVELOPER' }),
248
+ ]);
249
+ expect(stub.requests.map(request => request.path)).toEqual([
250
+ `${LISTING}user_ids=user_1&auth_config_ids=ac_1&statuses=ACTIVE&limit=100`,
251
+ ]);
252
+ })
253
+ );
254
+ });
255
+});