@devries-cameron20 / composio-1 / commits / 19eebd4d7
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.

fix(cli): read dev toolkits connection status in the resolved project (#5364)

This PR: - closes [PRDE-2212](https://linear.app/composio/issue/PRDE-2212/cli-e2e-tests-fake-backend-operation-suites-and-agent-journeys-with) - builds on top of https://github.com/ComposioHQ/composio/pull/5363; split from https://github.com/ComposioHQ/composio/pull/5334 - reads developer toolkit connection status in the resolved project rather than the key’s implicit default - shares project and optional acting-user resolution, retains catalog output when optional project lookup fails, and warns when --connected cannot be applied - keeps the passing operations, whoami, and agent-signin suites passing, including the no-project connected-filter regression in the CLI suite - passes the full CLI suite, CLI and workspace typechecks, Effect diagnostics, Oxlint, Prettier, and keyless Docker operations, whoami, and agent-signin suites The CLI test workflow runs for PRs targeting `next`, not this stack base; full CI completes after retargeting. The existing Docker scenarios cover these corrections; no recording changes are needed.

Alberto Schiabel committed Nov 16, 2026 at 13:22 UTC 19eebd4d7d00af1167886476ff18676a16d7eebc
9 files changed +620 -133
.agents/skills/cli-command/references/implementation.md
+1 -1
@@ -6,7 +6,7 @@ The [contributor guide](../../../../ts/packages/cli/CONTRIBUTING.md) traces one
6
7 - Groups register children through `withRegisteredSubcommands`, which supplies parsed identity and inherited policy. Direct `Command.withSubcommands` bypasses it.
8 - `withCommandMeta` declares login, hooks, telemetry family, and unsupported shared flags. Handlers do not repeat login gates or lifecycle reporting.
9 -- `CommandSurface` supplies root/dev context and dev shared flags. `actingUser()` resolves the acting user and project; `actingUserOption()` or `devActingUserOption(project)` finds an optional one for a developer project the command resolved. A user filter does not use a test-user fallback.
9 +- `CommandSurface` supplies root/dev context and dev shared flags. `actingUser()` resolves the acting user and project; `devActingUserOption(project)` finds an optional one for a developer project the command resolved. A user filter does not use a test-user fallback.
10 - The same command definition can have multiple registrations. Root shortcuts do not need copied handlers or descriptions.
11 - Changes to command paths or help summaries regenerate `COMMANDS.md` with `pnpm --filter @composio/cli run commands:map`.
12
ts/packages/cli/AGENTS.md
+2 -2
@@ -66,10 +66,10 @@ Rules:
66 - `<group>.<name>.handler.ts` exports the handler as a function of a plain params type it declares itself; the command proves it provides those params when it passes the handler to `Command.make`. Do not derive the params type from the `Command` value (no phantom commands, no `GetCmdParams`).
67 - A command that exists in both the root tree and the `dev` tree is defined once. The group supplies what differs between the two surfaces through `Command.withSharedFlags` and `Command.provide`, not through a second `Command.make` with a copied description. `--user-id` and `--project-name` are shared flags of the `dev` group (`dev.cmd.ts`), accepted before or after the subcommand name and documented once on every `dev` page; a handler reads them, and the tree it runs in, from `CommandSurface` (`surface.ts`) and never declares either flag itself, since `withSharedFlags` rejects a duplicate on a direct subcommand. A `dev` command that cannot honor one of them yet (it cannot target another project, or it does not act for a user) declares it in its `CommandMeta`: `withCommandMeta({ sharedFlags: NO_SHARED_FLAGS })` for both, `{ sharedFlags: { userId: false } }` for one, piped where its group registers it, or on a group entry for every subcommand under it. The selected command rejects such a flag right after it began, with a `CommandInputError` naming the command that ran (`dev projects list`, not the `dev projects` group that declared it), which telemetry records too; never type a command path for the message. The `dev` group's own `--mode` toggle calls `rejectSharedFlags` (`surface.ts`) with its own wording. `execute` and `playground-execute` keep two registrations because their names differ; they share one handler.
68 - A hint, example, or message that names a command (`composio …`) names a real registration on the tree it names: `orgs` is a root command, so `composio dev orgs switch` is wrong. `test/src/commands/command-references.test.ts` finds every `composio <words>` in a string or template literal under `src/` and fails when the words stop at a group or before any command; prose that only reads like a command goes in its `NOT_COMMANDS` list.
69 -- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `actingUserOption` / `devActingUserOption` (for commands that also run without one; the latter takes the developer project already resolved) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
69 +- A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `devActingUserOption` (for a dev command that also runs without one, given the developer project it resolved) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
70 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
71 - A group registers its subcommands with `withRegisteredSubcommands` (`src/commands/registration.ts`), never `Command.withSubcommands`, so each subcommand gets its command identity.
72 -- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`. A `dev` command that reads or writes a project's resources (auth configs, connected accounts, trigger instances, logs) resolves its developer project with `resolveDeveloperResourceProject` (`surface.ts`: `--project-name`'s, else the directory's, else the backend's default developer project, read once from session info and named on stderr even off a terminal, since these commands once let the backend pick it) and sends those requests on `ComposioClientSingleton.getFor` with it (`developerProjectClient`), or passes it to the repository method that takes it: `get()` carries no org or project, so the backend would pick the project per request. A command that always required a developer project (`dev playground-execute`, `dev triggers listen`, `dev connected-accounts list` and `link`) uses `resolveSurfaceProject('developer')` or `actingUser`, which fail with `ProjectResolutionError` instead. Neither ever sends a request to a directory project outside the logged-in org (or, with no stored org, outside the key's orgs).
72 +- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`. A `dev` command that reads or writes a project's resources (auth configs, connected accounts, trigger instances, logs, a tool router session) resolves its developer project with `resolveDeveloperResourceProject` (`surface.ts`: `--project-name`'s, else the directory's, else the backend's default developer project, read once from session info and named on stderr even off a terminal, since these commands once let the backend pick it) and sends those requests on `ComposioClientSingleton.getFor` with it (`developerProjectClient`), or passes it to the repository method that takes it: `get()` carries no org or project, so the backend would pick the project per request. A command that always required a developer project (`dev playground-execute`, `dev triggers listen`, `dev connected-accounts list` and `link`) uses `resolveSurfaceProject('developer')` or `actingUser`, which fail with `ProjectResolutionError` instead. Neither ever sends a request to a directory project outside the logged-in org (or, with no stored org, outside the key's orgs).
73 - A group entry is recognised by its place in the tree: `<dir>/<dir>.cmd.ts` or `<dir>/root-<dir>.cmd.ts` with other `.cmd.ts` files below `<dir>/`. The same name with nothing below it (`logout/logout.cmd.ts`) is a top-level command. Every command needs a test; a group entry does not, though one with a default action (`generate`) still gets one.
74
75 Legacy shape still present while commands migrate: `<group>/commands/<group>.<name>.cmd.ts` holding flags, handler, helpers, and errors in one file, and top-level `<name>.cmd.ts` doing the same. Migrate a command to the directory shape when you touch it for more than a one-line fix, one command per PR.
ts/packages/cli/CHANGELOG.md
+2
@@ -4,6 +4,8 @@
4
5 ### Patch Changes
6
7 +- `composio dev toolkits list` and `info` now read a user's connection status in the resolved developer project. When no directory project applies, `--user-id` or the global test user can use the default developer project. A failed project lookup leaves the catalog available and warns when `--connected` cannot be applied.
8 +
9 - A directory developer project must belong to the stored login's org, checked before any request. With no stored org, the CLI checks every page of the active key's org list. Resource commands refuse a project outside that boundary and name why they use the default developer project instead.
10
11 - `composio dev` resource commands now act on the directory's developer project or `--project-name`, rather than leaving the backend to choose. Without a directory project they keep working by resolving the default developer project once from session info and naming it on stderr, including in scripts. Project lookup failures preserve their cause and recovery advice.
ts/packages/cli/src/commands/surface.ts
+47 -51
@@ -108,12 +108,12 @@ export type ActingUserSource = 'consumer' | 'flag' | 'directory-test-user' | 'gl
108
109 /**
110 * The user a command acts as (glossary "Acting user"), with the project it was resolved
111 - * against. `actingUserOption` leaves the project optional; see there.
111 + * against.
112 */
113 -export interface ActingUser<Project = ResolvedCommandProject> {
113 +export interface ActingUser {
114 readonly userId: string;
115 readonly source: ActingUserSource;
116 - readonly project: Project;
116 + readonly project: ResolvedCommandProject;
117 }
118
119 /** No step of the acting-user rule found a user for the command. */
@@ -144,22 +144,20 @@ const missingUserMessage = (tree: CommandTree, projectName: Option.Option<string
144
145 /**
146 * The test user the directory configures (`.composio/project.json`), for a command that runs
147 - * against the directory's project. A `--project-name` that names another project does not
148 - * borrow it, so the command falls back to the global test user; `namedProjectId` is the id of
149 - * the project `--project-name` resolved to, or none without the flag.
147 + * against the directory's project (`projectId`, the project the command resolved). Another
148 + * project, one `--project-name` names or the default developer project standing in for the
149 + * directory's, does not borrow it, so the command falls back to the global test user.
150 */
151 const directoryTestUserId = (
152 directoryProject: Option.Option<{
153 readonly projectId: string;
154 readonly testUserId: Option.Option<string>;
155 }>,
156 - namedProjectId: Option.Option<string>
156 + projectId: string
157 ): Option.Option<string> =>
158 pipe(
159 directoryProject,
160 - Option.filter(
161 - keys => Option.isNone(namedProjectId) || Option.contains(namedProjectId, keys.projectId)
162 - ),
160 + Option.filter(keys => keys.projectId === projectId),
161 Option.flatMap(keys => keys.testUserId)
162 );
163
@@ -209,8 +207,8 @@ const consumerUser = (project: ResolvedCommandProject) =>
207 Option.map(userId => ({ userId, source: 'consumer' as const }))
208 );
209
212 -/** The dev tree's user for a project, `namedProjectId` being the `--project-name` project's id. */
213 -const devUser = (namedProjectId: Option.Option<string>) =>
210 +/** The dev tree's user for the developer project `projectId` the command resolved. */
211 +const devUser = (projectId: string) =>
212 Effect.gen(function* () {
213 const surface = yield* CommandSurface;
214 const userContext = yield* ComposioUserContext;
@@ -221,7 +219,7 @@ const devUser = (namedProjectId: Option.Option<string>) =>
219 );
220 return devActingUser({
221 flag: surface.userId,
224 - directoryTestUserId: directoryTestUserId(directoryProject, namedProjectId),
222 + directoryTestUserId: directoryTestUserId(directoryProject, projectId),
223 globalTestUserId: userContext.data.testUserId,
224 });
225 });
@@ -243,10 +241,7 @@ export const actingUser = () =>
241 ? { mode: 'consumer' }
242 : { mode: 'developer', projectName: Option.getOrUndefined(projectName) }
243 );
246 - const user =
247 - tree === 'root'
248 - ? consumerUser(project)
249 - : yield* devUser(Option.as(projectName, project.projectId));
244 + const user = tree === 'root' ? consumerUser(project) : yield* devUser(project.projectId);
245 yield* announceFallback(user);
246 if (Option.isNone(user)) {
247 return yield* new MissingActingUserError({
@@ -258,39 +253,6 @@ export const actingUser = () =>
253 return { ...user.value, project } satisfies ActingUser;
254 });
255
261 -/**
262 - * The acting user for a command that also runs without one, by the same rule as `actingUser`.
263 - * On the dev tree it resolves only the project `--project-name` names, so `project` is none when
264 - * the command runs against the directory's project through the default client; on the root
265 - * tree it is the consumer project. Names a test user standing in on stderr, as `actingUser`
266 - * does. Fails only when that project cannot be resolved.
267 - */
268 -export const actingUserOption = () =>
269 - Effect.gen(function* () {
270 - const surface = yield* CommandSurface;
271 - if (surface.tree === 'root') {
272 - const project = yield* resolveCommandProject({ mode: 'consumer' });
273 - return Option.map(
274 - consumerUser(project),
275 - (user): ActingUser<Option.Option<ResolvedCommandProject>> => ({
276 - ...user,
277 - project: Option.some(project),
278 - })
279 - );
280 - }
281 - const namedProject = yield* Effect.transposeOption(
282 - Option.map(surface.projectName, projectName =>
283 - resolveCommandProject({ mode: 'developer', projectName })
284 - )
285 - );
286 - const user = yield* devUser(Option.map(namedProject, project => project.projectId));
287 - yield* announceFallback(user);
288 - return Option.map(user, (found): ActingUser<Option.Option<ResolvedCommandProject>> => ({
289 - ...found,
290 - project: namedProject,
291 - }));
292 - });
293 -
256 /**
257 * The dev tree's acting user for a command that also runs without one, against the developer
258 * project the command resolved (`resolveSurfaceProject('developer')`), by the same rule as
@@ -300,11 +262,45 @@ export const actingUserOption = () =>
262 */
263 export const devActingUserOption = (project: ResolvedCommandProject) =>
264 Effect.gen(function* () {
303 - const user = yield* devUser(Option.some(project.projectId));
265 + const user = yield* devUser(project.projectId);
266 yield* announceFallback(user);
267 return Option.map(user, (found): ActingUser => ({ ...found, project }));
268 });
269
270 +/**
271 + * The developer project and acting user of a dev command whose main work needs neither (it only
272 + * adds a user's connection status): the user is none when the project is. The backend's default
273 + * developer project stands in for the directory's (`resolveDeveloperResourceProject`, named on
274 + * stderr) only when it can serve a user: `--user-id` or the global test user, since the
275 + * directory's test user belongs to the directory's own project. Without `--project-name`, a
276 + * project that cannot be resolved, for whatever reason, is none; a `--project-name` that cannot
277 + * be resolved still fails.
278 + */
279 +export const resolveSurfaceProjectAndUserOption = Effect.gen(function* () {
280 + const surface = yield* CommandSurface;
281 + const userContext = yield* ComposioUserContext;
282 + const userBeyondDirectory = Option.orElse(surface.userId, () => userContext.data.testUserId);
283 + const resolved = (
284 + Option.isSome(userBeyondDirectory)
285 + ? resolveDeveloperResourceProject
286 + : resolveSurfaceProject('developer')
287 + ).pipe(Effect.map(Option.some));
288 + const project = yield* Option.isSome(surface.projectName)
289 + ? resolved
290 + : resolved.pipe(
291 + Effect.catch(error =>
292 + Effect.logDebug('No developer project for connection status:', error).pipe(
293 + Effect.as(Option.none<ResolvedCommandProject>())
294 + )
295 + )
296 + );
297 + const user = yield* Effect.map(
298 + Effect.transposeOption(Option.map(project, devActingUserOption)),
299 + Option.flatten
300 + );
301 + return { project, user };
302 +});
303 +
304 /** A shared flag of the `dev` group. */
305 export type SharedFlag = '--user-id' | '--project-name';
306
ts/packages/cli/src/commands/toolkits/info/toolkits.info.handler.ts
+19 -20
@@ -7,7 +7,7 @@ import { resolveToolRouterSession } from 'src/effects/create-tool-router-session
7 import { extractMessage } from 'src/utils/api-error-extraction';
8 import { reportFailure } from 'src/effects/report-failure';
9 import { commandInputError } from 'src/commands/errors';
10 -import { actingUserOption } from 'src/commands/surface';
10 +import { resolveSurfaceProjectAndUserOption } from 'src/commands/surface';
11 import { BROWSE_TOOLKITS_HINT, formatToolkitInfo, formatToolkitInfoJson } from '../format';
12 import { ToolkitsInfoRequestError } from './toolkits.info.errors';
13
@@ -19,10 +19,12 @@ export type ToolkitsInfoParams = {
19 const invalidInput = commandInputError('dev toolkits info');
20
21 /**
22 - * Shows a toolkit with its connection status for the surface's user: the `dev`
23 - * group's `--user-id`, then the project test user id, then the global one. A missing
24 - * `<slug>` fails with a `CommandInputError` before any request; a failed lookup or an
25 - * unknown toolkit is reported on stderr and exits 1.
22 + * Shows a toolkit with its connection status in the developer project
23 + * (`resolveSurfaceProjectAndUserOption`: `--project-name`'s, the directory's, or for `--user-id`
24 + * or the global test user the backend's default one) for the surface's user: the `dev` group's
25 + * `--user-id`, then the project test user id, then the global one. Without a developer project the toolkit is shown without
26 + * connection status. A missing `<slug>` fails with a `CommandInputError` before any request; a
27 + * failed lookup or an unknown toolkit is reported on stderr and exits 1.
28 */
29 export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
30 Effect.gen(function* () {
@@ -38,18 +40,14 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
40
41 const slugValue = slug.value;
42 // Resolved outside the session lookup, whose failures only drop the connection status.
41 - const acting = yield* actingUserOption();
43 + const { project, user: acting } = yield* resolveSurfaceProjectAndUserOption;
44 const repo = yield* ComposioToolkitsRepository;
43 - // The client of the project --project-name names; none keeps the default client.
44 - const namedClient = yield* Effect.transposeOption(
45 - Option.map(
46 - Option.flatMap(acting, found => found.project),
47 - project => clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId })
48 - )
49 - );
50 - const resolvedUserId = Option.map(acting, found => found.userId);
45
52 - if (Option.isNone(acting)) {
46 + if (Option.isNone(project)) {
47 + yield* ui.log.info(
48 + 'No developer project to read connection status from; showing toolkit details without it. Run `composio dev init`, or pass --user-id or --project-name.'
49 + );
50 + } else if (Option.isNone(acting)) {
51 yield* ui.log.info(
52 'No test user id found; showing toolkit details without connection status.'
53 );
@@ -61,11 +59,12 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
59 Effect.gen(function* () {
60 const detailedToolkitOpt = yield* repo.getToolkitDetailed(slugValue).pipe(Effect.option);
61
64 - if (Option.isSome(resolvedUserId)) {
65 - const client = Option.isSome(namedClient)
66 - ? namedClient.value
67 - : yield* clientSingleton.get();
68 - const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
62 + if (Option.isSome(acting)) {
63 + const client = yield* clientSingleton.getFor({
64 + orgId: acting.value.project.orgId,
65 + projectId: acting.value.project.projectId,
66 + });
67 + const { sessionId } = yield* resolveToolRouterSession(client, acting.value.userId);
68 const sessionToolkits = yield* client.toolRouter.session
69 // Only the first item is read, and only a few of its fields.
70 .toolkits(sessionId, { toolkits: [slugValue] }, idempotent)
ts/packages/cli/src/commands/toolkits/list/toolkits.list.handler.ts
+28 -18
@@ -1,6 +1,10 @@
1 import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';
2 import { Array as Arr, Effect, Option } from 'effect';
3 -import { actingUserOption, fallbackNotice } from 'src/commands/surface';
3 +import {
4 + fallbackNotice,
5 + resolveSurfaceProjectAndUserOption,
6 + warnOnStderr,
7 +} from 'src/commands/surface';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
10 import { idempotent } from 'src/services/composio-request';
@@ -42,9 +46,16 @@ export const applyConnectedFilter = (
46 return { rows, filterSkipped: params.connectedOnly && params.userResolved };
47 };
48
49 +/** Why the listing carries no connection status when no developer project was resolved. */
50 +const NO_PROJECT_STATUS_MESSAGE =
51 + 'No developer project to read connection status from; showing toolkits without it. Run `composio dev init`, or pass --user-id or --project-name.';
52 +
53 /**
46 - * Lists the toolkit catalog. When a user is known, the rows also carry that user's connection
47 - * status, read from a tool router session; a failed session read only drops the status.
54 + * Lists the toolkit catalog. When the developer project and a user are known
55 + * (`resolveSurfaceProjectAndUserOption`: `--project-name`'s project, the directory's, or for
56 + * `--user-id` or the global test user the backend's default one), the rows also carry that
57 + * user's connection status, read from a tool router session in that project; a failed session
58 + * read only drops the status. Without a developer project the catalog is listed without it.
59 */
60 export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams) =>
61 Effect.gen(function* () {
@@ -54,23 +65,22 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
65
66 const clampedLimit = clampLimit(limit);
67 // Resolved outside the session lookup, whose failures only drop the connection status.
57 - const user = yield* actingUserOption();
58 - // The client of the project --project-name names; none keeps the default client.
59 - const namedClient = yield* Effect.transposeOption(
60 - Option.map(
61 - Option.flatMap(user, found => found.project),
62 - project => clientSingleton.getFor({ orgId: project.orgId, projectId: project.projectId })
63 - )
64 - );
68 + const { project, user } = yield* resolveSurfaceProjectAndUserOption;
69 +
70 + if (Option.isNone(project)) {
71 + yield* ui.log.info(NO_PROJECT_STATUS_MESSAGE);
72 + }
73
66 - // `actingUserOption` named the test user standing in; say how to pick another.
74 + // `devActingUserOption` named the test user standing in; say how to pick another.
75 if (Option.isSome(Option.flatMap(user, fallbackNotice))) {
76 yield* ui.log.message('To show status for a specific user, use `--user-id`.');
77 }
78
79 if (Option.isSome(connected) && Option.isNone(user)) {
72 - yield* ui.log.warn(
73 - '`--connected` requires a user id. Use `--user-id` or run `composio dev init`.'
80 + yield* warnOnStderr(
81 + Option.isNone(project)
82 + ? '`--connected` filter could not be applied — developer project unavailable. Showing the unfiltered catalog.'
83 + : '`--connected` requires a user id. Use `--user-id` or run `composio dev init`.'
84 );
85 }
86
@@ -85,9 +95,9 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
95 onNone: () => Effect.succeedNone,
96 onSome: resolved =>
97 Effect.gen(function* () {
88 - const client = yield* Option.match(namedClient, {
89 - onSome: Effect.succeed,
90 - onNone: () => clientSingleton.get(),
98 + const client = yield* clientSingleton.getFor({
99 + orgId: resolved.project.orgId,
100 + projectId: resolved.project.projectId,
101 });
102 const { sessionId } = yield* resolveToolRouterSession(client, resolved.userId);
103 return Option.some({ client, sessionId });
@@ -144,7 +154,7 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
154 }
155 );
156 if (filterSkipped) {
147 - yield* ui.log.warn('`--connected` filter could not be applied — session data unavailable.');
157 + yield* warnOnStderr('`--connected` filter could not be applied — session data unavailable.');
158 }
159
160 if (rows.length === 0) {
ts/packages/cli/test/src/commands/surface.acting-user.test.ts
+204 -21
@@ -3,20 +3,24 @@ import { describe, expect, it } from '@effect/vitest';
3 import { Effect, Layer, Option } from 'effect';
4 import {
5 actingUser,
6 - actingUserOption,
6 CommandSurface,
7 + devActingUserOption,
8 fallbackNotice,
9 MissingActingUserError,
10 + resolveSurfaceProject,
11 + resolveDeveloperResourceProject,
12 + resolveSurfaceProjectAndUserOption,
13 type ActingUserSource,
14 type CommandTree,
15 } from 'src/commands/surface';
16 import type { ProjectKeys } from 'src/models/project-keys';
17 +import { ProjectResolutionError } from 'src/services/command-project';
18 import { ComposioClientSingleton } from 'src/services/composio-clients';
19 import { ProjectContext } from 'src/services/project-context';
20 import { TerminalUI } from 'src/services/terminal-ui';
21 import { ComposioUserContext } from 'src/services/user-context';
22 import { mockAccountResources } from 'test/__utils__/layers/accounts';
19 -import { makeOrgProject } from 'test/__utils__/models/account';
23 +import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
24 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
25
26 const ORG_ID = 'org_test';
@@ -24,6 +28,8 @@ const CONSUMER_USER_ID = `consumer-user-${ORG_ID}`;
28 const CONSUMER_PROJECT_ID = 'consumer_project_test';
29 const DIRECTORY_PROJECT_ID = 'proj_directory';
30 const OTHER_PROJECT_ID = 'proj_other';
31 +/** The developer project the backend acts on for a request that names none. */
32 +const DEFAULT_PROJECT_ID = 'proj_newest';
33
34 const projects = [
35 makeOrgProject({ id: DIRECTORY_PROJECT_ID, name: 'directory', orgId: ORG_ID }),
@@ -63,7 +69,17 @@ const actingUserLayer = (fixture: Fixture, warnings: Array<string>) => {
69 email: Option.none(),
70 testUserId: has('directory') ? Option.some('directory-user') : Option.none(),
71 };
66 - const resources = mockAccountResources({ projects }, {});
72 + const resources = mockAccountResources(
73 + {
74 + projects,
75 + sessionInfo: makeSessionInfo({
76 + orgId: ORG_ID,
77 + projectNanoId: DEFAULT_PROJECT_ID,
78 + projectName: 'newest',
79 + }),
80 + },
81 + {}
82 + );
83 // The account resources answer only the fields `resolveCommandProject` reads.
84 const client = {
85 ...resources,
@@ -96,6 +112,8 @@ const actingUserLayer = (fixture: Fixture, warnings: Array<string>) => {
112 ...terminalUITestImpl.log,
113 warn: message => Effect.sync(() => warnings.push(message)),
114 },
115 + // Off a terminal a warning that must still show is a plain stderr line.
116 + error: message => Effect.sync(() => warnings.push(message)),
117 })
118 ),
119 Layer.succeed(
@@ -265,34 +283,199 @@ describe('an empty consumer user id', () => {
283 expect(error).toBeInstanceOf(MissingActingUserError);
284 })
285 );
286 +});
287 +
288 +describe('devActingUserOption', () => {
289 + it.effect.each(cases.filter(({ tree }) => tree === 'dev'))(
290 + '[Given] $name [Then] finds the rule’s user for the resolved project, or none',
291 + fixture =>
292 + Effect.gen(function* () {
293 + const warnings: Array<string> = [];
294 + const user = yield* run(
295 + Effect.flatMap(resolveSurfaceProject('developer'), devActingUserOption),
296 + fixture,
297 + warnings
298 + );
299 + const expected = expectedUser(fixture);
300 +
301 + expect(warnings).toEqual(expectedNotices(fixture));
302 + expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(expected);
303 + expect(Option.map(user, found => found.project.projectId)).toEqual(
304 + Option.map(expected, () => expectedProjectId(fixture))
305 + );
306 + })
307 + );
308 +});
309 +
310 +const withoutDirectoryProject = Layer.succeed(
311 + ProjectContext,
312 + ProjectContext.of({ resolve: Effect.succeedNone })
313 +);
314 +
315 +/** A directory set up, by someone else, for a project in an org the user is not logged in to. */
316 +const directoryProjectElsewhere = Layer.succeed(
317 + ProjectContext,
318 + ProjectContext.of({
319 + resolve: Effect.succeedSome({
320 + orgId: 'org_elsewhere',
321 + projectId: 'proj_elsewhere',
322 + projectName: Option.some('elsewhere'),
323 + orgName: Option.none(),
324 + email: Option.none(),
325 + testUserId: Option.some('elsewhere-user'),
326 + }),
327 + })
328 +);
329 +
330 +const NO_DIRECTORY_PROJECT_NOTICE =
331 + 'Warning: No developer project is set up for this directory; using "newest" (proj_newest), the newest developer project in the org you are logged in to, instead. Run `composio dev init` to choose one, or pass --project-name.';
332 +
333 +const DIRECTORY_PROJECT_ELSEWHERE_NOTICE =
334 + 'Warning: This directory\'s developer project is in org "org_elsewhere", not the org you are logged in to ("org_test"); using "newest" (proj_newest), the newest developer project in the org you are logged in to, instead. Run `composio orgs switch` to use the directory\'s org, or `composio dev init` to set this directory up in yours.';
335 +
336 +describe('resolveDeveloperResourceProject', () => {
337 + it.effect.each([
338 + { projectName: 'absent', expected: DIRECTORY_PROJECT_ID },
339 + { projectName: 'other', expected: OTHER_PROJECT_ID },
340 + ] as const)(
341 + '[Given] --project-name $projectName [Then] resolves that project with no notice',
342 + ({ projectName, expected }) =>
343 + Effect.gen(function* () {
344 + const warnings: Array<string> = [];
345 + const project = yield* run(
346 + resolveDeveloperResourceProject,
347 + { tree: 'dev', candidates: 'none', projectName },
348 + warnings
349 + );
350 +
351 + expect(project.projectId).toBe(expected);
352 + expect(warnings).toEqual([]);
353 + })
354 + );
355
269 - it.effect('[Given] an empty consumer user id [Then] actingUserOption finds none', () =>
356 + it.effect.each([
357 + {
358 + given: 'no directory project',
359 + layer: withoutDirectoryProject,
360 + notice: NO_DIRECTORY_PROJECT_NOTICE,
361 + },
362 + {
363 + given: 'a directory project in another org',
364 + layer: directoryProjectElsewhere,
365 + notice: DIRECTORY_PROJECT_ELSEWHERE_NOTICE,
366 + },
367 + ])(
368 + '[Given] $given [Then] uses the default developer project and says so on stderr',
369 + ({ layer, notice }) =>
370 + Effect.gen(function* () {
371 + const warnings: Array<string> = [];
372 + const project = yield* run(
373 + resolveDeveloperResourceProject.pipe(Effect.provide(layer)),
374 + { tree: 'dev', candidates: 'none', projectName: 'absent' },
375 + warnings
376 + );
377 +
378 + expect(project).toMatchObject({
379 + orgId: ORG_ID,
380 + projectId: DEFAULT_PROJECT_ID,
381 + source: 'developer-default',
382 + });
383 + expect(warnings).toEqual([notice]);
384 + })
385 + );
386 +
387 + it.effect('[Given] a --project-name the org does not hold [Then] fails', () =>
388 Effect.gen(function* () {
271 - const user = yield* run(actingUserOption(), fixture);
389 + const error = yield* run(
390 + Effect.flip(
391 + resolveDeveloperResourceProject.pipe(
392 + Effect.provide(
393 + CommandSurface.dev({ userId: Option.none(), projectName: Option.some('missing') })
394 + )
395 + )
396 + ),
397 + { tree: 'dev', candidates: 'none', projectName: 'absent' }
398 + );
399
273 - expect(user).toEqual(Option.none());
400 + expect(error).toBeInstanceOf(ProjectResolutionError);
401 + expect(error).toMatchObject({ reason: 'project_not_found' });
402 })
403 );
404 +
405 + it.effect(
406 + '[Given] the default project stands in for another org’s directory project [Then] its test user does not',
407 + () =>
408 + Effect.gen(function* () {
409 + const warnings: Array<string> = [];
410 + const user = yield* run(
411 + Effect.flatMap(resolveDeveloperResourceProject, devActingUserOption).pipe(
412 + Effect.provide(directoryProjectElsewhere)
413 + ),
414 + { tree: 'dev', candidates: 'global', projectName: 'absent' },
415 + warnings
416 + );
417 +
418 + expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
419 + Option.some({ userId: 'global-user', source: 'global-test-user' })
420 + );
421 + })
422 + );
423 });
424
278 -describe('actingUserOption', () => {
279 - it.effect.each(cases)('[Given] $name [Then] finds the rule’s user, or none', fixture =>
425 +describe('resolveSurfaceProjectAndUserOption', () => {
426 + it.effect('[Given] a directory project and its test user [Then] finds both', () =>
427 + Effect.gen(function* () {
428 + const { project, user } = yield* run(resolveSurfaceProjectAndUserOption, {
429 + tree: 'dev',
430 + candidates: 'directory',
431 + projectName: 'absent',
432 + });
433 +
434 + expect(Option.map(project, found => found.projectId)).toEqual(
435 + Option.some(DIRECTORY_PROJECT_ID)
436 + );
437 + expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(
438 + Option.some({ userId: 'directory-user', source: 'directory-test-user' })
439 + );
440 + })
441 + );
442 +
443 + it.effect.each([
444 + { candidates: 'flag', userId: 'flag-user' },
445 + { candidates: 'global', userId: 'global-user' },
446 + ] as const)(
447 + '[Given] no directory project and a $candidates user [Then] uses the default project, saying so',
448 + ({ candidates, userId }) =>
449 + Effect.gen(function* () {
450 + const warnings: Array<string> = [];
451 + const { project, user } = yield* run(
452 + resolveSurfaceProjectAndUserOption.pipe(Effect.provide(withoutDirectoryProject)),
453 + { tree: 'dev', candidates, projectName: 'absent' },
454 + warnings
455 + );
456 +
457 + expect(Option.map(project, found => found.projectId)).toEqual(
458 + Option.some(DEFAULT_PROJECT_ID)
459 + );
460 + expect(Option.map(user, found => found.userId)).toEqual(Option.some(userId));
461 + expect(warnings[0]).toBe(NO_DIRECTORY_PROJECT_NOTICE);
462 + })
463 + );
464 +
465 + it.effect.each([
466 + { given: 'no directory project', layer: withoutDirectoryProject },
467 + { given: 'a directory project in another org', layer: directoryProjectElsewhere },
468 + ])('[Given] $given and no user but the directory’s [Then] finds neither, quietly', ({ layer }) =>
469 Effect.gen(function* () {
470 const warnings: Array<string> = [];
282 - const user = yield* run(actingUserOption(), fixture, warnings);
283 - const expected = expectedUser(fixture);
471 + const result = yield* run(
472 + resolveSurfaceProjectAndUserOption.pipe(Effect.provide(layer)),
473 + { tree: 'dev', candidates: 'none', projectName: 'absent' },
474 + warnings
475 + );
476
285 - expect(warnings).toEqual(expectedNotices(fixture));
286 - // Only the project --project-name names is resolved on the dev tree.
287 - const project =
288 - fixture.tree === 'dev' && fixture.projectName === 'absent'
289 - ? Option.none()
290 - : Option.some(expectedProjectId(fixture));
291 -
292 - expect(Option.map(user, ({ userId, source }) => ({ userId, source }))).toEqual(expected);
293 - expect(
294 - Option.map(user, found => Option.map(found.project, resolved => resolved.projectId))
295 - ).toEqual(Option.map(expected, () => project));
477 + expect(result).toEqual({ project: Option.none(), user: Option.none() });
478 + expect(warnings).toEqual([]);
479 })
480 );
481 });
ts/packages/cli/test/src/commands/toolkits/info/toolkits.info.client.cmd.test.ts
+119 -1
@@ -1,7 +1,17 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, DateTime, Effect } from 'effect';
3 import type { ToolkitDetailed } from 'src/models/toolkits';
4 -import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { cli, cliExit, MockConsole, TestLive } from 'test/__utils__';
5 +import {
6 + DEFAULT_PROJECT_SCOPE,
7 + defaultDeveloperProjectAccountData,
8 + DIRECTORY_PROJECT_SCOPE,
9 + inDeveloperProjectDirectory,
10 + loginWithoutDeveloperProject,
11 + NO_DIRECTORY_PROJECT_NOTICE,
12 + OTHER_DEVELOPER_PROJECT,
13 + OTHER_PROJECT_SCOPE,
14 +} from 'test/__utils__/layers/developer-project';
15 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
16
17 const gmail: ToolkitDetailed = {
@@ -88,3 +98,111 @@ describe('CLI: composio dev toolkits info over the API client', () => {
98 );
99 });
100 });
101 +
102 +// The connection status comes from a session in the developer project the command resolved,
103 +// never in the one the backend would pick for the key.
104 +describe('CLI: composio dev toolkits info reads connection status in the developer project', () => {
105 + const config = ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } });
106 + const gmailPage = () =>
107 + Response.json({
108 + items: [
109 + {
110 + name: 'Gmail',
111 + slug: 'gmail',
112 + enabled: true,
113 + is_no_auth: false,
114 + composio_managed_auth_schemes: ['OAUTH2'],
115 + meta: { description: 'Email service to send and receive emails', logo: '' },
116 + connected_account: null,
117 + },
118 + ],
119 + next_cursor: null,
120 + });
121 +
122 + layer(
123 + TestLive({
124 + ...inDeveloperProjectDirectory,
125 + baseConfigProvider: config,
126 + toolkitsData: { detailedToolkits: [gmail] },
127 + })
128 + )(it => {
129 + it.effect.each([
130 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
131 + {
132 + given: '--project-name',
133 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
134 + scope: OTHER_PROJECT_SCOPE,
135 + },
136 + ])('[Given] $given [Then] opens its session in that project', ({ args, scope }) =>
137 + Effect.gen(function* () {
138 + const stub = toolkitsOver(gmailPage);
139 + yield* cli(['dev', 'toolkits', 'info', 'gmail', ...args]).pipe(Effect.provide(stub.layer));
140 +
141 + expect(stub.requests.map(request => request.path)).toEqual([
142 + '/api/v3.1/tool_router/session',
143 + `${SESSION_TOOLKITS}?toolkits=gmail`,
144 + ]);
145 + expect(stub.scopes).toEqual([scope, scope]);
146 + })
147 + );
148 + });
149 +
150 + layer(
151 + TestLive({
152 + baseConfigProvider: config,
153 + toolkitsData: { detailedToolkits: [gmail] },
154 + accountData: defaultDeveloperProjectAccountData(),
155 + })
156 + )(it => {
157 + it.effect(
158 + '[Given] --user-id in a directory set up for no project [Then] reads its status in the default developer project, saying so',
159 + () =>
160 + Effect.gen(function* () {
161 + yield* loginWithoutDeveloperProject;
162 + const stub = toolkitsOver(gmailPage);
163 + const { exitCode } = yield* cliExit([
164 + 'dev',
165 + 'toolkits',
166 + 'info',
167 + 'gmail',
168 + '--user-id',
169 + 'alice',
170 + ]).pipe(Effect.provide(stub.layer));
171 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
172 +
173 + expect(exitCode).toBe(0);
174 + expect(stub.scopes).toEqual([DEFAULT_PROJECT_SCOPE, DEFAULT_PROJECT_SCOPE]);
175 + expect(lines).toContain(NO_DIRECTORY_PROJECT_NOTICE);
176 + expect(JSON.parse(lines.at(-1) ?? '{}')).toMatchObject({ slug: 'gmail' });
177 + })
178 + );
179 + });
180 +
181 + layer(
182 + TestLive({
183 + baseConfigProvider: config,
184 + toolkitsData: { detailedToolkits: [gmail] },
185 + })
186 + )(it => {
187 + it.effect(
188 + '[Given] no user in a directory set up for no project [Then] shows the toolkit without connection status',
189 + () =>
190 + Effect.gen(function* () {
191 + yield* loginWithoutDeveloperProject;
192 + const stub = toolkitsOver(gmailPage);
193 + const { exitCode } = yield* cliExit(['dev', 'toolkits', 'info', 'gmail']).pipe(
194 + Effect.provide(stub.layer)
195 + );
196 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
197 +
198 + expect(exitCode).toBe(0);
199 + expect(stub.requests).toEqual([]);
200 + expect(lines).toContain(
201 + 'No developer project to read connection status from; showing toolkit details without it. Run `composio dev init`, or pass --user-id or --project-name.'
202 + );
203 + expect(lines).not.toContain(NO_DIRECTORY_PROJECT_NOTICE);
204 + expect(JSON.parse(lines.at(-1) ?? '{}')).toMatchObject({ slug: 'gmail' });
205 + })
206 + );
207 + });
208 +});
ts/packages/cli/test/src/commands/toolkits/list/toolkits.list.cmd.test.ts
+198 -19
@@ -1,12 +1,23 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
3 -import { cli, TestLive, MockConsole } from 'test/__utils__';
2 +import { ConfigProvider, DateTime, Effect, Layer, Option } from 'effect';
3 +import { cli, cliExit, TestLive, MockConsole } from 'test/__utils__';
4 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { Toolkits } from 'src/models/toolkits';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 +import { ProjectContext } from 'src/services/project-context';
8 import { notFoundError } from 'test/__utils__/layers/not-found';
9 import { exitCodeOf } from 'test/__utils__/exit-code';
10 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
11 +import {
12 + DEFAULT_PROJECT_SCOPE,
13 + defaultDeveloperProjectAccountData,
14 + DIRECTORY_PROJECT_SCOPE,
15 + inDeveloperProjectDirectory,
16 + loginWithoutDeveloperProject,
17 + NO_DIRECTORY_PROJECT_NOTICE,
18 + OTHER_DEVELOPER_PROJECT,
19 + OTHER_PROJECT_SCOPE,
20 +} from 'test/__utils__/layers/developer-project';
21 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
22 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
23
@@ -155,21 +166,24 @@ describe('CLI: composio dev toolkits list', () => {
166 }
167 );
168
158 - layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
159 - '[Given] explicit --user-id [Then] shows connected status column',
160 - it => {
161 - it.effect('shows connected column with explicit user id', () =>
162 - Effect.gen(function* () {
163 - yield* cli(['dev', 'toolkits', 'list', '--user-id', 'default']);
164 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
165 - const output = lines.join('\n');
169 + layer(
170 + TestLive({
171 + baseConfigProvider: testConfigProvider,
172 + toolkitsData,
173 + accountData: defaultDeveloperProjectAccountData(),
174 + })
175 + )('[Given] explicit --user-id [Then] shows connected status column', it => {
176 + it.effect('shows connected column with explicit user id', () =>
177 + Effect.gen(function* () {
178 + yield* cli(['dev', 'toolkits', 'list', '--user-id', 'default']);
179 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
180 + const output = lines.join('\n');
181
167 - expect(output).toContain('Connected');
168 - expect(output).toContain('Listing 3 of 3 toolkits');
169 - })
170 - );
171 - }
172 - );
182 + expect(output).toContain('Connected');
183 + expect(output).toContain('Listing 3 of 3 toolkits');
184 + })
185 + );
186 + });
187
188 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
189 '[Given] --query "email"',
@@ -321,7 +335,7 @@ describe('CLI: composio dev toolkits list', () => {
335 const stdout = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' });
336
337 expect(stderr).toContain(
324 - '`--connected` filter could not be applied — session data unavailable.'
338 + 'Warning: `--connected` filter could not be applied — session data unavailable.'
339 );
340 expect(
341 (JSON.parse(String(stdout.at(-1))) as Array<{ slug: string }>).map(row => row.slug)
@@ -335,12 +349,28 @@ describe('CLI: composio dev toolkits list', () => {
349 it => {
350 it.effect('[Then] warns that the filter needs a user id and lists the catalog', () =>
351 Effect.gen(function* () {
338 - yield* cli(['dev', 'toolkits', 'list', '--connected']);
352 + // Logged in without a global test user, in a directory whose project has none either.
353 + yield* loginWithoutDeveloperProject;
354 + const directoryProject = Layer.succeed(
355 + ProjectContext,
356 + ProjectContext.of({
357 + resolve: Effect.succeedSome({
358 + ...DIRECTORY_PROJECT_SCOPE,
359 + projectName: Option.none(),
360 + orgName: Option.none(),
361 + email: Option.none(),
362 + testUserId: Option.none(),
363 + }),
364 + })
365 + );
366 + yield* cli(['dev', 'toolkits', 'list', '--connected']).pipe(
367 + Effect.provide(directoryProject)
368 + );
369 const stderr = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' });
370 const stdout = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' });
371
372 expect(stderr[0]).toBe(
343 - '`--connected` requires a user id. Use `--user-id` or run `composio dev init`.'
373 + 'Warning: `--connected` requires a user id. Use `--user-id` or run `composio dev init`.'
374 );
375 expect(stderr.join('\n')).toContain('Listing 3 of 3 toolkits');
376 expect(
@@ -399,3 +429,152 @@ describe('CLI: composio dev toolkits list', () => {
429 );
430 });
431 });
432 +
433 +// The connection status comes from a session in the developer project the command resolved,
434 +// never in the one the backend would pick for the key.
435 +describe('CLI: composio dev toolkits list reads connection status in the developer project', () => {
436 + const emptyPage = () =>
437 + Response.json({
438 + items: [],
439 + next_cursor: null,
440 + total_pages: 1,
441 + current_page: 1,
442 + total_items: 0,
443 + });
444 +
445 + layer(
446 + TestLive({
447 + ...inDeveloperProjectDirectory,
448 + baseConfigProvider: testConfigProvider,
449 + toolkitsData,
450 + })
451 + )(it => {
452 + it.effect.each([
453 + { given: 'a directory set up for a project', args: [], scope: DIRECTORY_PROJECT_SCOPE },
454 + {
455 + given: '--project-name',
456 + args: ['--project-name', OTHER_DEVELOPER_PROJECT.name],
457 + scope: OTHER_PROJECT_SCOPE,
458 + },
459 + ])('[Given] $given [Then] opens its session in that project', ({ args, scope }) =>
460 + Effect.gen(function* () {
461 + const stub = stubSessionToolkits(emptyPage);
462 + yield* cli(['dev', 'toolkits', 'list', ...args]).pipe(Effect.provide(stub.layer));
463 +
464 + expect(stub.requests.map(request => request.path)).toEqual([
465 + '/api/v3.1/tool_router/session',
466 + `${SESSION_TOOLKITS_PATH}?limit=30`,
467 + ]);
468 + expect(stub.scopes).toEqual([scope, scope]);
469 + })
470 + );
471 + });
472 +
473 + layer(
474 + TestLive({
475 + baseConfigProvider: testConfigProvider,
476 + toolkitsData,
477 + accountData: defaultDeveloperProjectAccountData(),
478 + })
479 + )(it => {
480 + it.effect(
481 + '[Given] --user-id in a directory set up for no project [Then] opens its session in the default developer project, saying so',
482 + () =>
483 + Effect.gen(function* () {
484 + yield* loginWithoutDeveloperProject;
485 + const stub = stubSessionToolkits(emptyPage);
486 + const { exitCode } = yield* cliExit([
487 + 'dev',
488 + 'toolkits',
489 + 'list',
490 + '--user-id',
491 + 'alice',
492 + ]).pipe(Effect.provide(stub.layer));
493 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
494 +
495 + expect(exitCode).toBe(0);
496 + expect(stub.scopes).toEqual([DEFAULT_PROJECT_SCOPE, DEFAULT_PROJECT_SCOPE]);
497 + expect(lines).toContain(NO_DIRECTORY_PROJECT_NOTICE);
498 + expect(lines.join('\n')).toContain('Listing 3 of 3 toolkits');
499 + })
500 + );
501 + });
502 +
503 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(it => {
504 + it.effect(
505 + '[Given] no user in a directory set up for no project [Then] lists the catalog without connection status',
506 + () =>
507 + Effect.gen(function* () {
508 + yield* loginWithoutDeveloperProject;
509 + const stub = stubSessionToolkits(emptyPage);
510 + const { exitCode } = yield* cliExit(['dev', 'toolkits', 'list']).pipe(
511 + Effect.provide(stub.layer)
512 + );
513 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
514 +
515 + expect(exitCode).toBe(0);
516 + expect(stub.requests).toEqual([]);
517 + expect(lines).toContain(
518 + 'No developer project to read connection status from; showing toolkits without it. Run `composio dev init`, or pass --user-id or --project-name.'
519 + );
520 + expect(lines).not.toContain(NO_DIRECTORY_PROJECT_NOTICE);
521 + })
522 + );
523 + });
524 +
525 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(it => {
526 + it.effect(
527 + '[Given] a failed project lookup with redirected stderr [Then] names the skipped filter and keeps the catalog and successful exit',
528 + () =>
529 + Effect.gen(function* () {
530 + yield* loginWithoutDeveloperProject;
531 + const stub = stubClientResources(['auth'], () =>
532 + Response.json(
533 + { error: { message: 'Session service unavailable', status: 500, code: 500 } },
534 + { status: 500, headers: { 'x-should-retry': 'false' } }
535 + )
536 + );
537 + const terminal = redirectedTerminalUI();
538 + const { exitCode } = yield* cliExit([
539 + 'dev',
540 + 'toolkits',
541 + 'list',
542 + '--connected',
543 + '--user-id',
544 + 'alice',
545 + ]).pipe(Effect.provide([stub.layer, terminal.layer]));
546 +
547 + expect(exitCode).toBe(0);
548 + expect(JSON.parse(terminal.stdout()).map((row: { slug: string }) => row.slug)).toEqual([
549 + 'gmail',
550 + 'slack',
551 + 'github',
552 + ]);
553 + expect(terminal.stderr()).toBe(
554 + 'Warning: `--connected` filter could not be applied — developer project unavailable. Showing the unfiltered catalog.\n'
555 + );
556 + })
557 + );
558 +
559 + it.effect(
560 + '[Given] --connected in a directory set up for no project [Then] warns that the filter needs a developer project and lists the catalog',
561 + () =>
562 + Effect.gen(function* () {
563 + yield* loginWithoutDeveloperProject;
564 + const stub = stubSessionToolkits(emptyPage);
565 + const { exitCode } = yield* cliExit(['dev', 'toolkits', 'list', '--connected']).pipe(
566 + Effect.provide(stub.layer)
567 + );
568 + const stderr = yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' });
569 +
570 + expect(exitCode).toBe(0);
571 + expect(stub.requests).toEqual([]);
572 + expect(stderr).toContain(
573 + 'Warning: `--connected` filter could not be applied — developer project unavailable. Showing the unfiltered catalog.'
574 + );
575 + expect(stderr.join('\n')).not.toContain('`--connected` requires a user id.');
576 + expect(stderr.join('\n')).toContain('Listing 3 of 3 toolkits');
577 + })
578 + );
579 + });
580 +});