diff --git a/package.json b/package.json index a09595a64..304dbe0e8 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "test": "vitest run", "test:watch": "vitest watch", "test:ui": "vitest --ui", + "test:e2e": "vitest run --config vitest.e2e.config.ts", "build": "tsc -p tsconfig.build.json", "start": "node dist/index.js", "dev": "tsx src/index.ts", diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 27775449e..7d531ced6 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -459,7 +459,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { console.log(getDisplayableAsciiArt()); // Start TUI with skipOnboarding since we already handled it - await startTUIChat({ + const tuiOptions: any = { initialPrompt: prompt, resume: options.resume, configPath: options.config, @@ -467,8 +467,48 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { additionalRules: options.rule, toolPermissionOverrides: permissionOverrides, skipOnboarding: true, - }); - return; + }; + + // If we detected piped input, create a custom stdin for TUI + if ((options as any).hasPipedInput) { + try { + const fs = await import("fs"); + const { ReadStream } = await import("tty"); + const ttyFd = fs.openSync("/dev/tty", "r"); + const customStdin = new ReadStream(ttyFd); + tuiOptions.customStdin = customStdin; + logger.debug("Created custom TTY stdin for TUI mode"); + } catch (error) { + logger.debug( + "Failed to create custom stdin, TUI may not work properly:", + error, + ); + } + } + + try { + await startTUIChat(tuiOptions); + return; + } catch (error) { + // If TUI fails (likely due to TTY issues with piped input), fall back to headless mode + if ( + error instanceof Error && + (error.message.includes("TUI initialization failed") || + error.message.includes("setRawMode") || + error.message.includes("Raw mode is not supported")) + ) { + logger.debug( + "TUI mode failed, falling back to headless mode:", + error.message, + ); + // Clear any partial output and switch to headless mode + console.clear(); + options.headless = true; + } else { + // Re-throw unexpected errors + throw error; + } + } } // Run headless mode diff --git a/src/e2e/pipe-input-tui.test.ts b/src/e2e/pipe-input-tui.test.ts new file mode 100644 index 000000000..99932a6da --- /dev/null +++ b/src/e2e/pipe-input-tui.test.ts @@ -0,0 +1,226 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; + +import { + createTestContext, + cleanupTestContext, + runCLI, + createTestConfig, + type CLITestContext, +} from "../test-helpers/cli-helpers.js"; + +describe("E2E: Pipe Input to TUI Mode", () => { + let context: CLITestContext; + + const testConfig = `name: Test Assistant +version: 1.0.0 +schema: v1 +models: + - model: gpt-4 + provider: openai + apiKey: test-key + roles: + - chat`; + + const testEnv = { OPENAI_API_KEY: "test-key" }; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + await cleanupTestContext(context); + }); + + describe("piped input handling in test environment", () => { + it("should maintain backward compatibility with explicit -p flag", async () => { + await createTestConfig(context, testConfig); + + const result = await runCLI(context, { + args: ["-p", "--config", context.configPath!], + env: testEnv, + input: "Explicit headless mode", + timeout: 5000, + expectError: true, + }); + + // With explicit -p flag, should be in headless mode + // Should show headless mode error (no prompt provided when input is ignored in test) + expect(result.stderr).toContain("A prompt is required when using the -p/--print flag"); + expect(result.exitCode).not.toBe(0); + }); + + it("should handle explicit -p flag with prompt argument", async () => { + await createTestConfig(context, testConfig); + + const result = await runCLI(context, { + args: ["-p", "--config", context.configPath!, "Test prompt"], + env: testEnv, + timeout: 5000, + expectError: true, + }); + + // With explicit -p flag and prompt, should attempt headless mode + // Will fail due to missing LLM configuration, but that's expected + expect(result.exitCode).not.toBe(0); + + // Should not show the "prompt required" error since we provided one + expect(result.stderr).not.toContain("A prompt is required when using the -p/--print flag"); + }); + + it("should try to start TUI mode when no explicit flags are provided", async () => { + await createTestConfig(context, testConfig); + + const result = await runCLI(context, { + args: ["--config", context.configPath!], + env: testEnv, + input: "This will be ignored in test environment", + timeout: 3000, // Shorter timeout since we expect quick failure + expectError: true, + }); + + // Without -p flag, should attempt TUI mode + // In test environment, this will likely fail quickly due to stdin/TTY issues + // but the important thing is that it doesn't immediately error about missing prompt + expect(result.stderr).not.toContain("A prompt is required when using the -p/--print flag"); + + // Should exit with error due to test environment limitations + expect(result.exitCode).not.toBe(0); + }); + + it("should handle platform differences in subprocess execution", async () => { + await createTestConfig(context, testConfig); + + // Test that the CLI can be executed on different platforms without crashing + const result = await runCLI(context, { + args: ["--config", context.configPath!, "Test cross-platform"], + env: testEnv, + timeout: 3000, + expectError: true, + }); + + // The key is that it should not crash immediately + // Platform-specific behavior may vary, but basic execution should work + expect(result.exitCode).toBeDefined(); + expect(typeof result.stdout).toBe("string"); + expect(typeof result.stderr).toBe("string"); + + // On any platform, should not show headless-mode specific errors + // when no -p flag is provided + expect(result.stderr).not.toContain("A prompt is required when using the -p/--print flag"); + }); + }); + + describe("configuration and environment handling", () => { + it("should handle invalid configuration gracefully", async () => { + // Test with malformed config + await createTestConfig(context, "invalid: yaml\nno: models: here"); + + const result = await runCLI(context, { + args: ["--config", context.configPath!], + env: testEnv, + timeout: 3000, + expectError: true, + }); + + // Should fail due to invalid config, not due to pipe handling + expect(result.exitCode).not.toBe(0); + }); + + it("should handle missing config file", async () => { + const result = await runCLI(context, { + args: ["--config", "/nonexistent/config.yaml"], + env: testEnv, + timeout: 3000, + expectError: true, + }); + + // Should fail due to missing config + expect(result.exitCode).not.toBe(0); + }); + + it("should handle various environment variables", async () => { + await createTestConfig(context, testConfig); + + // Test with different environment configurations + const testEnvs = [ + { ...testEnv, NODE_ENV: "production" }, + { ...testEnv, NODE_ENV: "development" }, + { ...testEnv, CI: "true" }, + ]; + + for (const env of testEnvs) { + const result = await runCLI(context, { + args: ["--config", context.configPath!], + env, + timeout: 3000, + expectError: true, + }); + + // Should handle different environments without crashing + expect(result.exitCode).toBeDefined(); + } + }); + }); + + describe("argument processing", () => { + it("should handle various flag combinations", async () => { + await createTestConfig(context, testConfig); + + const flagCombinations = [ + ["--verbose", "--config", context.configPath!], + ["--config", context.configPath!, "--verbose"], + ["--config", context.configPath!, "prompt with spaces"], + ]; + + for (const args of flagCombinations) { + const result = await runCLI(context, { + args, + env: testEnv, + timeout: 3000, + expectError: true, + }); + + // Should process arguments without immediate crashes + expect(result.exitCode).toBeDefined(); + } + }); + + it("should handle help and version flags", async () => { + // These should work without config + const helpResult = await runCLI(context, { + args: ["--help"], + timeout: 3000, + }); + + expect(helpResult.exitCode).toBe(0); + expect(helpResult.stdout).toContain("Continue CLI"); + + const versionResult = await runCLI(context, { + args: ["--version"], + timeout: 3000, + }); + + expect(versionResult.exitCode).toBe(0); + expect(versionResult.stdout).toMatch(/\d+\.\d+\.\d+/); + }); + }); +}); + +/** + * Note: This test suite focuses on testing the CLI behavior within the constraints + * of the test environment. The actual pipe input detection cannot be fully tested + * here because: + * + * 1. readStdinSync() returns null when CONTINUE_CLI_TEST=true to prevent hanging + * 2. TUI mode requires real TTY access which isn't available in test subprocesses + * 3. Cross-platform TTY behavior varies significantly + * + * However, we test: + * - Backward compatibility with explicit flags + * - Proper argument processing + * - Error handling for various scenarios + * - Platform-agnostic behavior + * + * For manual testing of the full pipe functionality, use: + * npm run build && echo "test" | node dist/index.js + */ \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index aabd18629..25e14da8c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -62,6 +62,28 @@ addCommonOptions(program) ) .option("--resume", "Resume from last session") .action(async (prompt, options) => { + // Handle piped input - detect it early and decide on mode + let stdinInput = null; + + if (!options.print) { + // Check if there's piped input available + stdinInput = readStdinSync(); + if (stdinInput) { + // Use piped input as the initial prompt + if (prompt) { + // Combine stdin and prompt argument + prompt = `${stdinInput}\n\n${prompt}`; + } else { + // Only stdin input, use as initial prompt + prompt = stdinInput; + } + + // We have piped input but want to use TUI mode + // Store a flag to pass custom stdin to TUI + (options as any).hasPipedInput = true; + } + } + // Configure console overrides FIRST, before any other logging const isHeadless = options.print; configureConsoleForHeadless(isHeadless); @@ -101,16 +123,16 @@ addCommonOptions(program) logger.debug("Verbose logging enabled"); } - // Check for piped input when using -p flag - if (options.print) { - const stdinInput = readStdinSync(); - if (stdinInput) { + // Handle piped input for headless mode (only if we haven't already read it) + if (options.print && !stdinInput) { + const headlessStdinInput = readStdinSync(); + if (headlessStdinInput) { if (prompt) { // Combine stdin and prompt argument - stdin comes first in XML block - prompt = `\n${stdinInput}\n\n\n${prompt}`; + prompt = `\n${headlessStdinInput}\n\n\n${prompt}`; } else { // Only stdin input, use as-is - prompt = stdinInput; + prompt = headlessStdinInput; } } } diff --git a/src/ui/index.ts b/src/ui/index.ts index 12a88e303..d29361885 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -1,11 +1,5 @@ -import { render } from "ink"; -import React from "react"; - import { PermissionMode } from "../permissions/types.js"; import { initializeServices } from "../services/index.js"; -import { ServiceContainerProvider } from "../services/ServiceContainerContext.js"; - -import { AppRoot } from "./AppRoot.js"; export { MarkdownRenderer } from "./MarkdownRenderer.js"; @@ -24,7 +18,9 @@ interface StartTUIChatOptions { skipOnboarding?: boolean; } -export async function startTUIChat(options: StartTUIChatOptions) { +export async function startTUIChat( + options: StartTUIChatOptions & { customStdin?: NodeJS.ReadStream }, +) { const { initialPrompt, resume, @@ -33,7 +29,9 @@ export async function startTUIChat(options: StartTUIChatOptions) { additionalRules, toolPermissionOverrides, skipOnboarding, + customStdin, } = options; + // Initialize services only if not already done (skipOnboarding means already initialized) if (!skipOnboarding) { initializeServices({ @@ -47,17 +45,41 @@ export async function startTUIChat(options: StartTUIChatOptions) { }); } + // Dynamically import Ink and React only when we need them + const [{ render }, React, { ServiceContainerProvider }, { AppRoot }] = + await Promise.all([ + import("ink"), + import("react"), + import("../services/ServiceContainerContext.js"), + import("./AppRoot.js"), + ]); + // Start the TUI immediately - it will handle loading states - const { unmount } = render( - React.createElement(ServiceContainerProvider, { - children: React.createElement(AppRoot, { - configPath, - initialPrompt, - resume, - additionalRules, + const renderOptions: any = {}; + if (customStdin) { + renderOptions.stdin = customStdin; + } + + let unmount: () => void; + try { + const result = render( + React.createElement(ServiceContainerProvider, { + children: React.createElement(AppRoot, { + configPath, + initialPrompt, + resume, + additionalRules, + }), }), - }), - ); + renderOptions, + ); + unmount = result.unmount; + } catch (error) { + // If TUI fails to start (e.g., TTY issues), throw a clear error + throw new Error( + `TUI initialization failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } // Handle cleanup process.on("SIGINT", () => { @@ -72,6 +94,15 @@ export async function startRemoteTUIChat( remoteUrl: string, initialPrompt?: string, ) { + // Dynamically import Ink and React only when we need them + const [{ render }, React, { ServiceContainerProvider }, { AppRoot }] = + await Promise.all([ + import("ink"), + import("react"), + import("../services/ServiceContainerContext.js"), + import("./AppRoot.js"), + ]); + // Start the TUI in remote mode - no services needed const { unmount } = render( React.createElement(ServiceContainerProvider, { diff --git a/src/util/stdin.test.ts b/src/util/stdin.test.ts new file mode 100644 index 000000000..5dd1ff2ef --- /dev/null +++ b/src/util/stdin.test.ts @@ -0,0 +1,202 @@ +import * as fs from "fs"; + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; + +// Mock fs module +vi.mock("fs"); + +describe("stdin handling", () => { + let originalEnv: typeof process.env; + let originalIsTTY: boolean | undefined; + + beforeEach(() => { + originalEnv = { ...process.env }; + originalIsTTY = process.stdin.isTTY; + vi.clearAllMocks(); + }); + + afterEach(() => { + process.env = originalEnv; + (process.stdin as any).isTTY = originalIsTTY; + }); + + describe("readStdinSync", () => { + it("should return null in test environments", async () => { + // Test that the function respects test environment variables + process.env.NODE_ENV = "test"; + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(result).toBe(null); + }); + + it("should return null when CONTINUE_CLI_TEST is set", async () => { + process.env.CONTINUE_CLI_TEST = "true"; + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(result).toBe(null); + }); + + it("should return null when VITEST is set", async () => { + process.env.VITEST = "true"; + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(result).toBe(null); + }); + + it("should return null when stdin is a TTY", async () => { + // Clear test environment variables + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + + // Mock stdin as TTY + (process.stdin as any).isTTY = true; + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(result).toBe(null); + }); + + it("should attempt to read when stdin is not a TTY", async () => { + // Clear test environment variables + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + + // Mock stdin as not TTY (piped) + (process.stdin as any).isTTY = false; + + // Mock fs.readFileSync to return test data + const mockReadFileSync = vi.mocked(fs.readFileSync); + mockReadFileSync.mockReturnValue("test input data"); + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8"); + expect(result).toBe("test input data"); + }); + + it("should handle fs.readFileSync errors gracefully", async () => { + // Clear test environment variables + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + + // Mock stdin as not TTY + (process.stdin as any).isTTY = false; + + // Mock fs.readFileSync to throw an error + const mockReadFileSync = vi.mocked(fs.readFileSync); + mockReadFileSync.mockImplementation(() => { + throw new Error("EAGAIN: resource temporarily unavailable"); + }); + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(result).toBe(null); + }); + + it("should trim whitespace from stdin input", async () => { + // Clear test environment variables + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + + // Mock stdin as not TTY + (process.stdin as any).isTTY = false; + + // Mock fs.readFileSync to return data with whitespace + const mockReadFileSync = vi.mocked(fs.readFileSync); + mockReadFileSync.mockReturnValue(" test input with whitespace \n"); + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(result).toBe("test input with whitespace"); + }); + + it("should handle undefined isTTY property", async () => { + // Clear test environment variables + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + + // Mock stdin with undefined isTTY (some environments) + (process.stdin as any).isTTY = undefined; + + // Mock fs.readFileSync to return test data + const mockReadFileSync = vi.mocked(fs.readFileSync); + mockReadFileSync.mockReturnValue("undefined tty test"); + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8"); + expect(result).toBe("undefined tty test"); + }); + + it("should handle CI environment with TTY correctly", async () => { + // Clear test environment variables except CI + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + process.env.CI = "true"; + + // Mock stdin as TTY in CI + (process.stdin as any).isTTY = true; + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + // Should return null in CI when stdin is a TTY + expect(result).toBe(null); + }); + }); + + describe("platform compatibility", () => { + it("should work on different Node.js versions", async () => { + // Test that the function doesn't rely on Node.js version-specific features + const { readStdinSync } = await import("./stdin.js"); + + // Should not throw errors regardless of environment + expect(() => readStdinSync()).not.toThrow(); + }); + + it("should handle file descriptor availability", async () => { + // Clear test environment variables + delete process.env.NODE_ENV; + delete process.env.VITEST; + delete process.env.CONTINUE_CLI_TEST; + delete process.env.JEST_WORKER_ID; + + (process.stdin as any).isTTY = false; + + // Mock fs.readFileSync to simulate fd 0 not available + const mockReadFileSync = vi.mocked(fs.readFileSync); + mockReadFileSync.mockImplementation(() => { + throw new Error("EBADF: bad file descriptor"); + }); + + const { readStdinSync } = await import("./stdin.js"); + const result = readStdinSync(); + + // Should handle the error gracefully + expect(result).toBe(null); + }); + }); +}); \ No newline at end of file