@devries-cameron20 / composio Mirror · read-only / commits / 10e93add6
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, 17:15 UTC

fix(cli): address bugbot review findings from the guardrails stack (#3886)

Follow-up to https://github.com/ComposioHQ/composio/pull/3885, which is now merged into `next`. This PR: - reports pending-login cache read failures as I/O errors instead of masking them as decode failures (`composio login --poll`) - restores pairwise polarity assertions for the `semverComparator` Array.sort compatibility case - consolidates the duplicated ephemeral HTTP server test helper in `test/__utils__/http-server.ts` - makes server-owned connected-account statuses forward-compatible while preserving the credential-stripping schema allowlist - redacts raw payload values from connected-account parse warnings and adds regression coverage for unknown statuses and secret-bearing malformed payloads - documents why the client-singleton test re-derives the consumer cache cwd hash ## Rebase notes Rebased onto `origin/next` at `ef1ec9148`. - Dropped the empty `GITHUB_*` compatibility commit; that contract is already present on `next` through https://github.com/ComposioHQ/composio/pull/3880. - Adapted the connected-account decoder rename to the service extracted upstream in `connected-account-selection.ts`. ## Context Fix-forward PR for actionable Cursor Bugbot findings on the guardrails stack (#3877–#3885). The stale decode-error string match and unused release helper were already resolved upstream, and the `vi.stubEnv(..., undefined)` concern is not actionable on Vitest 4.1.10.

Alberto Schiabel committed Aug 3, 2026 at 19:20 UTC 10e93add6b4ee2e541b705b90e4ee8624d0e25da
14 files changed +247 -172
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+2 -2
@@ -24,7 +24,7 @@ import {
24 groupCachedConnectedAccountsByToolkit,
25 resolveDefaultConnectedAccountsByToolkit,
26 } from 'src/services/connected-account-selection';
27 -import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
27 +import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
28
29 class ConnectionPollingError extends Data.TaggedError('commands/ConnectionPollingError')<{
30 readonly message: string;
@@ -538,7 +538,7 @@ const handleListConnectedAccounts = (params: {
538 }),
539 })
540 );
541 - const connectedAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(
541 + const connectedAccounts = yield* decodeConnectedAccountItems(accounts.items).pipe(
542 Effect.mapError(
543 cause =>
544 new ConnectedAccountsDecodeError({
ts/packages/cli/src/commands/listen.cmd.ts
+2 -4
@@ -23,7 +23,7 @@ import { parseJsonRecord } from 'src/utils/parse-json';
23 import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
24 import { matchesTriggerListenFilters } from './triggers/filter';
25 import { parseTriggerListenEvent } from './triggers/parse';
26 -import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
26 +import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
27
28 type TriggerCreateParams = NonNullable<
29 Parameters<RawComposioClient['triggerInstances']['upsert']>[1]
@@ -177,9 +177,7 @@ const resolveConnectedAccountIdForTrigger = (params: {
177 cause,
178 }),
179 });
180 - const selectableAccounts = yield* decodeConnectedAccountItemsWithFallback(
181 - connectedAccounts.items
182 - ).pipe(
180 + const selectableAccounts = yield* decodeConnectedAccountItems(connectedAccounts.items).pipe(
181 Effect.mapError(
182 cause =>
183 new ListenCommandError({
ts/packages/cli/src/commands/login.cmd.ts
+14 -3
@@ -94,7 +94,7 @@ type PendingLoginSession = Schema.Schema.Type<typeof PendingLoginSession>;
94
95 class PendingLoginError extends Data.TaggedError('commands/PendingLoginError')<{
96 readonly message: string;
97 - readonly reason: 'invalid' | 'missing' | 'expired';
97 + readonly reason: 'invalid' | 'io' | 'missing' | 'expired';
98 readonly cause?: unknown;
99 }> {}
100
@@ -151,8 +151,19 @@ const readPendingLoginSession = Effect.gen(function* () {
151 });
152 }
153
154 - const session = yield* fs.readFileString(filePath, 'utf8').pipe(
155 - Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(PendingLoginSession))),
154 + const rawSession = yield* fs.readFileString(filePath, 'utf8').pipe(
155 + Effect.mapError(
156 + cause =>
157 + new PendingLoginError({
158 + message: 'Failed to read pending login cache',
159 + reason: 'io',
160 + cause,
161 + })
162 + )
163 + );
164 + const session = yield* Schema.decodeUnknown(Schema.parseJson(PendingLoginSession))(
165 + rawSession
166 + ).pipe(
167 Effect.mapError(
168 cause =>
169 new PendingLoginError({
ts/packages/cli/src/effects/decode-connected-account-list.ts
+56 -39
@@ -1,8 +1,7 @@
1 -import { Effect, Schema } from 'effect';
2 -import type { ParseResult } from 'effect';
1 +import { Effect, ParseResult, Schema } from 'effect';
2 import {
3 ConnectedAccountItems,
5 - ConnectedAccountItemsPermissive,
4 + isKnownConnectedAccountStatus,
5 } from 'src/models/connected-accounts';
6 import {
7 ConnectedAccountListResponse,
@@ -10,17 +9,49 @@ import {
9 } from 'src/services/composio-clients';
10 import { TerminalUI } from 'src/services/terminal-ui';
11
12 +/**
13 + * Renders a `ParseError` as `path: kind` pairs only — never the failing
14 + * values. A container-level failure would otherwise echo the raw payload,
15 + * which can include credential-bearing fields (`state`, `data`, ...) the
16 + * connected-account schemas deliberately exclude.
17 + */
18 +const formatParseErrorRedacted = (error: ParseResult.ParseError): string =>
19 + ParseResult.ArrayFormatter.formatErrorSync(error)
20 + .map(issue => `${issue.path.join('.') || '(root)'}: ${issue._tag}`)
21 + .join(', ');
22 +
23 +/**
24 + * Warns when the server returned `status` values newer than this CLI build's
25 + * known set. Status values are non-credential by design, so printing them
26 + * verbatim is safe — and exactly what the user needs to act on.
27 + */
28 +const warnOnUnknownStatuses = (
29 + items: ReadonlyArray<{ readonly status: string }>
30 +): Effect.Effect<void, never, TerminalUI> =>
31 + Effect.gen(function* () {
32 + const unknown = [
33 + ...new Set(items.map(item => item.status).filter(s => !isKnownConnectedAccountStatus(s))),
34 + ];
35 + if (unknown.length === 0) return;
36 + const ui = yield* TerminalUI;
37 + yield* ui.log.warn(
38 + `Server returned connected account status(es) this CLI does not ` +
39 + `recognize: ${unknown.join(', ')}. Run "composio upgrade" to pick up ` +
40 + `the latest CLI.`
41 + );
42 + });
43 +
44 /**
45 * Decodes a raw `client.connectedAccounts.list(...)` response against
46 * `ConnectedAccountListResponse`, falling back to the raw payload on
47 * `ParseError`.
48 *
18 - * Forward-compat: a future Apollo status would otherwise brick the caller
19 - * via the closed `Schema.Literal(...)`. On decode failure we warn via
20 - * `ui.log.warn` (pointing the user at `composio upgrade`) and return the
21 - * unvalidated raw response — safe because the three current call sites
22 - * only render non-credential fields (`id`, `alias`, `word_id`,
23 - * `toolkit.slug`, `status`, ...).
49 + * `status` is an open enum (`ConnectedAccountStatus`), so a status newer than
50 + * this CLI build decodes fine and only triggers the "composio upgrade"
51 + * warning. The raw fallback remains for other shape skew (pagination fields,
52 + * renames, ...) — safe because the three current call sites only render
53 + * non-credential fields (`id`, `alias`, `word_id`, `toolkit.slug`,
54 + * `status`, ...).
55 */
56 export const decodeConnectedAccountListWithFallback = (
57 rawResult: unknown
@@ -28,13 +59,14 @@ export const decodeConnectedAccountListWithFallback = (
59 Effect.gen(function* () {
60 const ui = yield* TerminalUI;
61 return yield* Schema.decodeUnknown(ConnectedAccountListResponse)(rawResult).pipe(
62 + Effect.tap(result => warnOnUnknownStatuses(result.items)),
63 Effect.catchTag('ParseError', error =>
64 Effect.gen(function* () {
65 yield* ui.log.warn(
34 - `Server returned a connection field this CLI does not recognize ` +
35 - `(likely a newly-added status). Run "composio upgrade" to pick up ` +
36 - `the latest schema. Continuing with raw response.\n\n` +
37 - `Decode error: ${error.message}`
66 + `Server response did not match the shape this CLI expects. Run ` +
67 + `"composio upgrade" to pick up the latest CLI. Continuing with ` +
68 + `raw response.\n\n` +
69 + `Mismatched fields: ${formatParseErrorRedacted(error)}`
70 );
71 // Safe: callers only read non-credential fields.
72 return rawResult as ConnectedAccountListResponseType;
@@ -46,34 +78,19 @@ export const decodeConnectedAccountListWithFallback = (
78 /**
79 * Item-level variant of {@link decodeConnectedAccountListWithFallback} for
80 * call sites that decode `response.items` rather than the whole list
49 - * response. Same forward-compat contract: on `ParseError` (e.g. a status
50 - * value newer than this CLI's closed `Schema.Literal(...)`) warn via
51 - * `ui.log.warn` and retry with `status` widened to `Schema.String`.
81 + * response.
82 *
53 - * Unlike the list-response helper above, this one must NOT fall back to the
54 - * raw payload: `link --list` JSON-dumps the decoded items to stdout, so the
83 + * `status` is an open enum, so a status newer than this CLI build decodes
84 + * instead of failing — we just warn, pointing at `composio upgrade`. Unlike
85 + * the list-response helper above, this one must NOT fall back to the raw
86 + * payload: `link --list` JSON-dumps the decoded items to stdout, so the
87 * schema's field allowlist is what keeps credential-bearing fields (`state`,
56 - * `data`, ...) out of pipeable output. The permissive re-decode preserves
57 - * that allowlist; truly malformed data still fails with `ParseError`.
88 + * `data`, ...) out of pipeable output. Truly malformed data fails with
89 + * `ParseError`.
90 */
59 -export const decodeConnectedAccountItemsWithFallback = (
91 +export const decodeConnectedAccountItems = (
92 rawItems: unknown
93 ): Effect.Effect<ConnectedAccountItems, ParseResult.ParseError, TerminalUI> =>
62 - Effect.gen(function* () {
63 - const ui = yield* TerminalUI;
64 - return yield* Schema.decodeUnknown(ConnectedAccountItems)(rawItems).pipe(
65 - Effect.catchTag('ParseError', error =>
66 - Effect.gen(function* () {
67 - yield* ui.log.warn(
68 - `Server returned a connection field this CLI does not recognize ` +
69 - `(likely a newly-added status). Run "composio upgrade" to pick up ` +
70 - `the latest schema. Continuing with a permissive schema.\n\n` +
71 - `Decode error: ${error.message}`
72 - );
73 - const permissive = yield* Schema.decodeUnknown(ConnectedAccountItemsPermissive)(rawItems);
74 - // Identical shape modulo the widened `status`; callers render it as text.
75 - return permissive as ConnectedAccountItems;
76 - })
77 - )
78 - );
79 - });
94 + Schema.decodeUnknown(ConnectedAccountItems)(rawItems).pipe(
95 + Effect.tap(items => warnOnUnknownStatuses(items))
96 + );
ts/packages/cli/src/models/connected-accounts.ts
+28 -21
@@ -1,5 +1,32 @@
1 import { Schema } from 'effect';
2
3 +/**
4 + * Statuses this CLI build knows about. The server owns this enum and may add
5 + * values at any time, so schemas must stay open (see
6 + * {@link ConnectedAccountStatus}) — use {@link isKnownConnectedAccountStatus}
7 + * to detect values newer than this build.
8 + */
9 +export const KnownConnectedAccountStatus = Schema.Literal(
10 + 'INITIALIZING',
11 + 'INITIATED',
12 + 'ACTIVE',
13 + 'FAILED',
14 + 'EXPIRED',
15 + 'INACTIVE',
16 + 'REVOKED'
17 +);
18 +export type KnownConnectedAccountStatus = typeof KnownConnectedAccountStatus.Type;
19 +
20 +export const isKnownConnectedAccountStatus = Schema.is(KnownConnectedAccountStatus);
21 +
22 +/**
23 + * Open enum for the server-owned account status: the known literals document
24 + * the values this build understands, the `Schema.String` branch lets a newer
25 + * status decode instead of failing the whole payload. Callers only compare
26 + * against literals or render the value as text, so widening is safe.
27 + */
28 +export const ConnectedAccountStatus = Schema.Union(KnownConnectedAccountStatus, Schema.String);
29 +
30 /**
31 * A connected account item from the list or retrieve endpoints.
32 * Field names match the raw API response (snake_case).
@@ -13,15 +40,7 @@ export const ConnectedAccountItem = Schema.Struct({
40 id: Schema.String,
41 word_id: Schema.optional(Schema.NullOr(Schema.String)),
42 alias: Schema.optional(Schema.NullOr(Schema.String)),
16 - status: Schema.Literal(
17 - 'INITIALIZING',
18 - 'INITIATED',
19 - 'ACTIVE',
20 - 'FAILED',
21 - 'EXPIRED',
22 - 'INACTIVE',
23 - 'REVOKED'
24 - ),
43 + status: ConnectedAccountStatus,
44 status_reason: Schema.optionalWith(Schema.NullOr(Schema.String), { default: () => null }),
45 is_disabled: Schema.Boolean,
46 user_id: Schema.String,
@@ -42,15 +61,3 @@ export type ConnectedAccountItem = Schema.Schema.Type<typeof ConnectedAccountIte
61
62 export const ConnectedAccountItems = Schema.Array(ConnectedAccountItem);
63 export type ConnectedAccountItems = Schema.Schema.Type<typeof ConnectedAccountItems>;
45 -
46 -/**
47 - * Forward-compatible variant of {@link ConnectedAccountItem}: identical field
48 - * allowlist (same credential-stripping guarantee as above) with `status`
49 - * widened to accept values newer than this CLI build's closed literal union.
50 - */
51 -export const ConnectedAccountItemPermissive = Schema.Struct({
52 - ...ConnectedAccountItem.fields,
53 - status: Schema.String,
54 -}).annotations({ identifier: 'ConnectedAccountItemPermissive' });
55 -
56 -export const ConnectedAccountItemsPermissive = Schema.Array(ConnectedAccountItemPermissive);
ts/packages/cli/src/services/connected-account-selection.ts
+7 -8
@@ -1,16 +1,15 @@
1 import type { Composio } from '@composio/client';
2 import { Data, Effect, Option, Schema } from 'effect';
3 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
4 -import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
4 +import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
5 import type { TerminalUI } from 'src/services/terminal-ui';
6
7 -// `ConnectedAccountItem` widened with an `'UNKNOWN'` sentinel for statuses
8 -// the closed schema doesn't yet know about. Selection only picks `'ACTIVE'`,
9 -// so unknown rows still drop out — but without falsely labeling them
7 +// `status` is an open enum, so this is shape-identical to
8 +// `ConnectedAccountItem`; tool-router rows normalize statuses outside the
9 +// known set to an `'UNKNOWN'` sentinel. Selection only picks `'ACTIVE'`, so
10 +// unknown rows still drop out — but without falsely labeling them
11 // `'INACTIVE'` (= user-disabled).
11 -export type SelectableConnectedAccount = Omit<ConnectedAccountItem, 'status'> & {
12 - readonly status: ConnectedAccountItem['status'] | 'UNKNOWN';
13 -};
12 +export type SelectableConnectedAccount = ConnectedAccountItem;
13
14 export const CachedConnectedAccountSummarySchema = Schema.Struct({
15 id: Schema.String,
@@ -171,7 +170,7 @@ export const resolveConnectedAccountForToolkit = (params: {
170 cause,
171 }),
172 });
174 - const selectableAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(
173 + const selectableAccounts = yield* decodeConnectedAccountItems(accounts.items).pipe(
174 Effect.mapError(
175 cause =>
176 new ConnectedAccountResolutionError({
ts/packages/cli/src/services/tool-router-session-connections.ts
+2 -5
@@ -1,6 +1,6 @@
1 -import { Data, Effect, Schema } from 'effect';
1 +import { Data, Effect } from 'effect';
2 import type { Composio } from '@composio/client';
3 -import { ConnectedAccountItem } from 'src/models/connected-accounts';
3 +import { isKnownConnectedAccountStatus } from 'src/models/connected-accounts';
4 import {
5 compareNewestFirst,
6 groupCachedConnectedAccountsByToolkit,
@@ -49,9 +49,6 @@ export type ToolRouterSessionConnectionContext = {
49 >;
50 };
51
52 -// Derived from the model schema so the known-status list can't drift from it.
53 -const isKnownConnectedAccountStatus = Schema.is(ConnectedAccountItem.fields.status);
54 -
52 const normalizeConnectedAccountStatus = (
53 status?: string | null
54 ): SelectableConnectedAccount['status'] =>
ts/packages/cli/test/__utils__/http-server.ts
+38 -35
@@ -1,4 +1,4 @@
1 -import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
1 +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2 import { Effect } from 'effect';
3
4 /**
@@ -42,44 +42,47 @@ export async function withHttpServer(
42 }
43
44 /**
45 - * Effect variant of {@link withHttpServer}: the server lifecycle is managed
46 - * with acquireUseRelease so `use` can be an Effect run by @effect/vitest.
45 + * Spin up a local HTTP server on an ephemeral port as a scoped resource and
46 + * return its base URL. Scope closure tears the server down.
47 */
48 -export function withHttpServerEffect<A, E, R>(
49 - handler: (req: IncomingMessage, res: ServerResponse) => void,
50 - use: (baseUrl: string) => Effect.Effect<A, E, R>
51 -): Effect.Effect<A, E, R> {
52 - return Effect.acquireUseRelease(
53 - Effect.promise(async () => {
54 - const server = createServer(handler);
55 - await new Promise<void>((resolve, reject) => {
56 - server.once('error', reject);
57 - server.listen({ port: 0, host: '127.0.0.1' }, () => {
58 - server.off('error', reject);
59 - resolve();
60 - });
61 - });
62 -
63 - const address = server.address();
64 - if (address === null || typeof address === 'string') {
65 - throw new Error('Failed to bind test server to an ephemeral port');
66 - }
67 -
68 - return { server, baseUrl: `http://127.0.0.1:${address.port}` };
69 - }),
70 - ({ baseUrl }) => use(baseUrl),
71 - ({ server }) =>
48 +export const startTestHttpServer = (handler: (req: IncomingMessage, res: ServerResponse) => void) =>
49 + Effect.map(
50 + Effect.acquireRelease(
51 Effect.promise(
52 () =>
74 - new Promise<void>((resolve, reject) => {
75 - server.close(error => {
76 - if (error) {
77 - reject(error);
78 - return;
79 - }
80 - resolve();
53 + new Promise<Server>((resolve, reject) => {
54 + const server = createServer(handler);
55 + server.once('error', reject);
56 + server.listen({ port: 0, host: '127.0.0.1' }, () => {
57 + server.off('error', reject);
58 + resolve(server);
59 });
60 })
83 - )
61 + ),
62 + server =>
63 + Effect.promise(
64 + () =>
65 + new Promise<void>((resolve, reject) => {
66 + server.close(error => (error ? reject(error) : resolve()));
67 + })
68 + )
69 + ),
70 + server => {
71 + const address = server.address();
72 + if (address === null || typeof address === 'string') {
73 + throw new Error('Failed to bind test server to an ephemeral port');
74 + }
75 + return `http://127.0.0.1:${address.port}`;
76 + }
77 );
78 +
79 +/**
80 + * Effect variant of {@link withHttpServer}: the server lifecycle comes from
81 + * {@link startTestHttpServer} so `use` can be an Effect run by @effect/vitest.
82 + */
83 +export function withHttpServerEffect<A, E, R>(
84 + handler: (req: IncomingMessage, res: ServerResponse) => void,
85 + use: (baseUrl: string) => Effect.Effect<A, E, R>
86 +): Effect.Effect<A, E, R> {
87 + return Effect.scoped(Effect.flatMap(startTestHttpServer(handler), use));
88 }
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.list.cmd.test.ts
+2 -2
@@ -233,8 +233,8 @@ describe('CLI: composio dev connected-accounts list', () => {
233 {
234 ...testConnectedAccounts[0],
235 id: 'con_future_status',
236 - // Cast bypasses the closed status literal — that's the point.
237 - status: 'FUTURE_NOT_YET_KNOWN' as ConnectedAccountItem['status'],
236 + // Open enum: a status newer than this build decodes as a plain string.
237 + status: 'FUTURE_NOT_YET_KNOWN',
238 },
239 ];
240
ts/packages/cli/test/src/commands/login.cmd.test.ts
+23
@@ -334,6 +334,29 @@ describe('CLI: composio login', () => {
334 });
335 });
336
337 + layer(TestLive())(it => {
338 + it.scoped(
339 + '[Given] an unreadable pending login cache [Then] poll reports the read failure, not a decode failure',
340 + () =>
341 + Effect.gen(function* () {
342 + const fs = yield* FileSystem.FileSystem;
343 + const cacheDir = yield* setupCacheDir;
344 + // A directory at the cache path passes the exists check but fails the read.
345 + yield* fs.makeDirectory(path.join(cacheDir, 'pending-login-session.json'), {
346 + recursive: true,
347 + });
348 +
349 + const error = yield* cli(['login', '--poll']).pipe(Effect.flip);
350 +
351 + expect(error).toMatchObject({
352 + _tag: 'commands/PendingLoginError',
353 + reason: 'io',
354 + message: 'Failed to read pending login cache',
355 + });
356 + })
357 + );
358 + });
359 +
360 layer(TestLive())(it => {
361 it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
362 Effect.gen(function* () {
ts/packages/cli/test/src/effects/compare-semver.test.ts
+7 -3
@@ -281,9 +281,13 @@ describe('compare-semver.ts', () => {
281 }
282 }
283
284 - // Since we can't actually use the Effect in Array.sort, just verify
285 - // the comparison results are consistent with sort expectations
286 - expect(comparisons.length).toBe(3); // 3 comparisons for 3 elements
284 + // Since we can't actually use the Effect in Array.sort, verify each
285 + // pairwise result carries the polarity an ascending sort relies on
286 + expect(comparisons).toEqual([
287 + { versions: ['2.0.0', '1.0.0'], result: 1 },
288 + { versions: ['2.0.0', '3.0.0'], result: -1 },
289 + { versions: ['1.0.0', '3.0.0'], result: -1 },
290 + ]);
291 })
292 );
293 });
ts/packages/cli/test/src/effects/decode-connected-account-list.test.ts
+62 -14
@@ -1,7 +1,9 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Console, Effect, Layer, ParseResult } from 'effect';
3 -import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
4 -import type { ConnectedAccountItem } from 'src/models/connected-accounts';
3 +import {
4 + decodeConnectedAccountItems,
5 + decodeConnectedAccountListWithFallback,
6 +} from 'src/effects/decode-connected-account-list';
7 import { MockConsole } from 'test/__utils__';
8 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
9
@@ -32,11 +34,11 @@ const makeItem = (overrides?: Record<string, unknown>) => ({
34 ...overrides,
35 });
36
35 -describe('decodeConnectedAccountItemsWithFallback', () => {
36 - layer(TestLayer)('[Given] items matching the strict schema', it => {
37 +describe('decodeConnectedAccountItems', () => {
38 + layer(TestLayer)('[Given] items with statuses this CLI build knows', it => {
39 it.effect('decodes without warning', () =>
40 Effect.gen(function* () {
39 - const items = yield* decodeConnectedAccountItemsWithFallback([makeItem()]);
41 + const items = yield* decodeConnectedAccountItems([makeItem()]);
42
43 expect(items).toStrictEqual([makeItem()]);
44 expect(yield* MockConsole.getLines()).toStrictEqual([]);
@@ -45,7 +47,7 @@ describe('decodeConnectedAccountItemsWithFallback', () => {
47 });
48
49 layer(TestLayer)('[Given] a status newer than this CLI build', it => {
48 - it.effect('warns, keeps the unknown status, and still strips credential fields', () =>
50 + it.effect('decodes, warns with only the status value, and still strips credential fields', () =>
51 Effect.gen(function* () {
52 const raw = makeItem({
53 status: 'QUANTUM_LINKED',
@@ -53,25 +55,24 @@ describe('decodeConnectedAccountItemsWithFallback', () => {
55 data: { refresh_token: 'must-not-leak' },
56 });
57
56 - const items = yield* decodeConnectedAccountItemsWithFallback([raw]);
58 + const items = yield* decodeConnectedAccountItems([raw]);
59
58 - expect(items).toStrictEqual([
59 - makeItem({ status: 'QUANTUM_LINKED' }) as unknown as ConnectedAccountItem,
60 - ]);
60 + expect(items).toStrictEqual([makeItem({ status: 'QUANTUM_LINKED' })]);
61 expect(JSON.stringify(items)).not.toContain('must-not-leak');
62
63 const output = (yield* MockConsole.getLines()).join('\n');
64 - expect(output).toContain('does not recognize');
64 + expect(output).toContain('QUANTUM_LINKED');
65 expect(output).toContain('composio upgrade');
66 + expect(output).not.toContain('must-not-leak');
67 })
68 );
69 });
70
70 - layer(TestLayer)('[Given] a payload the permissive schema cannot decode', it => {
71 - it.effect('fails with ParseError instead of leaking the raw payload', () =>
71 + layer(TestLayer)('[Given] a malformed payload', it => {
72 + it.effect('fails with ParseError', () =>
73 Effect.gen(function* () {
74 const error = yield* Effect.flip(
74 - decodeConnectedAccountItemsWithFallback([{ definitely: 'not-an-account' }])
75 + decodeConnectedAccountItems([{ definitely: 'not-an-account' }])
76 );
77
78 expect(ParseResult.isParseError(error)).toBe(true);
@@ -79,3 +80,50 @@ describe('decodeConnectedAccountItemsWithFallback', () => {
80 );
81 });
82 });
83 +
84 +describe('decodeConnectedAccountListWithFallback', () => {
85 + layer(TestLayer)('[Given] a response with a status newer than this CLI build', it => {
86 + it.effect('decodes and warns instead of falling back to the raw payload', () =>
87 + Effect.gen(function* () {
88 + const result = yield* decodeConnectedAccountListWithFallback({
89 + items: [makeItem({ status: 'QUANTUM_LINKED' })],
90 + total_items: 1,
91 + total_pages: 1,
92 + current_page: 1,
93 + next_cursor: null,
94 + });
95 +
96 + expect(result.items).toStrictEqual([makeItem({ status: 'QUANTUM_LINKED' })]);
97 +
98 + const output = (yield* MockConsole.getLines()).join('\n');
99 + expect(output).toContain('QUANTUM_LINKED');
100 + expect(output).toContain('composio upgrade');
101 + })
102 + );
103 + });
104 +
105 + layer(TestLayer)('[Given] a shape-skewed response carrying credential fields', it => {
106 + it.effect('falls back to raw but never echoes payload values in the warning', () =>
107 + Effect.gen(function* () {
108 + // `items` is not an array: the decode fails at the container level,
109 + // where an unredacted formatter would print the whole actual value.
110 + const raw = {
111 + items: { 0: makeItem({ state: { access_token: 'must-not-leak' } }) },
112 + total_items: 1,
113 + total_pages: 1,
114 + current_page: 1,
115 + next_cursor: null,
116 + };
117 +
118 + const result = yield* decodeConnectedAccountListWithFallback(raw);
119 +
120 + expect(result).toBe(raw);
121 +
122 + const output = (yield* MockConsole.getLines()).join('\n');
123 + expect(output).toContain('composio upgrade');
124 + expect(output).toContain('items');
125 + expect(output).not.toContain('must-not-leak');
126 + })
127 + );
128 + });
129 +});
ts/packages/cli/test/src/effects/install-skill.test.ts
+1 -36
@@ -1,4 +1,3 @@
1 -import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
1 import { describe, expect, it, vi } from '@effect/vitest';
2 import { Config, ConfigProvider, Effect, Exit, Layer } from 'effect';
3 import { FetchHttpClient, FileSystem, HttpClient, Path } from '@effect/platform';
@@ -6,6 +5,7 @@ import type * as PlatformError from '@effect/platform/Error';
5 import { BunFileSystem, BunPath } from '@effect/platform-bun';
6 import * as tempy from 'tempy';
7 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
8 +import { startTestHttpServer } from 'test/__utils__/http-server';
9 import {
10 inferSkillReleaseChannel,
11 installSkill,
@@ -56,41 +56,6 @@ const makeInstallEffect = (
56 Effect.scoped
57 );
58
59 -/**
60 - * Spin up a local HTTP server on an ephemeral port as a scoped resource and
61 - * return its base URL. Scope closure tears the server down.
62 - */
63 -const startTestHttpServer = (handler: (req: IncomingMessage, res: ServerResponse) => void) =>
64 - Effect.map(
65 - Effect.acquireRelease(
66 - Effect.promise(
67 - () =>
68 - new Promise<Server>((resolve, reject) => {
69 - const server = createServer(handler);
70 - server.once('error', reject);
71 - server.listen({ port: 0, host: '127.0.0.1' }, () => {
72 - server.off('error', reject);
73 - resolve(server);
74 - });
75 - })
76 - ),
77 - server =>
78 - Effect.promise(
79 - () =>
80 - new Promise<void>((resolve, reject) => {
81 - server.close(error => (error ? reject(error) : resolve()));
82 - })
83 - )
84 - ),
85 - server => {
86 - const address = server.address();
87 - if (address === null || typeof address === 'string') {
88 - throw new Error('Failed to bind test server to an ephemeral port');
89 - }
90 - return `http://127.0.0.1:${address.port}`;
91 - }
92 - );
93 -
59 const startSkillReleaseServer = (skillZip: Uint8Array) =>
60 startTestHttpServer((req, res) => {
61 if (req.url === '/skill.zip') {
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+3
@@ -23,6 +23,9 @@ const okResponse = () =>
23 headers: { 'Content-Type': 'application/json' },
24 });
25
26 +// Mirrors the module-private `cwdHash` in src/services/consumer-short-term-cache.ts
27 +// (djb2Hash + base36): the seeded cache key below must be byte-identical to what
28 +// the service computes for process.cwd() when it looks up the CLI session.
29 const cwdHash = (cwd: string): string => {
30 let hash = 5381;
31 for (let index = 0; index < cwd.length; index += 1) {