@devries-cameron20 / composio-1 / commits / 2deb239e9
Fork 0

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

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

## Summary `TerminalUI` classified the terminal with a single aggregate: ```ts isInteractive = stdinIsTTY && stdoutIsTTY && stderrIsTTY; ``` and reused it for three unrelated decisions: whether Clack may prompt, whether `ui.output()` emits machine data, and caller behavior in login, setup, and the update notice. That let output routing change program behavior: - Redirecting stdout made `login` look non-interactive even though stdin and stderr were still usable, so `composio login | tee log` silently switched to the headless instructions path. - Redirecting only stdin made `ui.output()` write machine data onto a human-visible stdout terminal, because the output gate keyed off the prompting aggregate instead of stdout. - Capturing stderr changed stdout data emission, even though it is purely a reporting-mode concern. This PR separates the three capability axes so each stream owns exactly one decision: | Axis | Rule | | --- | --- | | Prompting | `canPrompt = stdinIsTTY && stderrIsTTY` — stdout is irrelevant | | Machine output | `ui.output(data)` writes only when stdout is **not** a TTY, or with explicit `{ force: true }` (unchanged) | | Decoration | `canDecorate = stderrIsTTY` (unchanged) | The aggregate `isInteractive` capability is removed rather than renamed, so no caller can reintroduce the conflation. ## Changes - `services/terminal-ui.ts`: `TerminalCapabilities` now exposes `canPrompt` instead of `isInteractive`; `output()` gates on `stdoutIsTTY` alone. The live implementation is now built by an exported `makeTerminalUI(streams)` factory so tests can exercise real behavior against injected streams; `TerminalUILive` passes `process.{stdin,stdout,stderr}` as before. - `commands/login.cmd.ts`: waiting for browser login is a prompting decision (`canPrompt`); intro/notes are stderr chrome (`canDecorate`). Piping stdout no longer reroutes authentication. - `commands/setup.cmd.ts`: the `--yes` guards for local changes now key off `canPrompt`. - `services/update-check.ts`: the update notice is advisory output for a human watching stderr, not part of any command's result, so it now keys off `canDecorate` — piping stdout no longer suppresses it, and it still never touches stdout, so piped data stays clean. - Telemetry continues to receive the raw per-stream TTY bits (unchanged). - `ts/packages/cli/AGENTS.md`: output conventions now document the three independent stream contracts. ## Tests - Full 8-combination TTY matrix at the classifier level. - Behavioral tests with fake sink streams and mocked Clack prompts, proving behavior rather than returned booleans: - stdin redirected, stdout+stderr TTY: prompts fall back to defaults without invoking Clack, `ui.output()` does **not** leak JSON to the visible terminal, `force` still writes, decoration renders; - stdout piped, stdin+stderr TTY: the Clack prompt actually runs, machine data emits, decoration renders; - stderr captured, stdin+stdout TTY: no prompts, no decoration, stdout suppressed unless forced; - everything redirected: machine data still emits. - Login regression: with stdout piped but stdin/stderr TTYs, `composio login --no-browser` enters the interactive wait (poll spinner) path and does not print the headless/agent instructions. - Update-notice regressions: still shown when stdout is piped or stdin is redirected; suppressed only when stderr is captured. ## Notes This is the shared prerequisite for https://github.com/ComposioHQ/composio/pull/3951 (captured-stderr plain renderer) and https://github.com/ComposioHQ/composio/pull/3945 (agent-friendly headless login). It intentionally implements neither feature; both PRs should rebase onto this once merged. No changeset: `@composio/cli` is Changesets-ignored. ## Verification - `pnpm typecheck` (repo root) - `pnpm --filter @composio/cli test` (validate:skills, validate:boundaries, full vitest suite) - `eslint` and `prettier --check` on all touched files VHS recordings skipped: internal capability wiring, no visible command-surface change.

