An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): centralize interactivity contract — no command hangs in non-TTY/CI (#2463)
Joeyfcf4f22995b9
diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjsindex 396a3d6a03..6836322a05 100644--- a/packages/cli/src/commands/init.mjs+++ b/packages/cli/src/commands/init.mjs@@ -20,6 +20,7 @@ import {CLI_ROOT} from '../utils/paths.mjs';import {getRunPrefix} from '../utils/package-manager.mjs';import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';import {listTemplates} from './template.mjs';+import {requireInteractive} from '../utils/interactive.mjs';const VALID_FEATURES = ['agents', 'theme', 'template'];const run = getRunPrefix();@@ -179,6 +180,15 @@ export function registerInit(program) {}// Interactive wizard+ //+ // Guard: this wizard blocks on prompts. In a non-interactive context+ // (CI, piped stdin/stdout, no TTY) it would hang forever. Fail fast+ // with actionable guidance via the shared interactivity contract.+ requireInteractive({+ command: 'init',+ hint: `\`${run} xds init --all\` or \`--features agents,theme,template\``,+ });+p.intro('Welcome to XDS');p.note(diff --git a/packages/cli/src/commands/interactive-guard.test.mjs b/packages/cli/src/commands/interactive-guard.test.mjsnew file mode 100644index 0000000000..c5097f489b--- /dev/null+++ b/packages/cli/src/commands/interactive-guard.test.mjs@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Subprocess no-hang tests for the interactivity contract.+ *+ * The wizard command `init` blocks on @clack/prompts. In a+ * non-interactive context it must fail fast (exit 1) instead of hanging.+ * These tests spawn the CLI as a real subprocess with stdin/stdout NOT a TTY+ * (stdio 'ignore'/'pipe'), which is exactly the CI / piped condition. If the+ * guard were missing, spawnSync would hit the timeout (signal SIGTERM,+ * status null) — so asserting `signal === null && status === 1` proves the+ * process exited cleanly rather than hanging.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {fileURLToPath} from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI = path.resolve(__dirname, '..', '..', 'bin', 'xds.mjs');++let tmpDir;++function runCli(args) {+ return spawnSync(process.execPath, [CLI, ...args], {+ cwd: tmpDir,+ encoding: 'utf8',+ timeout: 20_000,+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {...process.env, FORCE_COLOR: '0', CI: ''},+ });+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-interactive-guard-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('init non-interactive safety', () => {+ it('fails fast (exit 1, no hang) and writes no files', () => {+ const r = runCli(['init']);+ expect(r.signal).toBeNull();+ expect(r.status).toBe(1);+ expect(fs.readdirSync(tmpDir)).toEqual([]);+ });++ it('prints actionable guidance (--all / --features)', () => {+ const out = (() => {+ const r = runCli(['init']);+ return r.stderr + r.stdout;+ })();+ expect(out).toMatch(/requires a TTY/i);+ expect(out).toMatch(/--all/);+ expect(out).toMatch(/--features/);+ });++ it('still runs --features agents non-interactively (guard does not over-catch)', () => {+ const r = runCli(['init', '--features', 'agents']);+ expect(r.signal).toBeNull();+ expect(r.status).toBe(0);+ expect(fs.readdirSync(tmpDir).length).toBeGreaterThan(0);+ });+});diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjsindex 88bd401c36..8942772bfd 100644--- a/packages/cli/src/commands/swizzle.mjs+++ b/packages/cli/src/commands/swizzle.mjs@@ -15,6 +15,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import * as p from '@clack/prompts';import {findCoreDir, listComponents} from '../utils/paths.mjs';+import {isInteractive} from '../utils/interactive.mjs';import {jsonOut, jsonError} from '../lib/json.mjs';import {buildGapReportPreview,@@ -239,6 +240,15 @@ export function registerSwizzle(program) {}// Interactive gap report prompt+ //+ // This prompt is OPTIONAL — the swizzle copy already succeeded above.+ // In a non-interactive context (CI, piped I/O, no TTY) we must not+ // block on it; skip gracefully rather than hang. Use --gap with+ // explicit flags for non-interactive gap reporting.+ if (!isInteractive()) {+ return;+ }+if (!gapConfig.command && !checkGhCli()) {// Silently skip if gh isn't available and no custom command configuredreturn;diff --git a/packages/cli/src/utils/interactive.mjs b/packages/cli/src/utils/interactive.mjsnew file mode 100644index 0000000000..fd59c78146--- /dev/null+++ b/packages/cli/src/utils/interactive.mjs@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Interactivity contract for the CLI.+ *+ * A single source of truth for "can this process prompt the user?". Several+ * commands launch @clack/prompts wizards; in a non-interactive context (CI,+ * piped stdin/stdout, no TTY) those prompts block forever. Historically each+ * command answered this question differently — some checked `stdout.isTTY`,+ * one checked `stdin.isTTY`, one added `!process.env.CI`, and some had no+ * guard at all. This module centralizes the check so every command behaves+ * identically.+ *+ * Two entry points, for two situations:+ *+ * - `requireInteractive()` — for commands whose prompt IS the work+ * (e.g. `xds init`, `xds theme`). With no TTY there is nothing to do, so+ * fail fast (exit 1) with actionable, non-interactive guidance.+ *+ * - `isInteractive()` — for commands with an OPTIONAL secondary prompt+ * (e.g. swizzle's post-copy "report a gap?"). The primary work already+ * succeeded; callers use this to skip the prompt gracefully.+ */++/**+ * True when the process can safely run an interactive prompt.+ *+ * Requires BOTH stdin and stdout to be TTYs (clack reads stdin and renders to+ * stdout) and that we are not in a CI environment. A CI runner may allocate a+ * pseudo-TTY, so `process.env.CI` is an explicit override: never prompt in CI.+ *+ * @param {object} [env] - Override hook for tests.+ * @param {boolean} [env.stdinTTY=process.stdin.isTTY]+ * @param {boolean} [env.stdoutTTY=process.stdout.isTTY]+ * @param {boolean} [env.ci=Boolean(process.env.CI)]+ * @returns {boolean}+ */+export function isInteractive({+ stdinTTY = Boolean(process.stdin && process.stdin.isTTY),+ stdoutTTY = Boolean(process.stdout && process.stdout.isTTY),+ ci = Boolean(process.env.CI),+} = {}) {+ if (ci) return false;+ return stdinTTY && stdoutTTY;+}++/**+ * Guard for commands whose primary action is an interactive wizard. When the+ * process is non-interactive, prints an actionable error and exits 1 instead+ * of hanging on a prompt that will never receive input.+ *+ * @param {object} options+ * @param {string} options.command - Command name for the message, e.g. 'init'.+ * @param {string} options.hint - Concrete non-interactive invocation, e.g.+ * '`pnpm xds init --all` or `--features agents,theme,template`'.+ * @param {boolean} [options.json=false] - When true, the command does not+ * support --json; we still exit 1 but skip the human-formatted guidance.+ * @param {object} [env] - Forwarded to isInteractive (test hook).+ * @returns {void} Returns when interactive; otherwise calls process.exit(1).+ */+export function requireInteractive({command, hint, json = false} = {}, env) {+ if (isInteractive(env)) return;+ const name = command ? `xds ${command}` : 'this command';+ console.error(+ `Error: \`${name}\` with no flags is interactive and requires a TTY.`,+ );+ if (hint) {+ console.error(`Run non-interactively with: ${hint}`);+ }+ if (!json) {+ console.error(+ 'Detected a non-interactive environment (no TTY, piped I/O, or CI=1).',+ );+ }+ process.exit(1);+}diff --git a/packages/cli/src/utils/interactive.test.mjs b/packages/cli/src/utils/interactive.test.mjsnew file mode 100644index 0000000000..dc53090a18--- /dev/null+++ b/packages/cli/src/utils/interactive.test.mjs@@ -0,0 +1,68 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Unit tests for the interactivity contract.+ *+ * isInteractive() is pure given its injected env, so these are fast unit+ * tests. The "does the command actually fail fast instead of hanging" proof+ * lives in the per-command subprocess tests (init/theme non-interactive).+ */++import {describe, it, expect, vi, afterEach} from 'vitest';+import {isInteractive, requireInteractive} from './interactive.mjs';++describe('isInteractive', () => {+ it('is true only when stdin AND stdout are TTYs and not CI', () => {+ expect(isInteractive({stdinTTY: true, stdoutTTY: true, ci: false})).toBe(true);+ });++ it('is false when stdin is not a TTY (piped input)', () => {+ expect(isInteractive({stdinTTY: false, stdoutTTY: true, ci: false})).toBe(false);+ });++ it('is false when stdout is not a TTY (piped output)', () => {+ expect(isInteractive({stdinTTY: true, stdoutTTY: false, ci: false})).toBe(false);+ });++ it('is false in CI even with a pseudo-TTY on both streams', () => {+ expect(isInteractive({stdinTTY: true, stdoutTTY: true, ci: true})).toBe(false);+ });+});++describe('requireInteractive', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('returns (does not exit) when interactive', () => {+ const exit = vi.spyOn(process, 'exit').mockImplementation(() => {+ throw new Error('exit should not be called');+ });+ expect(() =>+ requireInteractive(+ {command: 'init', hint: '`xds init --all`'},+ {stdinTTY: true, stdoutTTY: true, ci: false},+ ),+ ).not.toThrow();+ expect(exit).not.toHaveBeenCalled();+ });++ it('exits 1 with actionable guidance when non-interactive', () => {+ const exit = vi+ .spyOn(process, 'exit')+ .mockImplementation(() => {+ throw new Error('__exit__');+ });+ const err = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(() =>+ requireInteractive(+ {command: 'theme', hint: '`xds theme <preset>`'},+ {stdinTTY: false, stdoutTTY: false, ci: false},+ ),+ ).toThrow('__exit__');+ expect(exit).toHaveBeenCalledWith(1);+ const output = err.mock.calls.map(c => c.join(' ')).join('\n');+ expect(output).toMatch(/requires a TTY/i);+ expect(output).toMatch(/xds theme <preset>/);+ });+});