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

refactor(cli): drop test conditionals and untangle operator chains (#4898)

This PR: - applies the review rules from https://github.com/ComposioHQ/composio/pull/4855 across the CLI test suite: no conditionals in test bodies, `.each()` instead of `for`, and no assertions on whitespace emitted by `effect/cli` - replaces `Exit.isFailure(exit) ? Cause.squash(...) : undefined`, `Effect.catch(() => Effect.void)` and `try/catch` in tests with `Effect.flip`, so failure tests assert the error tag and message instead of only that something failed - turns test-generating loops into `describe.each` / `it.effect.each` tables (1507 → 1654 tests, all from split cases) - adds `routeRequests(routes, otherwise)` to `test/__utils__/services/stub-composio-client.ts` and uses it for stub responders that branched on the request (same helper as #4855) - removes line-scanning JSON helpers (`parseJsonFromLines`, `parseLastJson`, `extractFirstJsonObject`) in favor of parsing the last output line, and checks parsed JSON where tests matched padded table rows - flattens nested ternaries and long `||`/`&&`/`??` chains in 14 `src` files into early returns, named booleans, and small helpers (`pluginLifecycleAction`, `proxyFailureDetail`, `DECISION_BY_APPROVAL_PATH`, `toCheckStatus`), with no behavior change ## Context Stateful test doubles (fake `claude`/`codex` hosts, fake filesystems, HTTP servers, child processes) and setup/teardown hooks keep their branching, because that branching is the behavior they simulate. In test files, `for` loops go from 58 to 7, `if` statements from 132 to 51, and `try` blocks from 13 to 0; what remains lives in those doubles and hooks. `extract-error-details.ts` and `stub-composio-client.ts` carry the same change as #4855, so whichever merges second should rebase cleanly.

Alberto Schiabel committed Oct 15, 2026 at 19:53 UTC 96c546b2a7bb89129e2d33869ae2d0316530588b
69 files changed +1477 -1771
ts/packages/cli/src/analytics/events.ts
+14 -12
@@ -191,6 +191,7 @@ const KNOWN_COMMAND_TOKENS = new Set([
191 ]);
192
193 const TOOL_NOT_FOUND_PATTERN = /\btool\b.*\bnot found\b/i;
194 +const TOOL_VALIDATION_PATTERN = /\b(?:validation|invalid parameter|invalid argument)\b/i;
195 const TOOL_NOT_FOUND_CODES: ReadonlySet<number> = new Set([
196 1147, // MCP_ToolNotFound
197 1800, // ActionExecute_ToolNotFound
@@ -822,23 +823,24 @@ export const isMaybeToolNotFoundError = (params: {
823 readonly errorSlug?: string;
824 readonly status?: number;
825 readonly apiCode?: number;
825 -}): boolean =>
826 - (typeof params.apiCode === 'number' && TOOL_NOT_FOUND_CODES.has(params.apiCode)) ||
827 - params.status === 404 ||
828 - params.errorSlug?.toLowerCase().includes('notfound') === true ||
829 - TOOL_NOT_FOUND_PATTERN.test(params.message ?? '');
826 +}): boolean => {
827 + if (typeof params.apiCode === 'number' && TOOL_NOT_FOUND_CODES.has(params.apiCode)) return true;
828 + if (params.status === 404) return true;
829 + const errorSlug = params.errorSlug?.toLowerCase() ?? '';
830 + if (errorSlug.includes('notfound')) return true;
831 + return TOOL_NOT_FOUND_PATTERN.test(params.message ?? '');
832 +};
833
834 export const isMaybeToolValidationError = (params: {
835 readonly message?: string;
836 readonly errorSlug?: string;
837 readonly apiCode?: number;
835 -}): boolean =>
836 - (typeof params.apiCode === 'number' && TOOL_VALIDATION_CODES.has(params.apiCode)) ||
837 - params.errorSlug?.toLowerCase().includes('validation') === true ||
838 - params.errorSlug?.toLowerCase().includes('invalidparameter') === true ||
839 - /\bvalidation\b/i.test(params.message ?? '') ||
840 - /\binvalid parameter\b/i.test(params.message ?? '') ||
841 - /\binvalid argument\b/i.test(params.message ?? '');
838 +}): boolean => {
839 + if (typeof params.apiCode === 'number' && TOOL_VALIDATION_CODES.has(params.apiCode)) return true;
840 + const errorSlug = params.errorSlug?.toLowerCase() ?? '';
841 + if (errorSlug.includes('validation') || errorSlug.includes('invalidparameter')) return true;
842 + return TOOL_VALIDATION_PATTERN.test(params.message ?? '');
843 +};
844
845 export const getToolExecuteToolNotFoundEvent = (params: {
846 readonly toolSlug: string;
ts/packages/cli/src/commands/debug.cmd.ts
+9 -5
@@ -5,7 +5,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
5 import { renderCommandHintGraph } from 'src/services/command-hints';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { detectMasterFromHost } from 'src/services/master-detector';
8 -import { resolveCommandProject } from 'src/services/command-project';
8 +import { resolveCommandProject, type ResolvedCommandProject } from 'src/services/command-project';
9
10 const debugError = commandInputError('debug');
11
@@ -15,6 +15,12 @@ const printCommandHintGraph = Effect.suspend(() =>
15 )
16 );
17
18 +// Only a consumer project carries the playground user the API key acts for.
19 +const consumerUserIdOf = (project: ResolvedCommandProject | undefined): string | null => {
20 + if (project?.projectType !== 'CONSUMER') return null;
21 + return project.consumerUserId ?? null;
22 +};
23 +
24 const printDebugApiInfo = Effect.gen(function* () {
25 const ui = yield* TerminalUI;
26 const confirmed = yield* ui.confirm(
@@ -40,15 +46,13 @@ const printDebugApiInfo = Effect.gen(function* () {
46 : Effect.fail(error)
47 )
48 );
49 + const consumerUserId = consumerUserIdOf(Option.getOrUndefined(consumerProject));
50 return yield* ui.output(
51 JSON.stringify(
52 {
53 apiKey,
54 orgId: orgId ?? null,
48 - consumerUserId:
49 - Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'
50 - ? (consumerProject.value.consumerUserId ?? null)
51 - : null,
55 + consumerUserId,
56 },
57 null,
58 2
ts/packages/cli/src/commands/init.cmd.ts
+13 -11
@@ -338,17 +338,19 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
338 testUserId: Option.none(),
339 });
340
341 - const selectedProject: OrgProject =
342 - yes || orgProjects.data.length === 1
343 - ? (selectDefaultProject({
344 - projects: orgProjects.data,
345 - defaultOrgId: orgIdValue,
346 - defaultProjectId: projectIdValue,
347 - }) ?? orgProjects.data[0])
348 - : yield* ui.select<OrgProject>(
349 - 'Select a developer project:',
350 - orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))
351 - );
341 + const skipProjectPicker = yes || orgProjects.data.length === 1;
342 + const defaultProject =
343 + selectDefaultProject({
344 + projects: orgProjects.data,
345 + defaultOrgId: orgIdValue,
346 + defaultProjectId: projectIdValue,
347 + }) ?? orgProjects.data[0];
348 + const selectedProject: OrgProject = skipProjectPicker
349 + ? defaultProject
350 + : yield* ui.select<OrgProject>(
351 + 'Select a developer project:',
352 + orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))
353 + );
354
355 const selected = orgProjectToKeys(selectedProject);
356 yield* ui.log.step(`Using developer project "${selectedProject.name}"`);
ts/packages/cli/src/commands/install.cmd.ts
+10 -12
@@ -143,12 +143,11 @@ const resolveBinDir = (params: {
143 * command wrote byte for byte, so any disagreement makes every delegated
144 * install look stale and forces a needless inline rewrite.
145 */
146 -export const renderWithHome = (dir: string, homedir: string): string =>
147 - dir === homedir
148 - ? '$HOME'
149 - : dir.startsWith(`${homedir}/`)
150 - ? `$HOME/${dir.slice(homedir.length + 1)}`
151 - : dir;
146 +export const renderWithHome = (dir: string, homedir: string): string => {
147 + if (dir === homedir) return '$HOME';
148 + if (dir.startsWith(`${homedir}/`)) return `$HOME/${dir.slice(homedir.length + 1)}`;
149 + return dir;
150 +};
151
152 export const pathBlockForShell = (shell: Shell, binDir: string, homedir: string): string => {
153 const rendered = renderWithHome(binDir, homedir);
@@ -290,15 +289,14 @@ const LEGACY_FISH_INSTALL_DIR_PREFIX = 'set --export COMPOSIO_INSTALL_DIR "';
289 * `set --export COMPOSIO_INSTALL_DIR "<dir>"`. Matched structurally on the
290 * prefix/quotes (any dir), like `isManagedPathAssignment`.
291 */
292 +const isQuotedAssignment = (line: string, prefix: string): boolean =>
293 + line.startsWith(prefix) && line.endsWith('"') && line.length > prefix.length;
294 +
295 const isLegacyInstallDirAssignment = (line: string): boolean => {
296 const trimmed = line.trim();
297 return (
296 - (trimmed.startsWith(LEGACY_POSIX_INSTALL_DIR_PREFIX) &&
297 - trimmed.endsWith('"') &&
298 - trimmed.length > LEGACY_POSIX_INSTALL_DIR_PREFIX.length) ||
299 - (trimmed.startsWith(LEGACY_FISH_INSTALL_DIR_PREFIX) &&
300 - trimmed.endsWith('"') &&
301 - trimmed.length > LEGACY_FISH_INSTALL_DIR_PREFIX.length)
298 + isQuotedAssignment(trimmed, LEGACY_POSIX_INSTALL_DIR_PREFIX) ||
299 + isQuotedAssignment(trimmed, LEGACY_FISH_INSTALL_DIR_PREFIX)
300 );
301 };
302
ts/packages/cli/src/commands/listen.cmd.ts
+5 -10
@@ -279,6 +279,9 @@ const extractEventFileId = (eventData: Record<string, unknown>): string => {
279 const parseStreamPath = (expression: string) =>
280 Effect.gen(function* () {
281 const trimmed = expression.trim();
282 + const pathTokens: Array<string | number> = [];
283 + // An empty --stream streams the whole event.
284 + if (trimmed.length === 0) return pathTokens;
285 if (!trimmed.startsWith('.')) {
286 return yield* Effect.fail(
287 invalidOptionValue(
@@ -288,7 +291,6 @@ const parseStreamPath = (expression: string) =>
291 );
292 }
293
291 - const pathTokens: Array<string | number> = [];
294 const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;
295 let lastIndex = 0;
296
@@ -465,9 +467,7 @@ const resolveListenSetup = (params: {
467 ? yield* parseTimeoutMs(params.timeout.value)
468 : undefined;
469 const streamPath = Option.isSome(params.stream)
468 - ? params.stream.value.trim().length === 0
469 - ? []
470 - : yield* parseStreamPath(params.stream.value)
470 + ? yield* parseStreamPath(params.stream.value)
471 : undefined;
472
473 return {
@@ -638,12 +638,7 @@ export const listenCmd = Command.make(
638 yield* emitStreamLine(`event: ${eventFilePath}`, ui);
639
640 if (shouldStream) {
641 - const streamValue =
642 - streamPath === undefined
643 - ? eventData
644 - : streamPath.length === 0
645 - ? eventData
646 - : applyStreamPath(eventData, streamPath);
641 + const streamValue = applyStreamPath(eventData, streamPath ?? []);
642 yield* emitStreamLine(`stream: ${formatStreamValue(streamValue)}`, ui);
643 }
644
ts/packages/cli/src/commands/login.cmd.ts
+6 -6
@@ -888,17 +888,17 @@ export const loginCmd = Command.make(
888 return yield* invalidOptionValue('Use either `--key` or `--user-api-key`, not both.');
889 }
890
891 - if (
892 - poll &&
893 - (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)
894 - ) {
891 + const hasBrowserOrSessionFlag = noBrowser || noWait;
892 + const hasDirectLoginFlag = Option.isSome(key) || Option.isSome(userApiKey);
893 +
894 + if (poll && (hasBrowserOrSessionFlag || hasDirectLoginFlag || agent)) {
895 return yield* invalidOptionValue(
896 '`--poll` cannot be combined with browser, session, direct-login, or agent flags.',
897 '--poll'
898 );
899 }
900
901 - if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
901 + if (agent && (hasBrowserOrSessionFlag || hasDirectLoginFlag)) {
902 return yield* invalidOptionValue(
903 '`--agent` cannot be combined with browser, session, or direct-login flags.',
904 '--agent'
@@ -909,7 +909,7 @@ export const loginCmd = Command.make(
909 return yield* invalidOptionValue('`--org` requires `--user-api-key`.', '--org');
910 }
911
912 - if (Option.isSome(userApiKey) && (noBrowser || noWait || Option.isSome(key))) {
912 + if (Option.isSome(userApiKey) && (hasBrowserOrSessionFlag || Option.isSome(key))) {
913 return yield* invalidOptionValue(
914 '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.',
915 '--user-api-key'
ts/packages/cli/src/commands/setup.cmd.ts
+11 -4
@@ -18,6 +18,8 @@ import {
18 SETUP_TARGETS,
19 uninstallSetupTargets,
20 type AgentHost,
21 + type SetupTargetDetection,
22 + type SetupUnsupportedReasonCode,
23 } from 'src/services/setup';
24 import { SetupCommandError, type SetupFailureReasonCode } from 'src/services/setup-command-error';
25 import { TerminalUI } from 'src/services/terminal-ui';
@@ -64,6 +66,14 @@ const setupCommandError = (
66 ...(cause === undefined ? {} : { cause }),
67 });
68
69 +// Only a host that is present but unsupported has a reason to report.
70 +const unsupportedReasonCodeOf = (
71 + detection: SetupTargetDetection
72 +): SetupUnsupportedReasonCode | undefined => {
73 + if (!detection.available || detection.supported) return undefined;
74 + return detection.unsupportedReasonCode ?? 'unknown';
75 +};
76 +
77 const setupBaseCmd = Command.make(
78 'setup',
79 { target, yes, ifPresent, uninstall },
@@ -85,10 +95,7 @@ const setupBaseCmd = Command.make(
95 available: detection.available,
96 supported: detection.supported,
97 hostVersion: detection.version,
88 - unsupportedReasonCode:
89 - detection.available && !detection.supported
90 - ? (detection.unsupportedReasonCode ?? 'unknown')
91 - : undefined,
98 + unsupportedReasonCode: unsupportedReasonCodeOf(detection),
99 hostConfigDirPresent: detection.configDirPresent,
100 hostBinaryInKnownPaths: detection.binaryInKnownPaths,
101 invocationOrigin,
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+93 -99
@@ -509,12 +509,11 @@ const emitExecuteFailureTelemetry = (params: {
509 const isNoConnectionError =
510 normalized instanceof ComposioNoActiveConnectionError || Boolean(mapped.override);
511
512 - const event = isMaybeToolValidationError({
513 - message,
514 - errorSlug,
515 - apiCode,
516 - })
517 - ? getToolExecuteValidationFailedEvent({
512 + const isValidationError = isMaybeToolValidationError({ message, errorSlug, apiCode });
513 + const executionStage = params.stage === 'validation' ? 'execution' : params.stage;
514 + const failureEvent = () => {
515 + if (isValidationError) {
516 + return getToolExecuteValidationFailedEvent({
517 toolSlug: params.toolSlug,
518 toolkitSlug,
519 args: params.args,
@@ -526,67 +525,54 @@ const emitExecuteFailureTelemetry = (params: {
525 invocationOrigin,
526 surface: params.surface,
527 projectMode: params.projectMode,
529 - stage:
530 - params.stage === 'dry_run'
531 - ? 'dry_run'
532 - : params.stage === 'validation'
533 - ? 'execution'
534 - : 'execution',
528 + stage: params.stage === 'dry_run' ? 'dry_run' : 'execution',
529 failureOrigin,
530 logId: params.logId,
537 - })
538 - : isMaybeToolNotFoundError({
539 - message,
540 - errorSlug,
541 - status,
542 - apiCode,
543 - })
544 - ? getToolExecuteToolNotFoundEvent({
545 - toolSlug: params.toolSlug,
546 - toolkitSlug,
547 - args: params.args,
548 - invocationOrigin,
549 - surface: params.surface,
550 - projectMode: params.projectMode,
551 - stage: params.stage === 'validation' ? 'execution' : params.stage,
552 - failureOrigin,
553 - logId: params.logId,
554 - errorSlug,
555 - status,
556 - apiCode,
557 - message,
558 - })
559 - : getToolExecuteFailedEvent({
560 - toolSlug: params.toolSlug,
561 - toolkitSlug,
562 - args: params.args,
563 - invocationOrigin,
564 - surface: params.surface,
565 - projectMode: params.projectMode,
566 - stage: params.stage === 'validation' ? 'execution' : params.stage,
567 - failureOrigin,
568 - logId: params.logId,
569 - errorSlug,
570 - status,
571 - apiCode,
572 - message,
573 - errorName: normalized instanceof Error ? normalized.name : undefined,
574 - isNoConnectionError,
575 - });
531 + });
532 + }
533 + if (isMaybeToolNotFoundError({ message, errorSlug, status, apiCode })) {
534 + return getToolExecuteToolNotFoundEvent({
535 + toolSlug: params.toolSlug,
536 + toolkitSlug,
537 + args: params.args,
538 + invocationOrigin,
539 + surface: params.surface,
540 + projectMode: params.projectMode,
541 + stage: executionStage,
542 + failureOrigin,
543 + logId: params.logId,
544 + errorSlug,
545 + status,
546 + apiCode,
547 + message,
548 + });
549 + }
550 + return getToolExecuteFailedEvent({
551 + toolSlug: params.toolSlug,
552 + toolkitSlug,
553 + args: params.args,
554 + invocationOrigin,
555 + surface: params.surface,
556 + projectMode: params.projectMode,
557 + stage: executionStage,
558 + failureOrigin,
559 + logId: params.logId,
560 + errorSlug,
561 + status,
562 + apiCode,
563 + message,
564 + errorName: normalized instanceof Error ? normalized.name : undefined,
565 + isNoConnectionError,
566 + });
567 + };
568
577 - yield* trackCliEventEffect(event);
569 + yield* trackCliEventEffect(failureEvent());
570
571 if (isNoConnectionError) {
572 return;
573 }
574
583 - if (
584 - isMaybeToolValidationError({
585 - message,
586 - errorSlug,
587 - apiCode,
588 - })
589 - ) {
575 + if (isValidationError) {
576 yield* trackCliCodactFailureEffect({
577 failureType: 'wrong_tool_input_param',
578 toolInfo: {
@@ -1967,8 +1953,9 @@ export const rootToolsCmd$Execute = Command.make(
1953 skipToolParamsCheck,
1954 skipChecks,
1955 }) =>
1970 - parallel
1971 - ? runParallelFromCommand({
1956 + Effect.gen(function* () {
1957 + if (parallel) {
1958 + return yield* runParallelFromCommand({
1959 surface: 'root',
1960 projectMode: 'consumer',
1961 getSchema,
@@ -1976,24 +1963,27 @@ export const rootToolsCmd$Execute = Command.make(
1963 skipConnectionCheck,
1964 skipToolParamsCheck,
1965 skipChecks,
1979 - })
1980 - : additionalSlugs.length > 0
1981 - ? Effect.fail(invalidArguments('Additional tool slugs require --parallel.'))
1982 - : runToolsExecute({
1983 - slug,
1984 - data,
1985 - file,
1986 - account,
1987 - userId: Option.none(),
1988 - projectName: Option.none(),
1989 - surface: 'root',
1990 - projectMode: 'consumer',
1991 - getSchema,
1992 - dryRun,
1993 - skipConnectionCheck,
1994 - skipToolParamsCheck,
1995 - skipChecks,
1996 - })
1966 + });
1967 + }
1968 + if (additionalSlugs.length > 0) {
1969 + return yield* invalidArguments('Additional tool slugs require --parallel.');
1970 + }
1971 + return yield* runToolsExecute({
1972 + slug,
1973 + data,
1974 + file,
1975 + account,
1976 + userId: Option.none(),
1977 + projectName: Option.none(),
1978 + surface: 'root',
1979 + projectMode: 'consumer',
1980 + getSchema,
1981 + dryRun,
1982 + skipConnectionCheck,
1983 + skipToolParamsCheck,
1984 + skipChecks,
1985 + });
1986 + })
1987 ).pipe(
1988 Command.withDescription(
1989 'Execute a tool by slug. Validates inputs against cached schemas and checks connections\nautomatically — just try it and it will tell you what to fix.'
@@ -2037,8 +2027,9 @@ export const devToolsCmd$Execute = Command.make(
2027 skipToolParamsCheck,
2028 skipChecks,
2029 }) =>
2040 - parallel
2041 - ? runParallelFromCommand({
2030 + Effect.gen(function* () {
2031 + if (parallel) {
2032 + return yield* runParallelFromCommand({
2033 surface: 'dev',
2034 projectMode: 'developer',
2035 getSchema,
@@ -2046,24 +2037,27 @@ export const devToolsCmd$Execute = Command.make(
2037 skipConnectionCheck,
2038 skipToolParamsCheck,
2039 skipChecks,
2049 - })
2050 - : additionalSlugs.length > 0
2051 - ? Effect.fail(invalidArguments('Additional tool slugs require --parallel.'))
2052 - : runToolsExecute({
2053 - slug,
2054 - data,
2055 - file,
2056 - account,
2057 - userId,
2058 - projectName,
2059 - surface: 'dev',
2060 - projectMode: 'developer',
2061 - getSchema,
2062 - dryRun,
2063 - skipConnectionCheck,
2064 - skipToolParamsCheck,
2065 - skipChecks,
2066 - })
2040 + });
2041 + }
2042 + if (additionalSlugs.length > 0) {
2043 + return yield* invalidArguments('Additional tool slugs require --parallel.');
2044 + }
2045 + return yield* runToolsExecute({
2046 + slug,
2047 + data,
2048 + file,
2049 + account,
2050 + userId,
2051 + projectName,
2052 + surface: 'dev',
2053 + projectMode: 'developer',
2054 + getSchema,
2055 + dryRun,
2056 + skipConnectionCheck,
2057 + skipToolParamsCheck,
2058 + skipChecks,
2059 + });
2060 + })
2061 ).pipe(
2062 Command.withDescription(
2063 'Test tool executions against playground users using your developer project auth configs.\nUses --user-id when provided, otherwise falls back to your local or global playground test user id.\nArguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.'
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
+2 -1
@@ -61,7 +61,8 @@ const causeDetail = (cause: unknown): string | undefined => {
61
62 const withCauseDetail = (message: string, cause: unknown): string => {
63 const detail = causeDetail(cause);
64 - return detail !== undefined && detail !== message ? `${message}\nCaused by: ${detail}` : message;
64 + if (detail === undefined || detail === message) return message;
65 + return `${message}\nCaused by: ${detail}`;
66 };
67
68 const clientApiErrorMessage = (error: ClientApiError): string =>
ts/packages/cli/src/services/run-helpers-runtime.ts
+12 -10
@@ -144,6 +144,17 @@ export const parseJson = (text: string): unknown => {
144 );
145 };
146
147 +// The most specific text a failed proxy response carries: a bare JSON string,
148 +// then its `message`, then its `error`, then the raw body.
149 +const proxyFailureDetail = (parsed: unknown, raw: string): string | undefined => {
150 + if (typeof parsed === 'string') return parsed;
151 + if (Predicate.isObject(parsed)) {
152 + if (typeof parsed.message === 'string') return parsed.message;
153 + if (typeof parsed.error === 'string') return parsed.error;
154 + }
155 + return raw.trim() || undefined;
156 +};
157 +
158 const executeId = () => crypto.randomUUID().slice(0, 8);
159
160 const truncateDebugText = (value: unknown, max = 240) => {
@@ -697,16 +708,7 @@ const createProxyHelper = (params: {
708 const raw = await response.text();
709 const parsed = parseJson(raw);
710 if (!response.ok) {
700 - const responseMessage = Predicate.isObject(parsed) ? parsed.message : undefined;
701 - const responseError = Predicate.isObject(parsed) ? parsed.error : undefined;
702 - const detail =
703 - typeof parsed === 'string'
704 - ? parsed
705 - : typeof responseMessage === 'string'
706 - ? responseMessage
707 - : typeof responseError === 'string'
708 - ? responseError
709 - : raw.trim() || undefined;
711 + const detail = proxyFailureDetail(parsed, raw);
712 const error = new Error(
713 `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`
714 );
ts/packages/cli/src/services/setup.ts
+11 -9
@@ -834,6 +834,16 @@ export const inspectSetupTargets = (
834 return inspected;
835 });
836
837 +const pluginLifecycleAction = (
838 + operation: 'setup' | 'uninstall',
839 + status: InspectedSetupTarget
840 +): 'installed' | 'enabled' | 'configured' | 'uninstalled' => {
841 + if (operation === 'uninstall') return 'uninstalled';
842 + if (!status.plugin_installed) return 'installed';
843 + if (!status.plugin_enabled) return 'enabled';
844 + return 'configured';
845 +};
846 +
847 const runSetupTargets = <E, R>(
848 inspected: ReadonlyArray<InspectedSetupTarget>,
849 runAdapter: (
@@ -873,19 +883,11 @@ const runSetupTargets = <E, R>(
883 })
884 );
885 if (result.plugin_changed) {
876 - const action =
877 - operation === 'uninstall'
878 - ? 'uninstalled'
879 - : !status.plugin_installed
880 - ? 'installed'
881 - : !status.plugin_enabled
882 - ? 'enabled'
883 - : 'configured';
886 yield* trackCliEventEffect(
887 getPluginLifecycleSucceededEvent({
888 operation,
889 target: result.target,
888 - action,
890 + action: pluginLifecycleAction(operation, status),
891 invocationOrigin,
892 cliVersion: APP_VERSION,
893 })
ts/packages/cli/src/services/tool-file-uploads.ts
+10 -12
@@ -55,6 +55,12 @@ const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isObje
55 const getSchemaVariant = (value: unknown): ReadonlyArray<JsonSchema> =>
56 Array.isArray(value) ? value.filter(isSchemaRecord) : [];
57
58 +// `items` is either one schema or a tuple of schemas; keep only the schema records.
59 +const getItemSchemas = (items: unknown): ReadonlyArray<JsonSchema> => {
60 + if (Array.isArray(items)) return items.filter(isSchemaRecord);
61 + return isSchemaRecord(items) ? [items] : [];
62 +};
63 +
64 const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [
65 ...getSchemaVariant(schema?.anyOf),
66 ...getSchemaVariant(schema?.oneOf),
@@ -154,13 +160,9 @@ export const findFileUploadablePaths = (
160 findFileUploadablePaths(variant, basePath)
161 );
162
157 - const itemPaths = Array.isArray(schema.items)
158 - ? schema.items.flatMap(item =>
159 - isSchemaRecord(item) ? findFileUploadablePaths(item, basePath) : []
160 - )
161 - : isSchemaRecord(schema.items)
162 - ? findFileUploadablePaths(schema.items, basePath)
163 - : [];
163 + const itemPaths = getItemSchemas(schema.items).flatMap(item =>
164 + findFileUploadablePaths(item, basePath)
165 + );
166
167 const seen = new Set<string>();
168 return [...directPropertyPaths, ...variantPaths, ...itemPaths].filter(pathParts => {
@@ -375,11 +377,7 @@ const hydrateFileUploads = (
377 }
378
379 if (schema?.type === 'array' && Array.isArray(value) && schema.items) {
378 - const itemSchema = Array.isArray(schema.items)
379 - ? schema.items.find(isSchemaRecord)
380 - : isSchemaRecord(schema.items)
381 - ? schema.items
382 - : undefined;
380 + const itemSchema = getItemSchemas(schema.items).at(0);
381
382 return yield* Effect.all(
383 value.map(item => hydrateFileUploads(item, itemSchema, ctx)),
ts/packages/cli/src/services/tool-permissions.ts
+7 -8
@@ -914,6 +914,12 @@ const COMPLETION_COPY: Readonly<
914 },
915 };
916
917 +const DECISION_BY_APPROVAL_PATH: ReadonlyMap<string, PermissionDecision> = new Map([
918 + ['/allow-session', 'allow_session'],
919 + ['/allow-once', 'allow_once'],
920 + ['/deny', 'deny'],
921 +]);
922 +
923 const completionHtml = (decision: PermissionDecision) => {
924 const { title, body } = COMPLETION_COPY[decision];
925 return `<!doctype html>
@@ -993,14 +999,7 @@ const requestPermissionInBrowser = (params: {
999 return;
1000 }
1001
996 - const decision =
997 - url.pathname === '/allow-session'
998 - ? 'allow_session'
999 - : url.pathname === '/allow-once'
1000 - ? 'allow_once'
1001 - : url.pathname === '/deny'
1002 - ? 'deny'
1003 - : undefined;
1002 + const decision = DECISION_BY_APPROVAL_PATH.get(url.pathname);
1003 if (!decision) {
1004 res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Not found');
1005 return;
ts/packages/cli/src/services/update-check.ts
+11 -5
@@ -49,6 +49,15 @@ export interface UpdateStatus {
49 lastChecked: string | null;
50 }
51
52 +const toCheckStatus = (params: {
53 + readonly updateAvailable: boolean;
54 + readonly versionsKnown: boolean;
55 +}): UpdateStatus['checkStatus'] => {
56 + if (params.updateAvailable) return 'update-available';
57 + if (!params.versionsKnown) return 'unknown';
58 + return 'up-to-date';
59 +};
60 +
61 const UpdateCheckStateSchema = Schema.fromJsonString(
62 Schema.Struct({
63 lastChecked: Schema.String,
@@ -295,11 +304,8 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
304 validLatest && semver.prerelease(validLatest) === null ? validLatest : null;
305 const updateAvailable =
306 validCurrent !== null && latestStable !== null && semver.gt(latestStable, validCurrent);
298 - const checkStatus = updateAvailable
299 - ? 'update-available'
300 - : refreshFailed || validCurrent === null || latestStable === null
301 - ? 'unknown'
302 - : 'up-to-date';
307 + const versionsKnown = !refreshFailed && validCurrent !== null && latestStable !== null;
308 + const checkStatus = toCheckStatus({ updateAvailable, versionsKnown });
309
310 return {
311 current: config.currentVersion,
ts/packages/cli/test/src/analytics.dispatch.test.ts
+4 -9
@@ -37,13 +37,8 @@ vi.mock('node:child_process', () => ({
37
38 const originalArgv = [...process.argv];
39
40 -const cwdHash = (cwd: string): string => {
41 - let hash = 5381;
42 - for (let index = 0; index < cwd.length; index += 1) {
43 - hash = (hash * 33) ^ cwd.charCodeAt(index);
44 - }
45 - return Math.abs(hash >>> 0).toString(36);
46 -};
40 +/** The cache key of `/workspace/project`: its djb2 hash in base 36. */
41 +const WORKSPACE_PROJECT_CWD_HASH = '1uj8qfp';
42
43 // Design contract: `FetchHttpClient.Fetch` is an `effect` `Context.Reference`
44 // whose default value (`globalThis.fetch`) is memoized on first read (see the
@@ -145,7 +140,7 @@ describe('CLI analytics dispatch', () => {
140 JSON.stringify({
141 older: {
142 probablyMyCliSessionsByCwdHash: {
148 - [cwdHash(cwd)]: {
143 + [WORKSPACE_PROJECT_CWD_HASH]: {
144 id: 'cli_s_older',
145 // The TestClock sits at epoch 0, so these fixed instants are
146 // deterministically 30s and 60s in the future.
@@ -155,7 +150,7 @@ describe('CLI analytics dispatch', () => {
150 },
151 newer: {
152 probablyMyCliSessionsByCwdHash: {
158 - [cwdHash(cwd)]: {
153 + [WORKSPACE_PROJECT_CWD_HASH]: {
154 id: 'cli_s_newer',
155 expiresAt: '1970-01-01T00:01:00.000Z',
156 },
ts/packages/cli/test/src/analytics.events.test.ts
+11 -6
@@ -544,11 +544,12 @@ describe('CLI analytics journey taxonomy', () => {
544 ).toBe(stage);
545 });
546
547 - it('maps every analytics event name to a declared journey stage', () => {
548 - for (const name of Object.values(CLI_ANALYTICS_EVENTS)) {
547 + it.each(Object.values(CLI_ANALYTICS_EVENTS))(
548 + 'maps analytics event %s to a declared journey stage',
549 + name => {
550 expect(CLI_JOURNEY_STAGES).toContain(CLI_EVENT_JOURNEY_STAGES[name]);
551 }
551 - });
552 + );
553
554 it('stamps standalone setup and tool-invocation events with their stages', () => {
555 expect(
@@ -688,17 +689,21 @@ describe('CLI analytics journey taxonomy', () => {
689 expect(shellDelegations).toHaveLength(1);
690 expect(installInvocations).toHaveLength(2);
691 expect(shellDelegations[0]).toContain('COMPOSIO_CLI_INVOCATION_ORIGIN=installer');
692 + });
693
692 - for (const shell of ['zsh', 'bash', 'fish']) {
694 + it.each(['zsh', 'bash', 'fish'])(
695 + 'keeps the %s installer variant from invoking the CLI itself',
696 + shell => {
697 const variantScript = readFileSync(
698 new URL(`../../../../../install/${shell}.sh`, import.meta.url),
699 'utf8'
700 );
701 // Variants never invoke the CLI themselves: they re-exec the base installer with the
698 - // shell pinned, so the delegation asserted above stays the only CLI install call.
702 + // shell pinned, so the base installer's shell-setup delegation stays the only CLI
703 + // install call.
704 expect(variantScript).not.toContain('"$exe"');
705 expect(variantScript).not.toContain(' install --shell');
706 expect(variantScript).toContain('COMPOSIO_INSTALL_SHELL="$variant_shell"');
707 }
703 - });
708 + );
709 });
ts/packages/cli/test/src/cli-main.test.ts
+29 -8
@@ -5,9 +5,31 @@ import { describe, expect, it } from 'vitest';
5 import * as tempy from 'tempy';
6
7 describe('CLI process error handling', () => {
8 - it('records help and version as successes and invalid help as a failure', () => {
9 - const configDirectory = tempy.temporaryDirectory();
10 - for (const args of [[], ['help'], ['--help'], ['--version'], ['help', 'orgz']]) {
8 + it.each([
9 + { args: [], status: 0, recorded: 'CLI_COMMAND_SUCCEEDED', absent: 'CLI_COMMAND_FAILED' },
10 + { args: ['help'], status: 0, recorded: 'CLI_COMMAND_SUCCEEDED', absent: 'CLI_COMMAND_FAILED' },
11 + {
12 + args: ['--help'],
13 + status: 0,
14 + recorded: 'CLI_COMMAND_SUCCEEDED',
15 + absent: 'CLI_COMMAND_FAILED',
16 + },
17 + {
18 + args: ['--version'],
19 + status: 0,
20 + recorded: 'CLI_COMMAND_SUCCEEDED',
21 + absent: 'CLI_COMMAND_FAILED',
22 + },
23 + {
24 + args: ['help', 'orgz'],
25 + status: 1,
26 + recorded: 'CLI_COMMAND_FAILED',
27 + absent: 'CLI_COMMAND_SUCCEEDED',
28 + },
29 + ])(
30 + 'records help and version as successes and invalid help as a failure: `composio $args` is $recorded',
31 + ({ args, status, recorded, absent }) => {
32 + const configDirectory = tempy.temporaryDirectory();
33 const result = spawnSync('bun', ['run', 'src/bin.ts', ...args], {
34 cwd: process.cwd(),
35 encoding: 'utf8',
@@ -20,12 +42,11 @@ describe('CLI process error handling', () => {
42 COMPOSIO_CLI_TELEMETRY_DEBUG: '1',
43 },
44 });
23 - const invalid = args.includes('orgz');
24 - expect(result.status).toBe(invalid ? 1 : 0);
25 - expect(result.stderr).toContain(invalid ? 'CLI_COMMAND_FAILED' : 'CLI_COMMAND_SUCCEEDED');
26 - expect(result.stderr).not.toContain(invalid ? 'CLI_COMMAND_SUCCEEDED' : 'CLI_COMMAND_FAILED');
45 + expect(result.status).toBe(status);
46 + expect(result.stderr).toContain(recorded);
47 + expect(result.stderr).not.toContain(absent);
48 }
28 - });
49 + );
50
51 it('prints unreported typed execute failures and exits non-zero', () => {
52 const configDirectory = tempy.temporaryDirectory();
ts/packages/cli/test/src/commands/agent/agent.cmd.test.ts
+58 -116
@@ -22,6 +22,12 @@ const agentSignupResponse = {
22 },
23 };
24
25 +const jsonResponse = (body: unknown) =>
26 + new Response(JSON.stringify(body), {
27 + status: 200,
28 + headers: { 'Content-Type': 'application/json' },
29 + });
30 +
31 describe('CLI: composio agent', () => {
32 afterEach(() => {
33 vi.restoreAllMocks();
@@ -41,7 +47,7 @@ describe('CLI: composio agent', () => {
47
48 const identity = yield* readStoredAgentIdentity;
49
44 - expect(Option.getOrUndefined(identity)?.composio_agent_key).toBe('cak_test_agent');
50 + expect(Option.getOrThrow(identity).composio_agent_key).toBe('cak_test_agent');
51 expect(yield* fs.readFileString(agentConfigPath, 'utf8')).toBe(encodedIdentity);
52 expect((yield* fs.stat(agentConfigPath)).mode & 0o777).toBe(0o600);
53 })
@@ -63,29 +69,16 @@ describe('CLI: composio agent', () => {
69 layer(TestLive())(it => {
70 it.effect('agent signup works when the CLI is not signed in', () =>
71 Effect.gen(function* () {
66 - vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
67 - const url =
68 - typeof requestInput === 'string'
69 - ? requestInput
70 - : requestInput instanceof URL
71 - ? requestInput.toString()
72 - : requestInput.url;
73 -
74 - if (url.includes('/api/signup')) {
75 - return new Response(JSON.stringify(agentSignupResponse), {
76 - status: 200,
77 - headers: { 'Content-Type': 'application/json' },
78 - });
79 - }
80 -
81 - return new Response(JSON.stringify({}), {
82 - status: 200,
83 - headers: { 'Content-Type': 'application/json' },
84 - });
85 - });
72 + const fetchSpy = vi
73 + .spyOn(globalThis, 'fetch')
74 + .mockImplementation(async () => jsonResponse(agentSignupResponse));
75
76 yield* cli(['agent', 'signup']);
77
78 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
79 + expect.stringContaining('/api/signup'),
80 + expect.objectContaining({ method: 'POST' })
81 + );
82 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
83 expect(output).toContain('composio agent signup signs you up as a Composio agent');
84 expect(output).toContain('fully non-interactive');
@@ -118,30 +111,18 @@ describe('CLI: composio agent', () => {
111 layer(TestLive())(it => {
112 it.effect('top-level signup makes clear it signs up an agent', () =>
113 Effect.gen(function* () {
121 - vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
122 - const url =
123 - typeof requestInput === 'string'
124 - ? requestInput
125 - : requestInput instanceof URL
126 - ? requestInput.toString()
127 - : requestInput.url;
128 -
129 - if (url.includes('/api/signup')) {
130 - return new Response(JSON.stringify(agentSignupResponse), {
131 - status: 200,
132 - headers: { 'Content-Type': 'application/json' },
133 - });
134 - }
135 -
136 - return new Response(JSON.stringify({}), {
137 - status: 200,
138 - headers: { 'Content-Type': 'application/json' },
139 - });
140 - });
114 + const fetchSpy = vi
115 + .spyOn(globalThis, 'fetch')
116 + .mockImplementation(async () => jsonResponse(agentSignupResponse));
117
118 yield* cli(['signup']);
119 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
120
121 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
122 + expect.stringContaining('/api/signup'),
123 + expect.objectContaining({ method: 'POST' })
124 + );
125 +
126 expect(output).toContain('composio signup signs you up as a Composio agent');
127 })
128 );
@@ -154,57 +135,32 @@ describe('CLI: composio agent', () => {
135 const fs = yield* FileSystem.FileSystem;
136 const cacheDir = yield* setupCacheDir;
137 expect((yield* fs.stat(path.join(cacheDir, 'agent.json'))).mode & 0o777).toBe(0o600);
157 - vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
158 - const url =
159 - typeof requestInput === 'string'
160 - ? requestInput
161 - : requestInput instanceof URL
162 - ? requestInput.toString()
163 - : requestInput.url;
164 -
165 - if (url.includes('/api/mail')) {
166 - expect(new Headers(init?.headers).get('authorization')).toBe('Bearer cak_test_agent');
167 - return new Response(
168 - JSON.stringify({
169 - count: 1,
170 - messages: [
171 - {
172 - id: 'msg_123',
173 - from: 'person@example.com',
174 - subject: 'Hello',
175 - preview: 'Hi agent',
176 - },
177 - ],
178 - }),
179 - {
180 - status: 200,
181 - headers: { 'Content-Type': 'application/json' },
182 - }
183 - );
184 - }
185 -
186 - return new Response(JSON.stringify({}), {
187 - status: 200,
188 - headers: { 'Content-Type': 'application/json' },
189 - });
190 - });
138 + const inbox = {
139 + count: 1,
140 + messages: [
141 + {
142 + id: 'msg_123',
143 + from: 'person@example.com',
144 + subject: 'Hello',
145 + preview: 'Hi agent',
146 + },
147 + ],
148 + };
149 + const fetchSpy = vi
150 + .spyOn(globalThis, 'fetch')
151 + .mockImplementation(async () => jsonResponse(inbox));
152
153 yield* cli(['agent', 'inbox']);
154 const lines = yield* MockConsole.getLines({ stripAnsi: true });
155
195 - expect(lines).toEqual([
196 - JSON.stringify({
197 - count: 1,
198 - messages: [
199 - {
200 - id: 'msg_123',
201 - from: 'person@example.com',
202 - subject: 'Hello',
203 - preview: 'Hi agent',
204 - },
205 - ],
206 - }),
207 - ]);
156 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
157 + expect.stringContaining('/api/mail'),
158 + expect.objectContaining({
159 + method: 'GET',
160 + headers: expect.objectContaining({ Authorization: 'Bearer cak_test_agent' }),
161 + })
162 + );
163 + expect(lines).toEqual([JSON.stringify(inbox)]);
164 })
165 );
166 });
@@ -212,37 +168,23 @@ describe('CLI: composio agent', () => {
168 layer(TestLive())(it => {
169 it.effect('agent login restores an existing agent from composio_agent_key', () =>
170 Effect.gen(function* () {
215 - vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
216 - const url =
217 - typeof requestInput === 'string'
218 - ? requestInput
219 - : requestInput instanceof URL
220 - ? requestInput.toString()
221 - : requestInput.url;
222 -
223 - if (url.includes('/api/whoami')) {
224 - expect(new Headers(init?.headers).get('authorization')).toBe('Bearer cak_existing');
225 - return new Response(
226 - JSON.stringify({
227 - ...agentSignupResponse,
228 - composio_agent_key: 'cak_existing',
229 - agent_key: 'cak_existing',
230 - }),
231 - {
232 - status: 200,
233 - headers: { 'Content-Type': 'application/json' },
234 - }
235 - );
236 - }
237 -
238 - return new Response(JSON.stringify({}), {
239 - status: 200,
240 - headers: { 'Content-Type': 'application/json' },
241 - });
242 - });
171 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
172 + jsonResponse({
173 + ...agentSignupResponse,
174 + composio_agent_key: 'cak_existing',
175 + agent_key: 'cak_existing',
176 + })
177 + );
178
179 yield* cli(['agent', 'login', 'cak_existing']);
180
181 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
182 + expect.stringContaining('/api/whoami'),
183 + expect.objectContaining({
184 + method: 'GET',
185 + headers: expect.objectContaining({ Authorization: 'Bearer cak_existing' }),
186 + })
187 + );
188 const ctx = yield* ComposioUserContext;
189 expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_agent');
190 expect(Option.getOrUndefined(ctx.data.orgId)).toBe('org_agent');
ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.ts
+10 -12
@@ -1,7 +1,7 @@
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 import * as BunPath from '@effect/platform-bun/BunPath';
3 import { describe, expect, it, layer } from '@effect/vitest';
4 -import { Cause, Effect, Exit, FileSystem, Layer, Path } from 'effect';
4 +import { Effect, FileSystem, Layer, Path } from 'effect';
5 import * as tempy from 'tempy';
6 import { discoverSkillRoots } from 'src/effects/discover-skill-roots';
7 import { cli, TestLive } from 'test/__utils__';
@@ -116,17 +116,15 @@ describe('config experimental skill discovery', () => {
116 layer(TestLive())('config experimental state validation', it => {
117 it.effect('reports an invalid state as a structured domain failure', () =>
118 Effect.gen(function* () {
119 - const exit = yield* Effect.exit(cli(['config', 'experimental', 'listen', 'sometimes']));
120 -
121 - expect(Exit.isFailure(exit)).toBe(true);
122 - if (Exit.isFailure(exit)) {
123 - const failure = Cause.squash(exit.cause);
124 - expect(failure).toMatchObject({
125 - _tag: 'commands/CommandInputError',
126 - option: '<state>',
127 - message: 'Invalid state "sometimes". Use "on" or "off".',
128 - });
129 - }
119 + const failure = yield* cli(['config', 'experimental', 'listen', 'sometimes']).pipe(
120 + Effect.flip
121 + );
122 +
123 + expect(failure).toMatchObject({
124 + _tag: 'commands/CommandInputError',
125 + option: '<state>',
126 + message: 'Invalid state "sometimes". Use "on" or "off".',
127 + });
128 })
129 );
130 });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.client.cmd.test.ts
+19 -9
@@ -1,7 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 -import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
4 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
5
6 const testLayer = TestLive({
7 baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
@@ -15,19 +15,29 @@ describe('CLI: composio link over the API client', () => {
15 layer(testLayer)('[Given] the API rejects the link for a toolkit', it => {
16 it.effect('[Then] the API message and the browse hint are printed', () =>
17 Effect.gen(function* () {
18 - const stub = stubClientResources(['toolRouter'], request =>
19 - request.path.endsWith('/link')
20 - ? rejection(
21 - 400,
22 - 'Toolkit gmail is disabled for this project',
23 - 'ToolRouterV2_ToolkitDisabled'
24 - )
25 - : Response.json({
18 + const stub = stubClientResources(
19 + ['toolRouter'],
20 + routeRequests(
21 + [
22 + {
23 + method: 'POST',
24 + path: '/api/v3.1/tool_router/session/trs_stub_session/link',
25 + respond: () =>
26 + rejection(
27 + 400,
28 + 'Toolkit gmail is disabled for this project',
29 + 'ToolRouterV2_ToolkitDisabled'
30 + ),
31 + },
32 + ],
33 + () =>
34 + Response.json({
35 session_id: 'trs_stub_session',
36 config: { user_id: 'consumer-user-org_test' },
37 mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
38 tool_router_tools: [],
39 })
40 + )
41 );
42 yield* cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer));
43 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+48 -59
@@ -15,10 +15,8 @@ vi.mock('open', () => ({
15 default: vi.fn(async () => undefined),
16 }));
17
18 -const extractJsonObject = (output: string): Record<string, unknown> | null => {
19 - const jsonMatch = output.match(/\{[\s\S]*"status"[\s\S]*\}/);
20 - return jsonMatch ? JSON.parse(jsonMatch[0]) : null;
21 -};
18 +/** The command's JSON result: `ui.output` prints it as the last console line. */
19 +const parseLastLine = (lines: ReadonlyArray<string>): unknown => JSON.parse(String(lines.at(-1)));
20
21 const makeConnectedAccount = (overrides?: Partial<ConnectedAccountItem>): ConnectedAccountItem => ({
22 id: 'con_test_link',
@@ -144,12 +142,12 @@ describe('CLI: composio dev connected-accounts link', () => {
142 Effect.gen(function* () {
143 yield* cli(['link', 'gmail']);
144 const lines = yield* MockConsole.getLines({ stripAnsi: true });
147 - const parsed = extractJsonObject(lines.join('\n'));
145
149 - expect(parsed).not.toBeNull();
150 - expect(parsed?.status).toBe('success');
151 - expect(parsed?.connected_account_id).toBe('con_test_link');
152 - expect(parsed?.toolkit).toBe('gmail');
146 + expect(parseLastLine(lines)).toMatchObject({
147 + status: 'success',
148 + connected_account_id: 'con_test_link',
149 + toolkit: 'gmail',
150 + });
151 expect(vi.mocked(open)).toHaveBeenCalledOnce();
152 })
153 );
@@ -167,11 +165,11 @@ describe('CLI: composio dev connected-accounts link', () => {
165 yield* cli(['link', 'gmail', '--no-browser']);
166 const lines = yield* MockConsole.getLines({ stripAnsi: true });
167 const output = lines.join('\n');
170 - const parsed = extractJsonObject(output);
168
172 - expect(parsed).not.toBeNull();
173 - expect(parsed?.status).toBe('success');
174 - expect(parsed?.connected_account_id).toBe('con_test_link');
169 + expect(parseLastLine(lines)).toMatchObject({
170 + status: 'success',
171 + connected_account_id: 'con_test_link',
172 + });
173 expect(output).toContain('https://app.composio.dev/link?token=lt_test_token');
174 expect(output).toContain('Open this URL in your browser to authorize');
175 expect(output).not.toContain('Redirecting you to the authorization page');
@@ -195,7 +193,7 @@ describe('CLI: composio dev connected-accounts link', () => {
193
194 expect(output).toContain('default');
195 expect(output).toContain('castle');
198 - expect(output).toContain('"toolkit": "gmail"');
196 + expect(parseLastLine(lines)).toMatchObject({ toolkit: 'gmail' });
197 expect(vi.mocked(open)).not.toHaveBeenCalled();
198 })
199 );
@@ -236,18 +234,10 @@ describe('CLI: composio dev connected-accounts link', () => {
234 Effect.gen(function* () {
235 yield* cli(['link', 'gmail', '--no-wait']);
236 const lines = yield* MockConsole.getLines({ stripAnsi: true });
239 - const forcedLine = lines
240 - .map(line => {
241 - try {
242 - return JSON.parse(line) as { channel?: string; data?: string };
243 - } catch {
244 - return null;
245 - }
246 - })
247 - .find(line => line?.channel === 'FORCED');
248 -
249 - expect(forcedLine).toBeTruthy();
250 - expect(forcedLine?.data).toContain('"status": "pending"');
237 + const forcedLine = parseLastLine(lines) as { channel: string; data: string };
238 +
239 + expect(forcedLine.channel).toBe('FORCED');
240 + expect(JSON.parse(forcedLine.data)).toMatchObject({ status: 'pending' });
241 expect(vi.mocked(open)).not.toHaveBeenCalled();
242 })
243 );
@@ -265,19 +255,16 @@ describe('CLI: composio dev connected-accounts link', () => {
255 Effect.gen(function* () {
256 yield* cli(['link', 'gmail', '--no-wait']);
257 const lines = yield* MockConsole.getLines({ stripAnsi: true });
268 - const forcedLines = lines
269 - .map(line => {
270 - try {
271 - return JSON.parse(line) as { channel?: string; data?: string };
272 - } catch {
273 - return null;
274 - }
275 - })
276 - .filter(line => line?.channel === 'FORCED');
277 -
278 - expect(forcedLines).toHaveLength(1);
279 - expect(forcedLines[0]?.data).toContain('"status": "pending"');
280 - expect(forcedLines[0]?.data?.trim().startsWith('{')).toBe(true);
258 + const forcedLine = parseLastLine(lines) as { channel: string; data: string };
259 +
260 + // Every line before the payload is a log or note, never a second output().
261 + expect(lines.slice(0, -1)).toEqual([
262 + 'Open this URL in your browser to authorize',
263 + '[Redirect URL] https://app.composio.dev/link?token=lt_test_token',
264 + ]);
265 + expect(forcedLine.channel).toBe('FORCED');
266 + // The payload parses as JSON, so nothing (such as the raw URL) precedes it.
267 + expect(JSON.parse(forcedLine.data)).toMatchObject({ status: 'pending' });
268 })
269 );
270 });
@@ -328,11 +315,12 @@ describe('CLI: composio dev connected-accounts link', () => {
315 Effect.gen(function* () {
316 yield* cli(['link', 'gmail', '--list']);
317
331 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
318 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
319 + const output = lines.join('\n');
320 expect(output).not.toContain('must-not-leak');
321 expect(output).not.toContain('access_token');
322 expect(output).not.toContain('refresh_token');
335 - expect(extractJsonObject(output)).toStrictEqual({
323 + expect(parseLastLine(lines)).toStrictEqual({
324 toolkit: 'gmail',
325 total: 1,
326 items: [makeConnectedAccount()],
@@ -352,11 +340,11 @@ describe('CLI: composio dev connected-accounts link', () => {
340 Effect.gen(function* () {
341 yield* cli(['link', 'gmail']);
342 const lines = yield* MockConsole.getLines({ stripAnsi: true });
355 - const parsed = extractJsonObject(lines.join('\n'));
343
357 - expect(parsed).not.toBeNull();
358 - expect(parsed?.status).toBe('success');
359 - expect(parsed?.connected_account_id).toBe('con_test_link');
344 + expect(parseLastLine(lines)).toMatchObject({
345 + status: 'success',
346 + connected_account_id: 'con_test_link',
347 + });
348 })
349 );
350 });
@@ -421,12 +409,12 @@ describe('CLI: composio dev connected-accounts link', () => {
409 Effect.gen(function* () {
410 yield* cli(['link', 'gmail', '--no-wait']);
411 const lines = yield* MockConsole.getLines({ stripAnsi: true });
424 - const parsed = extractJsonObject(lines.join('\n'));
412
426 - expect(parsed).not.toBeNull();
427 - expect(parsed?.status).toBe('pending');
428 - expect(parsed?.connected_account_id).toBe('con_test_link');
429 - expect(parsed?.toolkit).toBe('gmail');
413 + expect(parseLastLine(lines)).toMatchObject({
414 + status: 'pending',
415 + connected_account_id: 'con_test_link',
416 + toolkit: 'gmail',
417 + });
418 })
419 );
420 });
@@ -453,10 +441,11 @@ describe('CLI: composio dev connected-accounts link', () => {
441 Effect.gen(function* () {
442 yield* cli(['link', 'gmail']);
443 const lines = yield* MockConsole.getLines({ stripAnsi: true });
456 - const parsed = extractJsonObject(lines.join('\n'));
444
458 - expect(lines.length).toBeGreaterThan(0);
459 - expect(parsed).toBeNull();
445 + expect(lines).toEqual([
446 + 'Linking gmail...',
447 + 'The API returned an incomplete link response (missing connected_account_id or redirect_url).',
448 + ]);
449 })
450 );
451 }
@@ -475,12 +464,12 @@ describe('CLI: composio dev connected-accounts link', () => {
464 Effect.gen(function* () {
465 yield* cli(['link', 'gmail']);
466 const lines = yield* MockConsole.getLines({ stripAnsi: true });
478 - const parsed = extractJsonObject(lines.join('\n'));
467
480 - expect(parsed).not.toBeNull();
481 - expect(parsed?.status).toBe('success');
482 - expect(parsed?.connected_account_id).toBe('con_test_link');
483 - expect(parsed?.toolkit).toBe('gmail');
468 + expect(parseLastLine(lines)).toMatchObject({
469 + status: 'success',
470 + connected_account_id: 'con_test_link',
471 + toolkit: 'gmail',
472 + });
473 })
474 );
475 });
@@ -549,7 +538,7 @@ describe('CLI: composio dev connected-accounts link', () => {
538
539 expect(output).toContain('Pass --alias to create another one');
540 expect(output).toContain('con_test_link');
552 - expect(output).not.toContain('"status": "success"');
541 + expect(output).not.toContain('"status"');
542 })
543 );
544 }
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+4 -17
@@ -8,19 +8,6 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
8 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
9 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
10
11 -const parseJsonFromLines = (lines: ReadonlyArray<string>) => {
12 - for (let i = lines.length - 1; i >= 0; i -= 1) {
13 - const line = lines[i];
14 - if (!line) continue;
15 - try {
16 - return JSON.parse(line) as Record<string, Array<Record<string, unknown>>>;
17 - } catch {
18 - // continue
19 - }
20 - }
21 - throw new Error('Expected JSON output but none found');
22 -};
23 -
11 const testConnections: ConnectedAccountItem[] = [
12 {
13 id: 'con_gmail_active',
@@ -140,7 +127,7 @@ describe('CLI: composio connections list', () => {
127 yield* cli(['connections', 'list']);
128
129 const lines = yield* MockConsole.getLines({ stripAnsi: true });
143 - const parsed = parseJsonFromLines(lines);
130 + const parsed = JSON.parse(String(lines.at(-1)));
131
132 expect(parsed).toEqual({
133 gmail: [{ status: 'ACTIVE', permission_group: null }],
@@ -167,7 +154,7 @@ describe('CLI: composio connections list', () => {
154 yield* cli(['connections', 'list']);
155
156 const lines = yield* MockConsole.getLines({ stripAnsi: true });
170 - const parsed = parseJsonFromLines(lines);
157 + const parsed = JSON.parse(String(lines.at(-1)));
158
159 expect(parsed).toEqual({
160 gmail: [{ status: 'ACTIVE', permission_group: null }],
@@ -188,7 +175,7 @@ describe('CLI: composio connections list', () => {
175 yield* cli(['connections', 'list', '--toolkit', 'github']);
176
177 const lines = yield* MockConsole.getLines({ stripAnsi: true });
191 - const parsed = parseJsonFromLines(lines);
178 + const parsed = JSON.parse(String(lines.at(-1)));
179
180 expect(parsed).toEqual({
181 github: [
@@ -236,7 +223,7 @@ describe('CLI: composio connections list', () => {
223 yield* cli(['connections', 'list']);
224
225 const lines = yield* MockConsole.getLines({ stripAnsi: true });
239 - const parsed = parseJsonFromLines(lines);
226 + const parsed = JSON.parse(String(lines.at(-1)));
227
228 expect(parsed).not.toHaveProperty('slack');
229 })
ts/packages/cli/test/src/commands/feature-visibility.test.ts
+9 -6
@@ -16,19 +16,22 @@ describe('CLI experimental feature visibility', () => {
16 expect(rootNames(true)).toContain('listen');
17 });
18
19 - for (const enabled of [false, true]) {
20 - layer(TestLive({ cliUserConfig: { experimentalFeatures: { listen: enabled } } }))(it => {
21 - it.effect(`uses the same visibility for root help and help aliases (listen=${enabled})`, () =>
19 + describe.each([
20 + { listen: false, helpAlias: 'Failure' },
21 + { listen: true, helpAlias: 'Success' },
22 + ])('listen=$listen', ({ listen, helpAlias }) => {
23 + layer(TestLive({ cliUserConfig: { experimentalFeatures: { listen } } }))(it => {
24 + it.effect('uses the same visibility for root help and help aliases', () =>
25 Effect.gen(function* () {
26 yield* cli(['--help']);
27 const output = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' })).join(
28 '\n'
29 );
27 - expect(output.includes('listen')).toBe(enabled);
30 + expect(output.includes('listen')).toBe(listen);
31 const result = yield* Effect.result(cli(['help', 'listen']));
29 - expect(result._tag === 'Success').toBe(enabled);
32 + expect(result._tag).toBe(helpAlias);
33 })
34 );
35 });
33 - }
36 + });
37 });
ts/packages/cli/test/src/commands/listen.client.cmd.test.ts
+52 -31
@@ -1,11 +1,8 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Cause, ConfigProvider, Effect, Exit } from 'effect';
2 +import { ConfigProvider, Effect } from 'effect';
3 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 -import {
6 - stubClientResources,
7 - type StubRequest,
8 -} from 'test/__utils__/services/stub-composio-client';
5 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
6
7 const testConfigProvider = ConfigProvider.fromEnv({
8 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
@@ -86,27 +83,33 @@ const notFound = {
83 },
84 };
85
89 -const isTriggerTypeLookup = (request: StubRequest) =>
90 - request.method === 'GET' && request.path.includes('/triggers_types/');
91 -
92 -const failureOf = (exit: Exit.Exit<unknown, unknown>) =>
93 - Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
86 +const TRIGGER_TYPES = '/api/v3.1/triggers_types/';
87 +const TRIGGER_UPSERT = '/api/v3.1/trigger_instances/';
88
89 describe('CLI: composio listen over the API client', () => {
90 layer(testLayer)('[Given] the API rejects the temporary trigger', it => {
91 it.effect('[Then] the failure quotes the status and response body', () =>
92 Effect.gen(function* () {
99 - const stub = stubClientResources(['triggerInstances', 'triggersTypes'], request =>
100 - isTriggerTypeLookup(request)
101 - ? Response.json({ slug: 'GMAIL_NEW_GMAIL_MESSAGE' })
102 - : Response.json(invalidConfig, { status: 400 })
93 + const stub = stubClientResources(
94 + ['triggerInstances', 'triggersTypes'],
95 + routeRequests(
96 + [
97 + {
98 + method: 'GET',
99 + path: TRIGGER_TYPES,
100 + respond: () => Response.json({ slug: 'GMAIL_NEW_GMAIL_MESSAGE' }),
101 + },
102 + ],
103 + () => Response.json(invalidConfig, { status: 400 })
104 + )
105 );
106 yield* enableListen;
105 - const exit = yield* Effect.exit(
106 - cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(Effect.provide(stub.layer))
107 + const failure = yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(
108 + Effect.provide(stub.layer),
109 + Effect.flip
110 );
111
109 - expect(failureOf(exit)).toMatchObject({
112 + expect(failure).toMatchObject({
113 _tag: 'commands/ListenCommandError',
114 reason: 'create_trigger',
115 message: `Failed to create temporary trigger "GMAIL_NEW_GMAIL_MESSAGE": Error: ${invalidConfigText}`,
@@ -117,17 +120,26 @@ describe('CLI: composio listen over the API client', () => {
120
121 it.effect('[Then] a trigger type the API does not know is reported as unknown', () =>
122 Effect.gen(function* () {
120 - const stub = stubClientResources(['triggerInstances', 'triggersTypes'], request =>
121 - isTriggerTypeLookup(request)
122 - ? Response.json(notFound, { status: 404 })
123 - : Response.json(invalidConfig, { status: 400 })
123 + const stub = stubClientResources(
124 + ['triggerInstances', 'triggersTypes'],
125 + routeRequests(
126 + [
127 + {
128 + method: 'GET',
129 + path: TRIGGER_TYPES,
130 + respond: () => Response.json(notFound, { status: 404 }),
131 + },
132 + ],
133 + () => Response.json(invalidConfig, { status: 400 })
134 + )
135 );
136 yield* enableListen;
126 - const exit = yield* Effect.exit(
127 - cli(['listen', 'GMAIL_NEW_GMAIL_MESAGE']).pipe(Effect.provide(stub.layer))
137 + const failure = yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESAGE']).pipe(
138 + Effect.provide(stub.layer),
139 + Effect.flip
140 );
141
130 - expect(failureOf(exit)).toMatchObject({
142 + expect(failure).toMatchObject({
143 _tag: 'commands/ListenCommandError',
144 reason: 'unknown_trigger',
145 message:
@@ -140,10 +152,18 @@ describe('CLI: composio listen over the API client', () => {
152 layer(testLayer)('[Given] the temporary trigger cannot be disabled', it => {
153 it.effect('[Then] the warning quotes the status and response body', () =>
154 Effect.gen(function* () {
143 - const stub = stubClientResources(['triggerInstances'], request =>
144 - request.method === 'POST'
145 - ? Response.json({ trigger_id: TRIGGER_ID })
146 - : Response.json(invalidConfig, { status: 400 })
155 + const stub = stubClientResources(
156 + ['triggerInstances'],
157 + routeRequests(
158 + [
159 + {
160 + method: 'POST',
161 + path: TRIGGER_UPSERT,
162 + respond: () => Response.json({ trigger_id: TRIGGER_ID }),
163 + },
164 + ],
165 + () => Response.json(invalidConfig, { status: 400 })
166 + )
167 );
168 yield* enableListen;
169 yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE', '--max-events', '1']).pipe(
@@ -165,11 +185,12 @@ describe('CLI: composio listen over the API client', () => {
185 Response.json(invalidConfig, { status: 400 })
186 );
187 yield* enableListen;
168 - const exit = yield* Effect.exit(
169 - cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(Effect.provide(stub.layer))
188 + const failure = yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(
189 + Effect.provide(stub.layer),
190 + Effect.flip
191 );
192
172 - expect(failureOf(exit)).toMatchObject({
193 + expect(failure).toMatchObject({
194 _tag: 'commands/ListenCommandError',
195 reason: 'connected_accounts',
196 message: `Failed to list connected accounts for "gmail": Error: ${invalidConfigText}`,
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+41 -58
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Cause, ConfigProvider, Effect, Exit } from 'effect';
2 +import { ConfigProvider, Effect } from 'effect';
3 import { ListenCommandError } from 'src/commands/listen.cmd';
4 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
@@ -187,72 +187,61 @@ describe('CLI: composio listen', () => {
187 it.effect('reports malformed trigger params as CLI input validation', () =>
188 Effect.gen(function* () {
189 yield* enableListen;
190 - const exit = yield* Effect.exit(
191 - cli(['listen', 'composio.connected_account.expired', '--params', '[]'])
192 - );
190 + const failure = yield* cli([
191 + 'listen',
192 + 'composio.connected_account.expired',
193 + '--params',
194 + '[]',
195 + ]).pipe(Effect.flip);
196
194 - expect(Exit.isFailure(exit)).toBe(true);
195 - if (Exit.isFailure(exit)) {
196 - const failure = Cause.squash(exit.cause);
197 - expect(failure).toMatchObject({ _tag: 'commands/CommandInputError', command: 'listen' });
198 - }
197 + expect(failure).toMatchObject({ _tag: 'commands/CommandInputError', command: 'listen' });
198 })
199 );
200
201 it.effect('reports malformed timeout values as CLI input validation', () =>
202 Effect.gen(function* () {
203 yield* enableListen;
205 - const exit = yield* Effect.exit(
206 - cli(['listen', 'composio.connected_account.expired', '--timeout', 'eventually'])
207 - );
204 + const failure = yield* cli([
205 + 'listen',
206 + 'composio.connected_account.expired',
207 + '--timeout',
208 + 'eventually',
209 + ]).pipe(Effect.flip);
210
209 - expect(Exit.isFailure(exit)).toBe(true);
210 - if (Exit.isFailure(exit)) {
211 - const failure = Cause.squash(exit.cause);
212 - expect(failure).toMatchObject({ _tag: 'commands/CommandInputError', command: 'listen' });
213 - }
211 + expect(failure).toMatchObject({ _tag: 'commands/CommandInputError', command: 'listen' });
212 })
213 );
214
215 it.effect('reports a missing active connection as a structured domain failure', () =>
216 Effect.gen(function* () {
217 yield* enableListen;
220 - const exit = yield* Effect.exit(cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']));
218 + const failure = yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(Effect.flip);
219
222 - expect(Exit.isFailure(exit)).toBe(true);
223 - if (Exit.isFailure(exit)) {
224 - const failure = Cause.squash(exit.cause);
225 - expect(failure).toBeInstanceOf(ListenCommandError);
226 - if (failure instanceof ListenCommandError) {
227 - expect(failure).toMatchObject({
228 - reason: 'connected_account_not_found',
229 - toolkitSlug: 'gmail',
230 - });
231 - }
232 - }
220 + expect(failure).toBeInstanceOf(ListenCommandError);
221 + expect(failure).toMatchObject({
222 + reason: 'connected_account_not_found',
223 + toolkitSlug: 'gmail',
224 + });
225 })
226 );
227
228 it.effect('reports an unknown trigger slug instead of a missing connection', () =>
229 Effect.gen(function* () {
230 yield* enableListen;
239 - const exit = yield* Effect.exit(cli(['listen', 'BOGUS_SLUG_XYZ']));
231 + const failure = yield* cli(['listen', 'BOGUS_SLUG_XYZ']).pipe(Effect.flip);
232
241 - expect(Exit.isFailure(exit)).toBe(true);
242 - if (Exit.isFailure(exit)) {
243 - const failure = Cause.squash(exit.cause);
244 - expect(failure).toBeInstanceOf(ListenCommandError);
245 - if (failure instanceof ListenCommandError) {
246 - expect(failure).toMatchObject({
247 - reason: 'unknown_trigger',
248 - slug: 'BOGUS_SLUG_XYZ',
249 - toolkitSlug: 'bogus',
250 - });
251 - expect(failure.message).toContain('Unknown trigger slug "BOGUS_SLUG_XYZ"');
252 - expect(failure.message).toContain('composio triggers list <toolkit>');
253 - expect(failure.message).not.toContain('composio link');
254 - }
255 - }
233 + expect(failure).toBeInstanceOf(ListenCommandError);
234 + expect(failure).toMatchObject({
235 + reason: 'unknown_trigger',
236 + slug: 'BOGUS_SLUG_XYZ',
237 + toolkitSlug: 'bogus',
238 + message: expect.stringContaining('Unknown trigger slug "BOGUS_SLUG_XYZ"'),
239 + });
240 + expect(failure).toHaveProperty(
241 + 'message',
242 + expect.stringContaining('composio triggers list <toolkit>')
243 + );
244 + expect(failure).toHaveProperty('message', expect.not.stringContaining('composio link'));
245 })
246 );
247 });
@@ -304,20 +293,14 @@ describe('CLI: composio listen', () => {
293 it.effect('[Then] reports an unknown trigger slug instead of a creation failure', () =>
294 Effect.gen(function* () {
295 yield* enableListen;
307 - const exit = yield* Effect.exit(cli(['listen', 'GMAIL_NEW_GMAIL_MESAGE']));
296 + const failure = yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESAGE']).pipe(Effect.flip);
297
309 - expect(Exit.isFailure(exit)).toBe(true);
310 - if (Exit.isFailure(exit)) {
311 - const failure = Cause.squash(exit.cause);
312 - expect(failure).toBeInstanceOf(ListenCommandError);
313 - if (failure instanceof ListenCommandError) {
314 - expect(failure).toMatchObject({
315 - reason: 'unknown_trigger',
316 - slug: 'GMAIL_NEW_GMAIL_MESAGE',
317 - });
318 - expect(failure.message).toContain('Unknown trigger slug "GMAIL_NEW_GMAIL_MESAGE"');
319 - }
320 - }
298 + expect(failure).toBeInstanceOf(ListenCommandError);
299 + expect(failure).toMatchObject({
300 + reason: 'unknown_trigger',
301 + slug: 'GMAIL_NEW_GMAIL_MESAGE',
302 + message: expect.stringContaining('Unknown trigger slug "GMAIL_NEW_GMAIL_MESAGE"'),
303 + });
304 })
305 );
306 });
ts/packages/cli/test/src/commands/login.cmd.test.ts
+42 -27
@@ -14,6 +14,7 @@ import { InternalServerError } from '@composio/client/effect';
14 import { ComposioSessionRepository } from 'src/services/composio-clients';
15 import { makeSessionInfo } from 'test/__utils__/models/account';
16 import type { MockAccountRequest } from 'test/__utils__/services/test-layer';
17 +import { routeRequests, type StubRoute } from 'test/__utils__/services/stub-composio-client';
18
19 vi.mock('open', () => ({
20 default: vi.fn(async () => undefined),
@@ -45,12 +46,21 @@ const mockFetchResponse = (body: unknown, status = 200) =>
46 headers: { 'Content-Type': 'application/json' },
47 });
48
48 -const requestUrl = (requestInput: RequestInfo | URL): string =>
49 - typeof requestInput === 'string'
50 - ? requestInput
51 - : requestInput instanceof URL
52 - ? requestInput.toString()
53 - : requestInput.url;
49 +const requestUrl = (requestInput: RequestInfo | URL): string => new Request(requestInput).url;
50 +
51 +const WHOAMI = '/api/whoami';
52 +
53 +/** Answers agents API requests through `routes`, and every other request with `{}`. */
54 +const stubFetch = (routes: ReadonlyArray<StubRoute>) =>
55 + vi.spyOn(globalThis, 'fetch').mockImplementation(async (requestInput, init) => {
56 + const request = new Request(requestInput, init);
57 + const url = new URL(request.url);
58 + return routeRequests(routes, () => mockFetchResponse({}))({
59 + method: request.method,
60 + path: `${url.pathname}${url.search}`,
61 + body: undefined,
62 + });
63 + });
64
65 const storedAgentIdentity = {
66 status: 'READY',
@@ -183,11 +193,9 @@ describe('CLI: composio login', () => {
193 () =>
194 Effect.gen(function* () {
195 yield* writeStoredAgentIdentity(storedAgentIdentity);
186 - vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>
187 - requestUrl(requestInput).includes('/api/whoami')
188 - ? mockFetchResponse(storedAgentIdentity)
189 - : mockFetchResponse({})
190 - );
196 + stubFetch([
197 + { method: 'GET', path: WHOAMI, respond: () => mockFetchResponse(storedAgentIdentity) },
198 + ]);
199
200 yield* cli(['login']);
201
@@ -214,11 +222,13 @@ describe('CLI: composio login', () => {
222 () =>
223 Effect.gen(function* () {
224 yield* writeStoredAgentIdentity(storedAgentIdentity);
217 - vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>
218 - requestUrl(requestInput).includes('/api/whoami')
219 - ? mockFetchResponse({ message: 'Invalid agent key' }, 401)
220 - : mockFetchResponse({})
221 - );
225 + stubFetch([
226 + {
227 + method: 'GET',
228 + path: WHOAMI,
229 + respond: () => mockFetchResponse({ message: 'Invalid agent key' }, 401),
230 + },
231 + ]);
232
233 yield* cli(['login']);
234
@@ -238,12 +248,15 @@ describe('CLI: composio login', () => {
248 () =>
249 Effect.gen(function* () {
250 yield* writeStoredAgentIdentity(storedAgentIdentity);
241 - vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput => {
242 - if (requestUrl(requestInput).includes('/api/whoami')) {
243 - throw new Error('network unreachable');
244 - }
245 - return mockFetchResponse({});
246 - });
251 + stubFetch([
252 + {
253 + method: 'GET',
254 + path: WHOAMI,
255 + respond: () => {
256 + throw new Error('network unreachable');
257 + },
258 + },
259 + ]);
260
261 yield* cli(['login']);
262
@@ -260,11 +273,13 @@ describe('CLI: composio login', () => {
273 () =>
274 Effect.gen(function* () {
275 yield* writeStoredAgentIdentity({ ...storedAgentIdentity, status: 'PENDING' });
263 - vi.spyOn(globalThis, 'fetch').mockImplementation(async requestInput =>
264 - requestUrl(requestInput).includes('/api/whoami')
265 - ? mockFetchResponse({ ...storedAgentIdentity, status: 'PENDING' })
266 - : mockFetchResponse({})
267 - );
276 + stubFetch([
277 + {
278 + method: 'GET',
279 + path: WHOAMI,
280 + respond: () => mockFetchResponse({ ...storedAgentIdentity, status: 'PENDING' }),
281 + },
282 + ]);
283
284 yield* cli(['login']);
285
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+4 -31
@@ -1,6 +1,6 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import * as FileSystem from 'effect/FileSystem';
3 -import { ConfigProvider, Console, Effect, Option } from 'effect';
3 +import { ConfigProvider, Effect, Option } from 'effect';
4 import path from 'node:path';
5 import * as constants from 'src/constants';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -9,9 +9,12 @@ import { writeStoredAgentIdentity } from 'src/services/agents';
9 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { cli, TestLive, MockConsole } from 'test/__utils__';
12 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
13
14 +// The confirm prompt is only reached from an interactive terminal.
15 const terminalUIWithConfirm = (confirmed: boolean) =>
16 TerminalUI.of({
17 + ...terminalUITestImpl,
18 capabilities: Effect.succeed(
19 getTerminalCapabilities({
20 stdin: { isTTY: true },
@@ -19,37 +22,7 @@ const terminalUIWithConfirm = (confirmed: boolean) =>
22 stderr: { isTTY: true },
23 })
24 ),
22 - output: data => Console.log(data),
23 - error: data => Console.error(data),
24 - intro: title => Console.log(`-- ${title} --`),
25 - outro: message => Console.log(`-- ${message} --`),
26 - log: {
27 - info: message => Console.log(message),
28 - success: message => Console.log(message),
29 - warn: message => Console.warn(message),
30 - error: message => Console.error(message),
31 - step: message => Console.log(message),
32 - message: message => Console.log(message),
33 - },
34 - note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
35 - select: (_message, options) => Effect.succeed(options[0]!.value),
25 confirm: () => Effect.succeed(confirmed),
37 - withSpinner: (message, effect, options) =>
38 - Effect.gen(function* () {
39 - const result = yield* effect;
40 - const successMsg =
41 - typeof options?.successMessage === 'function'
42 - ? options.successMessage(result)
43 - : (options?.successMessage ?? message);
44 - yield* Console.log(successMsg);
45 - return result;
46 - }),
47 - useMakeSpinner: (_message, use) =>
48 - use({
49 - message: (_msg: string) => Effect.void,
50 - stop: (msg?: string) => (msg ? Console.log(msg) : Effect.void),
51 - error: (msg?: string) => (msg ? Console.error(msg) : Effect.void),
52 - }),
26 });
27
28 const setupLoggedInAgent = Effect.gen(function* () {
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts
+8 -3
@@ -32,10 +32,15 @@ describe('CLI: composio dev projects list', () => {
32 ]);
33 expect(requests[0]?.scope.projectId).toBeUndefined();
34
35 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
35 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
36 + const output = lines.join('\n');
37 expect(output).toContain('Loaded 2 projects');
37 - expect(output).toContain(' Project One (project_1)');
38 - expect(output).toContain(' Project Two (project_2)');
38 + expect(output).toContain('Project One (project_1)');
39 + expect(output).toContain('Project Two (project_2)');
40 + expect(JSON.parse(String(lines.at(-1)))).toEqual([
41 + { id: 'project_1', name: 'Project One', is_selected_global_project: false },
42 + { id: 'project_2', name: 'Project Two', is_selected_global_project: false },
43 + ]);
44 expect(output).toContain(
45 'Hint: run `composio dev init` in a directory to bind it to a developer project.'
46 );
ts/packages/cli/test/src/commands/proxy.client.cmd.test.ts
+45 -41
@@ -1,7 +1,8 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Cause, ConfigProvider, Effect, Exit } from 'effect';
2 +import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 import {
5 + routeRequests,
6 stubClientResources,
7 type StubRequest,
8 } from 'test/__utils__/services/stub-composio-client';
@@ -18,49 +19,49 @@ const testLayer = TestLive({
19 const ENDPOINT = 'https://gmail.googleapis.com/gmail/v1/users/me/profile';
20 const proxyArgs = ['proxy', ENDPOINT, '--toolkit', 'gmail', '--skip-connection-check'];
21
21 -const isProxyExecute = (request: StubRequest) => request.path.endsWith('/proxy_execute');
22 +const PROXY_EXECUTE = '/api/v3.1/tool_router/session/trs_stub_session/proxy_execute';
23 +
24 +const isProxyExecute = (request: StubRequest) => request.path === PROXY_EXECUTE;
25
26 /** Proxy calls answered by `respond`; the session they run in is created normally. */
27 const proxyingOver = (respond: () => Response) =>
25 - stubClientResources(['toolRouter'], request =>
26 - isProxyExecute(request)
27 - ? respond()
28 - : Response.json({
29 - session_id: 'trs_stub_session',
30 - config: { user_id: 'consumer-user-org_test' },
31 - mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
32 - tool_router_tools: [],
33 - })
28 + stubClientResources(
29 + ['toolRouter'],
30 + routeRequests([{ method: 'POST', path: PROXY_EXECUTE, respond }], () =>
31 + Response.json({
32 + session_id: 'trs_stub_session',
33 + config: { user_id: 'consumer-user-org_test' },
34 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
35 + tool_router_tools: [],
36 + })
37 + )
38 );
39
36 -const run = (stub: ReturnType<typeof proxyingOver>) =>
37 - Effect.gen(function* () {
38 - const exit = yield* cli(proxyArgs).pipe(Effect.provide(stub.layer), Effect.exit);
39 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
40 - return { exit, output: lines.join('\n') };
41 - });
40 +const consoleOutput = MockConsole.getLines({ stripAnsi: true }).pipe(
41 + Effect.map(lines => lines.join('\n'))
42 +);
43
44 describe('CLI: composio proxy over the API client', () => {
45 layer(testLayer)('[Given] the API rejects the proxied call with an error envelope', it => {
46 it.effect('[Then] the envelope message and slug are printed and the command fails', () =>
47 Effect.gen(function* () {
47 - const { exit, output } = yield* run(
48 - proxyingOver(() =>
49 - Response.json(
50 - {
51 - error: {
52 - message: 'The endpoint is not allowed for this toolkit',
53 - code: 4311,
54 - slug: 'ToolRouterV2_ProxyEndpointNotAllowed',
55 - status: 403,
56 - },
48 + const stub = proxyingOver(() =>
49 + Response.json(
50 + {
51 + error: {
52 + message: 'The endpoint is not allowed for this toolkit',
53 + code: 4311,
54 + slug: 'ToolRouterV2_ProxyEndpointNotAllowed',
55 + status: 403,
56 },
58 - { status: 403 }
59 - )
57 + },
58 + { status: 403 }
59 )
60 );
61 + const failure = yield* cli(proxyArgs).pipe(Effect.provide(stub.layer), Effect.flip);
62 + const output = yield* consoleOutput;
63
63 - expect(Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined).toMatchObject({
64 + expect(failure).toMatchObject({
65 _tag: 'commands/ProxyRequestError',
66 message: `Failed to proxy GET ${ENDPOINT} via "gmail".`,
67 });
@@ -86,17 +87,16 @@ describe('CLI: composio proxy over the API client', () => {
87 layer(testLayer)('[Given] the proxied API answers with a 404', it => {
88 it.effect('[Then] the status and body are printed and the command succeeds', () =>
89 Effect.gen(function* () {
89 - const { exit, output } = yield* run(
90 - proxyingOver(() =>
91 - Response.json({
92 - status: 404,
93 - data: { error: { code: 404, message: 'Requested entity was not found.' } },
94 - headers: {},
95 - })
96 - )
90 + const stub = proxyingOver(() =>
91 + Response.json({
92 + status: 404,
93 + data: { error: { code: 404, message: 'Requested entity was not found.' } },
94 + headers: {},
95 + })
96 );
97 + yield* cli(proxyArgs).pipe(Effect.provide(stub.layer));
98 + const output = yield* consoleOutput;
99
99 - expect(Exit.isSuccess(exit)).toBe(true);
100 expect(output).toContain('Status: 404');
101 expect(output).toContain('"message": "Requested entity was not found."');
102 })
@@ -117,9 +117,13 @@ describe('CLI: composio proxy over the API client', () => {
117 { status: 500, headers: { 'retry-after-ms': '0' } }
118 )
119 );
120 - const { exit, output } = yield* run(stub);
120 + const failure = yield* cli(proxyArgs).pipe(Effect.provide(stub.layer), Effect.flip);
121 + const output = yield* consoleOutput;
122
122 - expect(Exit.isFailure(exit)).toBe(true);
123 + expect(failure).toMatchObject({
124 + _tag: 'commands/ProxyRequestError',
125 + message: `Failed to proxy GET ${ENDPOINT} via "gmail".`,
126 + });
127 expect(output).toContain('Internal error');
128 expect(stub.requests.filter(isProxyExecute)).toMatchObject([
129 { method: 'POST', body: { toolkit_slug: 'gmail', endpoint: ENDPOINT, method: 'GET' } },
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+15 -15
@@ -1,6 +1,6 @@
1 import { BadRequestError, type RequestOptions } from '@composio/client/effect';
2 import { describe, expect, it, layer } from '@effect/vitest';
3 -import { ConfigProvider, Effect, Exit, Option } from 'effect';
3 +import { ConfigProvider, Effect, Option } from 'effect';
4 import { afterEach, vi } from 'vitest';
5 import type {
6 SessionCreateParams,
@@ -250,10 +250,7 @@ describe('CLI: composio proxy', () => {
250
251 expect(createCalled).toBe(false);
252 expect(failure).toBeInstanceOf(ProxyCommandError);
253 - if (failure instanceof ProxyCommandError) {
254 - expect(failure.reason).toBe('toolkit_not_connected');
255 - expect(failure.toolkit).toBe('gmail');
256 - }
253 + expect(failure).toMatchObject({ reason: 'toolkit_not_connected', toolkit: 'gmail' });
254
255 expect(output).toContain('Toolkit "gmail" is not connected for this user');
256 expect(output).toContain('composio link gmail');
@@ -288,19 +285,22 @@ describe('CLI: composio proxy', () => {
285 },
286 });
287
291 - const { exit, output } = yield* Effect.gen(function* () {
292 - const exit = yield* cli([
288 + const { failure, output } = yield* Effect.gen(function* () {
289 + const failure = yield* cli([
290 'proxy',
291 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
292 '--toolkit',
293 'gmail',
294 '--skip-connection-check',
298 - ]).pipe(Effect.exit);
295 + ]).pipe(Effect.flip);
296 const lines = yield* MockConsole.getLines({ stripAnsi: true });
300 - return { exit, output: lines.join('\n') };
297 + return { failure, output: lines.join('\n') };
298 }).pipe(Effect.provide(live));
299
303 - expect(Exit.isFailure(exit)).toBe(true);
300 + expect(failure).toMatchObject({
301 + name: 'ComposioNoActiveConnectionError',
302 + toolkit: 'gmail',
303 + });
304
305 expect(output).toContain('No active connection found for toolkit "gmail"');
306 expect(output).toContain('composio link gmail');
@@ -334,19 +334,19 @@ describe('CLI: composio proxy', () => {
334 },
335 });
336
337 - const { exit, output } = yield* Effect.gen(function* () {
338 - const exit = yield* cli([
337 + const { failure, output } = yield* Effect.gen(function* () {
338 + const failure = yield* cli([
339 'proxy',
340 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
341 '--toolkit',
342 'gmail',
343 '--skip-connection-check',
344 - ]).pipe(Effect.exit);
344 + ]).pipe(Effect.flip);
345 const lines = yield* MockConsole.getLines({ stripAnsi: true });
346 - return { exit, output: lines.join('\n') };
346 + return { failure, output: lines.join('\n') };
347 }).pipe(Effect.provide(live));
348
349 - expect(Exit.isFailure(exit)).toBe(true);
349 + expect(failure).toMatchObject({ _tag: 'commands/ProxyRequestError' });
350 expect(output).toContain(
351 'GET proxy call via \\"gmail\\" requires user input before it can run (1 input request) and was not executed.'
352 );
ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts
+6 -9
@@ -1,7 +1,6 @@
1 -import assert from 'node:assert';
1 import path from 'node:path';
2 import { describe, expect, layer } from '@effect/vitest';
4 -import { Effect, Predicate } from 'effect';
3 +import { Effect } from 'effect';
4 import * as FileSystem from 'effect/FileSystem';
5 import { cli, liveEnvConfigProvider, TestLive } from 'test/__utils__';
6 import { makeTestToolkits } from 'test/__utils__/models/toolkits';
@@ -366,14 +365,12 @@ describe('CLI: composio generate py', () => {
365 const outputDir = path.join(cwd, '.generated', 'composio-py-invalid');
366
367 const args = ['generate', 'py', '--toolkits', 'nonexistent', '--output-dir', outputDir];
369 - const result = yield* cli(args).pipe(Effect.catch(e => Effect.succeed(e)));
368 + const failure = yield* cli(args).pipe(Effect.flip);
369
371 - assert.ok(Predicate.isTagged(result, 'commands/CommandInputError'));
372 - if (Predicate.isTagged(result, 'commands/CommandInputError')) {
373 - expect((result as unknown as { message: string }).message).toContain(
374 - 'Invalid toolkit(s): nonexistent'
375 - );
376 - }
370 + expect(failure).toMatchObject({
371 + _tag: 'commands/CommandInputError',
372 + message: expect.stringContaining('Invalid toolkit(s): nonexistent'),
373 + });
374 })
375 );
376
ts/packages/cli/test/src/commands/root-help-consistency.test.ts
+68 -55
@@ -29,31 +29,32 @@ const commandPaths = (
29 return [path, ...commandPaths(child, path)];
30 });
31
32 +// Experimental commands in the test config must be enabled independently of the graph.
33 +const visibleCommandPaths = commandPaths(
34 + buildRootCommand({ isDevModeEnabled: true, isExperimentalFeatureEnabled: () => true })
35 +)
36 + .filter(path => path[0] !== 'listen')
37 + .map(path => ({ path, command: path.join(' ') }));
38 +
39 describe('framework command help', () => {
40 afterEach(() => {
41 process.exitCode = undefined;
42 });
43
44 layer(TestLive())(it => {
38 - it.effect('renders every visible command from the same definitions used by parsing', () =>
39 - Effect.gen(function* () {
40 - const root = buildRootCommand({
41 - isDevModeEnabled: true,
42 - isExperimentalFeatureEnabled: () => true,
43 - });
44 - for (const path of commandPaths(root)) {
45 - // Experimental commands in the test config must be enabled independently of the graph.
46 - if (path[0] === 'listen') continue;
45 + it.effect.each(visibleCommandPaths)(
46 + 'renders $command from the same definitions used by parsing',
47 + ({ path }) =>
48 + Effect.gen(function* () {
49 const flag = yield* capture([...path, '--help']);
50 const alias = yield* capture(['help', ...path]);
49 - expect(flag.exitCode, path.join(' ')).toBe(0);
50 - expect(alias.exitCode, path.join(' ')).toBe(0);
51 - expect(alias.stdout, path.join(' ')).toBe(flag.stdout);
51 + expect(flag.exitCode).toBe(0);
52 + expect(alias.exitCode).toBe(0);
53 + expect(alias.stdout).toBe(flag.stdout);
54 expect(flag.stdout).toContain('USAGE');
55 expect(flag.stderr).toBe('');
56 expect(alias.stderr).toBe('');
55 - }
56 - })
57 + })
58 );
59
60 it.effect('includes flags previously missing from the hand-written pages', () =>
@@ -66,55 +67,67 @@ describe('framework command help', () => {
67 })
68 );
69
69 - it.effect('keeps errors and suggestions on stderr with a failing exit code', () =>
70 + it.effect.each([
71 + { args: ['help', 'frobnicate'] },
72 + { args: ['help', 'orgz'] },
73 + { args: ['tools', 'frobnicate'] },
74 + ])('keeps errors for $args on stderr with a failing exit code', ({ args }) =>
75 + Effect.gen(function* () {
76 + const output = yield* capture(args);
77 + expect(output.exitCode).toBe(1);
78 + expect(output.stdout).toBe('');
79 + expect(output.stderr).toContain('Unknown subcommand');
80 + })
81 + );
82 +
83 + it.effect('suggests the closest subcommand on stderr', () =>
84 Effect.gen(function* () {
71 - for (const args of [
72 - ['help', 'frobnicate'],
73 - ['help', 'orgz'],
74 - ['tools', 'frobnicate'],
75 - ]) {
76 - const output = yield* capture(args);
77 - expect(output.exitCode).toBe(1);
78 - expect(output.stdout).toBe('');
79 - expect(output.stderr).toContain('Unknown subcommand');
80 - }
85 expect((yield* capture(['help', 'orgz'])).stderr).toContain('Did you mean');
86 })
87 );
88
85 - it.effect('supports bare help, help aliases, and redundant help flags', () =>
89 + it.effect.each([
90 + { args: [] },
91 + { args: ['help'] },
92 + { args: ['help', '--help'] },
93 + { args: ['--help'] },
94 + { args: ['-h'] },
95 + ])('supports bare help, help aliases, and redundant help flags: $args', ({ args }) =>
96 + Effect.gen(function* () {
97 + const output = yield* capture(args);
98 + expect(output.exitCode).toBe(0);
99 + expect(output.stdout).toContain('Documentation:');
100 + expect(output.stderr).toBe('');
101 + })
102 + );
103 +
104 + it.effect.each([
105 + { path: ['login'], flag: '--agent' },
106 + { path: ['search'], flag: '--json' },
107 + { path: ['dev', 'connected-accounts', 'link'], flag: '--auth-config' },
108 + { path: ['dev', 'connected-accounts', 'link'], flag: '--user-id' },
109 + { path: ['dev', 'triggers', 'listen'], flag: '--user-id' },
110 + { path: ['dev', 'triggers', 'listen'], flag: '--forward' },
111 + { path: ['dev', 'triggers', 'listen'], flag: '--max-events' },
112 + { path: ['dev', 'triggers', 'disable'], flag: '--dangerously-allow' },
113 + ])('documents $flag on the previously unreachable $path page', ({ path, flag }) =>
114 Effect.gen(function* () {
87 - for (const args of [[], ['help'], ['help', '--help'], ['--help'], ['-h']]) {
88 - const output = yield* capture(args);
89 - expect(output.exitCode).toBe(0);
90 - expect(output.stdout).toContain('Documentation:');
91 - expect(output.stderr).toBe('');
92 - }
115 + const output = yield* capture([...path, '--help']);
116 + expect(output.exitCode).toBe(0);
117 + expect(output.stdout).toContain(flag);
118 })
119 );
120
96 - it.effect('documents the actual flags on previously unreachable nested pages', () =>
121 + it.effect('documents the previously unreachable dev projects switch page', () =>
122 Effect.gen(function* () {
98 - for (const [path, flags] of [
99 - [['login'], ['--agent']],
100 - [['search'], ['--json']],
101 - [
102 - ['dev', 'connected-accounts', 'link'],
103 - ['--auth-config', '--user-id'],
104 - ],
105 - [
106 - ['dev', 'triggers', 'listen'],
107 - ['--user-id', '--forward', '--max-events'],
108 - ],
109 - [['dev', 'triggers', 'disable'], ['--dangerously-allow']],
110 - ] as const) {
111 - const output = yield* capture([...path, '--help']);
112 - expect(output.exitCode).toBe(0);
113 - for (const flag of flags) expect(output.stdout, path.join(' ')).toContain(flag);
114 - }
123 const projectSwitch = yield* capture(['dev', 'projects', 'switch', '--help']);
124 expect(projectSwitch.stdout).toContain('composio dev projects switch');
125 expect(projectSwitch.stdout).toContain('Switch the developer project');
126 + })
127 + );
128 +
129 + it.effect('keeps hidden commands and flags off the root help page', () =>
130 + Effect.gen(function* () {
131 const root = yield* capture(['--help']);
132 expect(root.stdout).not.toContain('composio files');
133 expect(root.stdout).not.toContain('MODE');
@@ -123,9 +136,10 @@ describe('framework command help', () => {
136 })
137 );
138
126 - it.effect('renders parallel help through the framework before executing any tools', () =>
127 - Effect.gen(function* () {
128 - for (const path of [['execute'], ['dev', 'playground-execute']]) {
139 + it.effect.each([{ path: ['execute'] }, { path: ['dev', 'playground-execute'] }])(
140 + 'renders $path parallel help through the framework before executing any tools',
141 + ({ path }) =>
142 + Effect.gen(function* () {
143 const help = yield* capture([
144 ...path,
145 '--parallel',
@@ -139,8 +153,7 @@ describe('framework command help', () => {
153 expect(help.stdout).toContain('--parallel');
154 expect(help.stdout).toContain('--get-schema');
155 expect(help.stderr).toBe('');
142 - }
143 - })
156 + })
157 );
158
159 it.effect('preserves native help after a value-taking option', () =>
ts/packages/cli/test/src/commands/run.cmd.test.ts
+99 -113
@@ -4,9 +4,10 @@ import * as os from 'node:os';
4 import * as path from 'node:path';
5 import { pathToFileURL } from 'node:url';
6 import { describe, expect, layer } from '@effect/vitest';
7 +import { assertDefined } from '@effect/vitest/utils';
8 import * as BunServices from '@effect/platform-bun/BunServices';
9 import * as Path from 'effect/Path';
9 -import { Cause, ConfigProvider, Effect, Exit, Layer, Option, Sink, Stream } from 'effect';
10 +import { ConfigProvider, Effect, Layer, Sink, Stream } from 'effect';
11 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
12 import { afterEach, it, vi } from 'vitest';
13 import { createCliCommandTelemetryContext } from 'src/analytics/events';
@@ -33,13 +34,23 @@ const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromEnvRecord({
34 COMPOSIO_TOOL_DEBUG: '1',
35 });
36
36 -const readRunPreloadSource = (command: ReadonlyArray<string>): string => {
37 - const preloadPath = command[2];
38 - if (preloadPath === undefined) {
39 - throw new Error('Expected the run command to include a preload file.');
40 - }
41 - return fs.readFileSync(preloadPath, 'utf8');
42 -};
37 +/** The run command is `[bun, '--preload', preloadPath, ...]`. */
38 +const readRunPreloadSource = (command: ReadonlyArray<string>): string =>
39 + fs.readFileSync(String(command[2]), 'utf8');
40 +
41 +/** A script file in a temporary directory that is removed when the test's scope closes. */
42 +const tempScript = Effect.acquireRelease(
43 + Effect.sync(() => {
44 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
45 + const scriptPath = path.join(tempDir, 'script.ts');
46 + fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
47 + return { tempDir, scriptPath };
48 + }),
49 + ({ tempDir }) => Effect.sync(() => fs.rmSync(tempDir, { recursive: true, force: true }))
50 +);
51 +
52 +const SCRIPT = 'console.log("hi")';
53 +const SCRIPT_FLAGS = ['--perf-debug', '--tool-debug', '--telemetry-debug', '--help', '--version'];
54
55 const commandRuns = vi.fn((_: ChildProcess.Command) =>
56 Effect.succeed(ChildProcessSpawner.ExitCode(0))
@@ -115,8 +126,7 @@ describe('CLI: composio run', () => {
126 { invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN, parentRunId: undefined }
127 );
128 const runId = telemetryContext.runId;
118 - expect(runId).toBeDefined();
119 - if (runId === undefined) return;
129 + assertDefined(runId);
130
131 commandRuns.mockImplementation(command => {
132 expect(inspectRunCommand(command).env.COMPOSIO_CLI_PARENT_RUN_ID).toBe(runId);
@@ -155,9 +165,10 @@ describe('CLI: composio run', () => {
165 });
166 // Stand in for the terminal delivering Ctrl-C to the CLI only: the child is
167 // detached into its own process group and never sees it directly.
158 - for (const listener of process.listeners('SIGINT').slice(sigintBaseline)) {
159 - listener('SIGINT');
160 - }
168 + process
169 + .listeners('SIGINT')
170 + .slice(sigintBaseline)
171 + .forEach(listener => listener('SIGINT'));
172 return ChildProcessSpawner.ExitCode(0);
173 })
174 );
@@ -201,12 +212,11 @@ describe('CLI: composio run', () => {
212 expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);
213 // ... but the run log is advertised to the caller on stderr, so it has to outlive
214 // the run that printed it.
204 - const runLogPath = output
205 - .find(line => line.startsWith('RUN_LOG_FILE='))
206 - ?.slice('RUN_LOG_FILE='.length);
207 - expect(runLogPath).toBeDefined();
208 - expect(fs.existsSync(runLogPath!)).toBe(true);
209 - fs.rmSync(path.dirname(runLogPath!), { recursive: true, force: true });
215 + const runLogPath = String(output.find(line => line.startsWith('RUN_LOG_FILE='))).slice(
216 + 'RUN_LOG_FILE='.length
217 + );
218 + expect(fs.existsSync(runLogPath)).toBe(true);
219 + fs.rmSync(path.dirname(runLogPath), { recursive: true, force: true });
220 expect(process.exitCode).toBe(7);
221 })
222 );
@@ -303,29 +313,25 @@ describe('CLI: composio run', () => {
313 });
314
315 layer(RunTestLive())(it => {
306 - for (const flag of [
307 - '--acp-only',
308 - '--acp-only=false',
309 - '--no-acp-only',
310 - '--logs-off',
311 - '--logs-off=false',
312 - '--no-logs-off',
313 - '--foo_bar',
314 - '--foo_bar=value',
315 - ]) {
316 - it.effect(`[Given] the unknown ${flag} [Then] run rejects it as an unknown flag`, () =>
317 - Effect.gen(function* () {
318 - const exit = yield* cli(['run', flag, 'console.log(1)']).pipe(Effect.exit);
316 + it.effect.each([
317 + { flag: '--acp-only', name: '--acp-only' },
318 + { flag: '--acp-only=false', name: '--acp-only' },
319 + { flag: '--no-acp-only', name: '--no-acp-only' },
320 + { flag: '--logs-off', name: '--logs-off' },
321 + { flag: '--logs-off=false', name: '--logs-off' },
322 + { flag: '--no-logs-off', name: '--no-logs-off' },
323 + { flag: '--foo_bar', name: '--foo_bar' },
324 + { flag: '--foo_bar=value', name: '--foo_bar' },
325 + ])('[Given] the unknown $flag [Then] run rejects it as an unknown flag', ({ flag, name }) =>
326 + Effect.gen(function* () {
327 + const failure = yield* cli(['run', flag, 'console.log(1)']).pipe(Effect.flip);
328
320 - expect(Exit.isFailure(exit)).toBe(true);
321 - expect(commandRuns).not.toHaveBeenCalled();
322 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
323 - expect(output).toContain(
324 - `Unrecognized flag: ${flag.split('=')[0]} in command composio run`
325 - );
326 - })
327 - );
328 - }
329 + expect(failure).toMatchObject({ _tag: 'ShowHelp' });
330 + expect(commandRuns).not.toHaveBeenCalled();
331 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
332 + expect(output).toContain(`Unrecognized flag: ${name} in command composio run`);
333 + })
334 + );
335
336 it.effect('[Given] repeated invocations [Then] hidden flags do not leak', () =>
337 Effect.gen(function* () {
@@ -384,29 +390,23 @@ describe('CLI: composio run', () => {
390 layer(RunTestLive())(it => {
391 it.effect('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
392 Effect.gen(function* () {
387 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
388 - const scriptPath = path.join(tempDir, 'script.ts');
389 - fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
390 - try {
391 - yield* cli(['run', '--file', scriptPath, '--', 'hello']);
393 + const { scriptPath } = yield* tempScript;
394 + yield* cli(['run', '--file', scriptPath, '--', 'hello']);
395
393 - expect(commandRuns).toHaveBeenCalledTimes(1);
394 - const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
395 - expect(spawnConfig.cmd[0]).toBe(process.execPath);
396 - expect(spawnConfig.cmd[1]).toBe('--preload');
397 - expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
398 - expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
399 - expect(spawnConfig.cmd[4]).toBe('--');
400 - expect(spawnConfig.cmd[5]).toBe('hello');
401 - expect(spawnConfig.env).toEqual(expect.objectContaining({ BUN_BE_BUN: '1' }));
402 - expect(spawnConfig.extendEnv).toBe(true);
403 - expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
404 - expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);
405 - expect(fs.existsSync(spawnConfig.cmd[3]!)).toBe(false);
406 - expect(process.exitCode).toBe(0);
407 - } finally {
408 - fs.rmSync(tempDir, { recursive: true, force: true });
409 - }
396 + expect(commandRuns).toHaveBeenCalledTimes(1);
397 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
398 + expect(spawnConfig.cmd[0]).toBe(process.execPath);
399 + expect(spawnConfig.cmd[1]).toBe('--preload');
400 + expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
401 + expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
402 + expect(spawnConfig.cmd[4]).toBe('--');
403 + expect(spawnConfig.cmd[5]).toBe('hello');
404 + expect(spawnConfig.env).toEqual(expect.objectContaining({ BUN_BE_BUN: '1' }));
405 + expect(spawnConfig.extendEnv).toBe(true);
406 + expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
407 + expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);
408 + expect(fs.existsSync(spawnConfig.cmd[3]!)).toBe(false);
409 + expect(process.exitCode).toBe(0);
410 })
411 );
412 });
@@ -416,16 +416,14 @@ describe('CLI: composio run', () => {
416 '[Given] no inline code and no --file [Then] it fails with a typed usage error, not a defect',
417 () =>
418 Effect.gen(function* () {
419 - const exit = yield* cli(['run']).pipe(Effect.exit);
420 - expect(Exit.isFailure(exit)).toBe(true);
421 - if (!Exit.isFailure(exit)) return;
422 -
423 - const failure = Cause.findErrorOption(exit.cause);
424 - expect(Option.isSome(failure)).toBe(true);
425 - expect(failure.pipe(Option.getOrThrow)).toBeInstanceOf(CommandInputError);
426 - expect(String((failure.pipe(Option.getOrThrow) as CommandInputError).message)).toContain(
427 - 'Provide inline code or use --file to run a script file.'
428 - );
419 + const failure = yield* cli(['run']).pipe(Effect.flip);
420 +
421 + expect(failure).toBeInstanceOf(CommandInputError);
422 + expect(failure).toMatchObject({
423 + message: expect.stringContaining(
424 + 'Provide inline code or use --file to run a script file.'
425 + ),
426 + });
427 // Nothing was set up before the check, so no child process was started.
428 expect(commandRuns).not.toHaveBeenCalled();
429 })
@@ -437,51 +435,39 @@ describe('CLI: composio run', () => {
435 '[Given] --file=path inline form followed by --dry-run [Then] both parse as run flags',
436 () =>
437 Effect.gen(function* () {
440 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
441 - const scriptPath = path.join(tempDir, 'script.ts');
442 - fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
443 -
444 - try {
445 - yield* cli(['run', `--file=${scriptPath}`, '--dry-run']);
446 -
447 - expect(commandRuns).toHaveBeenCalledTimes(1);
448 - const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
449 - // `--file=...` must be recognized as a run flag: file mode compiles a
450 - // wrapper script (not `--eval` inline code), and `--dry-run` must not
451 - // leak into the forwarded script arguments.
452 - expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
453 - expect(spawnConfig.cmd).not.toContain('--dry-run');
454 - expect(process.exitCode).toBe(0);
455 - } finally {
456 - fs.rmSync(tempDir, { recursive: true, force: true });
457 - }
438 + const { scriptPath } = yield* tempScript;
439 + yield* cli(['run', `--file=${scriptPath}`, '--dry-run']);
440 +
441 + expect(commandRuns).toHaveBeenCalledTimes(1);
442 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
443 + // `--file=...` must be recognized as a run flag: file mode compiles a
444 + // wrapper script (not `--eval` inline code), and `--dry-run` must not
445 + // leak into the forwarded script arguments.
446 + expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
447 + expect(spawnConfig.cmd).not.toContain('--dry-run');
448 + expect(process.exitCode).toBe(0);
449 })
450 );
451 });
452
453 layer(RunTestLive())(it => {
463 - it.effect(
464 - 'forwards script flags with or without a delimiter without enabling them in the CLI',
465 - () =>
466 - Effect.gen(function* () {
467 - const script = 'console.log("hi")';
468 - const tail = ['--perf-debug', '--tool-debug', '--telemetry-debug', '--help', '--version'];
469 - for (const args of [
470 - [script, ...tail],
471 - [script, '--', ...tail],
472 - ['--', script, ...tail],
473 - ]) {
474 - yield* cli(['--perf-debug=false', 'run', ...args]);
475 - const spawned = inspectRunCommand(commandRuns.mock.calls.at(-1)![0]);
476 - expect(spawned.cmd.slice(5)).toEqual(['--', ...tail]);
477 - expect(spawned.env).toMatchObject({
478 - COMPOSIO_PERF_DEBUG: '0',
479 - COMPOSIO_TOOL_DEBUG: '0',
480 - COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
481 - });
482 - }
483 - expect(commandRuns).toHaveBeenCalledTimes(3);
484 - })
454 + it.effect.each([
455 + { layout: 'no delimiter', args: [SCRIPT, ...SCRIPT_FLAGS] },
456 + { layout: 'a delimiter after the code', args: [SCRIPT, '--', ...SCRIPT_FLAGS] },
457 + { layout: 'a delimiter before the code', args: ['--', SCRIPT, ...SCRIPT_FLAGS] },
458 + ])('forwards script flags with $layout without enabling them in the CLI', ({ args }) =>
459 + Effect.gen(function* () {
460 + yield* cli(['--perf-debug=false', 'run', ...args]);
461 +
462 + expect(commandRuns).toHaveBeenCalledTimes(1);
463 + const spawned = inspectRunCommand(commandRuns.mock.calls[0]![0]);
464 + expect(spawned.cmd.slice(5)).toEqual(['--', ...SCRIPT_FLAGS]);
465 + expect(spawned.env).toMatchObject({
466 + COMPOSIO_PERF_DEBUG: '0',
467 + COMPOSIO_TOOL_DEBUG: '0',
468 + COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
469 + });
470 + })
471 );
472 });
473
ts/packages/cli/test/src/commands/setup-skill.cmd.test.ts
+18 -9
@@ -25,16 +25,25 @@ describe('composio setup skill', () => {
25 expect(installSkill).toHaveBeenLastCalledWith({ target: 'openclaw', skillName: undefined });
26 })
27 );
28 - it.effect('rejects invalid targets and missing names before installation', () =>
28 + it.effect.each([
29 + { args: ['setup', 'skill'], error: { _tag: 'MissingArgument', argument: 'target' } },
30 + {
31 + args: ['setup', 'skill', 'cursor'],
32 + error: { _tag: 'InvalidValue', option: 'target', value: 'cursor' },
33 + },
34 + {
35 + args: ['setup', 'skill', 'claude', '--name'],
36 + error: { _tag: 'InvalidValue', option: 'name' },
37 + },
38 + ])('rejects invalid targets and missing names before installation: $args', ({ args, error }) =>
39 Effect.gen(function* () {
30 - for (const args of [
31 - ['setup', 'skill'],
32 - ['setup', 'skill', 'cursor'],
33 - ['setup', 'skill', 'claude', '--name'],
34 - ]) {
35 - const exit = yield* Effect.result(cli(args));
36 - expect(exit._tag).toBe('Failure');
37 - }
40 + const failure = yield* Effect.flip(cli(args));
41 +
42 + expect(failure).toMatchObject({
43 + _tag: 'ShowHelp',
44 + commandPath: ['composio', 'setup', 'skill'],
45 + errors: [error],
46 + });
47 expect(installSkill).not.toHaveBeenCalled();
48 })
49 );
ts/packages/cli/test/src/commands/setup.cmd.test.ts
+111 -142
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Cause, Effect, Exit, Fiber, Latch } from 'effect';
2 +import { Effect, Exit, Fiber, Latch } from 'effect';
3 import { TestClock } from 'effect/testing';
4 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
5 import { afterEach, vi } from 'vitest';
@@ -336,7 +336,16 @@ describe('CLI: composio setup', () => {
336 );
337 });
338
339 - for (const host of ['claude', 'codex'] as const) {
339 + describe.each([
340 + {
341 + host: 'claude',
342 + repairCommand: ['claude', 'plugin', 'enable', 'composio@composio', '--scope', 'user'],
343 + },
344 + {
345 + host: 'codex',
346 + repairCommand: ['codex', 'plugin', 'add', 'composio@composio', '--json'],
347 + },
348 + ] as const)('disabled $host plugin', ({ host, repairCommand }) => {
349 const disabled = makeFakeHosts({
350 [host]: { available: true, marketplace: 'canonical', plugin: 'disabled' },
351 });
@@ -345,26 +354,17 @@ describe('CLI: composio setup', () => {
354 commandRunner: disabled.runner,
355 setupSkillInstaller: makeSkillInstaller(true),
356 })
348 - )(`disabled ${host} plugin`, it => {
357 + )(it => {
358 it.effect('repairs the plugin through the native path', () =>
359 Effect.gen(function* () {
360 yield* cli(['setup', '--target', host, '--yes']);
361
362 expect(disabled.state[host].plugin).toBe('enabled');
354 - if (host === 'claude') {
355 - expect(disabled.commands).toContainEqual([
356 - 'claude',
357 - 'plugin',
358 - 'enable',
359 - 'composio@composio',
360 - '--scope',
361 - 'user',
362 - ]);
363 - }
363 + expect(disabled.commands).toContainEqual(repairCommand);
364 })
365 );
366 });
367 - }
367 + });
368
369 const freshCodex = makeFakeHosts({ codex: { available: true } });
370 layer(TestLive({ commandRunner: freshCodex.runner }))('fresh Codex install', it => {
@@ -892,15 +892,12 @@ describe('CLI: composio setup', () => {
892
893 it.effect('does not skip an explicitly requested missing host', () =>
894 Effect.gen(function* () {
895 - const exit = yield* Effect.exit(
896 - cli(['setup', '--target', 'claude', '--yes', '--if-present'])
895 + const failure = yield* cli(['setup', '--target', 'claude', '--yes', '--if-present']).pipe(
896 + Effect.flip
897 );
898 - expect(Exit.isFailure(exit)).toBe(true);
899 - if (Exit.isFailure(exit)) {
900 - expect(Cause.pretty(exit.cause)).toContain(
901 - 'claude is not installed or not available on PATH'
902 - );
903 - }
898 + expect(failure).toMatchObject({
899 + message: expect.stringContaining('claude is not installed or not available on PATH'),
900 + });
901 })
902 );
903 });
@@ -918,33 +915,30 @@ describe('CLI: composio setup', () => {
915 );
916 });
917
921 - for (const unsafeSource of [
918 + describe.each([
919 'http://github.com/ComposioHQ/composio-plugin-cc.git',
920 'https://token@github.com/ComposioHQ/composio-plugin-cc.git',
921 'https://github.com/ComposioHQ/composio-plugin-cc.git?token=secret',
925 - ]) {
922 + ])('unsafe marketplace source: %s', unsafeSource => {
923 const unsafeMarketplace = makeFakeHosts(
924 { claude: { available: true, marketplace: 'canonical' } },
925 { marketplaceSource: { claude: unsafeSource } }
926 );
930 - layer(TestLive({ commandRunner: unsafeMarketplace.runner }))(
931 - `unsafe marketplace source: ${unsafeSource}`,
932 - it => {
933 - it.effect('rejects a non-canonical GitHub URL', () =>
934 - Effect.gen(function* () {
935 - const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
936 -
937 - expect(Exit.isFailure(exit)).toBe(true);
938 - expect(
939 - unsafeMarketplace.commands.some(parts =>
940 - ['add', 'install', 'enable'].some(operation => parts.includes(operation))
941 - )
942 - ).toBe(false);
943 - })
944 - );
945 - }
946 - );
947 - }
927 + layer(TestLive({ commandRunner: unsafeMarketplace.runner }))(it => {
928 + it.effect('rejects a non-canonical GitHub URL', () =>
929 + Effect.gen(function* () {
930 + const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
931 +
932 + expect(Exit.isFailure(exit)).toBe(true);
933 + expect(
934 + unsafeMarketplace.commands.some(parts =>
935 + ['add', 'install', 'enable'].some(operation => parts.includes(operation))
936 + )
937 + ).toBe(false);
938 + })
939 + );
940 + });
941 + });
942
943 const failedInspection = makeFakeHosts(
944 { claude: { available: true } },
@@ -984,14 +978,12 @@ describe('CLI: composio setup', () => {
978 it => {
979 it.effect('fails automatic setup with actionable update instructions', () =>
980 Effect.gen(function* () {
987 - const exit = yield* Effect.exit(cli(['setup', '--target', 'auto', '--yes']));
981 + const failure = yield* cli(['setup', '--target', 'auto', '--yes']).pipe(Effect.flip);
982
989 - expect(Exit.isFailure(exit)).toBe(true);
990 - if (Exit.isFailure(exit)) {
991 - const renderedCause = Cause.pretty(exit.cause);
992 - expect(renderedCause).toContain('requires JSON plugin inspection');
993 - expect(renderedCause).toContain('claude update');
994 - }
983 + expect(failure).toMatchObject({
984 + message: expect.stringContaining('requires JSON plugin inspection'),
985 + });
986 + expect(failure).toMatchObject({ message: expect.stringContaining('claude update') });
987 expect(legacyClaude.commands.some(parts => parts.includes('--json'))).toBe(false);
988 expect(
989 legacyClaude.commands.some(parts =>
@@ -1007,12 +999,11 @@ describe('CLI: composio setup', () => {
999 it => {
1000 it.effect('fails automatic setup when no supported host remains', () =>
1001 Effect.gen(function* () {
1010 - const exit = yield* Effect.exit(cli(['setup', '--target', 'auto', '--yes']));
1002 + const failure = yield* cli(['setup', '--target', 'auto', '--yes']).pipe(Effect.flip);
1003
1012 - expect(Exit.isFailure(exit)).toBe(true);
1013 - if (Exit.isFailure(exit)) {
1014 - expect(Cause.pretty(exit.cause)).toContain('requires Codex 0.139.0 or newer');
1015 - }
1004 + expect(failure).toMatchObject({
1005 + message: expect.stringContaining('requires Codex 0.139.0 or newer'),
1006 + });
1007 })
1008 );
1009
@@ -1032,15 +1023,15 @@ describe('CLI: composio setup', () => {
1023
1024 it.effect('fails with an actionable upgrade message before running setup mutations', () =>
1025 Effect.gen(function* () {
1035 - const exit = yield* Effect.exit(cli(['setup', '--target', 'codex', '--yes']));
1026 + const failure = yield* cli(['setup', '--target', 'codex', '--yes']).pipe(Effect.flip);
1027
1037 - expect(Exit.isFailure(exit)).toBe(true);
1038 - if (Exit.isFailure(exit)) {
1039 - const renderedCause = Cause.pretty(exit.cause);
1040 - expect(renderedCause).toContain('requires Codex 0.139.0 or newer');
1041 - expect(renderedCause).toContain('codex update');
1042 - expect(renderedCause).not.toContain("unexpected argument '--json'");
1043 - }
1028 + expect(failure).toMatchObject({
1029 + message: expect.stringContaining('requires Codex 0.139.0 or newer'),
1030 + });
1031 + expect(failure).toMatchObject({ message: expect.stringContaining('codex update') });
1032 + expect(failure).not.toMatchObject({
1033 + message: expect.stringContaining("unexpected argument '--json'"),
1034 + });
1035 expect(legacyCodex.commands.some(parts => parts.includes('--json'))).toBe(false);
1036 expect(
1037 legacyCodex.commands.some(parts =>
@@ -1103,14 +1094,13 @@ describe('CLI: composio setup', () => {
1094 )('multi-host mutation failure', it => {
1095 it.effect('reports hosts completed before a later target fails', () =>
1096 Effect.gen(function* () {
1106 - const exit = yield* Effect.exit(cli(['setup', '--target', 'all', '--yes']));
1097 + const failure = yield* cli(['setup', '--target', 'all', '--yes']).pipe(Effect.flip);
1098
1108 - expect(Exit.isFailure(exit)).toBe(true);
1109 - if (Exit.isFailure(exit)) {
1110 - expect(Cause.pretty(exit.cause)).toContain(
1099 + expect(failure).toMatchObject({
1100 + message: expect.stringContaining(
1101 'Setup completed for claude before a later target failed'
1112 - );
1113 - }
1102 + ),
1103 + });
1104 expect(laterMutationFailure.state.claude).toMatchObject({
1105 marketplace: 'canonical',
1106 plugin: 'enabled',
@@ -1151,22 +1141,22 @@ describe('CLI: composio setup', () => {
1141 it.effect('times out instead of blocking setup forever', () =>
1142 Effect.gen(function* () {
1143 const fiber = yield* cli(['setup', '--target', 'claude', '--yes']).pipe(
1154 - Effect.exit,
1144 + Effect.flip,
1145 Effect.forkChild
1146 );
1147 yield* hostCommandReached.await;
1148 yield* Effect.yieldNow;
1149 yield* TestClock.adjust('2 minutes');
1160 - const exit = yield* Fiber.join(fiber);
1150 + const failure = yield* Fiber.join(fiber);
1151
1162 - expect(Exit.isFailure(exit)).toBe(true);
1163 - if (Exit.isFailure(exit)) {
1164 - const renderedCause = Cause.pretty(exit.cause);
1165 - expect(renderedCause).toContain(
1152 + expect(failure).toMatchObject({
1153 + message: expect.stringContaining(
1154 'The `claude --version` command timed out after 2 minutes'
1167 - );
1168 - expect(renderedCause).not.toContain('not installed or not available on PATH');
1169 - }
1155 + ),
1156 + });
1157 + expect(failure).not.toMatchObject({
1158 + message: expect.stringContaining('not installed or not available on PATH'),
1159 + });
1160 })
1161 );
1162 });
@@ -1191,19 +1181,11 @@ describe('CLI: composio setup', () => {
1181 layer(TestLive({ commandRunner: failedInstall.runner }))('native install failure', it => {
1182 it.effect('preserves the structured setup process failure as the command cause', () =>
1183 Effect.gen(function* () {
1194 - const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
1195 - expect(Exit.isFailure(exit)).toBe(true);
1196 - if (Exit.isFailure(exit)) {
1197 - const failure = Cause.squash(exit.cause);
1198 - expect(failure).toBeInstanceOf(SetupCommandError);
1199 - if (failure instanceof SetupCommandError) {
1200 - expect(failure.operation).toBe('setup');
1201 - expect(failure.cause).toBeInstanceOf(SetupProcessError);
1202 - if (failure.cause instanceof SetupProcessError) {
1203 - expect(failure.cause).toMatchObject({ target: 'claude', stage: 'mutate' });
1204 - }
1205 - }
1206 - }
1184 + const failure = yield* cli(['setup', '--target', 'claude', '--yes']).pipe(Effect.flip);
1185 +
1186 + expect(failure).toBeInstanceOf(SetupCommandError);
1187 + expect(failure).toMatchObject({ operation: 'setup', cause: expect.any(SetupProcessError) });
1188 + expect(failure).toMatchObject({ cause: { target: 'claude', stage: 'mutate' } });
1189 })
1190 );
1191 });
@@ -1226,13 +1208,6 @@ describe('CLI: composio setup', () => {
1208 });
1209 });
1210
1229 -const reasonCodeOf = (exit: Exit.Exit<unknown, unknown>): string | undefined => {
1230 - if (!Exit.isFailure(exit)) return undefined;
1231 - const failure = Cause.squash(exit.cause);
1232 - if (failure instanceof SetupCommandError) return failure.reasonCode;
1233 - return undefined;
1234 -};
1235 -
1211 const REASON_CODE_FIXTURES = {
1212 'only Claude Code installed': () => makeFakeHosts({ claude: { available: true } }),
1213 'no host installed': () => makeFakeHosts({}),
@@ -1246,37 +1221,32 @@ const REASON_CODE_FIXTURES = {
1221
1222 const REASON_CODE_CASES: ReadonlyArray<{
1223 readonly hosts: keyof typeof REASON_CODE_FIXTURES;
1249 - readonly argv: ReadonlyArray<string>;
1250 - readonly expected: string;
1224 + readonly cases: ReadonlyArray<{ readonly args: string; readonly expected: string }>;
1225 }> = [
1226 {
1227 hosts: 'only Claude Code installed',
1254 - argv: ['--target', 'all', '--yes'],
1255 - expected: 'all_requires_both_hosts',
1256 - },
1257 - {
1258 - hosts: 'only Claude Code installed',
1259 - argv: ['--target', 'codex', '--yes'],
1260 - expected: 'target_not_installed',
1261 - },
1262 - {
1263 - hosts: 'only Claude Code installed',
1264 - argv: ['--target', 'claude'],
1265 - expected: 'non_interactive_requires_yes',
1228 + cases: [
1229 + { args: '--target all --yes', expected: 'all_requires_both_hosts' },
1230 + { args: '--target codex --yes', expected: 'target_not_installed' },
1231 + { args: '--target claude', expected: 'non_interactive_requires_yes' },
1232 + ],
1233 },
1267 - { hosts: 'no host installed', argv: ['--yes'], expected: 'no_host_detected' },
1234 + { hosts: 'no host installed', cases: [{ args: '--yes', expected: 'no_host_detected' }] },
1235 {
1236 hosts: 'unsupported Codex only',
1270 - argv: ['--target', 'codex', '--yes'],
1271 - expected: 'unsupported_host',
1237 + cases: [
1238 + { args: '--target codex --yes', expected: 'unsupported_host' },
1239 + { args: '--yes', expected: 'unsupported_host' },
1240 + ],
1241 },
1273 - { hosts: 'unsupported Codex only', argv: ['--yes'], expected: 'unsupported_host' },
1242 {
1243 hosts: 'marketplace conflict',
1276 - argv: ['--target', 'claude', '--yes'],
1277 - expected: 'marketplace_conflict',
1244 + cases: [{ args: '--target claude --yes', expected: 'marketplace_conflict' }],
1245 + },
1246 + {
1247 + hosts: 'native install failure',
1248 + cases: [{ args: '--target claude --yes', expected: 'unknown' }],
1249 },
1279 - { hosts: 'native install failure', argv: ['--target', 'claude', '--yes'], expected: 'unknown' },
1250 ];
1251
1252 describe('CLI: composio setup failure reason codes', () => {
@@ -1284,19 +1254,18 @@ describe('CLI: composio setup failure reason codes', () => {
1254 process.exitCode = undefined;
1255 });
1256
1287 - for (const [hosts, makeHosts] of Object.entries(REASON_CODE_FIXTURES)) {
1288 - const fake = makeHosts();
1289 - layer(TestLive({ commandRunner: fake.runner }))(hosts, it => {
1290 - for (const { argv, expected } of REASON_CODE_CASES.filter(c => c.hosts === hosts)) {
1291 - it.effect(`codes \`setup ${argv.join(' ')}\` as ${expected}`, () =>
1292 - Effect.gen(function* () {
1293 - const exit = yield* Effect.exit(cli(['setup', ...argv]));
1294 - expect(reasonCodeOf(exit)).toBe(expected);
1295 - })
1296 - );
1297 - }
1257 + describe.each(REASON_CODE_CASES)('$hosts', ({ hosts, cases }) => {
1258 + layer(TestLive({ commandRunner: REASON_CODE_FIXTURES[hosts]().runner }))(it => {
1259 + it.effect.each(cases)('codes `setup $args` as $expected', ({ args, expected }) =>
1260 + Effect.gen(function* () {
1261 + const failure = yield* cli(['setup', ...args.split(' ')]).pipe(Effect.flip);
1262 +
1263 + expect(failure).toBeInstanceOf(SetupCommandError);
1264 + expect(failure).toMatchObject({ reasonCode: expected });
1265 + })
1266 + );
1267 });
1299 - }
1268 + });
1269 });
1270
1271 describe('CLI: composio setup rerun hints stay non-interactive safe', () => {
@@ -1304,19 +1273,15 @@ describe('CLI: composio setup rerun hints stay non-interactive safe', () => {
1273 process.exitCode = undefined;
1274 });
1275
1307 - const messageOf = (exit: Exit.Exit<unknown, unknown>): string | undefined => {
1308 - if (!Exit.isFailure(exit)) return undefined;
1309 - const failure = Cause.squash(exit.cause);
1310 - return failure instanceof Error ? failure.message : String(failure);
1311 - };
1312 -
1276 layer(TestLive({ commandRunner: REASON_CODE_FIXTURES['only Claude Code installed']().runner }))(
1277 'targeted host missing',
1278 it => {
1279 it.effect('target_not_installed rerun carries --yes', () =>
1280 Effect.gen(function* () {
1318 - const exit = yield* Effect.exit(cli(['setup', '--target', 'codex', '--yes']));
1319 - expect(messageOf(exit)).toContain('rerun `composio setup --yes --target codex`');
1281 + const failure = yield* cli(['setup', '--target', 'codex', '--yes']).pipe(Effect.flip);
1282 + expect(failure).toMatchObject({
1283 + message: expect.stringContaining('rerun `composio setup --yes --target codex`'),
1284 + });
1285 })
1286 );
1287 }
@@ -1327,8 +1292,10 @@ describe('CLI: composio setup rerun hints stay non-interactive safe', () => {
1292 it => {
1293 it.effect('no_host_detected rerun carries --yes', () =>
1294 Effect.gen(function* () {
1330 - const exit = yield* Effect.exit(cli(['setup', '--yes']));
1331 - expect(messageOf(exit)).toContain('rerun `composio setup --yes`');
1295 + const failure = yield* cli(['setup', '--yes']).pipe(Effect.flip);
1296 + expect(failure).toMatchObject({
1297 + message: expect.stringContaining('rerun `composio setup --yes`'),
1298 + });
1299 })
1300 );
1301 }
@@ -1339,8 +1306,10 @@ describe('CLI: composio setup rerun hints stay non-interactive safe', () => {
1306 it => {
1307 it.effect('marketplace_conflict rerun carries --yes', () =>
1308 Effect.gen(function* () {
1342 - const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
1343 - expect(messageOf(exit)).toContain('rerun `composio setup --yes --target claude`');
1309 + const failure = yield* cli(['setup', '--target', 'claude', '--yes']).pipe(Effect.flip);
1310 + expect(failure).toMatchObject({
1311 + message: expect.stringContaining('rerun `composio setup --yes --target claude`'),
1312 + });
1313 })
1314 );
1315 }
ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
+15 -19
@@ -1,7 +1,7 @@
1 import { mkdirSync, writeFileSync } from 'node:fs';
2 import { join } from 'node:path';
3 import { describe, expect, layer } from '@effect/vitest';
4 -import { Effect, Exit } from 'effect';
4 +import { Effect } from 'effect';
5 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
6 import { afterEach, beforeEach, vi } from 'vitest';
7 import { CommandRunner } from 'src/services/command-runner';
@@ -263,10 +263,7 @@ describe('CLI: composio setup telemetry', () => {
263 layer(TestLive({ commandRunner: legacyCodex.runner }))('unsupported Codex only', it => {
264 it.effect('tracks the normalized reason code and the installer skip', () =>
265 Effect.gen(function* () {
266 - const exit = yield* Effect.exit(
267 - cli(['setup', '--target', 'auto', '--yes', '--if-present'])
268 - );
269 - expect(Exit.isSuccess(exit)).toBe(true);
266 + yield* cli(['setup', '--target', 'auto', '--yes', '--if-present']);
267
268 expect(eventsNamed('CLI_SETUP_HOST_DETECTED')).toEqual(
269 expect.arrayContaining([
@@ -297,10 +294,7 @@ describe('CLI: composio setup telemetry', () => {
294 layer(TestLive({ commandRunner: noHosts.runner }))('no detected host', it => {
295 it.effect('tracks the installer skip when nothing is detected', () =>
296 Effect.gen(function* () {
300 - const exit = yield* Effect.exit(
301 - cli(['setup', '--target', 'auto', '--yes', '--if-present'])
302 - );
303 - expect(Exit.isSuccess(exit)).toBe(true);
297 + yield* cli(['setup', '--target', 'auto', '--yes', '--if-present']);
298
299 expect(eventsNamed('CLI_SETUP_SKIPPED')).toEqual([
300 expect.objectContaining({
@@ -319,14 +313,12 @@ describe('CLI: composio setup telemetry', () => {
313 yield* cli(['setup', '--target', 'auto', '--yes', '--if-present']);
314
315 const detected = eventsNamed('CLI_SETUP_HOST_DETECTED');
322 - expect(detected).toHaveLength(2);
323 - for (const event of detected) {
324 - expect(event.properties).toMatchObject({
325 - available: false,
326 - host_config_dir_present: false,
327 - host_binary_in_known_paths: expect.any(Boolean),
328 - });
329 - }
316 + const absentHost = expect.objectContaining({
317 + available: false,
318 + host_config_dir_present: false,
319 + host_binary_in_known_paths: expect.any(Boolean),
320 + });
321 + expect(detected.map(event => event.properties)).toEqual([absentHost, absentHost]);
322 })
323 );
324 });
@@ -398,8 +390,12 @@ describe('CLI: composio setup telemetry', () => {
390 )('native install failure', it => {
391 it.effect('tracks the per-host failure with its phase', () =>
392 Effect.gen(function* () {
401 - const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
402 - expect(Exit.isFailure(exit)).toBe(true);
393 + const failure = yield* cli(['setup', '--target', 'claude', '--yes']).pipe(Effect.flip);
394 + expect(failure).toMatchObject({
395 + _tag: 'services/SetupCommandError',
396 + operation: 'setup',
397 + cause: { _tag: 'services/SetupProcessError', target: 'claude' },
398 + });
399
400 const failureEvents = eventsNamed('CLI_PLUGIN_SETUP_FAILED');
401 expect(failureEvents).toEqual([
ts/packages/cli/test/src/commands/toolkits/toolkits.info.client.cmd.test.ts
+14 -19
@@ -2,10 +2,7 @@ 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__';
5 -import {
6 - stubClientResources,
7 - type StubRequest,
8 -} from 'test/__utils__/services/stub-composio-client';
5 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
6
7 const gmail: ToolkitDetailed = {
8 name: 'Gmail',
@@ -31,19 +28,20 @@ const testLayer = TestLive({
28 toolkitsData: { detailedToolkits: [gmail] },
29 });
30
34 -const isToolkits = (request: StubRequest) => request.path.includes('/toolkits');
31 +const SESSION_TOOLKITS = '/api/v3.1/tool_router/session/trs_stub_session/toolkits';
32
33 /** Session toolkit reads answered by `respond`; the session they run in is created normally. */
34 const toolkitsOver = (respond: () => Response) =>
38 - stubClientResources(['toolRouter'], request =>
39 - isToolkits(request)
40 - ? respond()
41 - : Response.json({
42 - session_id: 'trs_stub_session',
43 - config: { user_id: 'global-default' },
44 - mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
45 - tool_router_tools: [],
46 - })
35 + stubClientResources(
36 + ['toolRouter'],
37 + routeRequests([{ method: 'GET', path: SESSION_TOOLKITS, respond }], () =>
38 + Response.json({
39 + session_id: 'trs_stub_session',
40 + config: { user_id: 'global-default' },
41 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
42 + tool_router_tools: [],
43 + })
44 + )
45 );
46
47 describe('CLI: composio dev toolkits info over the API client', () => {
@@ -83,11 +81,8 @@ describe('CLI: composio dev toolkits info over the API client', () => {
81 is_composio_managed: null,
82 },
83 });
86 - expect(stub.requests.filter(isToolkits)).toEqual([
87 - {
88 - method: 'GET',
89 - path: '/api/v3.1/tool_router/session/trs_stub_session/toolkits?toolkits=gmail',
90 - },
84 + expect(stub.requests.filter(request => request.path.startsWith(SESSION_TOOLKITS))).toEqual([
85 + { method: 'GET', path: `${SESSION_TOOLKITS}?toolkits=gmail` },
86 ]);
87 })
88 );
ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
+6 -23
@@ -58,23 +58,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
58 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
59 });
60
61 -const parseLastJson = (lines: ReadonlyArray<string>) => {
62 - for (let i = lines.length - 1; i >= 0; i -= 1) {
63 - const line = lines[i];
64 - if (!line) continue;
65 - try {
66 - return JSON.parse(line) as {
67 - slug: string;
68 - latest_version: string | null;
69 - available_versions_last_20: string[];
70 - };
71 - } catch {
72 - // keep searching for the last JSON line
73 - }
74 - }
75 - throw new Error('Expected JSON output but none found');
76 -};
77 -
61 describe('CLI: composio dev toolkits version', () => {
62 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
63 '[Given] valid slug [Then] shows latest and last 20 versions',
@@ -84,16 +67,16 @@ describe('CLI: composio dev toolkits version', () => {
67 yield* cli(['dev', 'toolkits', 'version', 'gmail']);
68 const lines = yield* MockConsole.getLines({ stripAnsi: true });
69 const output = lines.join('\n');
87 - const json = parseLastJson(lines);
70 + const json = JSON.parse(String(lines.at(-1)));
71
72 expect(output).toContain('Toolkit: Gmail (gmail)');
73 expect(output).toContain('Latest Version: 20260101_25');
74 expect(output).toContain('Last 20 Available Versions:');
92 - expect(json.slug).toBe('gmail');
93 - expect(json.latest_version).toBe('20260101_25');
94 - expect(json.available_versions_last_20).toHaveLength(20);
95 - expect(json.available_versions_last_20[0]).toBe('20260101_06');
96 - expect(json.available_versions_last_20[19]).toBe('20260101_25');
75 + expect(json).toMatchObject({
76 + slug: 'gmail',
77 + latest_version: '20260101_25',
78 + available_versions_last_20: versionHistory.slice(-20),
79 + });
80 })
81 );
82 }
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+92 -134
@@ -3,7 +3,7 @@ import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { describe, expect, it, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 -import { Config, ConfigProvider, DateTime, Effect, Exit, Option, Predicate } from 'effect';
6 +import { Config, ConfigProvider, DateTime, Effect, Option } from 'effect';
7 import { APIConnectionError, BadRequestError } from '@composio/client/effect';
8 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
9 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -17,7 +17,6 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
17 import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
18 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
19 import { parseParallelExecuteArgs } from 'src/commands/tools/commands/tools.execute.cmd';
20 -import type { CommandInputError } from 'src/commands/errors';
20 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
21 import type { ToolkitDetailed } from 'src/models/toolkits';
22 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
@@ -104,30 +103,20 @@ const largeOutputConfigProvider = ConfigProvider.fromEnvRecord({
103 COMPOSIO_USER_API_KEY: 'test_api_key',
104 }).pipe(ConfigProvider.orElse(testArtifactConfigProvider));
105
107 -const expectInvalidValueMessage = (failure: unknown, message: string) => {
108 - expect(Predicate.isTagged(failure, 'commands/CommandInputError')).toBe(true);
109 - if (!Predicate.isTagged(failure, 'commands/CommandInputError')) return;
110 -
111 - expect((failure as CommandInputError).message).toContain(message);
112 -};
106 +const expectInvalidValueMessage = (failure: unknown, message: string) =>
107 + expect(failure).toMatchObject({
108 + _tag: 'commands/CommandInputError',
109 + message: expect.stringContaining(message),
110 + });
111
114 -const parseLastJson = (lines: ReadonlyArray<string>) => {
115 - for (let i = lines.length - 1; i >= 0; i -= 1) {
116 - const line = lines[i];
117 - if (!line) continue;
118 - try {
119 - return JSON.parse(line) as {
120 - successful: boolean;
121 - data: Record<string, unknown>;
122 - error: string | null;
123 - logId: string;
124 - };
125 - } catch {
126 - // keep searching for the last JSON line
127 - }
128 - }
129 - throw new Error('Expected JSON output but none found');
130 -};
112 +/** The command's JSON result: `ui.output` prints it as the last console line. */
113 +const parseLastJson = (lines: ReadonlyArray<string>) =>
114 + JSON.parse(String(lines.at(-1))) as {
115 + successful: boolean;
116 + data: Record<string, unknown>;
117 + error: string | null;
118 + logId: string;
119 + };
120
121 describe('CLI: composio execute', () => {
122 it.effect('returns a CLI validation error for malformed parallel arguments', () =>
@@ -1364,10 +1353,7 @@ describe('CLI: composio execute', () => {
1353 };
1354 expect(refreshed.version).toBe('20260115_00');
1355 expect(refreshed.inputSchema.type).toBe('object');
1367 - const propertyKeys = Object.keys(
1368 - (refreshed.inputSchema.properties ?? {}) as Record<string, unknown>
1369 - );
1370 - expect(propertyKeys).toContain('recipient_email');
1356 + expect(refreshed.inputSchema.properties).toHaveProperty('recipient_email');
1357 })
1358 );
1359 }
@@ -1434,7 +1420,7 @@ describe('CLI: composio execute', () => {
1420 '{"recipient":42}',
1421 ]).pipe(
1422 Effect.flip,
1437 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
1423 + Effect.map(error => (error as Error).message)
1424 );
1425
1426 expect(failure).toContain('Input validation failed for GMAIL_SEND_EMAIL');
@@ -1499,7 +1485,7 @@ describe('CLI: composio execute', () => {
1485 '{"recipient":42}',
1486 ]).pipe(
1487 Effect.flip,
1502 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
1488 + Effect.map(error => (error as Error).message)
1489 );
1490
1491 it.effect('never sends the tool call on a schema cache miss', () =>
@@ -1575,7 +1561,7 @@ describe('CLI: composio execute', () => {
1561 '{"recipient_email":"karan"}',
1562 ]).pipe(
1563 Effect.flip,
1578 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
1564 + Effect.map(error => (error as Error).message)
1565 );
1566 expect(dryRunFailure).toContain('Could not compile the cached JSON schema');
1567 })
@@ -1785,18 +1771,17 @@ describe('CLI: composio execute', () => {
1771 'GITHUB_CREATE_ISSUE',
1772 '-d',
1773 '{"title":"Bug"}',
1788 - ]).pipe(Effect.catch(() => Effect.void));
1774 + ]).pipe(Effect.flip);
1775
1776 const lines = yield* MockConsole.getLines({ stripAnsi: true });
1791 - const output = parseLastJson(lines);
1792 - const results =
1793 - Predicate.hasProperty(output, 'results') && Array.isArray(output.results)
1794 - ? output.results
1795 - : [];
1777 + const output = parseLastJson(lines) as unknown as {
1778 + successful: boolean;
1779 + results: ReadonlyArray<unknown>;
1780 + };
1781
1782 expect(output.successful).toBe(false);
1798 - expect(results).toHaveLength(2);
1799 - expect(results).toEqual(
1783 + expect(output.results).toHaveLength(2);
1784 + expect(output.results).toEqual(
1785 expect.arrayContaining([
1786 expect.objectContaining({ slug: 'GMAIL_SEND_EMAIL', successful: false }),
1787 expect.objectContaining({ slug: 'GITHUB_CREATE_ISSUE', successful: true }),
@@ -1840,8 +1825,10 @@ describe('CLI: composio execute', () => {
1825
1826 const lines = yield* MockConsole.getLines({ stripAnsi: true });
1827 const output = parseLastJson(lines);
1843 - expect(Predicate.isTagged(error, 'ReportedToolExecutionError')).toBe(true);
1844 - expect(error).toMatchObject({ reason: 'parallel_failed' });
1828 + expect(error).toMatchObject({
1829 + _tag: 'ReportedToolExecutionError',
1830 + reason: 'parallel_failed',
1831 + });
1832 expect(output).toMatchObject({
1833 successful: false,
1834 results: [
@@ -1960,19 +1947,10 @@ describe('CLI: composio execute', () => {
1947 const tempFile = path.join(os.tmpdir(), `composio-upload-${crypto.randomUUID()}.txt`);
1948 fs.writeFileSync(tempFile, 'hello from cli upload', 'utf8');
1949
1963 - const originalFetch = globalThis.fetch;
1964 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
1965 - const url =
1966 - typeof input === 'string'
1967 - ? input
1968 - : input instanceof URL
1969 - ? input.toString()
1970 - : input.url;
1971 - if (url === 'https://s3.test.composio.dev/upload') {
1972 - return Promise.resolve(new Response(null, { status: 200 }));
1973 - }
1974 - return originalFetch(input, init);
1975 - });
1950 + // The S3 upload is the only request that reaches `fetch`.
1951 + const fetchSpy = vi
1952 + .spyOn(globalThis, 'fetch')
1953 + .mockImplementation(async () => new Response(null, { status: 200 }));
1954
1955 yield* cli([
1956 'execute',
@@ -2059,19 +2037,10 @@ describe('CLI: composio execute', () => {
2037 const tempFile = path.join(os.tmpdir(), `composio-inject-${crypto.randomUUID()}.png`);
2038 fs.writeFileSync(tempFile, 'png-binary-ish', 'utf8');
2039
2062 - const originalFetch = globalThis.fetch;
2063 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
2064 - const url =
2065 - typeof input === 'string'
2066 - ? input
2067 - : input instanceof URL
2068 - ? input.toString()
2069 - : input.url;
2070 - if (url === 'https://s3.test.composio.dev/upload') {
2071 - return Promise.resolve(new Response(null, { status: 200 }));
2072 - }
2073 - return originalFetch(input, init);
2074 - });
2040 + // The S3 upload is the only request that reaches `fetch`.
2041 + const fetchSpy = vi
2042 + .spyOn(globalThis, 'fetch')
2043 + .mockImplementation(async () => new Response(null, { status: 200 }));
2044
2045 yield* cli([
2046 'execute',
@@ -2095,7 +2064,10 @@ describe('CLI: composio execute', () => {
2064 s3key: `uploads/${path.basename(tempFile)}`,
2065 },
2066 });
2098 - expect(fetchSpy).toHaveBeenCalled();
2067 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
2068 + 'https://s3.test.composio.dev/upload',
2069 + expect.objectContaining({ method: 'PUT' })
2070 + );
2071
2072 fs.rmSync(tempFile, { force: true });
2073 })
@@ -2151,19 +2123,10 @@ describe('CLI: composio execute', () => {
2123 const tempFile = path.join(os.tmpdir(), `composio-nested-${crypto.randomUUID()}.png`);
2124 fs.writeFileSync(tempFile, 'nested-png-binary-ish', 'utf8');
2125
2154 - const originalFetch = globalThis.fetch;
2155 - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
2156 - const url =
2157 - typeof input === 'string'
2158 - ? input
2159 - : input instanceof URL
2160 - ? input.toString()
2161 - : input.url;
2162 - if (url === 'https://s3.test.composio.dev/upload') {
2163 - return Promise.resolve(new Response(null, { status: 200 }));
2164 - }
2165 - return originalFetch(input, init);
2166 - });
2126 + // The S3 upload is the only request that reaches `fetch`.
2127 + const fetchSpy = vi
2128 + .spyOn(globalThis, 'fetch')
2129 + .mockImplementation(async () => new Response(null, { status: 200 }));
2130
2131 yield* cli([
2132 'execute',
@@ -2188,6 +2151,10 @@ describe('CLI: composio execute', () => {
2151 },
2152 },
2153 });
2154 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
2155 + 'https://s3.test.composio.dev/upload',
2156 + expect.objectContaining({ method: 'PUT' })
2157 + );
2158
2159 fs.rmSync(tempFile, { force: true });
2160 })
@@ -2243,21 +2210,13 @@ describe('CLI: composio execute', () => {
2210 );
2211 fs.writeFileSync(tempFile, 'hello from failed cli upload', 'utf8');
2212
2246 - const originalFetch = globalThis.fetch;
2247 - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
2248 - const url =
2249 - typeof input === 'string'
2250 - ? input
2251 - : input instanceof URL
2252 - ? input.toString()
2253 - : input.url;
2254 - if (url === 'https://s3.test.composio.dev/upload') {
2255 - return Promise.resolve(
2213 + // The S3 upload is the only request that reaches `fetch`.
2214 + const fetchSpy = vi
2215 + .spyOn(globalThis, 'fetch')
2216 + .mockImplementation(
2217 + async () =>
2218 new Response('Upload failed', { status: 500, statusText: 'Upload Failed' })
2257 - );
2258 - }
2259 - return originalFetch(input, init);
2260 - });
2219 + );
2220
2221 const failure = yield* cli([
2222 'execute',
@@ -2270,10 +2229,14 @@ describe('CLI: composio execute', () => {
2229 }),
2230 ]).pipe(
2231 Effect.flip,
2273 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2232 + Effect.map(error => (error as Error).message)
2233 );
2234
2235 expect(failure).toContain('Failed to upload file to S3');
2236 + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith(
2237 + 'https://s3.test.composio.dev/upload',
2238 + expect.objectContaining({ method: 'PUT' })
2239 + );
2240
2241 fs.rmSync(tempFile, { force: true });
2242 })
@@ -2318,7 +2281,7 @@ describe('CLI: composio execute', () => {
2281 '/tmp/example.txt',
2282 ]).pipe(
2283 Effect.flip,
2321 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2284 + Effect.map(error => (error as Error).message)
2285 );
2286
2287 expect(failure).toContain('has no file_uploadable input');
@@ -2382,7 +2345,7 @@ describe('CLI: composio execute', () => {
2345 '/tmp/example.txt',
2346 ]).pipe(
2347 Effect.flip,
2385 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2348 + Effect.map(error => (error as Error).message)
2349 );
2350
2351 expect(failure).toContain('has multiple file_uploadable inputs');
@@ -2702,7 +2665,7 @@ describe('CLI: composio execute', () => {
2665 'GMAIL_CREATE_EMAIL_DRAFT',
2666 '-d',
2667 '{\"recipient\":\"to@example.com\"}',
2705 - ]).pipe(Effect.catch(() => Effect.void));
2668 + ]).pipe(Effect.flip);
2669 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2670 const output = lines.join('\n');
2671
@@ -2733,7 +2696,7 @@ describe('CLI: composio execute', () => {
2696 'GMAIL_CREATE_EMAIL_DRAFT',
2697 '-d',
2698 '{"recipient":"to@example.com"}',
2736 - ]).pipe(Effect.catch(() => Effect.void));
2699 + ]).pipe(Effect.flip);
2700 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2701 const output = lines.join('\n');
2702
@@ -2793,16 +2756,16 @@ describe('CLI: composio execute', () => {
2756 )('[Given] Tool Router reports a failed execution with no error text', it => {
2757 it.effect('[Then] execute fails instead of reporting success', () =>
2758 Effect.gen(function* () {
2796 - const exit = yield* cli([
2759 + const failure = yield* cli([
2760 'execute',
2761 'GITHUB_STAR_REPO',
2762 '-d',
2763 '{"owner":"composio","repo":"composio"}',
2801 - ]).pipe(Effect.exit);
2764 + ]).pipe(Effect.flip);
2765 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2766 const output = parseLastJson(lines);
2767
2805 - expect(Exit.isFailure(exit)).toBe(true);
2768 + expect(failure).toMatchObject({ _tag: 'ReportedToolExecutionError' });
2769 expect(output.successful).toBe(false);
2770 expect(output.error).toBeNull();
2771 expect(output.logId).toBe('log_failed');
@@ -2834,16 +2797,16 @@ describe('CLI: composio execute', () => {
2797 )('[Given] Tool Router asks for user input [Then] execute fails without a result', it => {
2798 it.effect('reports that the tool requires user input', () =>
2799 Effect.gen(function* () {
2837 - const exit = yield* cli([
2800 + const failure = yield* cli([
2801 'execute',
2802 'GITHUB_STAR_REPO',
2803 '-d',
2804 '{"owner":"composio","repo":"composio"}',
2842 - ]).pipe(Effect.exit);
2805 + ]).pipe(Effect.flip);
2806 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2807 const output = parseLastJson(lines);
2808
2846 - expect(Exit.isFailure(exit)).toBe(true);
2809 + expect(failure).toMatchObject({ _tag: 'ReportedToolExecutionError' });
2810 expect(output.successful).toBe(false);
2811 expect(output.error).toContain(
2812 'Tool GITHUB_STAR_REPO requires user input before it can run (1 input request) and was not executed.'
@@ -2874,7 +2837,7 @@ describe('CLI: composio execute', () => {
2837 'GMAIL_CREATE_EMAIL_DRAFT',
2838 '-d',
2839 '{\"recipient\":\"to@example.com\"}',
2877 - ]).pipe(Effect.catch(() => Effect.void));
2840 + ]).pipe(Effect.flip);
2841 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2842 const output = lines.join('\n');
2843
@@ -2905,7 +2868,7 @@ describe('CLI: composio execute', () => {
2868 'GMAIL_CREATE_EMAIL_DRAFT',
2869 '-d',
2870 '{\"recipient\":\"to@example.com\"}',
2908 - ]).pipe(Effect.catch(() => Effect.void));
2871 + ]).pipe(Effect.flip);
2872 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2873 const output = lines.join('\n');
2874
@@ -2940,7 +2903,7 @@ describe('CLI: composio execute', () => {
2903 'GMAIL_CREATE_EMAIL_DRAFT',
2904 '-d',
2905 '{\"recipient\":\"to@example.com\"}',
2943 - ]).pipe(Effect.catch(() => Effect.void));
2906 + ]).pipe(Effect.flip);
2907 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2908 const output = lines.join('\n');
2909
@@ -2976,7 +2939,7 @@ describe('CLI: composio execute', () => {
2939 'GMAIL_CREATE_EMAIL_DRAFT',
2940 '-d',
2941 '{\"recipient\":\"to@example.com\"}',
2979 - ]).pipe(Effect.catch(() => Effect.void));
2942 + ]).pipe(Effect.flip);
2943 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2944 const output = lines.join('\n');
2945
@@ -3011,7 +2974,7 @@ describe('CLI: composio execute', () => {
2974 it.effect('omits connection tips for meta tool slugs', () =>
2975 Effect.gen(function* () {
2976 yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']).pipe(
3014 - Effect.catch(() => Effect.void)
2977 + Effect.flip
2978 );
2979 const lines = yield* MockConsole.getLines({ stripAnsi: true });
2980 const output = lines.join('\n');
@@ -3142,30 +3105,25 @@ describe('CLI: composio execute', () => {
3105 )('[Given] CI redaction enabled [Then] redacts id-like fields and logId', it => {
3106 it.effect('redacts id, threadId, logId but preserves labelIds', () =>
3107 Effect.gen(function* () {
3145 - const spy = vi
3146 - .spyOn(redactModule, 'redact')
3147 - .mockImplementation(
3148 - (({ prefix }: { value: string; prefix?: string }) =>
3149 - `${prefix ?? ''}<REDACTED>`) as typeof redactModule.redact
3150 - );
3108 + // The suite's `afterEach` restores this spy.
3109 + vi.spyOn(redactModule, 'redact').mockImplementation(
3110 + (({ prefix }: { value: string; prefix?: string }) =>
3111 + `${prefix ?? ''}<REDACTED>`) as typeof redactModule.redact
3112 + );
3113
3152 - try {
3153 - yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient_email":"to@example.com"}']);
3154 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
3155 - const output = parseLastJson(lines) as unknown as {
3156 - data: { id: string; labelIds: string[]; threadId: string };
3157 - logId: string;
3158 - successful: boolean;
3159 - };
3114 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient_email":"to@example.com"}']);
3115 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
3116 + const output = parseLastJson(lines) as unknown as {
3117 + data: { id: string; labelIds: string[]; threadId: string };
3118 + logId: string;
3119 + successful: boolean;
3120 + };
3121
3161 - expect(output.data.id).toBe('<REDACTED>');
3162 - expect(output.data.threadId).toBe('<REDACTED>');
3163 - expect(output.data.labelIds).toEqual(['SENT']);
3164 - expect(output.logId).toBe('log_<REDACTED>');
3165 - expect(output.successful).toBe(true);
3166 - } finally {
3167 - spy.mockRestore();
3168 - }
3122 + expect(output.data.id).toBe('<REDACTED>');
3123 + expect(output.data.threadId).toBe('<REDACTED>');
3124 + expect(output.data.labelIds).toEqual(['SENT']);
3125 + expect(output.logId).toBe('log_<REDACTED>');
3126 + expect(output.successful).toBe(true);
3127 })
3128 );
3129 });
ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts
+1 -14
@@ -4,19 +4,6 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
4 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { Tools } from 'src/models/tools';
6
7 -const parseLastJson = (lines: ReadonlyArray<string>) => {
8 - for (let i = lines.length - 1; i >= 0; i -= 1) {
9 - const line = lines[i];
10 - if (!line) continue;
11 - try {
12 - return JSON.parse(line) as Record<string, unknown>;
13 - } catch {
14 - // continue
15 - }
16 - }
17 - throw new Error('Expected JSON output but none found');
18 -};
19 -
7 const testTools: Tools = [
8 {
9 name: 'Send Email',
@@ -122,7 +109,7 @@ describe('CLI: composio tools info', () => {
109 Effect.gen(function* () {
110 yield* cli(['tools', 'info', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK']);
111 const lines = yield* MockConsole.getLines({ stripAnsi: true });
125 - const output = parseLastJson(lines) as {
112 + const output = JSON.parse(String(lines.at(-1))) as {
113 inputSchema: Record<string, unknown>;
114 };
115
ts/packages/cli/test/src/commands/tools/tools.search.client.cmd.test.ts
+18 -21
@@ -1,11 +1,8 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Cause, ConfigProvider, Effect, Exit } from 'effect';
2 +import { ConfigProvider, Effect } from 'effect';
3 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 -import {
6 - stubClientResources,
7 - type StubRequest,
8 -} from 'test/__utils__/services/stub-composio-client';
5 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
6
7 const sendEmailInput = {
8 type: 'object',
@@ -86,19 +83,20 @@ const searchResponse = {
83 next_steps_guidance: [],
84 };
85
89 -const isSearch = (request: StubRequest) => request.path.endsWith('/search');
86 +const SEARCH_PATH = '/api/v3.1/tool_router/session/trs_stub_session/search';
87
88 /** Searches answered by `respond`; the session they run in is created normally. */
89 const searchingOver = (respond: () => Response) =>
93 - stubClientResources(['toolRouter'], request =>
94 - isSearch(request)
95 - ? respond()
96 - : Response.json({
97 - session_id: 'trs_stub_session',
98 - config: { user_id: 'consumer-user-org_test' },
99 - mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
100 - tool_router_tools: [],
101 - })
90 + stubClientResources(
91 + ['toolRouter'],
92 + routeRequests([{ method: 'POST', path: SEARCH_PATH, respond }], () =>
93 + Response.json({
94 + session_id: 'trs_stub_session',
95 + config: { user_id: 'consumer-user-org_test' },
96 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
97 + tool_router_tools: [],
98 + })
99 + )
100 );
101
102 describe('CLI: composio search over the API client', () => {
@@ -139,10 +137,10 @@ describe('CLI: composio search over the API client', () => {
137 };
138 // Once as the log line and once as the piped output.
139 expect(lines).toEqual([JSON.stringify(payload, null, 2), JSON.stringify(payload, null, 2)]);
142 - expect(stub.requests.filter(isSearch)).toEqual([
140 + expect(stub.requests.filter(request => request.path === SEARCH_PATH)).toEqual([
141 {
142 method: 'POST',
145 - path: '/api/v3.1/tool_router/session/trs_stub_session/search',
143 + path: SEARCH_PATH,
144 body: { queries: [{ use_case: 'send an email' }] },
145 },
146 ]);
@@ -168,7 +166,7 @@ describe('CLI: composio search over the API client', () => {
166 const stub = searchingOver(() => Response.json(driftedResponse));
167 yield* cli(['search', 'send an email']).pipe(Effect.provide(stub.layer));
168 const lines = yield* MockConsole.getLines({ stripAnsi: true });
171 - const payload = JSON.parse(lines.at(-1) ?? '{}');
169 + const payload = JSON.parse(String(lines.at(-1)));
170
171 expect(payload.results).toEqual(searchResponse.results);
172 expect(payload.tool_schemas.primary).toEqual({
@@ -190,11 +188,10 @@ describe('CLI: composio search over the API client', () => {
188 { status: 400 }
189 )
190 );
193 - const exit = yield* cli(['search', 'send an email']).pipe(
191 + const failure = yield* cli(['search', 'send an email']).pipe(
192 Effect.provide(stub.layer),
195 - Effect.exit
193 + Effect.flip
194 );
197 - const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
195
196 expect(failure).toMatchObject({ _tag: 'commands/ToolsSearchRequestError' });
197 expect(extractErrorDetails(failure).message).toBe(
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+33 -86
@@ -53,59 +53,16 @@ const testLiveOptions = {
53 fixture: 'global-test-user-id' as const,
54 };
55
56 -const extractFirstJsonObject = (output: string): Record<string, unknown> | null => {
57 - const start = output.indexOf('{');
58 - if (start < 0) return null;
59 -
60 - let depth = 0;
61 - let inString = false;
62 - let escaped = false;
63 -
64 - for (let i = start; i < output.length; i += 1) {
65 - const char = output[i];
66 -
67 - if (inString) {
68 - if (escaped) {
69 - escaped = false;
70 - } else if (char === '\\') {
71 - escaped = true;
72 - } else if (char === '"') {
73 - inString = false;
74 - }
75 - continue;
76 - }
77 -
78 - if (char === '"') {
79 - inString = true;
80 - continue;
81 - }
82 -
83 - if (char === '{') {
84 - depth += 1;
85 - continue;
86 - }
87 -
88 - if (char === '}') {
89 - depth -= 1;
90 - if (depth === 0) {
91 - return JSON.parse(output.slice(start, i + 1)) as Record<string, unknown>;
92 - }
93 - }
94 - }
95 -
96 - return null;
97 -};
98 -
56 describe('CLI: composio search', () => {
57 layer(TestLive(testLiveOptions))('[Given] a blank query [Then] typed validation fails', it => {
58 it.effect('returns the structured missing-query error', () =>
59 Effect.gen(function* () {
60 const failure = yield* cli(['search', ' ']).pipe(Effect.flip);
61 expect(failure).toBeInstanceOf(CommandInputError);
105 - if (failure instanceof CommandInputError) {
106 - expect(failure.option).toBe('<query>');
107 - expect(failure.message).toBe('At least one query is required.');
108 - }
62 + expect(failure).toMatchObject({
63 + option: '<query>',
64 + message: 'At least one query is required.',
65 + });
66 })
67 );
68 });
@@ -116,9 +73,8 @@ describe('CLI: composio search', () => {
73 yield* cli(['search', 'send']);
74 const lines = yield* MockConsole.getLines({ stripAnsi: true });
75 const output = lines.join('\n');
119 - const parsed = extractFirstJsonObject(output);
76 + const parsed = JSON.parse(String(lines.at(-1)));
77
121 - expect(parsed).not.toBeNull();
78 expect(parsed).toHaveProperty('results');
79 expect(parsed).toHaveProperty('tool_schemas');
80 expect(parsed).toHaveProperty('connected_toolkits');
@@ -290,8 +246,9 @@ describe('CLI: composio search', () => {
246 const lines = yield* MockConsole.getLines({ stripAnsi: true });
247 const output = lines.join('\n');
248
293 - expect(output).toContain('"use_case": "send"');
294 - expect(output).toContain('"use_case": "create issue"');
249 + expect(JSON.parse(String(lines.at(-1)))).toMatchObject({
250 + results: [{ use_case: 'send' }, { use_case: 'create issue' }],
251 + });
252 expect(output).toContain('GMAIL_SEND_EMAIL');
253 expect(output).toContain('SLACK_SEND_MESSAGE');
254 expect(output).toContain('GITHUB_CREATE_ISSUE');
@@ -323,11 +280,11 @@ describe('CLI: composio search', () => {
280 yield* cli(['search', 'send', '--toolkits', 'gmail', '--human']);
281 const lines = yield* MockConsole.getLines({ stripAnsi: true });
282 const output = lines.join('\n');
326 - const humanOutput = output.split('\n{')[0] ?? output;
283
328 - expect(humanOutput).toContain('GMAIL_SEND_EMAIL');
329 - expect(humanOutput).not.toContain('SLACK_SEND_MESSAGE');
330 - expect(humanOutput).toContain('Found 1 tools');
284 + expect(output).toContain('GMAIL_SEND_EMAIL');
285 + expect(output).not.toContain('SLACK_SEND_MESSAGE');
286 + expect(output).not.toContain('"results"');
287 + expect(output).toContain('Found 1 tools');
288 })
289 );
290 }
@@ -360,9 +317,8 @@ describe('CLI: composio search', () => {
317 yield* cli(['search', 'send', '--json']);
318 const lines = yield* MockConsole.getLines({ stripAnsi: true });
319 const output = lines.join('\n');
363 - const parsed = extractFirstJsonObject(output);
320 + const parsed = JSON.parse(String(lines.at(-1)));
321
365 - expect(parsed).not.toBeNull();
322 expect(parsed).toHaveProperty('results');
323 expect(parsed).toHaveProperty('tool_schemas');
324 expect(parsed).toHaveProperty('connected_toolkits');
@@ -481,24 +437,19 @@ describe('CLI: composio search', () => {
437 Effect.gen(function* () {
438 yield* cli(['search', 'send']);
439 const lines = yield* MockConsole.getLines({ stripAnsi: true });
484 - const output = lines.join('\n');
485 - const parsed = extractFirstJsonObject(output);
486 - const nextSteps = parsed?.next_steps as
487 - | {
488 - steps?: Array<{ action: string; command: string }>;
489 - }
490 - | undefined;
491 -
492 - expect(nextSteps?.steps).toBeTruthy();
493 -
494 - const executeStep = nextSteps?.steps?.find(step => step.action === 'Execute a tool');
495 - expect(executeStep).toBeTruthy();
496 - expect(executeStep!.command).toContain('composio execute "GMAIL_SEND_EMAIL"');
497 - expect(executeStep!.command).toMatch(/-d '\{"to":"","subject":"","body":""\}'/);
498 -
499 - const linkStep = nextSteps?.steps?.find(step => step.action === 'Link a user account');
500 - expect(linkStep).toBeTruthy();
501 - expect(linkStep!.command).toBe('composio link gmail');
440 + const parsed = JSON.parse(String(lines.at(-1)));
441 +
442 + expect(parsed.next_steps.steps).toEqual(
443 + expect.arrayContaining([
444 + {
445 + action: 'Execute a tool',
446 + command: expect.stringMatching(
447 + /composio execute "GMAIL_SEND_EMAIL".*-d '\{"to":"","subject":"","body":""\}'/
448 + ),
449 + },
450 + { action: 'Link a user account', command: 'composio link gmail' },
451 + ])
452 + );
453 })
454 );
455 }
@@ -511,17 +462,13 @@ describe('CLI: composio search', () => {
462 Effect.gen(function* () {
463 yield* cli(['search', 'send']);
464 const lines = yield* MockConsole.getLines({ stripAnsi: true });
514 - const output = lines.join('\n');
515 - const parsed = extractFirstJsonObject(output);
516 - const nextSteps = parsed?.next_steps as
517 - | {
518 - steps?: Array<{ action: string; command: string }>;
519 - }
520 - | undefined;
521 -
522 - const executeStep = nextSteps?.steps?.find(step => step.action === 'Execute a tool');
523 - expect(executeStep).toBeTruthy();
524 - expect(executeStep!.command).toContain('-d "{}"');
465 + const parsed = JSON.parse(String(lines.at(-1)));
466 +
467 + expect(parsed.next_steps.steps).toEqual(
468 + expect.arrayContaining([
469 + { action: 'Execute a tool', command: expect.stringContaining('-d "{}"') },
470 + ])
471 + );
472 })
473 );
474 }
ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
+13 -21
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { Cause, ConfigProvider, Effect, Exit } from 'effect';
2 +import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 import type { TriggerTypes } from 'src/models/trigger-types';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -75,16 +75,12 @@ describe('CLI: composio dev triggers list', () => {
75 it => {
76 it.effect('uses root toolkit command in the no-results hint', () =>
77 Effect.gen(function* () {
78 - const exit = yield* Effect.exit(cli(['triggers', 'list', 'nonexistent']));
79 - expect(Exit.isFailure(exit)).toBe(true);
80 - if (Exit.isFailure(exit)) {
81 - const failure = Cause.squash(exit.cause);
82 - expect(failure).toMatchObject({
83 - _tag: 'commands/CommandInputError',
84 - option: '<toolkit>',
85 - message: expect.stringContaining('not available'),
86 - });
87 - }
78 + const failure = yield* cli(['triggers', 'list', 'nonexistent']).pipe(Effect.flip);
79 + expect(failure).toMatchObject({
80 + _tag: 'commands/CommandInputError',
81 + option: '<toolkit>',
82 + message: expect.stringContaining('not available'),
83 + });
84 const lines = yield* MockConsole.getLines({ stripAnsi: true });
85 const output = lines.join('\n');
86
@@ -204,16 +200,12 @@ describe('CLI: composio dev triggers list', () => {
200 it => {
201 it.effect('shows hint about verifying toolkit slug', () =>
202 Effect.gen(function* () {
207 - const exit = yield* Effect.exit(cli(['dev', 'triggers', 'list', 'nonexistent']));
208 - expect(Exit.isFailure(exit)).toBe(true);
209 - if (Exit.isFailure(exit)) {
210 - const failure = Cause.squash(exit.cause);
211 - expect(failure).toMatchObject({
212 - _tag: 'commands/CommandInputError',
213 - option: '<toolkit>',
214 - message: expect.stringContaining('not available'),
215 - });
216 - }
203 + const failure = yield* cli(['dev', 'triggers', 'list', 'nonexistent']).pipe(Effect.flip);
204 + expect(failure).toMatchObject({
205 + _tag: 'commands/CommandInputError',
206 + option: '<toolkit>',
207 + message: expect.stringContaining('not available'),
208 + });
209 const lines = yield* MockConsole.getLines({ stripAnsi: true });
210 const output = lines.join('\n');
211
ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts
+8 -7
@@ -1,4 +1,3 @@
1 -import assert from 'node:assert';
1 import path from 'node:path';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { Effect } from 'effect';
@@ -996,11 +995,13 @@ describe('CLI: composio generate ts', () => {
995 const outputDir = path.join(cwd, 'generated-invalid');
996
997 const args = ['generate', 'ts', '--toolkits', 'nonexistent', '--output-dir', outputDir];
999 - const result = yield* cli(args).pipe(Effect.catch(e => Effect.succeed(e)));
998 + const failure = yield* cli(args).pipe(Effect.flip);
999
1001 - assert.ok(result instanceof CommandInputError);
1002 - expect(result.option).toBe('--toolkits');
1003 - expect(result.message).toContain('Invalid toolkit(s): nonexistent');
1000 + expect(failure).toBeInstanceOf(CommandInputError);
1001 + expect(failure).toMatchObject({
1002 + option: '--toolkits',
1003 + message: expect.stringContaining('Invalid toolkit(s): nonexistent'),
1004 + });
1005 })
1006 );
1007
@@ -1227,9 +1228,9 @@ describe('CLI: composio generate ts', () => {
1228 Effect.gen(function* () {
1229 const args = ['generate', 'ts'];
1230
1230 - const result = yield* cli(args).pipe(Effect.catch(e => Effect.succeed(e)));
1231 + const failure = yield* cli(args).pipe(Effect.flip);
1232
1232 - expect(result).toEqual(
1233 + expect(failure).toEqual(
1234 new ComposioCorePkgNotFound({
1235 message: '@composio/core not found',
1236 cause: '@composio/core not installed',
ts/packages/cli/test/src/commands/version.cmd.test.ts
+2 -8
@@ -17,10 +17,7 @@ describe('CLI: composio', () => {
17 // instead of the merged buffer, so decoration written elsewhere can
18 // never leak into — or be mistaken for — this contract.
19 const stdoutLines = yield* MockConsole.getLines({ stream: 'stdout' });
20 - expect(stdoutLines.length).toBeGreaterThan(0);
21 - for (const line of stdoutLines) {
22 - expect(line).toBe(pkg.version);
23 - }
20 + expect(stdoutLines).toEqual([pkg.version]);
21 })
22 );
23 });
@@ -32,10 +29,7 @@ describe('CLI: composio', () => {
29 yield* cli(args);
30
31 const stdoutLines = yield* MockConsole.getLines({ stream: 'stdout' });
35 - expect(stdoutLines.length).toBeGreaterThan(0);
36 - for (const line of stdoutLines) {
37 - expect(line).toBe('1.2.3-test');
38 - }
32 + expect(stdoutLines).toEqual(['1.2.3-test']);
33 })
34 );
35 });
ts/packages/cli/test/src/config/telemetry.test.ts
+15 -11
@@ -18,18 +18,22 @@ describe('TELEMETRY_CONFIG', () => {
18 })
19 );
20
21 - it.effect('[Given] any opt-out, CI, or a test run [Then] telemetry is disabled', () =>
21 + it.effect.each([
22 + { name: 'COMPOSIO_CLI_TELEMETRY_DISABLED', value: 'yes' },
23 + { name: 'COMPOSIO_DISABLE_TELEMETRY', value: 'true' },
24 + { name: 'TELEMETRY_DISABLED', value: '1' },
25 + { name: 'CI', value: 'true' },
26 + { name: 'NODE_ENV', value: 'test' },
27 + ])(
28 + '[Given] an opt-out, CI, or a test run ($name=$value) [Then] telemetry is disabled',
29 + ({ name, value }) =>
30 + Effect.gen(function* () {
31 + deepStrictEqual((yield* read({ [name]: value })).DISABLED, true);
32 + })
33 + );
34 +
35 + it.effect('[Given] CI off outside a test run [Then] telemetry stays on', () =>
36 Effect.gen(function* () {
23 - const optOuts: ReadonlyArray<Record<string, string>> = [
24 - { COMPOSIO_CLI_TELEMETRY_DISABLED: 'yes' },
25 - { COMPOSIO_DISABLE_TELEMETRY: 'true' },
26 - { TELEMETRY_DISABLED: '1' },
27 - { CI: 'true' },
28 - { NODE_ENV: 'test' },
29 - ];
30 - for (const env of optOuts) {
31 - deepStrictEqual((yield* read(env)).DISABLED, true, JSON.stringify(env));
32 - }
37 deepStrictEqual((yield* read({ CI: 'false', NODE_ENV: 'development' })).DISABLED, false);
38 })
39 );
ts/packages/cli/test/src/effects/compare-semver.test.ts
+10 -15
@@ -270,24 +270,19 @@ describe('compare-semver.ts', () => {
270 describe('Array.sort Compatibility', () => {
271 it.effect('should work as Array.sort comparator for ascending order', () =>
272 Effect.gen(function* () {
273 - const versions = ['2.0.0', '1.0.0', '3.0.0'];
274 - const comparisons: Array<{ versions: [string, string]; result: number }> = [];
275 -
276 - // Simulate Array.sort behavior
277 - for (let i = 0; i < versions.length - 1; i++) {
278 - for (let j = i + 1; j < versions.length; j++) {
279 - const result = yield* semverComparator(versions[i], versions[j]);
280 - comparisons.push({ versions: [versions[i], versions[j]], result });
281 - }
282 - }
273 + const pairs = [
274 + ['2.0.0', '1.0.0'],
275 + ['2.0.0', '3.0.0'],
276 + ['1.0.0', '3.0.0'],
277 + ] as const;
278
279 // Since we can't actually use the Effect in Array.sort, verify each
280 // 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 - ]);
281 + const results = yield* Effect.forEach(pairs, ([left, right]) =>
282 + semverComparator(left, right)
283 + );
284 +
285 + expect(results).toEqual([1, -1, -1]);
286 })
287 );
288 });
ts/packages/cli/test/src/effects/generation-runtime.test.ts
+26 -29
@@ -1,5 +1,5 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { Cause, Effect, Exit } from 'effect';
2 +import { Cause, Effect } from 'effect';
3 import { generationOutcome } from 'src/effects/generation-runtime';
4 import {
5 GenerateTypeFromJsonSchemaError,
@@ -26,19 +26,20 @@ const foreign = <E extends Error & { readonly _tag: string }>(error: E): E => {
26
27 describe('generation-runtime', () => {
28 describe('rehydrateGenerationError', () => {
29 - it('rebuilds each error as an instance of the CLI class, keeping fields and stack', () => {
30 - const cases = [
31 - new SafeOutputPathError({
32 - filename: '../x.ts',
33 - outputDir: '/out',
34 - resolvedPath: '/x.ts',
35 - message: 'escapes',
36 - }),
37 - new TypeScriptTranspileError({ message: 'compile failed', cause: 'TS1005' }),
38 - new GenerateTypeFromJsonSchemaError({ message: 'bad schema', cause: new Error('inner') }),
39 - ] as const;
29 + const cases = [
30 + new SafeOutputPathError({
31 + filename: '../x.ts',
32 + outputDir: '/out',
33 + resolvedPath: '/x.ts',
34 + message: 'escapes',
35 + }),
36 + new TypeScriptTranspileError({ message: 'compile failed', cause: 'TS1005' }),
37 + new GenerateTypeFromJsonSchemaError({ message: 'bad schema', cause: new Error('inner') }),
38 + ] as const;
39
41 - for (const original of cases) {
40 + it.each(cases)(
41 + 'rebuilds $_tag as an instance of the CLI class, keeping fields and stack',
42 + original => {
43 const crossed = foreign(original);
44 expect(crossed).not.toBeInstanceOf(original.constructor);
45
@@ -48,7 +49,7 @@ describe('generation-runtime', () => {
49 expect(rehydrated.message).toBe(original.message);
50 expect(rehydrated.stack).toBe(original.stack);
51 }
51 - });
52 + );
53 });
54
55 describe('generationOutcome', () => {
@@ -64,29 +65,25 @@ describe('generation-runtime', () => {
65 it.effect('lifts a failure outcome to a typed failure of the CLI error class', () =>
66 Effect.gen(function* () {
67 const error = new TypeScriptTranspileError({ message: 'compile failed', cause: 'TS1005' });
67 - const exit = yield* Effect.exit(
68 - generationOutcome(() => Promise.resolve({ _tag: 'Failure' as const, error }))
69 - );
68 + const failure = yield* generationOutcome(() =>
69 + Promise.resolve({ _tag: 'Failure' as const, error })
70 + ).pipe(Effect.flip);
71
71 - expect(Exit.isFailure(exit)).toBe(true);
72 - if (Exit.isFailure(exit)) {
73 - const failure = Cause.squash(exit.cause);
74 - expect(failure).toBeInstanceOf(TypeScriptTranspileError);
75 - expect((failure as TypeScriptTranspileError).cause).toBe('TS1005');
76 - }
72 + expect(failure).toBeInstanceOf(TypeScriptTranspileError);
73 + expect(failure.cause).toBe('TS1005');
74 })
75 );
76
77 it.effect('keeps a rejected promise (a defect in the pipeline) as a defect', () =>
78 Effect.gen(function* () {
79 const boom = new Error('boom');
83 - const exit = yield* Effect.exit(generationOutcome<number>(() => Promise.reject(boom)));
80 + const cause = yield* generationOutcome<number>(() => Promise.reject(boom)).pipe(
81 + Effect.sandbox,
82 + Effect.flip
83 + );
84
85 - expect(Exit.isFailure(exit)).toBe(true);
86 - if (Exit.isFailure(exit)) {
87 - expect(Cause.hasDies(exit.cause)).toBe(true);
88 - expect(Cause.squash(exit.cause)).toBe(boom);
89 - }
85 + expect(Cause.hasDies(cause)).toBe(true);
86 + expect(Cause.squash(cause)).toBe(boom);
87 })
88 );
89 });
ts/packages/cli/test/src/effects/install-skill.test.ts
+6 -20
@@ -1,14 +1,5 @@
1 import { describe, expect, it, vi } from '@effect/vitest';
2 -import {
3 - Config,
4 - ConfigProvider,
5 - Effect,
6 - Exit,
7 - FileSystem,
8 - Layer,
9 - Path,
10 - PlatformError,
11 -} from 'effect';
2 +import { Config, ConfigProvider, Effect, FileSystem, Layer, Path, PlatformError } from 'effect';
3 import { FetchHttpClient, HttpClient } from 'effect/http';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
@@ -362,10 +353,7 @@ describe('install-skill', () => {
353 );
354
355 expect(error).toBeInstanceOf(CliReleaseResolutionError);
365 - if (error instanceof CliReleaseResolutionError) {
366 - expect(error.reason).toBe('decode');
367 - expect(error.cause).toBeDefined();
368 - }
356 + expect(error).toMatchObject({ reason: 'decode', cause: expect.anything() });
357 })
358 );
359
@@ -380,10 +368,7 @@ describe('install-skill', () => {
368 const error = yield* Effect.flip(makeInstallEffect(home, apiBaseUrl));
369
370 expect(error).toBeInstanceOf(SkillInstallError);
383 - if (error instanceof SkillInstallError) {
384 - expect(error.phase).toBe('release');
385 - expect(error.cause).toBeDefined();
386 - }
371 + expect(error).toMatchObject({ phase: 'release', cause: expect.anything() });
372 })
373 );
374
@@ -413,9 +398,10 @@ describe('install-skill', () => {
398 Effect.gen(function* () {
399 const apiBaseUrl = yield* startSkillReleaseServer(new TextEncoder().encode('not a zip'));
400 const home = tempy.temporaryDirectory();
416 - const exit = yield* Effect.exit(makeInstallEffect(home, apiBaseUrl));
401 + const error = yield* Effect.flip(makeInstallEffect(home, apiBaseUrl));
402
418 - expect(Exit.isFailure(exit)).toBe(true);
403 + expect(error).toBeInstanceOf(SkillInstallError);
404 + expect(error).toMatchObject({ phase: 'extract' });
405
406 const fs = yield* FileSystem.FileSystem;
407 const path = yield* Path.Path;
ts/packages/cli/test/src/effects/toolkit-from-tool-slug.test.ts
+19 -10
@@ -55,6 +55,19 @@ const learnedFileContent = (slugs: ReadonlyArray<string>, daysAgo = 0) =>
55 refreshedAt: DateTime.formatIso(DateTime.subtract(DateTime.nowUnsafe(), { days: daysAgo })),
56 });
57
58 +/**
59 + * A project catalog that lists each named project's toolkits. Unscoped
60 + * lookups, and projects it does not name, list nothing.
61 + */
62 +const projectCatalog =
63 + (toolkitsByProject: Readonly<Record<string, ReadonlyArray<string>>>) =>
64 + (scope?: ToolkitProjectScope) =>
65 + Effect.succeed(
66 + Object.entries(toolkitsByProject)
67 + .filter(([projectId]) => projectId === scope?.projectId)
68 + .flatMap(([, slugs]) => slugs.map(slug => makeToolkitFixture(slug)))
69 + );
70 +
71 interface ResolverOptions {
72 readonly getToolkits?: () => Effect.Effect<Toolkits, GetToolkitsError>;
73 readonly getProjectToolkits?: (
@@ -360,15 +373,13 @@ describe('toolkitFromToolSlug', () => {
373 )
374 );
375
363 - for (const learned of ['custom_grain', 'custom_grain_search_persons']) {
364 - it.live(`uses the active project's prefix instead of learned ${learned}`, () =>
376 + it.live.each(['custom_grain', 'custom_grain_search_persons'])(
377 + "uses the active project's prefix instead of learned %s",
378 + learned =>
379 withResolver(
380 {
381 seedLearnedFile: learnedFileContent([learned]),
368 - getProjectToolkits: scope =>
369 - Effect.succeed(
370 - scope?.projectId === 'proj_b' ? [makeToolkitFixture('custom_grain_search')] : []
371 - ),
382 + getProjectToolkits: projectCatalog({ proj_b: ['custom_grain_search'] }),
383 },
384 () =>
385 Effect.gen(function* () {
@@ -386,8 +397,7 @@ describe('toolkitFromToolSlug', () => {
397 ).toBe('custom');
398 })
399 )
389 - );
390 - }
400 + );
401
402 it.live('keeps a scoped discovery when an older background fetch completes later', () =>
403 Effect.gen(function* () {
@@ -556,8 +566,7 @@ describe('toolkitFromToolSlug', () => {
566 it.live('learns a custom toolkit found by a scoped lookup after an unscoped one', () =>
567 withResolver(
568 {
559 - getProjectToolkits: scope =>
560 - Effect.succeed(scope ? [makeToolkitFixture(CUSTOM_TOOLKIT)] : []),
569 + getProjectToolkits: projectCatalog({ proj_1: [CUSTOM_TOOLKIT] }),
570 seedLearnedFile: learnedFileContent([]),
571 },
572 ({ waitForLearnedFile }) =>
ts/packages/cli/test/src/services/agents.test.ts
+5 -4
@@ -76,10 +76,11 @@ describe('agent service response boundaries', () => {
76 const error = yield* fetchAgentInbox({ agentKey: 'expired_key' }).pipe(Effect.flip);
77
78 expect(error).toBeInstanceOf(AgentRequestError);
79 - if (!(error instanceof AgentRequestError)) return;
80 - expect(error.message).toBe('Agent key expired');
81 - expect(error.status).toBe(401);
82 - expect(error.pathname).toBe('/api/mail?limit=50');
79 + expect(error).toMatchObject({
80 + message: 'Agent key expired',
81 + status: 401,
82 + pathname: '/api/mail?limit=50',
83 + });
84 })
85 );
86 });
ts/packages/cli/test/src/services/cli-session-artifacts.test.ts
+9 -24
@@ -75,12 +75,8 @@ describe('CLI session artifacts', () => {
75 name: 'github issue output',
76 extension: '.json',
77 directoryPath,
78 - });
78 + }).pipe(Effect.flatMap(Effect.fromNullishOr));
79
80 - expect(filePath).toBeDefined();
81 - if (filePath === undefined) {
82 - return yield* Effect.die('Expected the session artifact to be stored');
83 - }
80 expect(path.dirname(filePath)).toBe(directoryPath);
81 expect(path.basename(filePath)).toMatch(/^github_issue_output_[a-f0-9]{8}\.json$/i);
82 expect(yield* fs.readFileString(filePath)).toBe('{"ok":true}');
@@ -111,12 +107,8 @@ describe('CLI session artifacts', () => {
107 const filePath = yield* storeCliSessionArtifact({
108 contents: '{}',
109 name: 'adhoc output',
114 - });
110 + }).pipe(Effect.flatMap(Effect.fromNullishOr));
111
116 - expect(filePath).toBeDefined();
117 - if (filePath === undefined) {
118 - return yield* Effect.die('Expected an adhoc artifact');
119 - }
112 const directoryPath = path.dirname(filePath);
113 expect(path.dirname(directoryPath)).toBe(artifactsRoot);
114 expect(path.basename(directoryPath)).toMatch(/^adhoc_[a-f0-9]{12}$/i);
@@ -140,12 +132,8 @@ describe('CLI session artifacts', () => {
132 contents: '{"session":true}',
133 name: 'session output',
134 ...sessionScope,
143 - });
135 + }).pipe(Effect.flatMap(Effect.fromNullishOr));
136
145 - expect(filePath).toBeDefined();
146 - if (filePath === undefined) {
147 - return yield* Effect.die('Expected a session-backed artifact');
148 - }
137 const directoryPath = path.dirname(filePath);
138 expect(path.dirname(directoryPath)).toBe(artifactsRoot);
139 expect(path.basename(directoryPath)).toMatch(/^cli_s_[a-z0-9]+_[a-f0-9]{10}$/i);
@@ -160,19 +148,16 @@ describe('CLI session artifacts', () => {
148
149 yield* appendCliSessionHistory({ entry: { sequence: 1 }, ...sessionScope });
150 yield* appendCliSessionHistory({ entry: { sequence: 2 }, ...sessionScope });
163 - const artifacts = yield* resolveCliSessionArtifacts(sessionScope);
164 -
165 - expect(Option.isSome(artifacts)).toBe(true);
166 - if (Option.isNone(artifacts)) {
167 - return yield* Effect.die('Expected session artifacts');
168 - }
169 - const lines = (yield* fs.readFileString(artifacts.value.historyFilePath, 'utf8'))
151 + const artifacts = yield* resolveCliSessionArtifacts(sessionScope).pipe(
152 + Effect.flatMap(Effect.fromOption)
153 + );
154 + const lines = (yield* fs.readFileString(artifacts.historyFilePath, 'utf8'))
155 .trim()
156 .split('\n')
157 .map(line => JSON.parse(line) as { sessionId: string; sequence: number });
158 expect(lines).toEqual([
174 - expect.objectContaining({ sessionId: artifacts.value.sessionId, sequence: 1 }),
175 - expect.objectContaining({ sessionId: artifacts.value.sessionId, sequence: 2 }),
159 + expect.objectContaining({ sessionId: artifacts.sessionId, sequence: 1 }),
160 + expect.objectContaining({ sessionId: artifacts.sessionId, sequence: 2 }),
161 ]);
162 })
163 );
ts/packages/cli/test/src/services/cli-user-config.test.ts
+49 -52
@@ -55,14 +55,13 @@ describe('ComposioCliUserConfig', () => {
55 );
56
57 return Effect.gen(function* () {
58 - try {
59 - const config = yield* ComposioCliUserConfig;
60 - assertEquals(config.channel, 'beta');
61 - assertEquals(config.isExperimentalFeatureEnabled('listen'), true);
62 - } finally {
63 - execPathSpy.mockRestore();
64 - }
65 - }).pipe(Effect.provide(CliUserConfigTest));
58 + const config = yield* ComposioCliUserConfig;
59 + assertEquals(config.channel, 'beta');
60 + assertEquals(config.isExperimentalFeatureEnabled('listen'), true);
61 + }).pipe(
62 + Effect.provide(CliUserConfigTest),
63 + Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore()))
64 + );
65 });
66
67 it.effect('defaults experimental features on in beta releases', () => {
@@ -235,52 +234,50 @@ describe('ComposioCliUserConfig', () => {
234 }).pipe(Effect.provide(CliUserConfigTest));
235 });
236
238 - for (const storedSubagent of [{ target: 'gemini' }, null]) {
239 - it.effect(
240 - `ignores a stored experimental_subagent of ${JSON.stringify(storedSubagent)} and writes it back unchanged`,
241 - () => {
242 - const cwd = tempy.temporaryDirectory();
243 - const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
244 - fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
245 - fs.writeFileSync(
246 - path.join(cwd, '.composio', 'config.json'),
247 - JSON.stringify({
248 - developer: { enabled: false, destructive_actions: true },
249 - experimental_subagent: storedSubagent,
250 - security: 'json',
251 - })
252 - );
237 + it.effect.each([{ storedSubagent: { target: 'gemini' } }, { storedSubagent: null }])(
238 + 'ignores a stored experimental_subagent of $storedSubagent and writes it back unchanged',
239 + ({ storedSubagent }) => {
240 + const cwd = tempy.temporaryDirectory();
241 + const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
242 + fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
243 + fs.writeFileSync(
244 + path.join(cwd, '.composio', 'config.json'),
245 + JSON.stringify({
246 + developer: { enabled: false, destructive_actions: true },
247 + experimental_subagent: storedSubagent,
248 + security: 'json',
249 + })
250 + );
251
254 - const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
255 - const CliUserConfigTest = Layer.provideMerge(
256 - ComposioCliUserConfigLive,
257 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
258 - );
252 + const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
253 + const CliUserConfigTest = Layer.provideMerge(
254 + ComposioCliUserConfigLive,
255 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
256 + );
257
260 - return Effect.gen(function* () {
261 - const fileSystem = yield* FileSystem.FileSystem;
262 - const config = yield* ComposioCliUserConfig;
263 - assertEquals(config.data.developerModeEnabled, false);
264 - assertEquals(config.data.developerDangerousCommandsEnabled, true);
265 - assertEquals(config.data.security, 'json');
266 -
267 - yield* config.update({ experimentalFeatures: { listen: true } });
268 -
269 - const persisted = yield* fileSystem.readFileString(
270 - path.join(cwd, '.composio', 'config.json'),
271 - 'utf8'
272 - );
273 - const parsed = JSON.parse(persisted) as Record<string, unknown>;
274 -
275 - assertEquals(parsed.developer, { enabled: false, destructive_actions: true });
276 - assertEquals(parsed.security, 'json');
277 - assertEquals(parsed.experimental_features, { listen: true });
278 - assertEquals('experimental_subagent' in parsed, true);
279 - assertEquals(parsed.experimental_subagent, storedSubagent);
280 - }).pipe(Effect.provide(CliUserConfigTest));
281 - }
282 - );
283 - }
258 + return Effect.gen(function* () {
259 + const fileSystem = yield* FileSystem.FileSystem;
260 + const config = yield* ComposioCliUserConfig;
261 + assertEquals(config.data.developerModeEnabled, false);
262 + assertEquals(config.data.developerDangerousCommandsEnabled, true);
263 + assertEquals(config.data.security, 'json');
264 +
265 + yield* config.update({ experimentalFeatures: { listen: true } });
266 +
267 + const persisted = yield* fileSystem.readFileString(
268 + path.join(cwd, '.composio', 'config.json'),
269 + 'utf8'
270 + );
271 + const parsed = JSON.parse(persisted) as Record<string, unknown>;
272 +
273 + assertEquals(parsed.developer, { enabled: false, destructive_actions: true });
274 + assertEquals(parsed.security, 'json');
275 + assertEquals(parsed.experimental_features, { listen: true });
276 + assertEquals('experimental_subagent' in parsed, true);
277 + assertEquals(parsed.experimental_subagent, storedSubagent);
278 + }).pipe(Effect.provide(CliUserConfigTest));
279 + }
280 + );
281
282 it.effect('replaces malformed persisted config with safe defaults', () => {
283 const cwd = tempy.temporaryDirectory();
ts/packages/cli/test/src/services/command-hints.test.ts
+4 -6
@@ -9,13 +9,11 @@ import {
9
10 describe('command-hints', () => {
11 it('has no dangling linked command ids', () => {
12 - const ids = new Set(Record.keys(COMMAND_HINTS));
12 + const ids = Record.keys(COMMAND_HINTS);
13 + const linkedIds = ids.flatMap(id => commandHintLinks(id));
14
14 - for (const id of ids) {
15 - for (const linkedId of commandHintLinks(id)) {
16 - expect(ids.has(linkedId)).toBe(true);
17 - }
18 - }
15 + expect(linkedIds.length).toBeGreaterThan(0);
16 + expect(ids).toEqual(expect.arrayContaining(linkedIds));
17 });
18
19 it('renders examples from the registry', () => {
ts/packages/cli/test/src/services/command-project.test.ts
+4 -4
@@ -171,10 +171,10 @@ describe('resolveCommandProject', () => {
171 Effect.flip,
172 Effect.forkChild
173 );
174 - for (let step = 0; step < 100 && fiber.pollUnsafe() === undefined; step++) {
175 - yield* Effect.yieldNow;
176 - yield* TestClock.adjust('1 minute');
177 - }
174 + yield* Effect.yieldNow.pipe(
175 + Effect.andThen(TestClock.adjust('1 minute')),
176 + Effect.repeat({ until: () => fiber.pollUnsafe() !== undefined, times: 100 })
177 + );
178 expect(fiber.pollUnsafe()).toBeDefined();
179 const error = yield* Fiber.join(fiber);
180
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+1 -3
@@ -240,9 +240,7 @@ describe('ComposioClientSingleton headers', () => {
240 expect(headers.has('x-extra')).toBe(false);
241 expect(headers.has('x-user-api-key')).toBe(false);
242 expect(headers.has('x-api-key')).toBe(false);
243 - for (const spy of consoleSpies) {
244 - expect(spy).not.toHaveBeenCalled();
245 - }
243 + expect(consoleSpies.flatMap(spy => spy.mock.calls)).toEqual([]);
244 }).pipe(
245 Effect.provide(
246 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
ts/packages/cli/test/src/services/composio-clients.test.ts
+5 -8
@@ -358,8 +358,9 @@ describe('composio-clients', () => {
358 });
359
360 describe('repository request core', () => {
361 - for (const method of ['getToolkits', 'getTools', 'getTriggerTypes'] as const) {
362 - it.effect(`${method} aborts an in-flight pagination request when interrupted`, () =>
361 + it.effect.each(['getToolkits', 'getTools', 'getTriggerTypes'] as const)(
362 + '%s aborts an in-flight pagination request when interrupted',
363 + method =>
364 Effect.gen(function* () {
365 const started = Promise.withResolvers<AbortSignal>();
366 const fetchSpy = vi
@@ -383,8 +384,7 @@ describe('composio-clients', () => {
384 expect(requestSignal.aborted).toBe(true);
385 expect(fetchSpy).toHaveBeenCalledTimes(2);
386 }).pipe(Effect.provide(withRepository))
386 - );
387 - }
387 + );
388
389 it.effect('fetches every toolkit page, sorted by slug, and counts each request', () =>
390 Effect.gen(function* () {
@@ -731,10 +731,7 @@ describe('ComposioToolkitsRepository toolkit lists', () => {
731
732 const requestOf = (fetchSpy: ReturnType<typeof spyOnToolkitsFetch>) => {
733 const [input, init] = fetchSpy.mock.calls[0]!;
734 - const url = new URL(input instanceof Request ? input.url : String(input));
735 - const headers = new Headers(input instanceof Request ? input.headers : undefined);
736 - new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
737 - return { url, headers };
734 + return { url: new URL(String(input)), headers: new Headers(init?.headers) };
735 };
736
737 it.effect(
ts/packages/cli/test/src/services/project-environment-detector.test.ts
+12 -28
@@ -1,7 +1,7 @@
1 import path from 'node:path';
2 import * as tempy from 'tempy';
3 import { describe, expect, layer, assert } from '@effect/vitest';
4 -import { beforeAll, afterAll } from 'vitest';
4 +import { beforeEach, vi } from 'vitest';
5 import { ConfigProvider, Effect, Layer, Result } from 'effect';
6 import { liveEnvConfigProvider } from 'test/__utils__';
7 import * as FileSystem from 'effect/FileSystem';
@@ -25,19 +25,9 @@ const writeFile = (fs: FileSystem.FileSystem, filePath: string, content: string)
25 });
26
27 describe('ProjectEnvironmentDetector', () => {
28 - let savedUserAgent: string | undefined;
29 -
30 - beforeAll(() => {
31 - savedUserAgent = process.env.npm_config_user_agent;
32 - delete process.env.npm_config_user_agent;
33 - });
34 -
35 - afterAll(() => {
36 - if (savedUserAgent !== undefined) {
37 - process.env.npm_config_user_agent = savedUserAgent;
38 - } else {
39 - delete process.env.npm_config_user_agent;
40 - }
28 + // `unstubEnvs` in the Vitest config restores the inherited value after each test.
29 + beforeEach(() => {
30 + vi.stubEnv('npm_config_user_agent', undefined);
31 });
32
33 describe('detectProjectEnvironment', () => {
@@ -347,13 +337,10 @@ describe('ProjectEnvironmentDetector', () => {
337 const detector = yield* ProjectEnvironmentDetector;
338 const cwd = tempy.temporaryDirectory();
339
350 - process.env.npm_config_user_agent = 'pnpm/9.15.0 npm/? node/v20.11.0';
351 - try {
352 - const result = yield* detector.detectJsPackageManager(cwd);
353 - expect(result).toBe('pnpm');
354 - } finally {
355 - delete process.env.npm_config_user_agent;
356 - }
340 + vi.stubEnv('npm_config_user_agent', 'pnpm/9.15.0 npm/? node/v20.11.0');
341 +
342 + const result = yield* detector.detectJsPackageManager(cwd);
343 + expect(result).toBe('pnpm');
344 })
345 );
346
@@ -364,13 +351,10 @@ describe('ProjectEnvironmentDetector', () => {
351 const detector = yield* ProjectEnvironmentDetector;
352 const cwd = tempy.temporaryDirectory();
353
367 - process.env.npm_config_user_agent = 'bun/1.1.0';
368 - try {
369 - const result = yield* detector.detectJsPackageManager(cwd);
370 - expect(result).toBe('bun');
371 - } finally {
372 - delete process.env.npm_config_user_agent;
373 - }
354 + vi.stubEnv('npm_config_user_agent', 'bun/1.1.0');
355 +
356 + const result = yield* detector.detectJsPackageManager(cwd);
357 + expect(result).toBe('bun');
358 })
359 );
360 });
ts/packages/cli/test/src/services/run-companion-modules.test.ts
+15 -9
@@ -43,6 +43,16 @@ const writeLiveCompanions = (installDirectory: string) => {
43 }
44 };
45
46 +// What an install upgraded from an older release still holds: every legacy
47 +// placeholder, empty.
48 +const writeLegacyPlaceholders = (installDirectory: string) => {
49 + for (const relativePath of RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS) {
50 + const filePath = path.join(installDirectory, relativePath);
51 + fs.mkdirSync(path.dirname(filePath), { recursive: true });
52 + fs.writeFileSync(filePath, '');
53 + }
54 +};
55 +
56 const stubRepairFetch = () => {
57 const fetchMock = vi.fn((url: string) =>
58 Promise.resolve(
@@ -149,11 +159,7 @@ describe('run-companion-modules', () => {
159 const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-legacy-'));
160 const execPath = path.join(installDirectory, 'composio');
161 writeLiveCompanions(installDirectory);
152 - for (const relativePath of RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS) {
153 - const filePath = path.join(installDirectory, relativePath);
154 - fs.mkdirSync(path.dirname(filePath), { recursive: true });
155 - fs.writeFileSync(filePath, '');
156 - }
162 + writeLegacyPlaceholders(installDirectory);
163 const fetchMock = stubRepairFetch();
164
165 return yield* Effect.gen(function* () {
@@ -407,8 +413,8 @@ describe('run-companion-modules', () => {
413 }).pipe(Effect.flip);
414
415 expect(fetchMock).toHaveBeenCalledOnce();
410 - const requestUrl = String(fetchMock.mock.calls[0]?.[0]);
411 - expect(requestUrl).toBe(
416 + const [[requestUrl]] = fetchMock.mock.calls;
417 + expect(String(requestUrl)).toBe(
418 'https://github-proxy.test/repos/fork-owner/fork-repo/releases/tags/%40composio%2Fcli%409.9.9-test'
419 );
420 }).pipe(
@@ -450,8 +456,8 @@ describe('run-companion-modules', () => {
456 }).pipe(Effect.flip);
457
458 expect(fetchMock).toHaveBeenCalledOnce();
453 - const requestUrl = String(fetchMock.mock.calls[0]?.[0]);
454 - expect(requestUrl).toBe(
459 + const [[requestUrl]] = fetchMock.mock.calls;
460 + expect(String(requestUrl)).toBe(
461 'https://prefixed-proxy.test/repos/ComposioHQ/composio/releases/tags/%40composio%2Fcli%408.8.8-test'
462 );
463 }).pipe(
ts/packages/cli/test/src/services/run-helpers-runtime.test.ts
+43 -52
@@ -21,9 +21,7 @@ const originalGlobalDescriptors = new Map(
21
22 const readInstalledFunction = (name: string): ((...args: ReadonlyArray<unknown>) => unknown) => {
23 const value: unknown = Reflect.get(globalThis, name);
24 - if (typeof value !== 'function') {
25 - throw new Error(`installRunHelpers() did not install ${name}().`);
26 - }
24 + assert(typeof value === 'function', `installRunHelpers() did not install ${name}().`);
25 return (...args) => Reflect.apply(value, undefined, [...args]);
26 };
27
@@ -59,9 +57,10 @@ describe('run-helpers-runtime', () => {
57 it('[Given] installed helpers [Then] every documented global is defined', async () => {
58 await installRunHelpers({ cliPrefix: ['composio'] });
59
62 - for (const name of ['execute', 'search', 'proxy', 'experimental_subAgent', 'invokeAgent']) {
63 - expect(typeof Reflect.get(globalThis, name)).toBe('function');
64 - }
60 + const helperNames = ['execute', 'search', 'proxy', 'experimental_subAgent', 'invokeAgent'];
61 + expect(helperNames.map(name => typeof Reflect.get(globalThis, name))).toEqual(
62 + helperNames.map(() => 'function')
63 + );
64 expect(Reflect.get(globalThis, 'z')).toBeDefined();
65 expect(Reflect.get(globalThis, 'zod')).toBe(Reflect.get(globalThis, 'z'));
66 });
@@ -69,32 +68,32 @@ describe('run-helpers-runtime', () => {
68 it('[Given] experimental_subAgent or invokeAgent [Then] both reject with the same removal message and alternative', async () => {
69 await installRunHelpers({ cliPrefix: ['composio'] });
70
72 - const outcomes = await Promise.allSettled([
71 + const [subAgent, invokeAgent] = await Promise.allSettled([
72 readInstalledFunction('experimental_subAgent')('p'),
73 readInstalledFunction('invokeAgent')('p'),
74 ]);
75
77 - const messages = outcomes.map(outcome =>
78 - outcome.status === 'rejected' && outcome.reason instanceof Error
79 - ? outcome.reason.message
80 - : undefined
81 - );
82 - expect(outcomes.map(outcome => outcome.status)).toEqual(['rejected', 'rejected']);
83 - expect(messages[0]).toContain('removed');
84 - expect(messages[0]).toContain('automatically approved permission requests');
85 - expect(messages[0]).toContain('let the calling agent summarize');
86 - expect(messages[1]).toBe(messages[0]);
76 + assert(subAgent?.status === 'rejected' && subAgent.reason instanceof Error);
77 + expect(subAgent.reason.message).toContain('removed');
78 + expect(subAgent.reason.message).toContain('automatically approved permission requests');
79 + expect(subAgent.reason.message).toContain('let the calling agent summarize');
80 + expect(invokeAgent).toMatchObject({
81 + status: 'rejected',
82 + reason: { message: subAgent.reason.message },
83 + });
84 });
85
89 - it('[Given] any arguments, including none [Then] experimental_subAgent rejects instead of throwing', async () => {
86 + it.each([
87 + { name: 'no arguments', args: [] },
88 + { name: 'a prompt and options', args: ['p', { target: 'codex' }] },
89 + { name: 'arbitrary extra arguments', args: [42, null, 'extra'] },
90 + ])('[Given] $name [Then] experimental_subAgent rejects instead of throwing', async ({ args }) => {
91 await installRunHelpers({ cliPrefix: ['composio'] });
91 - const subAgent = readInstalledFunction('experimental_subAgent');
92
93 - for (const args of [[], ['p', { target: 'codex' }], [42, null, 'extra']]) {
94 - const returned = subAgent(...args);
95 - expect(returned).toBeInstanceOf(Promise);
96 - await expect(returned).rejects.toThrow(/removed/);
97 - }
93 + const returned = readInstalledFunction('experimental_subAgent')(...args);
94 +
95 + expect(returned).toBeInstanceOf(Promise);
96 + await expect(returned).rejects.toThrow(/removed/);
97 });
98
99 it('[Given] a malformed proxy session response [Then] it rejects the HTTP boundary payload', async () => {
@@ -117,13 +116,11 @@ describe('run-helpers-runtime', () => {
116 });
117
118 const installedGlobals: unknown = globalThis;
120 - expect(Predicate.hasProperty(installedGlobals, 'proxy')).toBe(true);
121 - if (
122 - !Predicate.hasProperty(installedGlobals, 'proxy') ||
123 - typeof installedGlobals.proxy !== 'function'
124 - ) {
125 - throw new Error('installRunHelpers() did not install proxy().');
126 - }
119 + assert(
120 + Predicate.hasProperty(installedGlobals, 'proxy') &&
121 + typeof installedGlobals.proxy === 'function',
122 + 'installRunHelpers() did not install proxy().'
123 + );
124
125 await expect(installedGlobals.proxy('github')).rejects.toThrow(/session_id/);
126 expect(fetchMock).toHaveBeenCalledOnce();
@@ -279,13 +276,11 @@ describe('run-helpers-runtime', () => {
276 });
277
278 const installedGlobals: unknown = globalThis;
282 - expect(Predicate.hasProperty(installedGlobals, 'proxy')).toBe(true);
283 - if (
284 - !Predicate.hasProperty(installedGlobals, 'proxy') ||
285 - typeof installedGlobals.proxy !== 'function'
286 - ) {
287 - throw new Error('installRunHelpers() did not install proxy().');
288 - }
279 + assert(
280 + Predicate.hasProperty(installedGlobals, 'proxy') &&
281 + typeof installedGlobals.proxy === 'function',
282 + 'installRunHelpers() did not install proxy().'
283 + );
284
285 const proxyFetch = await installedGlobals.proxy('github');
286 await expect(proxyFetch('https://api.github.com/user')).rejects.toMatchObject({
@@ -333,13 +328,11 @@ describe('run-helpers-runtime', () => {
328 });
329
330 const installedGlobals: unknown = globalThis;
336 - expect(Predicate.hasProperty(installedGlobals, 'proxy')).toBe(true);
337 - if (
338 - !Predicate.hasProperty(installedGlobals, 'proxy') ||
339 - typeof installedGlobals.proxy !== 'function'
340 - ) {
341 - throw new Error('installRunHelpers() did not install proxy().');
342 - }
331 + assert(
332 + Predicate.hasProperty(installedGlobals, 'proxy') &&
333 + typeof installedGlobals.proxy === 'function',
334 + 'installRunHelpers() did not install proxy().'
335 + );
336
337 const proxyFetch = await installedGlobals.proxy('github');
338 await expect(proxyFetch('https://api.github.com/user')).rejects.toMatchObject({
@@ -373,13 +366,11 @@ describe('run-helpers-runtime', () => {
366 });
367
368 const installedGlobals: unknown = globalThis;
376 - expect(Predicate.hasProperty(installedGlobals, 'search')).toBe(true);
377 - if (
378 - !Predicate.hasProperty(installedGlobals, 'search') ||
379 - typeof installedGlobals.search !== 'function'
380 - ) {
381 - throw new Error('installRunHelpers() did not install search().');
382 - }
369 + assert(
370 + Predicate.hasProperty(installedGlobals, 'search') &&
371 + typeof installedGlobals.search === 'function',
372 + 'installRunHelpers() did not install search().'
373 + );
374
375 await expect(installedGlobals.search('test')).resolves.toMatchObject({
376 successful: true,
ts/packages/cli/test/src/services/running-cli-version.test.ts
+9 -10
@@ -14,14 +14,14 @@ const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
14
15 describe('running CLI version authority', () => {
16 layer(TestPlatform)(it => {
17 - it.effect('uses the compiled version in release builds despite installed tag metadata', () =>
18 - Effect.gen(function* () {
19 - const fs = yield* FileSystem.FileSystem;
20 - const path = yield* Path.Path;
21 - const installDirectory = yield* fs.makeTempDirectoryScoped();
22 - const execPath = path.join(installDirectory, 'composio');
23 -
24 - for (const installedTag of ['@composio/cli@9.9.9', '@composio/cli@0.2.31']) {
17 + it.effect.each(['@composio/cli@9.9.9', '@composio/cli@0.2.31'])(
18 + 'uses the compiled version in release builds despite installed tag metadata (%s)',
19 + installedTag =>
20 + Effect.gen(function* () {
21 + const fs = yield* FileSystem.FileSystem;
22 + const path = yield* Path.Path;
23 + const installDirectory = yield* fs.makeTempDirectoryScoped();
24 + const execPath = path.join(installDirectory, 'composio');
25 yield* fs.writeFileString(
26 path.join(installDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME),
27 installedTag
@@ -31,8 +31,7 @@ describe('running CLI version authority', () => {
31 expect(yield* resolveRunningCliReleaseTag(execPath, '0.3.0', true)).toBe(
32 '@composio/cli@0.3.0'
33 );
34 - }
35 - })
34 + })
35 );
36
37 it.effect('uses the compiled version in a release build without installed metadata', () =>
ts/packages/cli/test/src/services/terminal-ui.test.ts
+20 -30
@@ -3,7 +3,7 @@ import { describe, expect, it, layer } from '@effect/vitest';
3 import { beforeEach, vi } from 'vitest';
4 import * as p from '@clack/prompts';
5 import stringWidth from 'fast-string-width';
6 -import { Array as Arr, Data, Effect, Exit, pipe } from 'effect';
6 +import { Array as Arr, Data, Effect, pipe } from 'effect';
7 import {
8 clampSpinnerMessage,
9 getTerminalCapabilities,
@@ -277,9 +277,7 @@ describe('TerminalUI', () => {
277 expect(frames.length).toBeGreaterThan(0);
278 expect(frames[0]).toContain('New version available: @composio');
279 // A wrapped frame is what leaks lines on every redraw tick.
280 - for (const frame of frames) {
281 - expect(frame).not.toContain('\n');
282 - }
280 + expect(frames).not.toContainEqual(expect.stringContaining('\n'));
281 })
282 )
283 );
@@ -302,9 +300,7 @@ describe('TerminalUI', () => {
300 const frames = clampedFrames(stderr);
301 expect(frames.length).toBeGreaterThan(0);
302 expect(frames[0]).toContain('New version available: @composio');
305 - for (const frame of frames) {
306 - expect(frame).not.toContain('\n');
307 - }
303 + expect(frames).not.toContainEqual(expect.stringContaining('\n'));
304 })
305 )
306 );
@@ -326,10 +322,8 @@ describe('TerminalUI', () => {
322 const frames = clampedFrames(stderr);
323 expect(frames.length).toBeGreaterThan(0);
324 expect(frames[0]).toContain('New version');
329 - for (const frame of frames) {
330 - expect(frame).not.toContain('\n');
331 - expect(stringWidth(frame)).toBeLessThanOrEqual(20);
332 - }
325 + expect(frames).not.toContainEqual(expect.stringContaining('\n'));
326 + expect(Math.max(...frames.map(frame => stringWidth(frame)))).toBeLessThanOrEqual(20);
327 })
328 )
329 );
@@ -351,10 +345,8 @@ describe('TerminalUI', () => {
345 const frames = clampedFrames(stderr);
346 expect(frames.length).toBeGreaterThan(0);
347 expect(frames[0]).toContain('New version');
354 - for (const frame of frames) {
355 - expect(frame).not.toContain('\n');
356 - expect(stringWidth(frame)).toBeLessThanOrEqual(20);
357 - }
348 + expect(frames).not.toContainEqual(expect.stringContaining('\n'));
349 + expect(Math.max(...frames.map(frame => stringWidth(frame)))).toBeLessThanOrEqual(20);
350 })
351 )
352 );
@@ -371,9 +363,7 @@ describe('TerminalUI', () => {
363
364 const frames = clampedFrames(stderr);
365 expect(frames.length).toBeGreaterThan(0);
374 - for (const frame of frames) {
375 - expect(frame).not.toContain('\n');
376 - }
366 + expect(frames).not.toContainEqual(expect.stringContaining('\n'));
367 })
368 )
369 );
@@ -503,11 +493,11 @@ describe('TerminalUI', () => {
493 it.effect('withSpinner propagates errors', () =>
494 Effect.gen(function* () {
495 const ui = yield* TerminalUI;
506 - const exit = yield* Effect.exit(
507 - ui.withSpinner('loading', Effect.fail(new TestFailure({ message: 'network error' })))
508 - );
496 + const failure = yield* ui
497 + .withSpinner('loading', Effect.fail(new TestFailure({ message: 'network error' })))
498 + .pipe(Effect.flip);
499
510 - expect(Exit.isFailure(exit)).toBe(true);
500 + expect(failure).toEqual(new TestFailure({ message: 'network error' }));
501 })
502 );
503
@@ -519,13 +509,13 @@ describe('TerminalUI', () => {
509 Effect.gen(function* () {
510 const ui = yield* TerminalUI;
511
522 - const exit = yield* Effect.exit(
523 - ui.useMakeSpinner('fetching data', _spinner =>
512 + const failure = yield* ui
513 + .useMakeSpinner('fetching data', _spinner =>
514 Effect.fail(new TestFailure({ message: 'API returned 400' }))
515 )
526 - );
516 + .pipe(Effect.flip);
517
528 - expect(Exit.isFailure(exit)).toBe(true);
518 + expect(failure).toEqual(new TestFailure({ message: 'API returned 400' }));
519
520 // The spinner error message should be captured
521 const lines = yield* MockConsole.getLines();
@@ -589,17 +579,17 @@ describe('TerminalUI', () => {
579 Effect.gen(function* () {
580 const ui = yield* TerminalUI;
581
592 - const exit = yield* Effect.exit(
593 - ui.useMakeSpinner('fetching', spinner =>
582 + const failure = yield* ui
583 + .useMakeSpinner('fetching', spinner =>
584 Effect.gen(function* () {
585 // Simulate tapError pattern: callback calls spinner.error(), then the effect fails
586 yield* spinner.error('Login timed out. Please try again.');
587 return yield* new TestFailure({ message: 'timed out' });
588 })
589 )
600 - );
590 + .pipe(Effect.flip);
591
602 - expect(Exit.isFailure(exit)).toBe(true);
592 + expect(failure).toEqual(new TestFailure({ message: 'timed out' }));
593
594 const lines = yield* MockConsole.getLines();
595 // Should see the user's error message
ts/packages/cli/test/src/services/tool-input-validation.test.ts
+10 -8
@@ -3,7 +3,7 @@ import path from 'node:path';
3 import { describe, expect, it } from '@effect/vitest';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import * as BunPath from '@effect/platform-bun/BunPath';
6 -import { ConfigProvider, Effect, Layer } from 'effect';
6 +import { Array as Arr, ConfigProvider, Effect, Layer, Option } from 'effect';
7 import * as tempy from 'tempy';
8 import {
9 getCachedToolInputDefinition,
@@ -151,7 +151,7 @@ describe('tool input validation', () => {
151 definition
152 ).pipe(flipValidationError);
153
154 - expect(error.issues.some(issue => issue.startsWith('recipient_email:'))).toBe(true);
154 + expect(error.issues).toContainEqual(expect.stringMatching(/^recipient_email:/));
155 })
156 );
157
@@ -163,8 +163,8 @@ describe('tool input validation', () => {
163 definition
164 ).pipe(flipValidationError);
165
166 - expect(error.issues.some(issue => issue.startsWith('recipient_email:'))).toBe(true);
167 - expect(error.issues.some(issue => issue.startsWith('subject:'))).toBe(true);
166 + expect(error.issues).toContainEqual(expect.stringMatching(/^recipient_email:/));
167 + expect(error.issues).toContainEqual(expect.stringMatching(/^subject:/));
168 expect(error.issues).toContain(
169 '<root>: Unknown key "recipent_email". Use "recipient_email" instead. Allowed top-level keys: recipient_email, subject, body'
170 );
@@ -173,10 +173,12 @@ describe('tool input validation', () => {
173 });
174
175 describe('free-form object tool inputs', () => {
176 - const freeFormCase = loadObjectCases().find(entry => entry.id === 'nested-free-form-object');
177 - if (!freeFormCase) {
178 - throw new Error('Corpus is missing the nested-free-form-object case');
179 - }
176 + const freeFormCase = Arr.findFirst(
177 + loadObjectCases(),
178 + entry => entry.id === 'nested-free-form-object'
179 + ).pipe(
180 + Option.getOrThrowWith(() => new Error('Corpus is missing the nested-free-form-object case'))
181 + );
182
183 const freeFormDefinition = {
184 schemaPath: '/tmp/METABASE_POST_API_CARD.json',
ts/packages/cli/test/src/services/tool-permissions.test.ts
+18 -20
@@ -162,15 +162,14 @@ describe('tool permissions', () => {
162 },
163 });
164
165 - expect(Option.isSome(decoded)).toBe(true);
166 - if (Option.isSome(decoded)) {
167 - expect(decoded.value).toStrictEqual({
165 + expect(decoded).toStrictEqual(
166 + Option.some({
167 default: 'ask_every_call',
168 overrides: {
169 'GMAIL_SEND_EMAIL:__none__': 'ask_always',
170 },
172 - });
173 - }
171 + })
172 + );
173 });
174
175 it('drops only corrupt cache entries, keeping valid snapshots and allow decisions', () => {
@@ -188,8 +187,10 @@ describe('tool permissions', () => {
187
188 const decoded = decodeCacheFileTolerant(raw);
189
191 - expect(Object.keys(decoded.entries)).toStrictEqual(['good']);
192 - expect(Object.keys(decoded.allowEntries ?? {})).toStrictEqual(['kept']);
190 + expect(decoded).toStrictEqual({
191 + entries: { good },
192 + allowEntries: { kept: { expiresAt: PINNED_NOW + 60_000 } },
193 + });
194 });
195
196 it('returns an empty cache for unparseable cache files', () => {
@@ -269,10 +270,7 @@ describe('tool permissions', () => {
270 }).pipe(Effect.flip);
271
272 expect(failure).toBeInstanceOf(ToolPermissionDeniedError);
272 - if (failure instanceof ToolPermissionDeniedError) {
273 - expect(failure.deniedBy).toBe('permissions');
274 - expect(failure.toolSlug).toBe('GMAIL_SEND_EMAIL');
275 - }
273 + expect(failure).toMatchObject({ deniedBy: 'permissions', toolSlug: 'GMAIL_SEND_EMAIL' });
274 }).pipe(Effect.provide(ToolPermissionsTest))
275 );
276
@@ -286,10 +284,10 @@ describe('tool permissions', () => {
284 }).pipe(Effect.flip);
285
286 expect(failure).toBeInstanceOf(ToolPermissionDeniedError);
289 - if (failure instanceof ToolPermissionDeniedError) {
290 - expect(failure.deniedBy).toBe('permissions');
291 - expect(failure.message).toContain('permission prompts are disabled');
292 - }
287 + expect(failure).toMatchObject({
288 + deniedBy: 'permissions',
289 + message: expect.stringContaining('permission prompts are disabled'),
290 + });
291 }).pipe(Effect.provide(ToolPermissionsTest))
292 );
293
@@ -340,8 +338,8 @@ describe('tool permissions', () => {
338 'GET /api/v3.1/org/consumer/config',
339 'POST /api/v3.1/consumer/permissions/resolve',
340 ]);
343 - expect(snapshot?.enhancedControlsEnabled).toBe(true);
344 - expect(snapshot?.permissions).toEqual({ default: 'allow_all', overrides: {} });
341 + expect(snapshot).toHaveProperty('enhancedControlsEnabled', true);
342 + expect(snapshot).toHaveProperty('permissions', { default: 'allow_all', overrides: {} });
343 }).pipe(Effect.provide(ToolPermissionsTest))
344 );
345
@@ -353,8 +351,8 @@ describe('tool permissions', () => {
351 Effect.provide(stub.layer)
352 );
353
356 - expect(snapshot?.enhancedControlsEnabled).toBe(true);
357 - expect(snapshot?.permissions).toEqual({ default: 'ask_every_call' });
354 + expect(snapshot).toHaveProperty('enhancedControlsEnabled', true);
355 + expect(snapshot).toHaveProperty('permissions', { default: 'ask_every_call' });
356 expect(resolveGateState({ snapshot, toolSlug: 'GMAIL_SEND_EMAIL' })).toBe('ask_every_call');
357 expect(stub.requestErrors()).toMatchObject([
358 {
@@ -377,7 +375,7 @@ describe('tool permissions', () => {
375 Effect.provide(stub.layer)
376 );
377
380 - expect(snapshot?.permissions).toEqual({ default: 'ask_every_call' });
378 + expect(snapshot).toHaveProperty('permissions', { default: 'ask_every_call' });
379 expect(stub.requestErrors()).toMatchObject([
380 { path: '/api/v3.1/consumer/permissions/resolve', cause: { _tag: 'SchemaError' } },
381 ]);
ts/packages/cli/test/src/services/triggers-realtime.listen.test.ts
+13 -7
@@ -97,6 +97,15 @@ describe('TriggersRealtime.listenInProject', () => {
97
98 it.live('authorizes the private channel when the realtime client asks for it', () => {
99 const requests: Array<{ method: string; path: string; body: unknown }> = [];
100 + const responses: Record<string, unknown> = {
101 + '/api/v3.1/cli/realtime/credentials': {
102 + pusher_key: 'pk_test',
103 + pusher_cluster: 'mt1',
104 + project_id: 'pr_nano',
105 + },
106 + // `channel_data` only belongs to presence channels.
107 + '/api/v3.1/cli/realtime/auth': { auth: 'pk_test:signature', channel_data: '{"user_id":"1"}' },
108 + };
109 vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
110 const request = new Request(input, init);
111 const path = new URL(request.url).pathname;
@@ -106,10 +115,7 @@ describe('TriggersRealtime.listenInProject', () => {
115 path,
116 body: text === '' ? undefined : JSON.parse(text),
117 });
109 - return path.endsWith('/credentials')
110 - ? Response.json({ pusher_key: 'pk_test', pusher_cluster: 'mt1', project_id: 'pr_nano' })
111 - : // `channel_data` only belongs to presence channels.
112 - Response.json({ auth: 'pk_test:signature', channel_data: '{"user_id":"1"}' });
118 + return Response.json(responses[path]);
119 });
120
121 return Effect.gen(function* () {
@@ -119,16 +125,16 @@ describe('TriggersRealtime.listenInProject', () => {
125 );
126
127 const constructed = yield* Effect.promise(() => pusher.constructed);
122 - const authorized = yield* Effect.callback<unknown, Error>(resume => {
128 + const authorized = yield* Effect.callback<unknown>(resume => {
129 constructed.authorize(
130 { channelName: 'private-cli-pr_nano', socketId: '123.456' },
125 - (error, data) => resume(error ? Effect.fail(error) : Effect.succeed(data))
131 + (error, data) => resume(Effect.succeed({ error, data }))
132 );
133 });
134 yield* Fiber.interrupt(listening);
135
136 expect(constructed).toMatchObject({ key: 'pk_test', cluster: 'mt1' });
131 - expect(authorized).toEqual({ auth: 'pk_test:signature' });
137 + expect(authorized).toEqual({ error: null, data: { auth: 'pk_test:signature' } });
138 expect(requests).toEqual([
139 { method: 'GET', path: '/api/v3.1/cli/realtime/credentials', body: undefined },
140 {
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+28 -47
@@ -168,6 +168,24 @@ const restoreStubsAndMocks = Effect.sync(() => {
168 vi.restoreAllMocks();
169 });
170
171 +/** Write each companion file of a binary package under `sourceDir` with `contents`. */
172 +const writeCompanionFiles = (
173 + sourceDir: string,
174 + relativePaths: ReadonlyArray<string>,
175 + contents: string
176 +) =>
177 + Effect.gen(function* () {
178 + const fs = yield* FileSystem.FileSystem;
179 + const path = yield* Path.Path;
180 + yield* Effect.forEach(relativePaths, relativePath =>
181 + Effect.gen(function* () {
182 + const companionPath = path.join(sourceDir, relativePath);
183 + yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
184 + yield* fs.writeFileString(companionPath, contents);
185 + })
186 + );
187 + });
188 +
189 describe('UpgradeBinary', () => {
190 it.effect('wraps non-2xx releases fetch failures with fetch context (no tag branch)', () => {
191 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
@@ -185,9 +203,6 @@ describe('UpgradeBinary', () => {
203 ]);
204
205 expect(error).toBeInstanceOf(UpgradeBinaryError);
188 - if (!(error instanceof UpgradeBinaryError)) {
189 - throw error;
190 - }
206 expect(error.message).toBe('Failed to fetch releases from GitHub');
207 expect(String(error.cause)).toContain('HTTP 500');
208 }).pipe(Effect.ensuring(restoreStubsAndMocks));
@@ -210,9 +225,6 @@ describe('UpgradeBinary', () => {
225 ]);
226
227 expect(error).toBeInstanceOf(UpgradeBinaryError);
213 - if (!(error instanceof UpgradeBinaryError)) {
214 - throw error;
215 - }
228 expect(error.message).toBe('Failed to parse GitHub release JSON response');
229 }).pipe(Effect.ensuring(restoreStubsAndMocks));
230 });
@@ -234,20 +246,17 @@ describe('UpgradeBinary', () => {
246 ]);
247
248 expect(error).toBeInstanceOf(UpgradeBinaryError);
237 - if (!(error instanceof UpgradeBinaryError)) {
238 - throw error;
239 - }
249 expect(error.message).toBe('Failed to parse GitHub release JSON response');
250 }).pipe(Effect.ensuring(restoreStubsAndMocks));
251 });
252
253 it.effect('URL-encodes slash-containing tags in tagged release request path', () => {
254 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
246 - let receivedPath = '';
255 + let receivedPath: string | undefined;
256
257 return Effect.gen(function* () {
258 const apiBaseUrl = yield* scopedHttpServer((req, res) => {
250 - receivedPath = req.url ?? '';
259 + receivedPath = req.url;
260 res.writeHead(500, { 'content-type': 'application/json' });
261 res.end(JSON.stringify({ message: 'forced failure' }));
262 });
@@ -261,9 +270,6 @@ describe('UpgradeBinary', () => {
270 ]);
271
272 expect(error).toBeInstanceOf(UpgradeBinaryError);
264 - if (!(error instanceof UpgradeBinaryError)) {
265 - throw error;
266 - }
273 expect(receivedPath).toBe(
274 `/repos/test-owner/test-repo/releases/tags/${encodeURIComponent(tag)}`
275 );
@@ -443,9 +449,6 @@ describe('UpgradeBinary', () => {
449 );
450
451 expect(error).toBeInstanceOf(UpgradeBinaryError);
446 - if (!(error instanceof UpgradeBinaryError)) {
447 - throw error;
448 - }
452 expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
453 expect(String(error.cause)).toContain('beta-3.zip');
454 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
@@ -477,11 +480,7 @@ describe('UpgradeBinary', () => {
480
481 const companionRelativePaths =
482 yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
480 - for (const relativePath of companionRelativePaths) {
481 - const companionPath = path.join(sourceDir, relativePath);
482 - yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
483 - yield* fs.writeFileString(companionPath, 'support-file');
484 - }
483 + yield* writeCompanionFiles(sourceDir, companionRelativePaths, 'support-file');
484
485 const result = yield* runUpgradeSuccess([
486 ['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath],
@@ -522,11 +521,7 @@ describe('UpgradeBinary', () => {
521
522 const companionRelativePaths =
523 yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
525 - for (const relativePath of companionRelativePaths) {
526 - const companionPath = path.join(sourceDir, relativePath);
527 - yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
528 - yield* fs.writeFileString(companionPath, 'new-support-file');
529 - }
524 + yield* writeCompanionFiles(sourceDir, companionRelativePaths, 'new-support-file');
525 const observedCompanionPath = path.join(installDir, companionRelativePaths[0]!);
526 yield* fs.makeDirectory(path.dirname(observedCompanionPath), { recursive: true });
527 yield* fs.writeFileString(observedCompanionPath, 'old-support-file');
@@ -539,9 +534,6 @@ describe('UpgradeBinary', () => {
534 );
535
536 expect(error).toBeInstanceOf(UpgradeBinaryError);
542 - if (!(error instanceof UpgradeBinaryError)) {
543 - throw error;
544 - }
537 expect(error.message).toBe(
538 `Failed to replace binary: Failed to replace file at ${fakeExecPath}`
539 );
@@ -581,12 +573,11 @@ describe('UpgradeBinary', () => {
573 const companionRelativePaths =
574 yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
575 const missingRelativePath = companionRelativePaths.at(-1)!;
584 - for (const relativePath of companionRelativePaths) {
585 - if (relativePath === missingRelativePath) continue;
586 - const companionPath = path.join(sourceDir, relativePath);
587 - yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
588 - yield* fs.writeFileString(companionPath, 'new-support-file');
589 - }
576 + yield* writeCompanionFiles(
577 + sourceDir,
578 + companionRelativePaths.slice(0, -1),
579 + 'new-support-file'
580 + );
581 const observedCompanionPath = path.join(installDir, companionRelativePaths[0]!);
582 yield* fs.makeDirectory(path.dirname(observedCompanionPath), { recursive: true });
583 yield* fs.writeFileString(observedCompanionPath, 'old-support-file');
@@ -598,9 +589,6 @@ describe('UpgradeBinary', () => {
589 });
590
591 expect(error).toBeInstanceOf(UpgradeBinaryError);
601 - if (!(error instanceof UpgradeBinaryError)) {
602 - throw error;
603 - }
592 expect(error.message).toBe('Downloaded binary package is incomplete');
593 expect(String(error.cause)).toContain(missingRelativePath);
594 expect(yield* fs.readFileString(fakeExecPath)).toBe('old-binary');
@@ -636,11 +624,7 @@ describe('UpgradeBinary', () => {
624
625 const companionRelativePaths =
626 yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
639 - for (const relativePath of companionRelativePaths) {
640 - const companionPath = path.join(sourceDir, relativePath);
641 - yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
642 - yield* fs.writeFileString(companionPath, 'support-file');
643 - }
627 + yield* writeCompanionFiles(sourceDir, companionRelativePaths, 'support-file');
628
629 const result = yield* runUpgradeSuccess([
630 ['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath],
@@ -698,9 +682,6 @@ describe('UpgradeBinary', () => {
682 );
683
684 expect(error).toBeInstanceOf(UpgradeBinaryError);
701 - if (!(error instanceof UpgradeBinaryError)) {
702 - throw error;
703 - }
685 expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
686 expect(String(error.cause)).toContain('beta-3.zip');
687 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
ts/packages/cli/test/src/utils/atomic-write.test.ts
+5 -3
@@ -151,9 +151,11 @@ describe('atomicWritePrivateFileString', () => {
151 expect(collisionPaths).toHaveLength(5);
152 expect(new Set(collisionPaths)).toHaveLength(5);
153 expect(yield* fs.exists(target)).toBe(false);
154 - for (const collisionPath of collisionPaths) {
155 - expect(yield* fs.readFileString(collisionPath, 'utf8')).toBe('pre-existing contents');
156 - }
154 + expect(
155 + yield* Effect.forEach(collisionPaths, collisionPath =>
156 + fs.readFileString(collisionPath, 'utf8')
157 + )
158 + ).toEqual(Array.from({ length: 5 }, () => 'pre-existing contents'));
159 })
160 );
161
ts/packages/cli/test/src/utils/extract-zip-safely.test.ts
+18 -19
@@ -2,6 +2,7 @@ import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { describe, expect, it } from '@effect/vitest';
5 +import { onTestFinished } from 'vitest';
6 import {
7 extractZipSafely,
8 isSymlinkZipEntry,
@@ -10,13 +11,11 @@ import {
11
12 const FIXTURES_DIR = path.join(__dirname, 'zip-fixtures');
13
13 -const withTempDir = async (use: (dir: string) => Promise<void>): Promise<void> => {
14 +/** A fresh extraction target, removed once the current test finishes. */
15 +const makeTempDir = (): string => {
16 const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'extract-zip-safely-'));
15 - try {
16 - await use(dir);
17 - } finally {
18 - fs.rmSync(dir, { recursive: true, force: true });
19 - }
17 + onTestFinished(() => fs.rmSync(dir, { recursive: true, force: true }));
18 + return dir;
19 };
20
21 /**
@@ -44,26 +43,26 @@ describe('isSymlinkZipEntry', () => {
43
44 describe('extractZipSafely', () => {
45 it('extracts an archive of regular files and directories', async () => {
47 - await withTempDir(async dir => {
48 - await extractZipSafely(path.join(FIXTURES_DIR, 'benign.zip'), dir);
46 + const dir = makeTempDir();
47
50 - expect(fs.readFileSync(path.join(dir, 'a.txt'), 'utf8').trim()).toBe('hello');
51 - expect(fs.readFileSync(path.join(dir, 'sub', 'b.txt'), 'utf8').trim()).toBe('world');
52 - });
48 + await extractZipSafely(path.join(FIXTURES_DIR, 'benign.zip'), dir);
49 +
50 + expect(fs.readFileSync(path.join(dir, 'a.txt'), 'utf8').trim()).toBe('hello');
51 + expect(fs.readFileSync(path.join(dir, 'sub', 'b.txt'), 'utf8').trim()).toBe('world');
52 });
53
54 it.each([
55 ['symlink-absolute.zip', 'escape-abs'],
56 ['symlink-relative.zip', 'escape-rel'],
57 ])('refuses %s and plants nothing', async (fixture, entryName) => {
59 - await withTempDir(async dir => {
60 - await expect(extractZipSafely(path.join(FIXTURES_DIR, fixture), dir)).rejects.toThrow(
61 - UnsafeZipEntryError
62 - );
58 + const dir = makeTempDir();
59 +
60 + await expect(extractZipSafely(path.join(FIXTURES_DIR, fixture), dir)).rejects.toThrow(
61 + UnsafeZipEntryError
62 + );
63
64 - // The guard runs before the entry is written, so the target stays empty.
65 - expect(fs.readdirSync(dir)).toEqual([]);
66 - expect(fs.existsSync(path.join(dir, entryName))).toBe(false);
67 - });
64 + // The guard runs before the entry is written, so the target stays empty.
65 + expect(fs.readdirSync(dir)).toEqual([]);
66 + expect(fs.existsSync(path.join(dir, entryName))).toBe(false);
67 });
68 });
ts/packages/cli/test/src/utils/memoize-in-process.test.ts
+16 -20
@@ -1,5 +1,5 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { Deferred, Effect, Exit, Fiber } from 'effect';
2 +import { Cause, Deferred, Effect, Fiber } from 'effect';
3 import { clearInProcessMemos, memoizeInProcess } from 'src/utils/memoize-in-process';
4
5 describe('memoizeInProcess', () => {
@@ -25,16 +25,14 @@ describe('memoizeInProcess', () => {
25 it.effect('drops a failure so the next caller retries', () =>
26 Effect.gen(function* () {
27 let calls = 0;
28 + const outcomes = [Effect.fail(new Error('first call fails')), Effect.succeed(2)];
29 const load = memoizeInProcess({
30 keyOf: (key: string) => key,
30 - make: () =>
31 - Effect.suspend(() =>
32 - ++calls === 1 ? Effect.fail(new Error('first call fails')) : Effect.succeed(calls)
33 - ),
31 + make: () => Effect.suspend(() => outcomes[calls++]),
32 });
33
36 - const first = yield* Effect.exit(load('k'));
37 - expect(Exit.isFailure(first)).toBe(true);
34 + const first = yield* Effect.flip(load('k'));
35 + expect(first).toEqual(new Error('first call fails'));
36
37 expect(yield* load('k')).toBe(2);
38 expect(yield* load('k')).toBe(2);
@@ -45,16 +43,14 @@ describe('memoizeInProcess', () => {
43 it.effect('drops a defect so the next caller retries', () =>
44 Effect.gen(function* () {
45 let calls = 0;
46 + const outcomes = [Effect.die('first call dies'), Effect.succeed(2)];
47 const load = memoizeInProcess({
48 keyOf: (key: string) => key,
50 - make: () =>
51 - Effect.suspend(() =>
52 - ++calls === 1 ? Effect.die('first call dies') : Effect.succeed(calls)
53 - ),
49 + make: () => Effect.suspend(() => outcomes[calls++]),
50 });
51
56 - const first = yield* Effect.exit(load('k'));
57 - expect(Exit.isFailure(first)).toBe(true);
52 + const first = yield* load('k').pipe(Effect.sandbox, Effect.flip);
53 + expect(Cause.squash(first)).toBe('first call dies');
54
55 expect(yield* load('k')).toBe(2);
56 expect(calls).toBe(2);
@@ -92,24 +88,24 @@ describe('memoizeInProcess', () => {
88 Effect.gen(function* () {
89 const release = yield* Deferred.make<void>();
90 let calls = 0;
91 + const outcomes = [Effect.fail(new Error('first call fails')), Effect.succeed(2)];
92 const load = memoizeInProcess({
93 keyOf: (key: string) => key,
94 make: () =>
95 Effect.gen(function* () {
99 - calls += 1;
96 + const outcome = outcomes[calls++];
97 yield* Deferred.await(release);
101 - if (calls === 1) return yield* Effect.fail(new Error('first call fails'));
102 - return calls;
98 + return yield* outcome;
99 }),
100 });
101
106 - const first = yield* Effect.forkChild(Effect.exit(load('k')));
107 - const second = yield* Effect.forkChild(Effect.exit(load('k')));
102 + const first = yield* Effect.forkChild(Effect.flip(load('k')));
103 + const second = yield* Effect.forkChild(Effect.flip(load('k')));
104 yield* Effect.yieldNow;
105 yield* Deferred.succeed(release, undefined);
106
111 - expect(Exit.isFailure(yield* Fiber.join(first))).toBe(true);
112 - expect(Exit.isFailure(yield* Fiber.join(second))).toBe(true);
107 + expect(yield* Fiber.join(first)).toEqual(new Error('first call fails'));
108 + expect(yield* Fiber.join(second)).toEqual(new Error('first call fails'));
109 expect(yield* load('k')).toBe(2);
110 expect(calls).toBe(2);
111 })