1
+import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2
+import { describe, expect, it } from '@effect/vitest';
3
+import { Console, Effect, Layer, Option } from 'effect';
4
+import { HttpClient } from 'effect/http';
5
+import {
6
+ runConnectedAccountsList,
7
+ type ConnectedAccountsListParams,
8
+} from 'src/commands/connected-accounts/list/connected-accounts.list.handler';
9
+import { viewDetailsHint } from 'src/commands/connected-accounts/list/connected-accounts.list.format';
10
+import { CommandSurface } from 'src/commands/surface';
11
+import type { ConnectedAccountItem } from 'src/models/connected-accounts';
12
+import type { ProjectKeys } from 'src/models/project-keys';
13
+import { ComposioClientSingleton } from 'src/services/composio-clients';
14
+import { ProjectContext } from 'src/services/project-context';
15
+import { TerminalUI } from 'src/services/terminal-ui';
16
+import { ComposioUserContext } from 'src/services/user-context';
17
+import { MockConsole } from 'test/__utils__';
18
+import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts';
19
+import {
20
+ mockConnectedAccountResources,
21
+ resolveConnectedAccountsTestData,
22
+} from 'test/__utils__/layers/connected-accounts';
23
+import { makeOrgProject } from 'test/__utils__/models/account';
24
+import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
25
+
26
+const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({
27
+ id: 'con_gmail_active',
28
+ alias: null,
29
+ word_id: null,
30
+ status: 'ACTIVE',
31
+ status_reason: null,
32
+ is_disabled: false,
33
+ user_id: 'default',
34
+ toolkit: { slug: 'gmail' },
35
+ auth_config: {
36
+ id: 'ac_gmail_oauth',
37
+ auth_scheme: 'OAUTH2',
38
+ is_composio_managed: true,
39
+ is_disabled: false,
40
+ },
41
+ created_at: '2026-01-01T00:00:00Z',
42
+ updated_at: '2026-01-15T00:00:00Z',
43
+ test_request_endpoint: '',
44
+ ...overrides,
45
+});
46
+
47
+const ACCOUNTS: ReadonlyArray<ConnectedAccountItem> = [
48
+ account(),
49
+ account({ id: 'con_slack_active', user_id: 'user-123', toolkit: { slug: 'slack' } }),
50
+];
51
+
52
+const DIRECTORY_PROJECT: ProjectKeys = {
53
+ orgId: 'org_test',
54
+ projectId: 'proj_directory',
55
+ projectName: Option.some('directory'),
56
+ orgName: Option.none(),
57
+ email: Option.none(),
58
+ testUserId: Option.none(),
59
+};
60
+
61
+const NAMED_PROJECT = makeOrgProject({ id: 'proj_named', name: 'named', orgId: 'org_test' });
62
+
63
+// A resource the mocks below do not shadow reaches this transport and dies with its URL.
64
+const baseClient = make(
65
+ { auth: Auth.project('test'), baseURL: 'https://mock.invalid' },
66
+ HttpClient.make(request =>
67
+ Effect.die(
68
+ new Error(`unexpected network call from the connected-accounts list test: ${request.url}`)
69
+ )
70
+ )
71
+);
72
+
73
+/** One `connectedAccounts.list` call, with the scope of the client it went through. */
74
+interface ListRequest {
75
+ readonly scope: MockRequestScope;
76
+ readonly params: unknown;
77
+}
78
+
79
+interface ListFixture {
80
+ readonly accounts?: ReadonlyArray<ConnectedAccountItem>;
81
+ readonly userId?: Option.Option<string>;
82
+ readonly projectName?: Option.Option<string>;
83
+}
84
+
85
+/**
86
+ * What `runConnectedAccountsList` reads: the `dev` surface, a user with an org, a directory
87
+ * project, the account and connected-account families of the mock client, and a headless
88
+ * terminal whose stdout data lands in `outputs`. `requests` records every list call.
89
+ */
90
+const listTest = (fixture: ListFixture = {}) => {
91
+ const outputs: Array<string> = [];
92
+ const requests: Array<ListRequest> = [];
93
+ const resources = mockConnectedAccountResources(
94
+ resolveConnectedAccountsTestData({ items: [...(fixture.accounts ?? ACCOUNTS)] })
95
+ );
96
+ const clientFor = (scope: MockRequestScope): ComposioClientShape =>
97
+ // The shadows answer only the fields the handler reads, as in `test-layer.ts`.
98
+ ({
99
+ ...baseClient,
100
+ ...mockAccountResources({ projects: [NAMED_PROJECT] }, scope),
101
+ connectedAccounts: {
102
+ ...resources.connectedAccounts,
103
+ list: (params: Parameters<typeof resources.connectedAccounts.list>[0]) =>
104
+ Effect.sync(() => requests.push({ scope, params })).pipe(
105
+ Effect.andThen(resources.connectedAccounts.list(params))
106
+ ),
107
+ },
108
+ }) as unknown as ComposioClientShape;
109
+
110
+ const layer = Layer.mergeAll(
111
+ Layer.effect(Console.Console, MockConsole.make),
112
+ Layer.succeed(
113
+ TerminalUI,
114
+ TerminalUI.of({
115
+ ...terminalUITestImpl,
116
+ output: data =>
117
+ Effect.sync(() => {
118
+ outputs.push(data);
119
+ }),
120
+ })
121
+ ),
122
+ CommandSurface.dev({
123
+ userId: fixture.userId ?? Option.none(),
124
+ projectName: fixture.projectName ?? Option.none(),
125
+ }),
126
+ Layer.succeed(
127
+ ComposioUserContext,
128
+ ComposioUserContext.of({
129
+ data: {
130
+ apiKey: Option.some('uak_test'),
131
+ baseURL: 'https://mock.invalid',
132
+ webURL: 'https://platform.mock.invalid',
133
+ orgId: Option.some('org_test'),
134
+ projectId: Option.none(),
135
+ testUserId: Option.none(),
136
+ },
137
+ isLoggedIn: () => true,
138
+ logout: Effect.void,
139
+ login: () => Effect.void,
140
+ update: () => Effect.void,
141
+ })
142
+ ),
143
+ Layer.succeed(
144
+ ProjectContext,
145
+ ProjectContext.of({ resolve: Effect.succeed(Option.some(DIRECTORY_PROJECT)) })
146
+ ),
147
+ Layer.succeed(
148
+ ComposioClientSingleton,
149
+ ComposioClientSingleton.of({
150
+ get: () => Effect.succeed(clientFor({})),
151
+ getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)),
152
+ getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
153
+ })
154
+ )
155
+ );
156
+ return { layer, outputs, requests };
157
+};
158
+
159
+const params = (
160
+ overrides: Partial<ConnectedAccountsListParams> = {}
161
+): ConnectedAccountsListParams => ({
162
+ toolkits: Option.none(),
163
+ status: Option.none(),
164
+ limit: 30,
165
+ ...overrides,
166
+});
167
+
168
+const stderrLines = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
169
+const allLines = MockConsole.getLines({ stripAnsi: true });
170
+
171
+describe('runConnectedAccountsList', () => {
172
+ it.effect('[Given] no filters [Then] lists the directory project without filters', () => {
173
+ const { layer, requests } = listTest();
174
+ return Effect.gen(function* () {
175
+ yield* runConnectedAccountsList(params());
176
+
177
+ expect(requests).toEqual([
178
+ {
179
+ scope: { orgId: 'org_test', projectId: 'proj_directory' },
180
+ params: { toolkit_slugs: undefined, user_ids: undefined, statuses: undefined, limit: 30 },
181
+ },
182
+ ]);
183
+ }).pipe(Effect.provide(layer));
184
+ });
185
+
186
+ it.effect(
187
+ '[Given] --toolkits, --status and the shared --user-id [Then] sends each as a filter',
188
+ () => {
189
+ const { layer, requests } = listTest({ userId: Option.some('default') });
190
+ return Effect.gen(function* () {
191
+ yield* runConnectedAccountsList(
192
+ params({ toolkits: Option.some('gmail, slack'), status: Option.some('ACTIVE') })
193
+ );
194
+
195
+ expect(requests.map(request => request.params)).toEqual([
196
+ {
197
+ toolkit_slugs: ['gmail', 'slack'],
198
+ user_ids: ['default'],
199
+ statuses: ['ACTIVE'],
200
+ limit: 30,
201
+ },
202
+ ]);
203
+ }).pipe(Effect.provide(layer));
204
+ }
205
+ );
206
+
207
+ it.effect.each([
208
+ { limit: 0, expected: 1 },
209
+ { limit: 1001, expected: 1000 },
210
+ ])('[Given] --limit $limit [Then] requests $expected accounts', ({ limit, expected }) => {
211
+ const { layer, requests } = listTest();
212
+ return Effect.gen(function* () {
213
+ yield* runConnectedAccountsList(params({ limit }));
214
+
215
+ expect(requests.map(request => request.params)).toMatchObject([{ limit: expected }]);
216
+ }).pipe(Effect.provide(layer));
217
+ });
218
+
219
+ it.effect('[Given] the shared --project-name [Then] lists that developer project', () => {
220
+ const { layer, requests } = listTest({ projectName: Option.some('named') });
221
+ return Effect.gen(function* () {
222
+ yield* runConnectedAccountsList(params());
223
+
224
+ expect(requests.map(request => request.scope)).toEqual([
225
+ { orgId: 'org_test', projectId: 'proj_named' },
226
+ ]);
227
+ }).pipe(Effect.provide(layer));
228
+ });
229
+
230
+ it.effect('[Given] accounts [Then] prints them as JSON on stdout and hints at `info`', () => {
231
+ const { layer, outputs } = listTest();
232
+ return Effect.gen(function* () {
233
+ yield* runConnectedAccountsList(params());
234
+
235
+ expect(outputs.map(output => JSON.parse(output))).toEqual([
236
+ [
237
+ {
238
+ id: 'con_gmail_active',
239
+ alias: null,
240
+ word_id: null,
241
+ user_id: 'default',
242
+ toolkit_slug: 'gmail',
243
+ auth_config_id: 'ac_gmail_oauth',
244
+ auth_scheme: 'OAUTH2',
245
+ status: 'ACTIVE',
246
+ created_at: '2026-01-01T00:00:00Z',
247
+ },
248
+ {
249
+ id: 'con_slack_active',
250
+ alias: null,
251
+ word_id: null,
252
+ user_id: 'user-123',
253
+ toolkit_slug: 'slack',
254
+ auth_config_id: 'ac_gmail_oauth',
255
+ auth_scheme: 'OAUTH2',
256
+ status: 'ACTIVE',
257
+ created_at: '2026-01-01T00:00:00Z',
258
+ },
259
+ ],
260
+ ]);
261
+ const lines = yield* allLines;
262
+ expect(lines.some(line => line.startsWith('Listing 2 of 2 connected accounts'))).toBe(true);
263
+ expect(lines).toContain(viewDetailsHint('con_gmail_active'));
264
+ }).pipe(Effect.provide(layer));
265
+ });
266
+
267
+ it.effect.each([
268
+ {
269
+ given: 'every filter',
270
+ fixture: { userId: Option.some('nobody') },
271
+ flags: { toolkits: Option.some('notion'), status: Option.some('REVOKED' as const) },
272
+ expected:
273
+ 'No connected accounts found for toolkit "notion". Verify the toolkit slug with:\n> composio dev toolkits list',
274
+ },
275
+ {
276
+ given: '--user-id and --status',
277
+ fixture: { userId: Option.some('nobody') },
278
+ flags: { status: Option.some('REVOKED' as const) },
279
+ expected: 'No connected accounts found for user "nobody".',
280
+ },
281
+ {
282
+ given: '--status',
283
+ fixture: {},
284
+ flags: { status: Option.some('REVOKED' as const) },
285
+ expected: 'No connected accounts found with status "REVOKED".',
286
+ },
287
+ { given: 'no filter', fixture: {}, flags: {}, expected: 'No connected accounts found.' },
288
+ ])(
289
+ '[Given] an empty page and $given [Then] warns about the first filter and prints no data',
290
+ ({ fixture, flags, expected }) => {
291
+ const { layer, outputs } = listTest({ ...fixture, accounts: [] });
292
+ return Effect.gen(function* () {
293
+ yield* runConnectedAccountsList(params(flags));
294
+
295
+ expect(yield* stderrLines).toEqual([expected]);
296
+ expect(outputs).toEqual([]);
297
+ }).pipe(Effect.provide(layer));
298
+ }
299
+ );
300
+});