1
+import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2
+import * as BunPath from '@effect/platform-bun/BunPath';
3
+import { describe, expect, it } from '@effect/vitest';
4
+import { Array as Arr, Console, Effect, Layer, Option } from 'effect';
5
+import * as tempy from 'tempy';
6
+import { afterEach, vi } from 'vitest';
7
+import { runOrgsSwitch } from 'src/commands/orgs/switch/orgs.switch.handler';
8
+import { NO_ORG_SELECTED_OUTRO } from 'src/commands/orgs/switch/orgs.switch.format';
9
+import type { OrganizationSummary } from 'src/services/composio-account';
10
+import { ComposioClientSingleton } from 'src/services/composio-clients';
11
+import { NodeOs } from 'src/services/node-os';
12
+import { TerminalUI } from 'src/services/terminal-ui';
13
+import { ComposioUserContext } from 'src/services/user-context';
14
+import { MockConsole } from 'test/__utils__';
15
+import type { MockAccountRequest, MockRequestScope } from 'test/__utils__/layers/accounts';
16
+import { makeShadowClient } from 'test/__utils__/layers/shadow-client';
17
+import { makeSessionInfo } from 'test/__utils__/models/account';
18
+import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
19
+
20
+const analytics = vi.hoisted(() => ({ linked: [] as Array<string> }));
21
+
22
+// Records each analytics identity link instead of enqueueing an event.
23
+vi.mock('src/analytics/dispatch', async importOriginal => {
24
+ const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
25
+ const { Effect } = await import('effect');
26
+ return {
27
+ ...actual,
28
+ analyticsIdentityLinkingEnabled: Effect.succeed(true),
29
+ linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
30
+ Effect.sync(() => {
31
+ analytics.linked.push(apolloUserId);
32
+ })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
33
+ };
34
+});
35
+
36
+afterEach(() => {
37
+ analytics.linked.length = 0;
38
+});
39
+
40
+const ORGANIZATIONS: ReadonlyArray<OrganizationSummary> = [
41
+ { id: 'org_first', name: 'First Org' },
42
+ { id: 'org_current', name: 'Current Org' },
43
+ { id: 'org_third', name: 'Third Org' },
44
+];
45
+
46
+type LoginCall = readonly [apiKey: string, orgId?: string, testUserId?: string];
47
+
48
+interface OrgsSwitchFixture {
49
+ readonly apiKey?: Option.Option<string>;
50
+ readonly orgId?: Option.Option<string>;
51
+ readonly testUserId?: Option.Option<string>;
52
+ readonly organizations?: ReadonlyArray<OrganizationSummary>;
53
+ /** The org name the picker answers with; the first option when absent. */
54
+ readonly pick?: string;
55
+}
56
+
57
+/**
58
+ * What `runOrgsSwitch` reads: a user context whose `login` calls land in `logins`, the account
59
+ * family of the mock client, and a headless terminal whose picker answers with `pick` and
60
+ * records the options it was shown in `prompts`, and whose stdout data lands in `outputs`.
61
+ */
62
+const orgsSwitchTest = (fixture: OrgsSwitchFixture = {}) => {
63
+ const outputs: Array<string> = [];
64
+ const logins: Array<LoginCall> = [];
65
+ const prompts: Array<ReadonlyArray<{ readonly label: string; readonly hint?: string }>> = [];
66
+ const requests: Array<MockAccountRequest> = [];
67
+ const apiKey = fixture.apiKey ?? Option.some('uak_orgs_switch');
68
+ const accountData = {
69
+ organizations: fixture.organizations ?? ORGANIZATIONS,
70
+ sessionInfo: (scope: MockRequestScope) =>
71
+ makeSessionInfo({
72
+ orgId: scope.orgId ?? 'org_unknown',
73
+ orgName: 'Any Org',
74
+ orgMemberId: `member_${scope.orgId}`,
75
+ }),
76
+ onRequest: (request: MockAccountRequest) => {
77
+ requests.push(request);
78
+ },
79
+ };
80
+
81
+ const select = <A>(
82
+ _message: string,
83
+ options: ReadonlyArray<{ readonly value: A; readonly label: string; readonly hint?: string }>
84
+ ) =>
85
+ Effect.sync(() => {
86
+ prompts.push(options.map(({ label, hint }) => ({ label, hint })));
87
+ return Arr.findFirst(options, option => option.label === fixture.pick).pipe(
88
+ Option.orElse(() => Arr.head(options)),
89
+ Option.map(option => option.value),
90
+ Option.getOrThrow
91
+ );
92
+ });
93
+
94
+ const layer = Layer.mergeAll(
95
+ Layer.effect(Console.Console, MockConsole.make),
96
+ Layer.succeed(
97
+ TerminalUI,
98
+ TerminalUI.of({
99
+ ...terminalUITestImpl,
100
+ select,
101
+ output: data =>
102
+ Effect.sync(() => {
103
+ outputs.push(data);
104
+ }),
105
+ })
106
+ ),
107
+ Layer.succeed(
108
+ ComposioUserContext,
109
+ ComposioUserContext.of({
110
+ data: {
111
+ apiKey,
112
+ baseURL: 'https://mock.invalid',
113
+ webURL: 'https://platform.mock.invalid/',
114
+ orgId: fixture.orgId ?? Option.none(),
115
+ projectId: Option.none(),
116
+ testUserId: fixture.testUserId ?? Option.none(),
117
+ },
118
+ isLoggedIn: () => Option.isSome(apiKey),
119
+ logout: Effect.void,
120
+ login: (...call: LoginCall) =>
121
+ Effect.sync(() => {
122
+ logins.push(call);
123
+ }),
124
+ update: () => Effect.void,
125
+ })
126
+ ),
127
+ Layer.succeed(
128
+ ComposioClientSingleton,
129
+ ComposioClientSingleton.of({
130
+ get: () => Effect.succeed(makeShadowClient(accountData, {})),
131
+ getFor: (scope: MockRequestScope) => Effect.succeed(makeShadowClient(accountData, scope)),
132
+ getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
133
+ })
134
+ ),
135
+ // The analytics link is mocked; its signature still names the platform services.
136
+ BunFileSystem.layer,
137
+ BunPath.layer,
138
+ Layer.sync(NodeOs, () => {
139
+ const dir = tempy.temporaryDirectory();
140
+ return NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' });
141
+ })
142
+ );
143
+ return { layer, outputs, logins, prompts, requests };
144
+};
145
+
146
+const orgListLimits = (requests: ReadonlyArray<MockAccountRequest>) =>
147
+ requests
148
+ .filter(request => request.operation === 'org.list')
149
+ .map(request => (request.params as { readonly limit?: number } | undefined)?.limit);
150
+
151
+describe('runOrgsSwitch', () => {
152
+ it.effect('[Given] --org-id [Then] stores it without listing or prompting', () => {
153
+ const { layer, outputs, logins, prompts, requests } = orgsSwitchTest({
154
+ testUserId: Option.some('test_user'),
155
+ });
156
+ return Effect.gen(function* () {
157
+ yield* runOrgsSwitch({ orgId: Option.some('org_explicit'), limit: 50 });
158
+
159
+ expect(orgListLimits(requests)).toEqual([]);
160
+ expect(prompts).toEqual([]);
161
+ expect(logins).toEqual([['uak_orgs_switch', 'org_explicit', 'test_user']]);
162
+ expect(analytics.linked).toEqual(['member_org_explicit']);
163
+ expect(outputs).toEqual([JSON.stringify({ scope: 'global', org_id: 'org_explicit' })]);
164
+ }).pipe(Effect.provide(layer));
165
+ });
166
+
167
+ it.effect(
168
+ '[Given] several orgs and a current one [Then] the picker lists the current org first and stores the pick',
169
+ () => {
170
+ const { layer, outputs, logins, prompts } = orgsSwitchTest({
171
+ orgId: Option.some('org_current'),
172
+ pick: 'Third Org',
173
+ });
174
+ return Effect.gen(function* () {
175
+ yield* runOrgsSwitch({ orgId: Option.none(), limit: 50 });
176
+
177
+ expect(prompts).toEqual([
178
+ [
179
+ { label: 'Current Org', hint: 'org_current (current)' },
180
+ { label: 'First Org', hint: 'org_first' },
181
+ { label: 'Third Org', hint: 'org_third' },
182
+ ],
183
+ ]);
184
+ expect(logins).toEqual([['uak_orgs_switch', 'org_third', undefined]]);
185
+ expect(analytics.linked).toEqual(['member_org_third']);
186
+ expect(outputs).toEqual([JSON.stringify({ scope: 'global', org_id: 'org_third' })]);
187
+ }).pipe(Effect.provide(layer));
188
+ }
189
+ );
190
+
191
+ it.effect('[Given] several orgs and no current one [Then] the picker keeps the API order', () => {
192
+ const { layer, prompts } = orgsSwitchTest({ pick: 'First Org' });
193
+ return Effect.gen(function* () {
194
+ yield* runOrgsSwitch({ orgId: Option.none(), limit: 50 });
195
+
196
+ expect(prompts.map(options => options.map(option => option.hint))).toEqual([
197
+ ['org_first', 'org_current', 'org_third'],
198
+ ]);
199
+ }).pipe(Effect.provide(layer));
200
+ });
201
+
202
+ it.effect('[Given] one org [Then] it is stored without prompting', () => {
203
+ const { layer, logins, prompts } = orgsSwitchTest({
204
+ organizations: [{ id: 'org_only', name: 'Only Org' }],
205
+ });
206
+ return Effect.gen(function* () {
207
+ yield* runOrgsSwitch({ orgId: Option.none(), limit: 50 });
208
+
209
+ expect(prompts).toEqual([]);
210
+ expect(logins).toEqual([['uak_orgs_switch', 'org_only', undefined]]);
211
+ }).pipe(Effect.provide(layer));
212
+ });
213
+
214
+ it.effect('[Given] no orgs [Then] stores nothing, links nothing, and outputs nothing', () => {
215
+ const { layer, outputs, logins } = orgsSwitchTest({ organizations: [] });
216
+ return Effect.gen(function* () {
217
+ yield* runOrgsSwitch({ orgId: Option.none(), limit: 50 });
218
+
219
+ expect(logins).toEqual([]);
220
+ expect(analytics.linked).toEqual([]);
221
+ expect(outputs).toEqual([]);
222
+ expect(yield* MockConsole.getLines()).toContain(`-- ${NO_ORG_SELECTED_OUTRO} --`);
223
+ }).pipe(Effect.provide(layer));
224
+ });
225
+
226
+ it.effect.each([
227
+ { limit: 50, expected: 50 },
228
+ { limit: 0, expected: 1 },
229
+ { limit: -3, expected: 1 },
230
+ { limit: 1001, expected: 1000 },
231
+ ])('[Given] limit $limit [Then] requests $expected organizations', ({ limit, expected }) => {
232
+ const { layer, requests } = orgsSwitchTest();
233
+ return Effect.gen(function* () {
234
+ yield* runOrgsSwitch({ orgId: Option.none(), limit });
235
+
236
+ expect(orgListLimits(requests)).toEqual([expected]);
237
+ }).pipe(Effect.provide(layer));
238
+ });
239
+
240
+ it.effect(
241
+ '[Given] no stored API key [Then] fails with NotLoggedInError before any request',
242
+ () => {
243
+ const { layer, logins, requests } = orgsSwitchTest({ apiKey: Option.none() });
244
+ return Effect.gen(function* () {
245
+ const error = yield* Effect.flip(runOrgsSwitch({ orgId: Option.none(), limit: 50 }));
246
+
247
+ expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
248
+ expect(requests).toEqual([]);
249
+ expect(logins).toEqual([]);
250
+ }).pipe(Effect.provide(layer));
251
+ }
252
+ );
253
+});