Alberto Schiabel committed Jul 28, 2026 at 19:57 UTC 2deb239e94d89a4a57dd90d9a19705e7411873c9
14 files changed +501 -222
ts/packages/cli/AGENTS.md
+26 -6
@@ -111,14 +111,21 @@ Follow the Unix convention of separating human-readable decoration from machine-
111 - **stdout** — data only (`ui.output()`). Captured by pipes / `$(...)` / `> file`.
112 - **stderr** — all decoration (Clack spinners, logs, notes, intro/outro). Visible in terminal, invisible in pipes.
113
114 +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`):
115 +
116 +- **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.
117 +- **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.
118 +- **Decoration** (`canDecorate`) = `stderr.isTTY`. Spinners, logs, and notes only need stderr, so they still render when stdin or stdout is redirected.
119 +
120 Rules:
121
116 -1. All `TerminalUI` methods **except `output()`** write to stderr via Clack's `{ output: process.stderr }`, and only in interactive mode.
117 -2. `ui.output(data)` writes to stdout **only when piped** (checked via `process.stdout.isTTY`).
118 -3. When stdout is piped, **all decoration is suppressed** — `composio whoami | pbcopy` is completely silent and clipboard gets the clean key.
119 -4. **Data commands** (whoami, version, login, generate, etc.) call both decoration (stderr) and `ui.output()` (stdout).
120 -5. **Action commands** (logout, upgrade) produce no stdout data — output is purely decorative.
121 -6. **Never** write data to stderr or decoration to stdout.
122 +1. All `TerminalUI` methods **except `output()`** write to stderr via Clack's `{ output: process.stderr }`, and only when stderr is a TTY (`canDecorate`).
123 +2. `ui.output(data)` writes to stdout **only when stdout is piped** (or with explicit `force`). No other stream participates in that decision.
124 +3. Prompts (`ui.confirm`, `ui.select`) run only when `canPrompt`; otherwise they fall back to their defaults without blocking.
125 +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.
126 +5. **Data commands** (whoami, version, login, generate, etc.) call both decoration (stderr) and `ui.output()` (stdout).
127 +6. **Action commands** (logout, upgrade) produce no stdout data — output is purely decorative.
128 +7. **Never** write data to stderr or decoration to stdout, and never branch program behavior (auth paths, command flow) on stdout's TTY state.
129
130 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.
131
@@ -137,6 +144,19 @@ Effect.gen(function* () {
144
145 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.
146
147 +For table-driven tests over independent finite choices, use Effect Array do notation
148 +to build a typed Cartesian product instead of enumerating every case or nesting loops:
149 +
150 +```typescript
151 +const cases = pipe(
152 + Arr.Do,
153 + Arr.bind('firstAxis', () => choices),
154 + Arr.bind('secondAxis', () => choices)
155 +);
156 +```
157 +
158 +Each `Arr.bind` adds one independent axis to the generated cases.
159 +
160 ### Effect safety and migration seams
161
162 - 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.
ts/packages/cli/src/commands/login.cmd.ts
+5 -5
@@ -631,7 +631,7 @@ export const browserLogin = (params: {
631 expiresAt,
632 });
633
634 - const canPrompt = (yield* ui.capabilities).isInteractive;
634 + const { canPrompt, canDecorate } = yield* ui.capabilities;
635 const effectiveNoWait = params.noWait || !canPrompt;
636 const effectiveNoBrowser = params.noBrowser || effectiveNoWait;
637
@@ -641,7 +641,7 @@ export const browserLogin = (params: {
641 pollCommand,
642 });
643
644 - if (canPrompt) {
644 + if (canDecorate) {
645 yield* ui.log.info('Please login using the following URL:');
646 yield* ui.note(url, 'Login URL');
647 yield* ui.note(loginInstructions, 'Login instructions');
@@ -807,9 +807,9 @@ export const loginCmd = Command.make(
807 Effect.gen(function* () {
808 const ui = yield* TerminalUI;
809 const ctx = yield* ComposioUserContext;
810 - const canPrompt = (yield* ui.capabilities).isInteractive;
810 + const { canPrompt, canDecorate } = yield* ui.capabilities;
811
812 - if (canPrompt) {
812 + if (canDecorate) {
813 yield* ui.intro('composio login');
814 }
815
@@ -868,7 +868,7 @@ export const loginCmd = Command.make(
868 organizations: loginResult.organizations,
869 };
870 const pollSummary = formatPollLoginComplete(pollSummaryParams);
871 - if (canPrompt) {
871 + if (canDecorate) {
872 yield* ui.note(pollSummary, 'Login complete');
873 }
874 yield* ui.output(serializePollLoginResult(pollSummaryParams), { force: true });
ts/packages/cli/src/commands/setup.cmd.ts
+2 -2
@@ -180,7 +180,7 @@ const setupBaseCmd = Command.make(
180 }
181
182 if (!yes && removable.length > 0) {
183 - if (!terminal.isInteractive) {
183 + if (!terminal.canPrompt) {
184 return yield* setupCommandError(
185 'Non-interactive uninstall requires `--yes` to approve local changes.',
186 operation
@@ -228,7 +228,7 @@ const setupBaseCmd = Command.make(
228
229 const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));
230 if (!yes) {
231 - if (!terminal.isInteractive) {
231 + if (!terminal.canPrompt) {
232 return yield* setupCommandError(
233 'Non-interactive setup requires `--yes` to approve local changes.',
234 operation
ts/packages/cli/src/services/terminal-ui.ts
+180 -132
@@ -1,4 +1,5 @@
1 import process from 'node:process';
2 +import type { Writable } from 'node:stream';
3 import * as p from '@clack/prompts';
4 import { Context, Effect, Exit, Layer } from 'effect';
5
@@ -12,11 +13,29 @@ export type TerminalStdio = {
13 readonly stderr: TtyLikeStream;
14 };
15
16 +/**
17 + * Per-stream terminal capabilities.
18 + *
19 + * The three streams are independent contracts, so each derived capability
20 + * depends only on the streams that actually serve it:
21 + *
22 + * - `canPrompt` — stdin must accept human input and stderr must display the
23 + * Clack prompt. stdout is irrelevant: piping data must not change prompting
24 + * or authentication behavior.
25 + * - `canDecorate` — decoration (spinners, logs, notes) renders on stderr, so it
26 + * only needs stderr.
27 + * - machine output — `TerminalUI.output()` consults `stdoutIsTTY` alone.
28 + *
29 + * There is deliberately no aggregate "interactive" flag: it conflated these
30 + * concerns and let output routing change program behavior.
31 + */
32 export type TerminalCapabilities = {
33 readonly stdinIsTTY: boolean;
34 readonly stdoutIsTTY: boolean;
35 readonly stderrIsTTY: boolean;
19 - readonly isInteractive: boolean;
36 + /** Whether Clack prompts can run (`stdinIsTTY && stderrIsTTY`). */
37 + readonly canPrompt: boolean;
38 + /** Whether stderr decoration can render (`stderrIsTTY`). */
39 readonly canDecorate: boolean;
40 };
41
@@ -30,7 +49,7 @@ export const getTerminalCapabilities = (stdio: TerminalStdio): TerminalCapabilit
49 stdinIsTTY,
50 stdoutIsTTY,
51 stderrIsTTY,
33 - isInteractive: stdinIsTTY && stdoutIsTTY && stderrIsTTY,
52 + canPrompt: stdinIsTTY && stderrIsTTY,
53 canDecorate: stderrIsTTY,
54 };
55 };
@@ -60,9 +79,11 @@ export interface TerminalUI {
79 * Write raw data to stdout for piping and scripting.
80 *
81 * This is the ONLY method that writes to stdout — everything else goes to stderr.
63 - * When stdout is a TTY (interactive terminal), this is a no-op — the human already
82 + * When stdout is a TTY (a human is watching it), this is a no-op — the human already
83 * sees the data via decoration on stderr. When stdout is redirected (pipe, subshell,
65 - * file), the raw value is written for machine consumption.
84 + * file), the raw value is written for machine consumption. Only stdout's own TTY
85 + * state participates in this decision; redirecting stdin or stderr must never make
86 + * data leak onto a visible stdout terminal.
87 *
88 * Use this for values that scripts should capture (API keys, version strings, etc.).
89 */
@@ -115,7 +136,7 @@ export interface TerminalUI {
136
137 /**
138 * Ask the user a yes/no confirmation question.
118 - * In non-interactive mode (piped), returns `defaultValue` (defaults to `true`).
139 + * When prompting is unavailable, returns `defaultValue` (defaults to `true`).
140 */
141 readonly confirm: (
142 message: string,
@@ -124,7 +145,7 @@ export interface TerminalUI {
145
146 /**
147 * Present a single-select list to the user.
127 - * In non-interactive mode (piped), returns the first option's value.
148 + * When prompting is unavailable, returns the first option's value.
149 */
150 readonly select: <Value>(
151 message: string,
@@ -151,33 +172,20 @@ export interface TerminalUI {
172 export const TerminalUI = Context.GenericTag<TerminalUI>('services/TerminalUI');
173
174 // ---------------------------------------------------------------------------
154 -// TerminalUILive — production layer using @clack/prompts
175 +// makeTerminalUI — build a TerminalUI from explicit streams
176 // ---------------------------------------------------------------------------
177
178 /**
158 - * Whether the CLI can prompt for human input. Human-only prompts are shown only
159 - * when stdin/stdout/stderr are all TTYs; agent and shell pipelines get
160 - * non-interactive behavior.
161 - */
162 -const liveCapabilities = getTerminalCapabilities({
163 - stdin: process.stdin,
164 - stdout: process.stdout,
165 - stderr: process.stderr,
166 -});
167 -
168 -const canPrompt = liveCapabilities.isInteractive;
169 -
170 -/**
171 - * Whether the CLI can render auxiliary UI. Logs, notes, and spinners only need
172 - * stderr, so they can still be shown when stdin is redirected from /dev/null or
173 - * stdout is reserved for machine-readable JSON/data.
179 + * Intentionally a Node.js Writable rather than an Effect Sink: Clack accepts
180 + * Writable streams and writes to them synchronously.
181 */
175 -const canDecorate = liveCapabilities.canDecorate;
182 +type TerminalWritable = TtyLikeStream & Writable;
183
177 -/** Run a decoration side-effect only when stderr is a terminal. */
178 -function decorate(fn: () => void): void {
179 - if (canDecorate) fn();
180 -}
184 +type TerminalUIStreams = {
185 + readonly stdin: TtyLikeStream;
186 + readonly stdout: TerminalWritable;
187 + readonly stderr: TerminalWritable;
188 +};
189
190 function createClackSpinnerHandle(
191 s: p.SpinnerResult,
@@ -202,121 +210,161 @@ function createClackSpinnerHandle(
210 };
211 }
212
205 -/** No-op spinner handle used when decoration is suppressed (piped mode). */
213 +/** No-op spinner handle used when decoration is suppressed (stderr redirected). */
214 const silentSpinnerHandle: SpinnerHandle = {
215 message: () => Effect.void,
216 stop: () => Effect.void,
217 error: () => Effect.void,
218 };
219
212 -const makeLive: TerminalUI = {
213 - capabilities: Effect.succeed(liveCapabilities),
220 +/**
221 + * Build a TerminalUI backed by the given streams.
222 + *
223 + * Each stream governs exactly one concern:
224 + * - stdin + stderr decide prompting (`canPrompt`);
225 + * - stdout alone decides machine output (`output()` writes only when stdout
226 + * is not a TTY, or when `force` is set);
227 + * - stderr alone decides decoration (`canDecorate`).
228 + */
229 +export const makeTerminalUI = (streams: TerminalUIStreams): TerminalUI => {
230 + const capabilities = getTerminalCapabilities(streams);
231 + const { canPrompt, canDecorate, stdoutIsTTY } = capabilities;
232 + const stderr = streams.stderr;
233 +
234 + const decorate = (render: () => void): Effect.Effect<void> => {
235 + if (!canDecorate) {
236 + return Effect.void;
237 + }
238 + return Effect.sync(render);
239 + };
240 +
241 + return {
242 + capabilities: Effect.succeed(capabilities),
243 +
244 + output: (data, options) =>
245 + Effect.sync(() => {
246 + if (options?.force || !stdoutIsTTY) {
247 + streams.stdout.write(`${data}\n`);
248 + }
249 + }),
250 +
251 + error: data => Effect.sync(() => stderr.write(`${data}\n`)),
252 +
253 + intro: title => decorate(() => p.intro(title, { output: stderr })),
254 + outro: message => decorate(() => p.outro(message, { output: stderr })),
255 +
256 + log: {
257 + info: message => decorate(() => p.log.info(message, { output: stderr })),
258 + success: message => decorate(() => p.log.success(message, { output: stderr })),
259 + warn: message => decorate(() => p.log.warn(message, { output: stderr })),
260 + error: message => decorate(() => p.log.error(message, { output: stderr })),
261 + step: message => decorate(() => p.log.step(message, { output: stderr })),
262 + message: message => decorate(() => p.log.message(message, { output: stderr })),
263 + },
264 +
265 + note: (message, title) =>
266 + decorate(() => p.note(message, title ?? '', { format: line => line, output: stderr })),
267
215 - output: (data, options) =>
216 - Effect.sync(() => {
217 - if (options?.force || !canPrompt) {
218 - process.stdout.write(`${data}\n`);
268 + select: ((
269 + message: string,
270 + options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
271 + ) => {
272 + if (!canPrompt) {
273 + return Effect.succeed(options[0].value);
274 }
220 - }),
221 -
222 - error: data => Effect.sync(() => process.stderr.write(`${data}\n`)),
223 -
224 - intro: title => Effect.sync(() => decorate(() => p.intro(title, { output: process.stderr }))),
225 - outro: message => Effect.sync(() => decorate(() => p.outro(message, { output: process.stderr }))),
226 -
227 - log: {
228 - info: message =>
229 - Effect.sync(() => decorate(() => p.log.info(message, { output: process.stderr }))),
230 - success: message =>
231 - Effect.sync(() => decorate(() => p.log.success(message, { output: process.stderr }))),
232 - warn: message =>
233 - Effect.sync(() => decorate(() => p.log.warn(message, { output: process.stderr }))),
234 - error: message =>
235 - Effect.sync(() => decorate(() => p.log.error(message, { output: process.stderr }))),
236 - step: message =>
237 - Effect.sync(() => decorate(() => p.log.step(message, { output: process.stderr }))),
238 - message: message =>
239 - Effect.sync(() => decorate(() => p.log.message(message, { output: process.stderr }))),
240 - },
241 -
242 - note: (message, title) =>
243 - Effect.sync(() =>
244 - decorate(() => p.note(message, title ?? '', { format: line => line, output: process.stderr }))
245 - ),
246 -
247 - select: ((
248 - message: string,
249 - options: ReadonlyArray<{ value: unknown; label: string; hint?: string }>
250 - ) =>
251 - canPrompt
252 - ? Effect.promise(async () => {
253 - const result = await p.select({
254 - message,
255 - options: [...options],
256 - output: process.stderr,
257 - });
258 - // p.select returns Value | symbol (symbol on cancel)
259 - if (typeof result === 'symbol') return options[0].value;
260 - return result;
261 - })
262 - : Effect.succeed(options[0].value)) as TerminalUI['select'],
263 -
264 - confirm: (message, options) =>
265 - canPrompt
266 - ? Effect.promise(async () => {
267 - const result = await p.confirm({
268 - message,
269 - initialValue: options?.defaultValue ?? true,
270 - output: process.stderr,
271 - });
272 - // p.confirm returns boolean | symbol (symbol on cancel)
273 - return typeof result === 'boolean' ? result : false;
274 - })
275 - : Effect.succeed(options?.defaultValue ?? true),
276 -
277 - withSpinner: (message, effect, options) =>
278 - canDecorate
279 - ? Effect.acquireUseRelease(
275 +
276 + return Effect.promise(async () => {
277 + const result = await p.select({
278 + message,
279 + options: [...options],
280 + output: stderr,
281 + });
282 + // p.select returns Value | symbol (symbol on cancel)
283 + if (typeof result === 'symbol') return options[0].value;
284 + return result;
285 + });
286 + }) as TerminalUI['select'],
287 +
288 + confirm: (message, options) => {
289 + if (!canPrompt) {
290 + return Effect.succeed(options?.defaultValue ?? true);
291 + }
292 +
293 + return Effect.promise(async () => {
294 + const result = await p.confirm({
295 + message,
296 + initialValue: options?.defaultValue ?? true,
297 + output: stderr,
298 + });
299 + if (p.isCancel(result)) return false;
300 + return result;
301 + });
302 + },
303 +
304 + withSpinner: (message, effect, options) => {
305 + if (!canDecorate) {
306 + return effect;
307 + }
308 +
309 + return Effect.acquireUseRelease(
310 + Effect.sync(() => {
311 + const s = p.spinner({ output: stderr });
312 + s.start(message);
313 + return s;
314 + }),
315 + () => effect,
316 + (s, exit) =>
317 Effect.sync(() => {
281 - const s = p.spinner({ output: process.stderr });
282 - s.start(message);
283 - return s;
284 - }),
285 - () => effect,
286 - (s, exit) =>
287 - Effect.sync(() => {
288 - if (Exit.isSuccess(exit)) {
289 - const successMsg =
290 - typeof options?.successMessage === 'function'
291 - ? options.successMessage(exit.value)
292 - : (options?.successMessage ?? message);
293 - s.stop(successMsg);
294 - } else {
295 - s.error(options?.errorMessage ?? message);
318 + if (Exit.isSuccess(exit)) {
319 + let successMessage = message;
320 + const configuredSuccessMessage = options?.successMessage;
321 + if (typeof configuredSuccessMessage === 'function') {
322 + successMessage = configuredSuccessMessage(exit.value);
323 + } else if (configuredSuccessMessage !== undefined) {
324 + successMessage = configuredSuccessMessage;
325 }
297 - })
298 - )
299 - : effect,
326 + s.stop(successMessage);
327 + } else {
328 + s.error(options?.errorMessage ?? message);
329 + }
330 + })
331 + );
332 + },
333 +
334 + useMakeSpinner: (message, use) => {
335 + if (!canDecorate) {
336 + return use(silentSpinnerHandle);
337 + }
338
301 - useMakeSpinner: (message, use) =>
302 - canDecorate
303 - ? Effect.acquireUseRelease(
339 + return Effect.acquireUseRelease(
340 + Effect.sync(() => {
341 + const s = p.spinner({ output: stderr });
342 + s.start(message);
343 + const { handle, isStopped } = createClackSpinnerHandle(s, message);
344 + return { raw: s, handle, isStopped };
345 + }),
346 + ({ handle }) => use(handle),
347 + ({ raw, isStopped }, exit) =>
348 Effect.sync(() => {
305 - const s = p.spinner({ output: process.stderr });
306 - s.start(message);
307 - const { handle, isStopped } = createClackSpinnerHandle(s, message);
308 - return { raw: s, handle, isStopped };
309 - }),
310 - ({ handle }) => use(handle),
311 - ({ raw, isStopped }, exit) =>
312 - Effect.sync(() => {
313 - // Only clean up if the spinner hasn't been stopped/errored by the callback
314 - if (Exit.isFailure(exit) && !isStopped()) {
315 - raw.error(message);
316 - }
317 - })
318 - )
319 - : use(silentSpinnerHandle),
349 + // Only clean up if the spinner hasn't been stopped/errored by the callback
350 + if (Exit.isFailure(exit) && !isStopped()) {
351 + raw.error(message);
352 + }
353 + })
354 + );
355 + },
356 + };
357 };
358
322 -export const TerminalUILive = Layer.succeed(TerminalUI, makeLive);
359 +// ---------------------------------------------------------------------------
360 +// TerminalUILive — production layer using @clack/prompts
361 +// ---------------------------------------------------------------------------
362 +
363 +export const TerminalUILive = Layer.succeed(
364 + TerminalUI,
365 + makeTerminalUI({
366 + stdin: process.stdin,
367 + stdout: process.stdout,
368 + stderr: process.stderr,
369 + })
370 +);
ts/packages/cli/src/services/update-check.ts
+4 -2
@@ -173,8 +173,10 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
173 */
174 function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
175 return Effect.gen(function* () {
176 - const capabilities = yield* terminal.capabilities;
177 - if (!capabilities.isInteractive) return;
176 + // `terminal.error` writes even when stderr is redirected, so gate this
177 + // advisory notice explicitly while leaving stdout out of the decision.
178 + const { canDecorate } = yield* terminal.capabilities;
179 + if (!canDecorate) return;
180
181 const state = yield* readState;
182 const latestVersion = semver.valid(state.latestVersion);
ts/packages/cli/test/__utils__/services/terminal-ui-test.ts
+8 -8
@@ -1,5 +1,5 @@
1 import { Console, Effect, Exit, Layer } from 'effect';
2 -import { TerminalUI } from 'src/services/terminal-ui';
2 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
3
4 /**
5 * Test layer for TerminalUI that routes all output through Effect's Console.
@@ -8,13 +8,13 @@ import { TerminalUI } from 'src/services/terminal-ui';
8 * no ANSI codes, no spinners.
9 */
10 export const terminalUITestImpl = TerminalUI.of({
11 - capabilities: Effect.succeed({
12 - stdinIsTTY: false,
13 - stdoutIsTTY: false,
14 - stderrIsTTY: false,
15 - isInteractive: false,
16 - canDecorate: false,
17 - }),
11 + capabilities: Effect.succeed(
12 + getTerminalCapabilities({
13 + stdin: { isTTY: false },
14 + stdout: { isTTY: false },
15 + stderr: { isTTY: false },
16 + })
17 + ),
18 output: data => Console.log(data),
19 error: data => Console.error(data),
20
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+8 -8
@@ -5,7 +5,7 @@ import { extendConfigProvider } from 'src/services/config';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 -import { TerminalUI } from 'src/services/terminal-ui';
8 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
9 import open from 'open';
10 import { afterEach, vi } from 'vitest';
11
@@ -57,13 +57,13 @@ const testConfigProvider = ConfigProvider.fromMap(
57 ).pipe(extendConfigProvider);
58
59 const RecordingTerminalUI = TerminalUI.of({
60 - capabilities: Effect.succeed({
61 - stdinIsTTY: true,
62 - stdoutIsTTY: true,
63 - stderrIsTTY: true,
64 - isInteractive: true,
65 - canDecorate: true,
66 - }),
60 + capabilities: Effect.succeed(
61 + getTerminalCapabilities({
62 + stdin: { isTTY: true },
63 + stdout: { isTTY: true },
64 + stderr: { isTTY: true },
65 + })
66 + ),
67 output: (data, options) =>
68 Console.log(
69 JSON.stringify({
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+8 -8
@@ -2,7 +2,7 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Console, Effect } from 'effect';
3 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
4 import { extendConfigProvider } from 'src/services/config';
5 -import { TerminalUI } from 'src/services/terminal-ui';
5 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { cli, TestLive, MockConsole } from 'test/__utils__';
8 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -90,13 +90,13 @@ const testConfigProvider = ConfigProvider.fromMap(
90
91 const terminalUIWithConfirm = (confirmed: boolean) =>
92 TerminalUI.of({
93 - capabilities: Effect.succeed({
94 - stdinIsTTY: true,
95 - stdoutIsTTY: true,
96 - stderrIsTTY: true,
97 - isInteractive: true,
98 - canDecorate: true,
99 - }),
93 + capabilities: Effect.succeed(
94 + getTerminalCapabilities({
95 + stdin: { isTTY: true },
96 + stdout: { isTTY: true },
97 + stderr: { isTTY: true },
98 + })
99 + ),
100 output: data => Console.log(data),
101 error: data => Console.error(data),
102 intro: title => Console.log(`-- ${title} --`),
ts/packages/cli/test/src/commands/login.cmd.test.ts
+38 -1
@@ -1,12 +1,14 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 -import { Effect, Option } from 'effect';
3 +import { Console, Effect, Exit, Option } from 'effect';
4 import { HelpDoc, ValidationError } from '@effect/cli';
5 import path from 'node:path';
6 import { FileSystem } from '@effect/platform';
7 import { cli, MockConsole, TestLive } from 'test/__utils__';
8 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
9 import * as constants from 'src/constants';
10 import { setupCacheDir } from 'src/effects/setup-cache-dir';
11 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
12 import { ComposioUserContext } from 'src/services/user-context';
13
14 const mockFetchResponse = (body: unknown, status = 200) =>
@@ -124,6 +126,41 @@ describe('CLI: composio login', () => {
126 );
127 });
128
129 + describe('login with stdout piped', () => {
130 + const pipedStdoutUI = TerminalUI.of({
131 + ...terminalUITestImpl,
132 + capabilities: Effect.succeed(
133 + getTerminalCapabilities({
134 + stdin: { isTTY: true },
135 + stdout: { isTTY: false },
136 + stderr: { isTTY: true },
137 + })
138 + ),
139 + useMakeSpinner: (message, _use) =>
140 + Console.log(`[spinner] ${message}`).pipe(
141 + Effect.andThen(Effect.die(new Error('test: interactive poll loop entered')))
142 + ),
143 + });
144 +
145 + layer(TestLive({ terminalUI: pipedStdoutUI }))(it => {
146 + it.scoped(
147 + '[When] stdout is piped but stdin and stderr are TTYs [Then] login stays interactive instead of going headless',
148 + () =>
149 + Effect.gen(function* () {
150 + const exit = yield* Effect.exit(cli(['login', '--no-browser']));
151 +
152 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
153 + expect(output).toContain('[spinner] Waiting for login...');
154 + expect(output).toContain('Please login using the following URL');
155 + expect(output).not.toContain('Open this URL in your browser to log in:');
156 + expect(output).not.toContain('hint: For agents:');
157 + expect(output).not.toContain('Then run this command to complete login:');
158 + expect(Exit.isFailure(exit)).toBe(true);
159 + })
160 + );
161 + });
162 + });
163 +
164 layer(TestLive())(it => {
165 it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
166 Effect.gen(function* () {
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+8 -8
@@ -7,19 +7,19 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { UserDataWithDefaults } from 'src/models/user-data';
8 import { writeStoredAgentIdentity } from 'src/services/agents';
9 import { extendConfigProvider } from 'src/services/config';
10 -import { TerminalUI } from 'src/services/terminal-ui';
10 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
11 import { ComposioUserContext } from 'src/services/user-context';
12 import { cli, TestLive, MockConsole } from 'test/__utils__';
13
14 const terminalUIWithConfirm = (confirmed: boolean) =>
15 TerminalUI.of({
16 - capabilities: Effect.succeed({
17 - stdinIsTTY: true,
18 - stdoutIsTTY: true,
19 - stderrIsTTY: true,
20 - isInteractive: true,
21 - canDecorate: true,
22 - }),
16 + capabilities: Effect.succeed(
17 + getTerminalCapabilities({
18 + stdin: { isTTY: true },
19 + stdout: { isTTY: true },
20 + stderr: { isTTY: true },
21 + })
22 + ),
23 output: data => Console.log(data),
24 error: data => Console.error(data),
25 intro: title => Console.log(`-- ${title} --`),
ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
+8 -8
@@ -4,7 +4,7 @@ import { Effect, Exit } from 'effect';
4 import { afterEach, beforeEach, vi } from 'vitest';
5 import { CommandRunner } from 'src/services/command-runner';
6 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
7 -import { TerminalUI } from 'src/services/terminal-ui';
7 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
8 import { cli, TestLive } from 'test/__utils__';
9 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
10
@@ -162,13 +162,13 @@ const makeSkillInstaller = (initiallyReady = false) => {
162 // The cancellation path requires an interactive terminal to reach the confirm prompt.
163 const decliningUI = TerminalUI.of({
164 ...terminalUITestImpl,
165 - capabilities: Effect.succeed({
166 - stdinIsTTY: false,
167 - stdoutIsTTY: false,
168 - stderrIsTTY: false,
169 - isInteractive: true,
170 - canDecorate: false,
171 - }),
165 + capabilities: Effect.succeed(
166 + getTerminalCapabilities({
167 + stdin: { isTTY: true },
168 + stdout: { isTTY: false },
169 + stderr: { isTTY: true },
170 + })
171 + ),
172 confirm: () => Effect.succeed(false),
173 });
174
ts/packages/cli/test/src/services/terminal-ui.test.ts
+157 -15
@@ -1,27 +1,169 @@
1 +import { Writable } from 'node:stream';
2 import { describe, expect, it, layer } from '@effect/vitest';
2 -import { Data, Effect, Exit } from 'effect';
3 -import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
3 +import { beforeEach, vi } from 'vitest';
4 +import * as p from '@clack/prompts';
5 +import { Array as Arr, Data, Effect, Exit, pipe } from 'effect';
6 +import { getTerminalCapabilities, makeTerminalUI, TerminalUI } from 'src/services/terminal-ui';
7 import { TestLive, MockConsole } from 'test/__utils__';
8
9 +vi.mock('@clack/prompts', async importOriginal => {
10 + const actual = await importOriginal<typeof import('@clack/prompts')>();
11 + return { ...actual, confirm: vi.fn(), select: vi.fn() };
12 +});
13 +
14 class TestFailure extends Data.TaggedError('test/TestFailure')<{
15 readonly message: string;
16 }> {}
17
18 +const booleanStates = [false, true] as const;
19 +
20 +const ttyCombinations = pipe(
21 + Arr.Do,
22 + Arr.bind('stdin', () => booleanStates),
23 + Arr.bind('stdout', () => booleanStates),
24 + Arr.bind('stderr', () => booleanStates)
25 +);
26 +
27 +/** An intentional Node.js Writable test double matching Clack's output contract. */
28 +const makeSink = (isTTY: boolean) => {
29 + const chunks: string[] = [];
30 + const sink = new Writable({
31 + write(chunk, _encoding, callback) {
32 + chunks.push(String(chunk));
33 + callback();
34 + },
35 + });
36 + return Object.assign(sink, { isTTY, chunks });
37 +};
38 +
39 +const makeStreamedUi = (tty: { stdin: boolean; stdout: boolean; stderr: boolean }) => {
40 + const stdout = makeSink(tty.stdout);
41 + const stderr = makeSink(tty.stderr);
42 + const ui = makeTerminalUI({ stdin: { isTTY: tty.stdin }, stdout, stderr });
43 + return { ui, stdout, stderr };
44 +};
45 +
46 describe('TerminalUI', () => {
11 - it('classifies prompt and decoration capabilities independently', () => {
12 - expect(
13 - getTerminalCapabilities({
14 - stdin: { isTTY: false },
15 - stdout: { isTTY: true },
16 - stderr: { isTTY: true },
17 - })
18 - ).toEqual({
19 - stdinIsTTY: false,
20 - stdoutIsTTY: true,
21 - stderrIsTTY: true,
22 - isInteractive: false,
23 - canDecorate: true,
47 + it.each(ttyCombinations)(
48 + 'derives each capability from only the streams that serve it (stdin=$stdin, stdout=$stdout, stderr=$stderr)',
49 + ({ stdin, stdout, stderr }) => {
50 + expect(
51 + getTerminalCapabilities({
52 + stdin: { isTTY: stdin },
53 + stdout: { isTTY: stdout },
54 + stderr: { isTTY: stderr },
55 + })
56 + ).toEqual({
57 + stdinIsTTY: stdin,
58 + stdoutIsTTY: stdout,
59 + stderrIsTTY: stderr,
60 + canPrompt: stdin && stderr,
61 + canDecorate: stderr,
62 + });
63 + }
64 + );
65 +
66 + describe('each capability is decided only by its own streams (behavior, not booleans)', () => {
67 + beforeEach(() => {
68 + vi.mocked(p.confirm).mockReset();
69 + vi.mocked(p.select).mockReset();
70 });
71 +
72 + it.effect(
73 + 'stdin redirected, stdout+stderr TTY: prompts fall back, stdout stays clean, decoration renders',
74 + () =>
75 + Effect.gen(function* () {
76 + const { ui, stdout, stderr } = makeStreamedUi({
77 + stdin: false,
78 + stdout: true,
79 + stderr: true,
80 + });
81 +
82 + const confirmed = yield* ui.confirm('proceed?', { defaultValue: false });
83 + expect(confirmed).toBe(false);
84 + expect(p.confirm).not.toHaveBeenCalled();
85 +
86 + const selected = yield* ui.select('pick', [
87 + { value: 'first', label: 'First' },
88 + { value: 'second', label: 'Second' },
89 + ]);
90 + expect(selected).toBe('first');
91 + expect(p.select).not.toHaveBeenCalled();
92 +
93 + yield* ui.output('{"machine":"data"}');
94 + expect(stdout.chunks).toEqual([]);
95 +
96 + yield* ui.output('forced-data', { force: true });
97 + expect(stdout.chunks.join('')).toContain('forced-data');
98 +
99 + yield* ui.log.info('stdin-redirect decoration');
100 + expect(stderr.chunks.join('')).toContain('stdin-redirect decoration');
101 + })
102 + );
103 +
104 + it.effect(
105 + 'stdout piped, stdin+stderr TTY: prompting stays available, data emits, decoration renders',
106 + () =>
107 + Effect.gen(function* () {
108 + vi.mocked(p.confirm).mockResolvedValue(false);
109 + const { ui, stdout, stderr } = makeStreamedUi({
110 + stdin: true,
111 + stdout: false,
112 + stderr: true,
113 + });
114 +
115 + const confirmed = yield* ui.confirm('proceed?', { defaultValue: true });
116 + expect(p.confirm).toHaveBeenCalledTimes(1);
117 + expect(confirmed).toBe(false);
118 +
119 + yield* ui.output('{"machine":"data"}');
120 + expect(stdout.chunks.join('')).toContain('{"machine":"data"}');
121 +
122 + yield* ui.log.info('stdout-piped decoration');
123 + expect(stderr.chunks.join('')).toContain('stdout-piped decoration');
124 + })
125 + );
126 +
127 + it.effect(
128 + 'stderr captured, stdin+stdout TTY: no prompts, no decoration, stdout silent unless forced',
129 + () =>
130 + Effect.gen(function* () {
131 + const { ui, stdout, stderr } = makeStreamedUi({
132 + stdin: true,
133 + stdout: true,
134 + stderr: false,
135 + });
136 +
137 + const confirmed = yield* ui.confirm('proceed?', { defaultValue: true });
138 + expect(confirmed).toBe(true);
139 + expect(p.confirm).not.toHaveBeenCalled();
140 +
141 + yield* ui.log.info('captured decoration');
142 + expect(stderr.chunks).toEqual([]);
143 +
144 + yield* ui.output('{"machine":"data"}');
145 + expect(stdout.chunks).toEqual([]);
146 +
147 + yield* ui.output('forced-data', { force: true });
148 + expect(stdout.chunks.join('')).toContain('forced-data');
149 + })
150 + );
151 +
152 + it.effect('all streams redirected: machine output still emits', () =>
153 + Effect.gen(function* () {
154 + const { ui, stdout, stderr } = makeStreamedUi({
155 + stdin: false,
156 + stdout: false,
157 + stderr: false,
158 + });
159 +
160 + yield* ui.output('{"machine":"data"}');
161 + expect(stdout.chunks.join('')).toContain('{"machine":"data"}');
162 +
163 + yield* ui.log.info('invisible decoration');
164 + expect(stderr.chunks).toEqual([]);
165 + })
166 + );
167 });
168
169 layer(TestLive())(it => {
ts/packages/cli/test/src/services/update-check.test.ts
+41 -11
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
5 import { BunFileSystem, BunPath } from '@effect/platform-bun';
6 import { Effect, Fiber, Layer } from 'effect';
7 import { withHttpServerEffect } from 'test/__utils__/http-server';
8 -import type { TerminalUI } from 'src/services/terminal-ui';
8 +import { getTerminalCapabilities, type TerminalUI } from 'src/services/terminal-ui';
9 import {
10 createUpdateChecker,
11 parseLatestVersionFromReleases,
@@ -43,15 +43,19 @@ function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
43
44 const makeTerminal = (
45 output: string[],
46 - isInteractive = true
46 + tty: { stdin: boolean; stdout: boolean; stderr: boolean } = {
47 + stdin: true,
48 + stdout: true,
49 + stderr: true,
50 + }
51 ): Pick<TerminalUI, 'capabilities' | 'error'> => ({
48 - capabilities: Effect.succeed({
49 - stdinIsTTY: isInteractive,
50 - stdoutIsTTY: isInteractive,
51 - stderrIsTTY: isInteractive,
52 - isInteractive,
53 - canDecorate: isInteractive,
54 - }),
52 + capabilities: Effect.succeed(
53 + getTerminalCapabilities({
54 + stdin: { isTTY: tty.stdin },
55 + stdout: { isTTY: tty.stdout },
56 + stderr: { isTTY: tty.stderr },
57 + })
58 + ),
59 error: line => Effect.sync(() => output.push(line)),
60 });
61
@@ -216,18 +220,44 @@ describe('showUpdateNotice', () => {
220 }).pipe(Effect.provide(PlatformLayers))
221 );
222
219 - it.effect('does not print upgrade hint in non-interactive environments', () =>
223 + it.effect('does not print upgrade hint when stderr is captured', () =>
224 Effect.gen(function* () {
225 const config = makeConfig({ currentVersion: '0.2.0' });
226 writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
227 const { showUpdateNotice } = createUpdateChecker(config);
228
225 - yield* showUpdateNotice(makeTerminal(output, false));
229 + yield* showUpdateNotice(makeTerminal(output, { stdin: true, stdout: true, stderr: false }));
230
231 expect(output).toEqual([]);
232 }).pipe(Effect.provide(PlatformLayers))
233 );
234
235 + it.effect('still prints upgrade hint when stdout is piped but stderr is a terminal', () =>
236 + Effect.gen(function* () {
237 + const config = makeConfig({ currentVersion: '0.2.0' });
238 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
239 + const { showUpdateNotice } = createUpdateChecker(config);
240 +
241 + yield* showUpdateNotice(makeTerminal(output, { stdin: true, stdout: false, stderr: true }));
242 +
243 + expect(output).toHaveLength(1);
244 + expect(output[0]).toContain('Update available');
245 + }).pipe(Effect.provide(PlatformLayers))
246 + );
247 +
248 + it.effect('still prints upgrade hint when stdin is redirected', () =>
249 + Effect.gen(function* () {
250 + const config = makeConfig({ currentVersion: '0.2.0' });
251 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
252 + const { showUpdateNotice } = createUpdateChecker(config);
253 +
254 + yield* showUpdateNotice(makeTerminal(output, { stdin: false, stdout: true, stderr: true }));
255 +
256 + expect(output).toHaveLength(1);
257 + expect(output[0]).toContain('Update available');
258 + }).pipe(Effect.provide(PlatformLayers))
259 + );
260 +
261 it.effect('silently ignores corrupt state file', () =>
262 Effect.gen(function* () {
263 const config = makeConfig();
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+8 -8
@@ -6,7 +6,7 @@ import { existsSync, mkdirSync, readFileSync, mkdtempSync, writeFileSync } from
6 import { tmpdir } from 'node:os';
7 import path from 'node:path';
8 import { withHttpServer } from 'test/__utils__/http-server';
9 -import { TerminalUI } from 'src/services/terminal-ui';
9 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
10 import { UpgradeBinary, UpgradeBinaryError } from 'src/services/upgrade-binary';
11 import { NodeOs } from 'src/services/node-os';
12 import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-companion-modules';
@@ -14,13 +14,13 @@ import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-
14 const TerminalUINoop = Layer.succeed(
15 TerminalUI,
16 TerminalUI.of({
17 - capabilities: Effect.succeed({
18 - stdinIsTTY: false,
19 - stdoutIsTTY: false,
20 - stderrIsTTY: false,
21 - isInteractive: false,
22 - canDecorate: false,
23 - }),
17 + capabilities: Effect.succeed(
18 + getTerminalCapabilities({
19 + stdin: { isTTY: false },
20 + stdout: { isTTY: false },
21 + stderr: { isTTY: false },
22 + })
23 + ),
24 output: () => Effect.void,
25 error: () => Effect.void,
26 intro: () => Effect.void,