@devries-cameron20 / composio Mirror · read-only / commits / 3379d3305
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 08:30 UTC

refactor(cli): move `orgs switch` into the directory shape (#4995)

This PR: - moves `orgs switch` from `orgs/commands/orgs.switch.cmd.ts` to `orgs/switch/orgs.switch.{cmd,handler,format}.ts`, next to `orgs/list/` from #4972; the command file only declares `--org-id` and `--limit` and passes `runOrgsSwitch` to `Command.make`. `orgs/commands/` no longer exists - puts the intro, note, outros, success line, and the `{"scope":"global","org_id":…}` stdout JSON in `orgs.switch.format.ts`; the "no org selected" branch is an `Option.match`. The persisted result is unchanged: `ctx.login(apiKey, orgId, storedTestUserId)`, then the analytics link - replaces the handler's own "No user API key found" warning with `Effect.fromOption(ctx.data.apiKey, notLoggedIn)`. The `orgs` group already pipes `requireLogin`, so through the CLI the branch was unreachable and the logged-out exit is unchanged (`NotLoggedInError`, exit 1) - moves `orgs.switch.cmd.test.ts` to its mirrored path and extends it (logged out; `--org-id` with full stdout/stderr and the written `user_data.json` keeping the key and test user id; a single org auto-selected; no orgs leaving the stored org alone). Adds `orgs.switch.handler.test.ts`, which drives the interactive picker through the `TerminalUI` test double: current org listed first with its `(current)` hint, the picked org stored and linked, API order without a current org, no prompt for one org, the empty case, the limit clamp table, and a missing key - part of the CLI command-layout series (legacy-shape cleanup before U10); no user-visible change, so no CHANGELOG entry ## Context Verified: the extended `orgs.switch.cmd.test.ts` passes unchanged against the `origin/next` (c37b41dd8) source before the move. On the branch tip: `pnpm --filter @composio/cli typecheck` passes; `pnpm --filter @composio/cli test` 188 files, 2055 passed, 1 skipped, `validate:command-tests` at 2 exemptions (unchanged), `root-help-consistency.test.ts` green; `lint:effect` 0 diagnostics; `oxlint` and prettier clean on touched files; root `pnpm typecheck` passes. Binary smoke (isolated `HOME`, developer mode on, telemetry off): 21 invocations covering root/`orgs`/`orgs switch`/`orgs list`/`dev projects` `--help`, logged-out `orgs switch` (with and without `--org-id`, `--limit`), and logged-in `orgs switch --org-id`. stdout, stderr, exit codes, and the resulting `user_data.json` and `config.json` are byte-identical to an `origin/next` binary, apart from minified function names in one stack trace for an expected connection failure.

Alberto Schiabel committed Oct 20, 2026 at 20:00 UTC 3379d3305f1e5c586ec77b2df803d39a527cf8e4
8 files changed +517 -124
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts deleted
-63
@@ -1,63 +0,0 @@
1 -import { Command, Flag } from 'effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { runOrgSelection } from 'src/effects/select-org-project';
4 -import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
5 -import { TerminalUI } from 'src/services/terminal-ui';
6 -import { ComposioUserContext } from 'src/services/user-context';
7 -
8 -const orgId = Flag.String('org-id').pipe(
9 - Flag.optional,
10 - Flag.withDescription('Organization ID to use as global default')
11 -);
12 -
13 -const limit = Flag.Int('limit').pipe(
14 - Flag.withDefault(50),
15 - Flag.withDescription('Max orgs to fetch from API (default: 50)')
16 -);
17 -
18 -export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId, limit }) =>
19 - Effect.gen(function* () {
20 - const ui = yield* TerminalUI;
21 - const ctx = yield* ComposioUserContext;
22 - yield* ui.intro('composio orgs switch');
23 -
24 - const apiKey = Option.getOrUndefined(ctx.data.apiKey);
25 - if (!apiKey) {
26 - yield* ui.log.warn('No user API key found. Run `composio login` first.');
27 - yield* ui.outro('');
28 - return;
29 - }
30 -
31 - yield* ui.note(
32 - 'This updates your current org for CLI commands. Use `composio dev init` for local developer project setup.',
33 - 'Current org'
34 - );
35 -
36 - const result = yield* runOrgSelection({
37 - apiKey,
38 - explicitOrgId: Option.getOrUndefined(orgId),
39 - currentOrgId: Option.getOrUndefined(ctx.data.orgId),
40 - limit,
41 - });
42 -
43 - if (!result) {
44 - yield* ui.outro('No org selected.');
45 - return;
46 - }
47 -
48 - yield* ctx.login(apiKey, result.id, Option.getOrUndefined(ctx.data.testUserId));
49 - yield* linkAnalyticsIdentityForOrg({
50 - apiKey,
51 - orgId: result.id,
52 - });
53 -
54 - yield* ui.log.success(`Updated current org to "${result.name}".`);
55 - yield* ui.output(
56 - JSON.stringify({
57 - scope: 'global',
58 - org_id: result.id,
59 - })
60 - );
61 - yield* ui.outro('Current org updated.');
62 - })
63 -).pipe(Command.withDescription('Switch current organization context.'));
ts/packages/cli/src/commands/orgs/orgs.cmd.ts
+1 -1
@@ -1,7 +1,7 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Command } from 'effect/cli';
3 import { orgsCmd$List } from './list/orgs.list.cmd';
4 -import { orgsCmd$Switch } from './commands/orgs.switch.cmd';
4 +import { orgsCmd$Switch } from './switch/orgs.switch.cmd';
5
6 /**
7 * CLI entry point for organization context commands.
ts/packages/cli/src/commands/orgs/switch/orgs.switch.cmd.ts new
+16
@@ -0,0 +1,16 @@
1 +import { Command, Flag } from 'effect/cli';
2 +import { runOrgsSwitch } from './orgs.switch.handler';
3 +
4 +const orgId = Flag.String('org-id').pipe(
5 + Flag.optional,
6 + Flag.withDescription('Organization ID to use as global default')
7 +);
8 +
9 +const limit = Flag.Int('limit').pipe(
10 + Flag.withDefault(50),
11 + Flag.withDescription('Max orgs to fetch from API (default: 50)')
12 +);
13 +
14 +export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, runOrgsSwitch).pipe(
15 + Command.withDescription('Switch current organization context.')
16 +);
ts/packages/cli/src/commands/orgs/switch/orgs.switch.format.ts new
+19
@@ -0,0 +1,19 @@
1 +// --- stderr -----------------------------------------------------------------------------------
2 +
3 +export const ORGS_SWITCH_INTRO = 'composio orgs switch';
4 +export const CURRENT_ORG_NOTE_TITLE = 'Current org';
5 +export const CURRENT_ORG_NOTE =
6 + 'This updates your current org for CLI commands. Use `composio dev init` for local developer project setup.';
7 +export const NO_ORG_SELECTED_OUTRO = 'No org selected.';
8 +export const ORG_UPDATED_OUTRO = 'Current org updated.';
9 +
10 +export const updatedOrgMessage = (orgName: string) => `Updated current org to "${orgName}".`;
11 +
12 +// --- stdout -----------------------------------------------------------------------------------
13 +
14 +/** The org now stored as the global default. */
15 +export const formatSwitchedOrgJson = (orgId: string) =>
16 + JSON.stringify({
17 + scope: 'global',
18 + org_id: orgId,
19 + });
ts/packages/cli/src/commands/orgs/switch/orgs.switch.handler.ts new
+56
@@ -0,0 +1,56 @@
1 +import { Effect, Option } from 'effect';
2 +import { notLoggedIn } from 'src/commands/errors';
3 +import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
4 +import { runOrgSelection } from 'src/effects/select-org-project';
5 +import { TerminalUI } from 'src/services/terminal-ui';
6 +import { ComposioUserContext } from 'src/services/user-context';
7 +import {
8 + CURRENT_ORG_NOTE,
9 + CURRENT_ORG_NOTE_TITLE,
10 + NO_ORG_SELECTED_OUTRO,
11 + ORGS_SWITCH_INTRO,
12 + ORG_UPDATED_OUTRO,
13 + formatSwitchedOrgJson,
14 + updatedOrgMessage,
15 +} from './orgs.switch.format';
16 +
17 +/** The flags of `composio orgs switch`. */
18 +export type OrgsSwitchParams = {
19 + readonly orgId: Option.Option<string>;
20 + readonly limit: number;
21 +};
22 +
23 +/**
24 + * Stores `--org-id`, or the org picked from the user's organizations, as the global default.
25 + * The stored API key and test user id are kept; analytics is linked to the new membership.
26 + */
27 +export const runOrgsSwitch = ({ orgId, limit }: OrgsSwitchParams) =>
28 + Effect.gen(function* () {
29 + const ui = yield* TerminalUI;
30 + const ctx = yield* ComposioUserContext;
31 + // `requireLogin` on the `orgs` group has already proven the key is there.
32 + const apiKey = yield* Effect.fromOption(ctx.data.apiKey, notLoggedIn);
33 +
34 + yield* ui.intro(ORGS_SWITCH_INTRO);
35 + yield* ui.note(CURRENT_ORG_NOTE, CURRENT_ORG_NOTE_TITLE);
36 +
37 + const selected = yield* runOrgSelection({
38 + apiKey,
39 + explicitOrgId: Option.getOrUndefined(orgId),
40 + currentOrgId: Option.getOrUndefined(ctx.data.orgId),
41 + limit,
42 + });
43 +
44 + yield* Option.match(Option.fromUndefinedOr(selected), {
45 + onNone: () => ui.outro(NO_ORG_SELECTED_OUTRO),
46 + onSome: org =>
47 + Effect.gen(function* () {
48 + yield* ctx.login(apiKey, org.id, Option.getOrUndefined(ctx.data.testUserId));
49 + yield* linkAnalyticsIdentityForOrg({ apiKey, orgId: org.id });
50 +
51 + yield* ui.log.success(updatedOrgMessage(org.name));
52 + yield* ui.output(formatSwitchedOrgJson(org.id));
53 + yield* ui.outro(ORG_UPDATED_OUTRO);
54 + }),
55 + });
56 + });
ts/packages/cli/test/src/commands/orgs/orgs.switch.cmd.test.ts deleted
-60
@@ -1,60 +0,0 @@
1 -import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
3 -import { afterEach, vi } from 'vitest';
4 -import { cli, TestLive } from 'test/__utils__';
5 -import { makeSessionInfo } from 'test/__utils__/models/account';
6 -import type { MockRequestScope } from 'test/__utils__/services/test-layer';
7 -
8 -const analyticsMocks = vi.hoisted(() => ({
9 - linkCalls: [] as string[],
10 -}));
11 -
12 -vi.mock('src/analytics/dispatch', async importOriginal => {
13 - const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
14 - const { Effect } = await import('effect');
15 - return {
16 - ...actual,
17 - analyticsIdentityLinkingEnabled: Effect.succeed(true),
18 - linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
19 - Effect.sync(() => {
20 - analyticsMocks.linkCalls.push(apolloUserId);
21 - })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
22 - };
23 -});
24 -
25 -describe('CLI: composio orgs switch', () => {
26 - afterEach(() => {
27 - vi.restoreAllMocks();
28 - analyticsMocks.linkCalls.length = 0;
29 - });
30 -
31 - const testConfigProvider = ConfigProvider.fromEnvRecord({
32 - COMPOSIO_USER_API_KEY: 'uak_switch_test',
33 - });
34 -
35 - const sessionInfoScopes: MockRequestScope[] = [];
36 - layer(
37 - TestLive({
38 - baseConfigProvider: testConfigProvider,
39 - accountData: {
40 - sessionInfo: scope => {
41 - sessionInfoScopes.push(scope);
42 - return makeSessionInfo({
43 - orgId: 'org_selected',
44 - orgName: 'Selected Org',
45 - orgMemberId: 'member_selected',
46 - });
47 - },
48 - },
49 - })
50 - )(it => {
51 - it.effect('[Then] links analytics to the selected org membership', () =>
52 - Effect.gen(function* () {
53 - yield* cli(['orgs', 'switch', '--org-id', 'org_selected']);
54 -
55 - expect(sessionInfoScopes.map(scope => scope.orgId)).toEqual(['org_selected']);
56 - expect(analyticsMocks.linkCalls).toEqual(['member_selected']);
57 - })
58 - );
59 - });
60 -});
ts/packages/cli/test/src/commands/orgs/switch/orgs.switch.cmd.test.ts new
+172
@@ -0,0 +1,172 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import * as FileSystem from 'effect/FileSystem';
4 +import path from 'node:path';
5 +import { afterEach, vi } from 'vitest';
6 +import * as constants from 'src/constants';
7 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 +import { cli, MockConsole, TestLive } from 'test/__utils__';
9 +import { makeSessionInfo } from 'test/__utils__/models/account';
10 +import type { MockAccountRequest, MockRequestScope } from 'test/__utils__/services/test-layer';
11 +
12 +const analyticsMocks = vi.hoisted(() => ({
13 + linkCalls: [] as string[],
14 +}));
15 +
16 +vi.mock('src/analytics/dispatch', async importOriginal => {
17 + const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
18 + const { Effect } = await import('effect');
19 + return {
20 + ...actual,
21 + analyticsIdentityLinkingEnabled: Effect.succeed(true),
22 + linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
23 + Effect.sync(() => {
24 + analyticsMocks.linkCalls.push(apolloUserId);
25 + })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
26 + };
27 +});
28 +
29 +// The fixture stores a login with current org `org_test` and test user id `global-default`.
30 +const FIXTURE_WITH_TEST_USER = 'global-test-user-id';
31 +
32 +const SELECTED_SESSION_INFO = makeSessionInfo({
33 + orgId: 'org_selected',
34 + orgName: 'Selected Org',
35 + orgMemberId: 'member_selected',
36 +});
37 +
38 +/** The user config `ComposioUserContext` wrote to disk. */
39 +const readStoredUserConfig = Effect.gen(function* () {
40 + const fs = yield* FileSystem.FileSystem;
41 + const cacheDir = yield* setupCacheDir;
42 + const raw = yield* fs.readFileString(path.join(cacheDir, constants.USER_CONFIG_FILE_NAME));
43 + return JSON.parse(raw) as Record<string, unknown>;
44 +});
45 +
46 +describe('CLI: composio orgs switch', () => {
47 + afterEach(() => {
48 + vi.restoreAllMocks();
49 + analyticsMocks.linkCalls.length = 0;
50 + });
51 +
52 + layer(TestLive())('[Given] no API key', it => {
53 + it.effect('[Then] fails with NotLoggedInError', () =>
54 + Effect.gen(function* () {
55 + const error = yield* cli(['orgs', 'switch', '--org-id', 'org_selected']).pipe(Effect.flip);
56 + expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
57 + })
58 + );
59 + });
60 +
61 + const testConfigProvider = ConfigProvider.fromEnvRecord({
62 + COMPOSIO_USER_API_KEY: 'uak_switch_test',
63 + });
64 +
65 + const sessionInfoScopes: MockRequestScope[] = [];
66 + layer(
67 + TestLive({
68 + baseConfigProvider: testConfigProvider,
69 + accountData: {
70 + sessionInfo: scope => {
71 + sessionInfoScopes.push(scope);
72 + return SELECTED_SESSION_INFO;
73 + },
74 + },
75 + })
76 + )(it => {
77 + it.effect('[Then] links analytics to the selected org membership', () =>
78 + Effect.gen(function* () {
79 + yield* cli(['orgs', 'switch', '--org-id', 'org_selected']);
80 +
81 + expect(sessionInfoScopes.map(scope => scope.orgId)).toEqual(['org_selected']);
82 + expect(analyticsMocks.linkCalls).toEqual(['member_selected']);
83 + })
84 + );
85 + });
86 +
87 + const explicitRequests: MockAccountRequest[] = [];
88 + layer(
89 + TestLive({
90 + fixture: FIXTURE_WITH_TEST_USER,
91 + accountData: {
92 + sessionInfo: SELECTED_SESSION_INFO,
93 + organizations: [{ id: 'org_other', name: 'Other Org' }],
94 + onRequest: request => explicitRequests.push(request),
95 + },
96 + })
97 + )('[Given] --org-id', it => {
98 + it.effect(
99 + '[Then] stores that org, keeps the key and test user id, and prints it on stdout',
100 + () =>
101 + Effect.gen(function* () {
102 + yield* cli(['orgs', 'switch', '--org-id', 'org_selected']);
103 +
104 + expect(explicitRequests.map(request => request.operation)).not.toContain('org.list');
105 +
106 + const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
107 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
108 + expect(stdout).toEqual([JSON.stringify({ scope: 'global', org_id: 'org_selected' })]);
109 + expect(stderr).toEqual([
110 + '-- composio orgs switch --',
111 + '[Current org] This updates your current org for CLI commands. Use `composio dev init` for local developer project setup.',
112 + 'Selected organization: "org_selected" (org_selected)',
113 + 'Updated current org to "org_selected".',
114 + '-- Current org updated. --',
115 + ]);
116 +
117 + expect(yield* readStoredUserConfig).toMatchObject({
118 + api_key: 'test_api_key',
119 + org_id: 'org_selected',
120 + test_user_id: 'global-default',
121 + });
122 + })
123 + );
124 + });
125 +
126 + layer(
127 + TestLive({
128 + fixture: FIXTURE_WITH_TEST_USER,
129 + accountData: {
130 + sessionInfo: SELECTED_SESSION_INFO,
131 + organizations: [{ id: 'org_selected', name: 'Selected Org' }],
132 + },
133 + })
134 + )('[Given] no --org-id and one organization', it => {
135 + it.effect('[Then] selects it without prompting and stores it', () =>
136 + Effect.gen(function* () {
137 + yield* cli(['orgs', 'switch']);
138 +
139 + const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
140 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
141 + expect(stdout).toEqual([JSON.stringify({ scope: 'global', org_id: 'org_selected' })]);
142 + expect(stderr).toContain('Loaded 1 orgs');
143 + expect(stderr).toContain('Updated current org to "Selected Org".');
144 + expect((yield* readStoredUserConfig).org_id).toBe('org_selected');
145 + })
146 + );
147 + });
148 +
149 + layer(TestLive({ fixture: FIXTURE_WITH_TEST_USER, accountData: { organizations: [] } }))(
150 + '[Given] no --org-id and no organizations',
151 + it => {
152 + it.effect('[Then] warns, prints no data, and keeps the stored org', () =>
153 + Effect.gen(function* () {
154 + yield* cli(['orgs', 'switch']);
155 +
156 + const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
157 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
158 + expect(stdout).toEqual([]);
159 + expect(stderr).toEqual([
160 + '-- composio orgs switch --',
161 + '[Current org] This updates your current org for CLI commands. Use `composio dev init` for local developer project setup.',
162 + 'Loaded 0 orgs',
163 + 'No organizations found for this API key.',
164 + '-- No org selected. --',
165 + ]);
166 + expect((yield* readStoredUserConfig).org_id).toBe('org_test');
167 + expect(analyticsMocks.linkCalls).toEqual([]);
168 + })
169 + );
170 + }
171 + );
172 +});
ts/packages/cli/test/src/commands/orgs/switch/orgs.switch.handler.test.ts new
+253
@@ -0,0 +1,253 @@
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 +});