Skip to content

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

fix(cli): separate prompt, output, and decoration capabilities (#3964)

Alberto Schiabel2deb239e94d8
diff --git a/ts/packages/cli/AGENTS.md b/ts/packages/cli/AGENTS.md
index ca50eae95..472b4c34b 100644
--- a/ts/packages/cli/AGENTS.md
+++ b/ts/packages/cli/AGENTS.md
@@ -111,14 +111,21 @@ Follow the Unix convention of separating human-readable decoration from machine-
- **stdout** — data only (`ui.output()`). Captured by pipes / `$(...)` / `> file`.
- **stderr** — all decoration (Clack spinners, logs, notes, intro/outro). Visible in terminal, invisible in pipes.
+The three streams are **independent contracts**. Each capability depends only on the streams that actually serve it — there is deliberately no aggregate "interactive" flag (`TerminalCapabilities` in `src/services/terminal-ui.ts`):
+
+- **Prompting** (`canPrompt`) = `stdin.isTTY && stderr.isTTY`. stdin must accept input and stderr must display the Clack prompt. stdout is irrelevant: piping data must never change prompting or authentication behavior — `composio login | tee` behaves exactly like an attended login.
+- **Machine output** = `!stdout.isTTY`. `ui.output(data)` writes only when stdout is redirected (pipe, subshell, file), or when the caller passes `{ force: true }`. Redirecting stdin or stderr must never make data leak onto a visible stdout terminal.
+- **Decoration** (`canDecorate`) = `stderr.isTTY`. Spinners, logs, and notes only need stderr, so they still render when stdin or stdout is redirected.
+
Rules:
-1. All `TerminalUI` methods **except `output()`** write to stderr via Clack's `{ output: process.stderr }`, and only in interactive mode.
-2. `ui.output(data)` writes to stdout **only when piped** (checked via `process.stdout.isTTY`).
-3. When stdout is piped, **all decoration is suppressed** — `composio whoami | pbcopy` is completely silent and clipboard gets the clean key.
-4. **Data commands** (whoami, version, login, generate, etc.) call both decoration (stderr) and `ui.output()` (stdout).
-5. **Action commands** (logout, upgrade) produce no stdout data — output is purely decorative.
-6. **Never** write data to stderr or decoration to stdout.
+1. All `TerminalUI` methods **except `output()`** write to stderr via Clack's `{ output: process.stderr }`, and only when stderr is a TTY (`canDecorate`).
+2. `ui.output(data)` writes to stdout **only when stdout is piped** (or with explicit `force`). No other stream participates in that decision.
+3. Prompts (`ui.confirm`, `ui.select`) run only when `canPrompt`; otherwise they fall back to their defaults without blocking.
+4. Piped stdout stays clean: `composio whoami | pbcopy` puts only the key in the clipboard — decoration still renders on the terminal via stderr, and is suppressed only when stderr itself is captured.
+5. **Data commands** (whoami, version, login, generate, etc.) call both decoration (stderr) and `ui.output()` (stdout).
+6. **Action commands** (logout, upgrade) produce no stdout data — output is purely decorative.
+7. **Never** write data to stderr or decoration to stdout, and never branch program behavior (auth paths, command flow) on stdout's TTY state.
When adding a new command: ask "Does this produce a value scripts should capture?" — yes → `ui.output(value)` + `ui.log.*`/`ui.note()`. No → decoration only.
@@ -137,6 +144,19 @@ Effect.gen(function* () {
Key patterns: `Effect.all([...], { concurrency: 'unbounded' })` for parallel work, `Layer.provide()` for dependency composition, `Effect.mapError()` / `Effect.catchTag()` for typed errors, `Effect.scoped` for resource cleanup.
+For table-driven tests over independent finite choices, use Effect Array do notation
+to build a typed Cartesian product instead of enumerating every case or nesting loops:
+
+```typescript
+const cases = pipe(
+ Arr.Do,
+ Arr.bind('firstAxis', () => choices),
+ Arr.bind('secondAxis', () => choices)
+);
+```
+
+Each `Arr.bind` adds one independent axis to the generated cases.
+
### Effect safety and migration seams
- Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Either`, `Exit`, `Cause`, `ValidationError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index c34234e71..1a4a71844 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -631,7 +631,7 @@ export const browserLogin = (params: {
expiresAt,
});
- const canPrompt = (yield* ui.capabilities).isInteractive;
+ const { canPrompt, canDecorate } = yield* ui.capabilities;
const effectiveNoWait = params.noWait || !canPrompt;
const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
@@ -641,7 +641,7 @@ export const browserLogin = (params: {
pollCommand,
});
- if (canPrompt) {
+ if (canDecorate) {
yield* ui.log.info('Please login using the following URL:');
yield* ui.note(url, 'Login URL');
yield* ui.note(loginInstructions, 'Login instructions');
@@ -807,9 +807,9 @@ export const loginCmd = Command.make(
Effect.gen(function* () {
const ui = yield* TerminalUI;
const ctx = yield* ComposioUserContext;
- const canPrompt = (yield* ui.capabilities).isInteractive;
+ const { canPrompt, canDecorate } = yield* ui.capabilities;
- if (canPrompt) {
+ if (canDecorate) {
yield* ui.intro('composio login');
}
@@ -868,7 +868,7 @@ export const loginCmd = Command.make(
organizations: loginResult.organizations,
};
const pollSummary = formatPollLoginComplete(pollSummaryParams);
- if (canPrompt) {
+ if (canDecorate) {
yield* ui.note(pollSummary, 'Login complete');
}
yield* ui.output(serializePollLoginResult(pollSummaryParams), { force: true });
diff --git a/ts/packages/cli/src/commands/setup.cmd.ts b/ts/packages/cli/src/commands/setup.cmd.ts
index e4e7b2bff..b5458731a 100644
--- a/ts/packages/cli/src/commands/setup.cmd.ts
+++ b/ts/packages/cli/src/commands/setup.cmd.ts
@@ -180,7 +180,7 @@ const setupBaseCmd = Command.make(
}
if (!yes && removable.length > 0) {
- if (!terminal.isInteractive) {
+ if (!terminal.canPrompt) {
return yield* setupCommandError(
'Non-interactive uninstall requires `--yes` to approve local changes.',
operation
@@ -228,7 +228,7 @@ const setupBaseCmd = Command.make(
const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));
if (!yes) {
- if (!terminal.isInteractive) {
+ if (!terminal.canPrompt) {
return yield* setupCommandError(
'Non-interactive setup requires `--yes` to approve local changes.',
operation
diff --git a/ts/packages/cli/src/services/terminal-ui.ts b/ts/packages/cli/src/services/terminal-ui.ts
index dfd7c7a65..d4b42f63b 100644
--- a/ts/packages/cli/src/services/terminal-ui.ts
+++ b/ts/packages/cli/src/services/terminal-ui.ts
@@ -1,4 +1,5 @@
import process from 'node:process';
+import type { Writable } from 'node:stream';
import * as p from '@clack/prompts';
import { Context, Effect, Exit, Layer } from 'effect';
@@ -12,11 +13,29 @@ export type TerminalStdio = {
readonly stderr: TtyLikeStream;
};
+/**
+ * Per-stream terminal capabilities.
+ *
+ * The three streams are independent contracts, so each derived capability
+ * depends only on the streams that actually serve it:
+ *
+ * - `canPrompt` — stdin must accept human input and stderr must display the
+ * Clack prompt. stdout is irrelevant: piping data must not change prompting
+ * or authentication behavior.
+ * - `canDecorate` — decoration (spinners, logs, notes) renders on stderr, so it
+ * only needs stderr.
+ * - machine output — `TerminalUI.output()` consults `stdoutIsTTY` alone.
+ *
+ * There is deliberately no aggregate "interactive" flag: it conflated these
+ * concerns and let output routing change program behavior.
+ */
export type TerminalCapabilities = {
readonly stdinIsTTY: boolean;
readonly stdoutIsTTY: boolean;
readonly stderrIsTTY: boolean;
- readonly isInteractive: boolean;
+ /** Whether Clack prompts can run (`stdinIsTTY && stderrIsTTY`). */
+ readonly canPrompt: boolean;
+ /** Whether stderr decoration can render (`stderrIsTTY`). */
readonly canDecorate: boolean;
};
@@ -30,7 +49,7 @@ export const getTerminalCapabilities = (stdio: TerminalStdio): TerminalCapabilit
stdinIsTTY,
stdoutIsTTY,
stderrIsTTY,
- isInteractive: stdinIsTTY && stdoutIsTTY && stderrIsTTY,
+ canPrompt: stdinIsTTY && stderrIsTTY,
canDecorate: stderrIsTTY,
};
};
@@ -60,9 +79,11 @@ export interface TerminalUI {
* Write raw data to stdout for piping and scripting.
*
* This is the ONLY method that writes to stdout — everything else goes to stderr.
- * When stdout is a TTY (interactive terminal), this is a no-op — the human already
+ * When stdout is a TTY (a human is watching it), this is a no-op — the human already
* sees the data via decoration on stderr. When stdout is redirected (pipe, subshell,
- * file), the raw value is written for machine consumption.
+ * file), the raw value is written for machine consumption. Only stdout's own TTY
+ * state participates in this decision; redirecting stdin or stderr must never make
+ * data leak onto a visible stdout terminal.
*
* Use this for values that scripts should capture (API keys, version strings, etc.).
*/
@@ -115,7 +136,7 @@ export interface TerminalUI {
/**
* Ask the user a yes/no confirmation question.
- * In non-interactive mode (piped), returns `defaultValue` (defaults to `true`).
+ * When prompting is unavailable, returns `defaultValue` (defaults to `true`).
*/
readonly confirm: (
message: string,
@@ -124,7 +145,7 @@ export interface TerminalUI {
/**
* Present a single-select list to the user.
- * In non-interactive mode (piped), returns the first option's value.
+ * When prompting is unavailable, returns the first option's value.
*/
readonly select: <Value>(
message: string,
@@ -151,33 +172,20 @@ export interface TerminalUI {
export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');
// ---------------------------------------------------------------------------
-// TerminalUILive — production layer using @clack/prompts
+// makeTerminalUI — build a TerminalUI from explicit streams
// ---------------------------------------------------------------------------
/**
- * Whether the CLI can prompt for human input. Human-only prompts are shown only
- * when stdin/stdout/stderr are all TTYs; agent and shell pipelines get
- * non-interactive behavior.
- */
-const liveCapabilities = getTerminalCapabilities({
- stdin: process.stdin,
- stdout: process.stdout,
- stderr: process.stderr,
-});
-
-const canPrompt = liveCapabilities.isInteractive;
-
-/**
- * Whether the CLI can render auxiliary UI. Logs, notes, and spinners only need
- * stderr, so they can still be shown when stdin is redirected from /dev/null or
- * stdout is reserved for machine-readable JSON/data.
+ * Intentionally a Node.js Writable rather than an Effect Sink: Clack accepts
+ * Writable streams and writes to them synchronously.
*/
-const canDecorate = liveCapabilities.canDecorate;
+type TerminalWritable = TtyLikeStream & Writable;
-/** Run a decoration side-effect only when stderr is a terminal. */
-function decorate(fn: () => void): void {
- if (canDecorate) fn();
-}
+type TerminalUIStreams = {
+ readonly stdin: TtyLikeStream;
+ readonly stdout: TerminalWritable;
+ readonly stderr: TerminalWritable;
+};
function createClackSpinnerHandle(
s: p.SpinnerResult,
@@ -202,121 +210,161 @@ function createClackSpinnerHandle(
};
}
-/** No-op spinner handle used when decoration is suppressed (piped mode). */
+/** No-op spinner handle used when decoration is suppressed (stderr redirected). */
const silentSpinnerHandle: SpinnerHandle = {
message: () => Effect.void,
stop: () => Effect.void,
error: () => Effect.void,
};
-const makeLive: TerminalUI = {
- capabilities: Effect.succeed(liveCapabilities),
+/**
+ * Build a TerminalUI backed by the given streams.
+ *
+ * Each stream governs exactly one concern:
+ * - stdin + stderr decide prompting (`canPrompt`);
+ * - stdout alone decides machine output (`output()` writes only when stdout
+ * is not a TTY, or when `force` is set);
+ * - stderr alone decides decoration (`canDecorate`).
+ */
+export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
+ const capabilities = getTerminalCapabilities(streams);
+ const { canPrompt, canDecorate, stdoutIsTTY } = capabilities;
+ const stderr = streams.stderr;
+
+ const decorate = (render: () => void): Effect.Effect<void> => {
+ if (!canDecorate) {
+ return Effect.void;
+ }
+ return Effect.sync(render);
+ };
+
+ return {
+ capabilities: Effect.succeed(capabilities),
+
+ output: (data, options) =>
+ Effect.sync(() => {
+ if (options?.force || !stdoutIsTTY) {
+ streams.stdout.write(`${data}\n`);
+ }
+ }),
+
+ error: data => Effect.sync(() => stderr.write(`${data}\n`)),
+
+ intro: title => decorate(() => p.intro(title, { output: stderr })),
+ outro: message => decorate(() => p.outro(message, { output: stderr })),
+
+ log: {
+ info: message => decorate(() => p.log.info(message, { output: stderr })),
+ success: message => decorate(() => p.log.success(message, { output: stderr })),
+ warn: message => decorate(() => p.log.warn(message, { output: stderr })),
+ error: message => decorate(() => p.log.error(message, { output: stderr })),
+ step: message => decorate(() => p.log.step(message, { output: stderr })),
+ message: message => decorate(() => p.log.message(message, { output: stderr })),
+ },
+
+ note: (message, title) =>
+ decorate(() => p.note(message, title ?? '', { format: line => line, output: stderr })),
- output: (data, options) =>
- Effect.sync(() => {
- if (options?.force || !canPrompt) {
- process.stdout.write(`${data}\n`);
+ select: ((
+ message: string,
+ options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
+ ) => {
+ if (!canPrompt) {
+ return Effect.succeed(options[0].value);
}
- }),
-
- error: data => Effect.sync(() => process.stderr.write(`${data}\n`)),
-
- intro: title => Effect.sync(() => decorate(() => p.intro(title, { output: process.stderr }))),
- outro: message => Effect.sync(() => decorate(() => p.outro(message, { output: process.stderr }))),
-
- log: {
- info: message =>
- Effect.sync(() => decorate(() => p.log.info(message, { output: process.stderr }))),
- success: message =>
- Effect.sync(() => decorate(() => p.log.success(message, { output: process.stderr }))),
- warn: message =>
- Effect.sync(() => decorate(() => p.log.warn(message, { output: process.stderr }))),
- error: message =>
- Effect.sync(() => decorate(() => p.log.error(message, { output: process.stderr }))),
- step: message =>
- Effect.sync(() => decorate(() => p.log.step(message, { output: process.stderr }))),
- message: message =>
- Effect.sync(() => decorate(() => p.log.message(message, { output: process.stderr }))),
- },
-
- note: (message, title) =>
- Effect.sync(() =>
- decorate(() => p.note(message, title ?? '', { format: line => line, output: process.stderr }))
- ),
-
- select: ((
- message: string,
- options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
- ) =>
- canPrompt
- ? Effect.promise(async () => {
- const result = await p.select({
- message,
- options: [...options],
- output: process.stderr,
- });
- // p.select returns Value | symbol (symbol on cancel)
- if (typeof result === 'symbol') return options[0].value;
- return result;
- })
- : Effect.succeed(options[0].value)) as TerminalUI['select'],
-
- confirm: (message, options) =>
- canPrompt
- ? Effect.promise(async () => {
- const result = await p.confirm({
- message,
- initialValue: options?.defaultValue ?? true,
- output: process.stderr,
- });
- // p.confirm returns boolean | symbol (symbol on cancel)
- return typeof result === 'boolean' ? result : false;
- })
- : Effect.succeed(options?.defaultValue ?? true),
-
- withSpinner: (message, effect, options) =>
- canDecorate
- ? Effect.acquireUseRelease(
+
+ return Effect.promise(async () => {
+ const result = await p.select({
+ message,
+ options: [...options],
+ output: stderr,
+ });
+ // p.select returns Value | symbol (symbol on cancel)
+ if (typeof result === 'symbol') return options[0].value;
+ return result;
+ });
+ }) as TerminalUI['select'],
+
+ confirm: (message, options) => {
+ if (!canPrompt) {
+ return Effect.succeed(options?.defaultValue ?? true);
+ }
+
+ return Effect.promise(async () => {
+ const result = await p.confirm({
+ message,
+ initialValue: options?.defaultValue ?? true,
+ output: stderr,
+ });
+ if (p.isCancel(result)) return false;
+ return result;
+ });
+ },
+
+ withSpinner: (message, effect, options) => {
+ if (!canDecorate) {
+ return effect;
+ }
+
+ return Effect.acquireUseRelease(
+ Effect.sync(() => {
+ const s = p.spinner({ output: stderr });
+ s.start(message);
+ return s;
+ }),
+ () => effect,
+ (s, exit) =>
Effect.sync(() => {
- const s = p.spinner({ output: process.stderr });
- s.start(message);
- return s;
- }),
- () => effect,
- (s, exit) =>
- Effect.sync(() => {
- if (Exit.isSuccess(exit)) {
- const successMsg =
- typeof options?.successMessage === 'function'
- ? options.successMessage(exit.value)
- : (options?.successMessage ?? message);
- s.stop(successMsg);
- } else {
- s.error(options?.errorMessage ?? message);
+ if (Exit.isSuccess(exit)) {
+ let successMessage = message;
+ const configuredSuccessMessage = options?.successMessage;
+ if (typeof configuredSuccessMessage === 'function') {
+ successMessage = configuredSuccessMessage(exit.value);
+ } else if (configuredSuccessMessage !== undefined) {
+ successMessage = configuredSuccessMessage;
}
- })
- )
- : effect,
+ s.stop(successMessage);
+ } else {
+ s.error(options?.errorMessage ?? message);
+ }
+ })
+ );
+ },
+
+ useMakeSpinner: (message, use) => {
+ if (!canDecorate) {
+ return use(silentSpinnerHandle);
+ }
- useMakeSpinner: (message, use) =>
- canDecorate
- ? Effect.acquireUseRelease(
+ return Effect.acquireUseRelease(
+ Effect.sync(() => {
+ const s = p.spinner({ output: stderr });
+ s.start(message);
+ const { handle, isStopped } = createClackSpinnerHandle(s, message);
+ return { raw: s, handle, isStopped };
+ }),
+ ({ handle }) => use(handle),
+ ({ raw, isStopped }, exit) =>
Effect.sync(() => {
- const s = p.spinner({ output: process.stderr });
- s.start(message);
- const { handle, isStopped } = createClackSpinnerHandle(s, message);
- return { raw: s, handle, isStopped };
- }),
- ({ handle }) => use(handle),
- ({ raw, isStopped }, exit) =>
- Effect.sync(() => {
- // Only clean up if the spinner hasn't been stopped/errored by the callback
- if (Exit.isFailure(exit) && !isStopped()) {
- raw.error(message);
- }
- })
- )
- : use(silentSpinnerHandle),
+ // Only clean up if the spinner hasn't been stopped/errored by the callback
+ if (Exit.isFailure(exit) && !isStopped()) {
+ raw.error(message);
+ }
+ })
+ );
+ },
+ };
};
-export const TerminalUILive = Layer.succeed(TerminalUI, makeLive);
+// ---------------------------------------------------------------------------
+// TerminalUILive — production layer using @clack/prompts
+// ---------------------------------------------------------------------------
+
+export const TerminalUILive = Layer.succeed(
+ TerminalUI,
+ makeTerminalUI({
+ stdin: process.stdin,
+ stdout: process.stdout,
+ stderr: process.stderr,
+ })
+);
diff --git a/ts/packages/cli/src/services/update-check.ts b/ts/packages/cli/src/services/update-check.ts
index 917384f43..d9319d062 100644
--- a/ts/packages/cli/src/services/update-check.ts
+++ b/ts/packages/cli/src/services/update-check.ts
@@ -173,8 +173,10 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
*/
function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
return Effect.gen(function* () {
- const capabilities = yield* terminal.capabilities;
- if (!capabilities.isInteractive) return;
+ // `terminal.error` writes even when stderr is redirected, so gate this
+ // advisory notice explicitly while leaving stdout out of the decision.
+ const { canDecorate } = yield* terminal.capabilities;
+ if (!canDecorate) return;
const state = yield* readState;
const latestVersion = semver.valid(state.latestVersion);
diff --git a/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts b/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
index 9681951bc..8c7c2d848 100644
--- a/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+++ b/ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
@@ -1,5 +1,5 @@
import { Console, Effect, Exit, Layer } from 'effect';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
/**
* Test layer for TerminalUI that routes all output through Effect's Console.
@@ -8,13 +8,13 @@ import { TerminalUI } from 'src/services/terminal-ui';
* no ANSI codes, no spinners.
*/
export const terminalUITestImpl = TerminalUI.of({
- capabilities: Effect.succeed({
- stdinIsTTY: false,
- stdoutIsTTY: false,
- stderrIsTTY: false,
- isInteractive: false,
- canDecorate: false,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: false },
+ stdout: { isTTY: false },
+ stderr: { isTTY: false },
+ })
+ ),
output: data => Console.log(data),
error: data => Console.error(data),
diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
index d7438b32b..2aaee58b9 100644
--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
@@ -5,7 +5,7 @@ import { extendConfigProvider } from 'src/services/config';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
import type { ConnectedAccountItem } from 'src/models/connected-accounts';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import open from 'open';
import { afterEach, vi } from 'vitest';
@@ -57,13 +57,13 @@ const testConfigProvider = ConfigProvider.fromMap(
).pipe(extendConfigProvider);
const RecordingTerminalUI = TerminalUI.of({
- capabilities: Effect.succeed({
- stdinIsTTY: true,
- stdoutIsTTY: true,
- stderrIsTTY: true,
- isInteractive: true,
- canDecorate: true,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: true },
+ stdout: { isTTY: true },
+ stderr: { isTTY: true },
+ })
+ ),
output: (data, options) =>
Console.log(
JSON.stringify({
diff --git a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
index 5dc15ed8d..fafd511c5 100644
--- a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, layer } from '@effect/vitest';
import { ConfigProvider, Console, Effect } from 'effect';
import type { ConnectedAccountItem } from 'src/models/connected-accounts';
import { extendConfigProvider } from 'src/services/config';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { ComposioUserContext } from 'src/services/user-context';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -90,13 +90,13 @@ const testConfigProvider = ConfigProvider.fromMap(
const terminalUIWithConfirm = (confirmed: boolean) =>
TerminalUI.of({
- capabilities: Effect.succeed({
- stdinIsTTY: true,
- stdoutIsTTY: true,
- stderrIsTTY: true,
- isInteractive: true,
- canDecorate: true,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: true },
+ stdout: { isTTY: true },
+ stderr: { isTTY: true },
+ })
+ ),
output: data => Console.log(data),
error: data => Console.error(data),
intro: title => Console.log(`-- ${title} --`),
diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.ts
index 168c1e0a6..b9d8a824c 100644
--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts
@@ -1,12 +1,14 @@
import { describe, expect, layer } from '@effect/vitest';
import { vi, afterEach } from 'vitest';
-import { Effect, Option } from 'effect';
+import { Console, Effect, Exit, Option } from 'effect';
import { HelpDoc, ValidationError } from '@effect/cli';
import path from 'node:path';
import { FileSystem } from '@effect/platform';
import { cli, MockConsole, TestLive } from 'test/__utils__';
+import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
import * as constants from 'src/constants';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { ComposioUserContext } from 'src/services/user-context';
const mockFetchResponse = (body: unknown, status = 200) =>
@@ -124,6 +126,41 @@ describe('CLI: composio login', () => {
);
});
+ describe('login with stdout piped', () => {
+ const pipedStdoutUI = TerminalUI.of({
+ ...terminalUITestImpl,
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: true },
+ stdout: { isTTY: false },
+ stderr: { isTTY: true },
+ })
+ ),
+ useMakeSpinner: (message, _use) =>
+ Console.log(`[spinner] ${message}`).pipe(
+ Effect.andThen(Effect.die(new Error('test: interactive poll loop entered')))
+ ),
+ });
+
+ layer(TestLive({ terminalUI: pipedStdoutUI }))(it => {
+ it.scoped(
+ '[When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive instead of going headless',
+ () =>
+ Effect.gen(function* () {
+ const exit = yield* Effect.exit(cli(['login', '--no-browser']));
+
+ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
+ expect(output).toContain('[spinner] Waiting for login...');
+ expect(output).toContain('Please login using the following URL');
+ expect(output).not.toContain('Open this URL in your browser to log in:');
+ expect(output).not.toContain('hint: For agents:');
+ expect(output).not.toContain('Then run this command to complete login:');
+ expect(Exit.isFailure(exit)).toBe(true);
+ })
+ );
+ });
+ });
+
layer(TestLive())(it => {
it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
Effect.gen(function* () {
diff --git a/ts/packages/cli/test/src/commands/logout.cmd.test.ts b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
index 4f5039ed3..e7a4e7cc8 100644
--- a/ts/packages/cli/test/src/commands/logout.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/logout.cmd.test.ts
@@ -7,19 +7,19 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { UserDataWithDefaults } from 'src/models/user-data';
import { writeStoredAgentIdentity } from 'src/services/agents';
import { extendConfigProvider } from 'src/services/config';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { ComposioUserContext } from 'src/services/user-context';
import { cli, TestLive, MockConsole } from 'test/__utils__';
const terminalUIWithConfirm = (confirmed: boolean) =>
TerminalUI.of({
- capabilities: Effect.succeed({
- stdinIsTTY: true,
- stdoutIsTTY: true,
- stderrIsTTY: true,
- isInteractive: true,
- canDecorate: true,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: true },
+ stdout: { isTTY: true },
+ stderr: { isTTY: true },
+ })
+ ),
output: data => Console.log(data),
error: data => Console.error(data),
intro: title => Console.log(`-- ${title} --`),
diff --git a/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts b/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
index cbc486bc0..39d62286b 100644
--- a/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
@@ -4,7 +4,7 @@ import { Effect, Exit } from 'effect';
import { afterEach, beforeEach, vi } from 'vitest';
import { CommandRunner } from 'src/services/command-runner';
import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { cli, TestLive } from 'test/__utils__';
import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
@@ -162,13 +162,13 @@ const makeSkillInstaller = (initiallyReady = false) => {
// The cancellation path requires an interactive terminal to reach the confirm prompt.
const decliningUI = TerminalUI.of({
...terminalUITestImpl,
- capabilities: Effect.succeed({
- stdinIsTTY: false,
- stdoutIsTTY: false,
- stderrIsTTY: false,
- isInteractive: true,
- canDecorate: false,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: true },
+ stdout: { isTTY: false },
+ stderr: { isTTY: true },
+ })
+ ),
confirm: () => Effect.succeed(false),
});
diff --git a/ts/packages/cli/test/src/services/terminal-ui.test.ts b/ts/packages/cli/test/src/services/terminal-ui.test.ts
index 4c0a2e22d..045e105da 100644
--- a/ts/packages/cli/test/src/services/terminal-ui.test.ts
+++ b/ts/packages/cli/test/src/services/terminal-ui.test.ts
@@ -1,27 +1,169 @@
+import { Writable } from 'node:stream';
import { describe, expect, it, layer } from '@effect/vitest';
-import { Data, Effect, Exit } from 'effect';
-import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
+import { beforeEach, vi } from 'vitest';
+import * as p from '@clack/prompts';
+import { Array as Arr, Data, Effect, Exit, pipe } from 'effect';
+import { getTerminalCapabilities, makeTerminalUI, TerminalUI } from 'src/services/terminal-ui';
import { TestLive, MockConsole } from 'test/__utils__';
+vi.mock('@clack/prompts', async importOriginal => {
+ const actual = await importOriginal<typeof import('@clack/prompts')>();
+ return { ...actual, confirm: vi.fn(), select: vi.fn() };
+});
+
class TestFailure extends Data.TaggedError('test/TestFailure')<{
readonly message: string;
}> {}
+const booleanStates = [false, true] as const;
+
+const ttyCombinations = pipe(
+ Arr.Do,
+ Arr.bind('stdin', () => booleanStates),
+ Arr.bind('stdout', () => booleanStates),
+ Arr.bind('stderr', () => booleanStates)
+);
+
+/** An intentional Node.js Writable test double matching Clack's output contract. */
+const makeSink = (isTTY: boolean) => {
+ const chunks: string[] = [];
+ const sink = new Writable({
+ write(chunk, _encoding, callback) {
+ chunks.push(String(chunk));
+ callback();
+ },
+ });
+ return Object.assign(sink, { isTTY, chunks });
+};
+
+const makeStreamedUi = (tty: { stdin: boolean; stdout: boolean; stderr: boolean }) => {
+ const stdout = makeSink(tty.stdout);
+ const stderr = makeSink(tty.stderr);
+ const ui = makeTerminalUI({ stdin: { isTTY: tty.stdin }, stdout, stderr });
+ return { ui, stdout, stderr };
+};
+
describe('TerminalUI', () => {
- it('classifies prompt and decoration capabilities independently', () => {
- expect(
- getTerminalCapabilities({
- stdin: { isTTY: false },
- stdout: { isTTY: true },
- stderr: { isTTY: true },
- })
- ).toEqual({
- stdinIsTTY: false,
- stdoutIsTTY: true,
- stderrIsTTY: true,
- isInteractive: false,
- canDecorate: true,
+ it.each(ttyCombinations)(
+ 'derives each capability from only the streams that serve it (stdin=$stdin, stdout=$stdout, stderr=$stderr)',
+ ({ stdin, stdout, stderr }) => {
+ expect(
+ getTerminalCapabilities({
+ stdin: { isTTY: stdin },
+ stdout: { isTTY: stdout },
+ stderr: { isTTY: stderr },
+ })
+ ).toEqual({
+ stdinIsTTY: stdin,
+ stdoutIsTTY: stdout,
+ stderrIsTTY: stderr,
+ canPrompt: stdin && stderr,
+ canDecorate: stderr,
+ });
+ }
+ );
+
+ describe('each capability is decided only by its own streams (behavior, not booleans)', () => {
+ beforeEach(() => {
+ vi.mocked(p.confirm).mockReset();
+ vi.mocked(p.select).mockReset();
});
+
+ it.effect(
+ 'stdin redirected, stdout+stderr TTY: prompts fall back, stdout stays clean, decoration renders',
+ () =>
+ Effect.gen(function* () {
+ const { ui, stdout, stderr } = makeStreamedUi({
+ stdin: false,
+ stdout: true,
+ stderr: true,
+ });
+
+ const confirmed = yield* ui.confirm('proceed?', { defaultValue: false });
+ expect(confirmed).toBe(false);
+ expect(p.confirm).not.toHaveBeenCalled();
+
+ const selected = yield* ui.select('pick', [
+ { value: 'first', label: 'First' },
+ { value: 'second', label: 'Second' },
+ ]);
+ expect(selected).toBe('first');
+ expect(p.select).not.toHaveBeenCalled();
+
+ yield* ui.output('{"machine":"data"}');
+ expect(stdout.chunks).toEqual([]);
+
+ yield* ui.output('forced-data', { force: true });
+ expect(stdout.chunks.join('')).toContain('forced-data');
+
+ yield* ui.log.info('stdin-redirect decoration');
+ expect(stderr.chunks.join('')).toContain('stdin-redirect decoration');
+ })
+ );
+
+ it.effect(
+ 'stdout piped, stdin+stderr TTY: prompting stays available, data emits, decoration renders',
+ () =>
+ Effect.gen(function* () {
+ vi.mocked(p.confirm).mockResolvedValue(false);
+ const { ui, stdout, stderr } = makeStreamedUi({
+ stdin: true,
+ stdout: false,
+ stderr: true,
+ });
+
+ const confirmed = yield* ui.confirm('proceed?', { defaultValue: true });
+ expect(p.confirm).toHaveBeenCalledTimes(1);
+ expect(confirmed).toBe(false);
+
+ yield* ui.output('{"machine":"data"}');
+ expect(stdout.chunks.join('')).toContain('{"machine":"data"}');
+
+ yield* ui.log.info('stdout-piped decoration');
+ expect(stderr.chunks.join('')).toContain('stdout-piped decoration');
+ })
+ );
+
+ it.effect(
+ 'stderr captured, stdin+stdout TTY: no prompts, no decoration, stdout silent unless forced',
+ () =>
+ Effect.gen(function* () {
+ const { ui, stdout, stderr } = makeStreamedUi({
+ stdin: true,
+ stdout: true,
+ stderr: false,
+ });
+
+ const confirmed = yield* ui.confirm('proceed?', { defaultValue: true });
+ expect(confirmed).toBe(true);
+ expect(p.confirm).not.toHaveBeenCalled();
+
+ yield* ui.log.info('captured decoration');
+ expect(stderr.chunks).toEqual([]);
+
+ yield* ui.output('{"machine":"data"}');
+ expect(stdout.chunks).toEqual([]);
+
+ yield* ui.output('forced-data', { force: true });
+ expect(stdout.chunks.join('')).toContain('forced-data');
+ })
+ );
+
+ it.effect('all streams redirected: machine output still emits', () =>
+ Effect.gen(function* () {
+ const { ui, stdout, stderr } = makeStreamedUi({
+ stdin: false,
+ stdout: false,
+ stderr: false,
+ });
+
+ yield* ui.output('{"machine":"data"}');
+ expect(stdout.chunks.join('')).toContain('{"machine":"data"}');
+
+ yield* ui.log.info('invisible decoration');
+ expect(stderr.chunks).toEqual([]);
+ })
+ );
});
layer(TestLive())(it => {
diff --git a/ts/packages/cli/test/src/services/update-check.test.ts b/ts/packages/cli/test/src/services/update-check.test.ts
index d1d50dd7e..96b1e6583 100644
--- a/ts/packages/cli/test/src/services/update-check.test.ts
+++ b/ts/packages/cli/test/src/services/update-check.test.ts
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { Effect, Fiber, Layer } from 'effect';
import { withHttpServerEffect } from 'test/__utils__/http-server';
-import type { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, type TerminalUI } from 'src/services/terminal-ui';
import {
createUpdateChecker,
parseLatestVersionFromReleases,
@@ -43,15 +43,19 @@ function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
const makeTerminal = (
output: string[],
- isInteractive = true
+ tty: { stdin: boolean; stdout: boolean; stderr: boolean } = {
+ stdin: true,
+ stdout: true,
+ stderr: true,
+ }
): Pick<TerminalUI, 'capabilities' | 'error'> => ({
- capabilities: Effect.succeed({
- stdinIsTTY: isInteractive,
- stdoutIsTTY: isInteractive,
- stderrIsTTY: isInteractive,
- isInteractive,
- canDecorate: isInteractive,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: tty.stdin },
+ stdout: { isTTY: tty.stdout },
+ stderr: { isTTY: tty.stderr },
+ })
+ ),
error: line => Effect.sync(() => output.push(line)),
});
@@ -216,18 +220,44 @@ describe('showUpdateNotice', () => {
}).pipe(Effect.provide(PlatformLayers))
);
- it.effect('does not print upgrade hint in non-interactive environments', () =>
+ it.effect('does not print upgrade hint when stderr is captured', () =>
Effect.gen(function* () {
const config = makeConfig({ currentVersion: '0.2.0' });
writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
const { showUpdateNotice } = createUpdateChecker(config);
- yield* showUpdateNotice(makeTerminal(output, false));
+ yield* showUpdateNotice(makeTerminal(output, { stdin: true, stdout: true, stderr: false }));
expect(output).toEqual([]);
}).pipe(Effect.provide(PlatformLayers))
);
+ it.effect('still prints upgrade hint when stdout is piped but stderr is a terminal', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.2.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
+ const { showUpdateNotice } = createUpdateChecker(config);
+
+ yield* showUpdateNotice(makeTerminal(output, { stdin: true, stdout: false, stderr: true }));
+
+ expect(output).toHaveLength(1);
+ expect(output[0]).toContain('Update available');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('still prints upgrade hint when stdin is redirected', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: '0.2.0' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
+ const { showUpdateNotice } = createUpdateChecker(config);
+
+ yield* showUpdateNotice(makeTerminal(output, { stdin: false, stdout: true, stderr: true }));
+
+ expect(output).toHaveLength(1);
+ expect(output[0]).toContain('Update available');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
it.effect('silently ignores corrupt state file', () =>
Effect.gen(function* () {
const config = makeConfig();
diff --git a/ts/packages/cli/test/src/services/upgrade-binary.test.ts b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
index 547ae5647..bf8612340 100644
--- a/ts/packages/cli/test/src/services/upgrade-binary.test.ts
+++ b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
@@ -6,7 +6,7 @@ import { existsSync, mkdirSync, readFileSync, mkdtempSync, writeFileSync } from
import { tmpdir } from 'node:os';
import path from 'node:path';
import { withHttpServer } from 'test/__utils__/http-server';
-import { TerminalUI } from 'src/services/terminal-ui';
+import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { UpgradeBinary, UpgradeBinaryError } from 'src/services/upgrade-binary';
import { NodeOs } from 'src/services/node-os';
import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-companion-modules';
@@ -14,13 +14,13 @@ import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-
const TerminalUINoop = Layer.succeed(
TerminalUI,
TerminalUI.of({
- capabilities: Effect.succeed({
- stdinIsTTY: false,
- stdoutIsTTY: false,
- stderrIsTTY: false,
- isInteractive: false,
- canDecorate: false,
- }),
+ capabilities: Effect.succeed(
+ getTerminalCapabilities({
+ stdin: { isTTY: false },
+ stdout: { isTTY: false },
+ stderr: { isTTY: false },
+ })
+ ),
output: () => Effect.void,
error: () => Effect.void,
intro: () => Effect.void,