From 2c95e2c3223d9fee7269ca958aa28b78a8646a0e Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Sat, 23 Aug 2025 02:49:20 -0700 Subject: [PATCH] feat: ctrl+c once to clear input, twice to exit --- extensions/cli/spec/ctrl-c-behavior.md | 28 +++++ .../__tests__/CtrlCProcessHandling.test.ts | 12 ++ extensions/cli/src/index.ts | 64 +++++++++- .../cli/src/ui/FreeTrialTransitionUI.tsx | 12 ++ extensions/cli/src/ui/MCPSelector.tsx | 7 +- extensions/cli/src/ui/Selector.tsx | 16 ++- extensions/cli/src/ui/UserInput.tsx | 8 ++ .../__tests__/BottomStatusBarCtrlC.test.tsx | 63 ++++++++++ .../cli/src/ui/__tests__/CtrlC.test.tsx | 119 ++++++++++++++++++ .../ui/__tests__/CtrlCInputClearing.test.tsx | 63 ++++++++++ .../cli/src/ui/components/BottomStatusBar.tsx | 94 ++++++++------ .../ui/components/ToolPermissionSelector.tsx | 4 +- extensions/cli/src/ui/hooks/useUserInput.ts | 17 ++- extensions/cli/src/ui/index.ts | 21 ++-- 14 files changed, 464 insertions(+), 64 deletions(-) create mode 100644 extensions/cli/spec/ctrl-c-behavior.md create mode 100644 extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts create mode 100644 extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx create mode 100644 extensions/cli/src/ui/__tests__/CtrlC.test.tsx create mode 100644 extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx diff --git a/extensions/cli/spec/ctrl-c-behavior.md b/extensions/cli/spec/ctrl-c-behavior.md new file mode 100644 index 000000000..72fd49b17 --- /dev/null +++ b/extensions/cli/spec/ctrl-c-behavior.md @@ -0,0 +1,28 @@ +# Ctrl+C Exit Behavior + +## Overview + +Ctrl+C operates on two levels: +1. **Menus/Selectors**: Immediate cancellation and return to previous state +2. **Main Application**: Two-stage exit requiring double Ctrl+C within 1 second + +## Two-Stage Exit (Main Application) + +### First Ctrl+C +- Shows temporary status message "ctrl+c to exit" in bottom-left status bar +- Message automatically disappears after 1 second +- Clears any text in the input field (if focused) +- Does **not** exit the application + +### Second Ctrl+C (within 1 second) +- Exits the application immediately +- Performs graceful shutdown + +### Second Ctrl+C (after 1 second) +- Treated as a new "first Ctrl+C" +- Shows exit message again +- User must press Ctrl+C twice within 1 second window to actually exit + +## Menu/Selector Cancellation + +Ctrl+C immediately cancels and returns to the previous state in all interactive menus and selectors. diff --git a/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts new file mode 100644 index 000000000..31782b653 --- /dev/null +++ b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it, vi } from "vitest"; + +describe("Process SIGINT handling functions", () => { + it("exports the necessary functions for exit message handling", async () => { + const indexModule = await import("../index.js"); + + // Verify the functions exist + expect(typeof indexModule.shouldShowExitMessage).toBe("function"); + expect(typeof indexModule.setExitMessageCallback).toBe("function"); + expect(typeof indexModule.setTUIUnmount).toBe("function"); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index cf3040968..78d10729e 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -23,6 +23,35 @@ import { logger } from "./util/logger.js"; import { readStdinSync } from "./util/stdin.js"; import { getVersion } from "./version.js"; +// TUI lifecycle and two-stage exit state management +let tuiUnmount: (() => void) | null; +let showExitMessage: boolean; +let exitMessageCallback: (() => void) | null; +let lastCtrlCTime: number; + +// Initialize state immediately to avoid temporal dead zone issues with exported functions +(function initializeTUIState() { + tuiUnmount = null; + showExitMessage = false; + exitMessageCallback = null; + lastCtrlCTime = 0; +})(); + +// Register TUI cleanup function for graceful shutdown +export function setTUIUnmount(unmount: () => void) { + tuiUnmount = unmount; +} + +// Register callback to trigger UI updates when exit message state changes +export function setExitMessageCallback(callback: () => void) { + exitMessageCallback = callback; +} + +// Check if "ctrl+c to exit" message should be displayed +export function shouldShowExitMessage(): boolean { + return showExitMessage; +} + // Add global error handlers to prevent uncaught errors from crashing the process process.on("unhandledRejection", (reason, promise) => { logger.error("Unhandled Rejection at:", { promise, reason }); @@ -262,10 +291,39 @@ try { process.exit(1); } -// Graceful shutdown - flush Sentry data +// Graceful shutdown with two-stage Ctrl+C exit + +// Remove all existing SIGINT listeners first +process.removeAllListeners("SIGINT"); + process.on("SIGINT", async () => { - await sentryService.flush(); - process.exit(0); + const now = Date.now(); + const timeSinceLastCtrlC = now - lastCtrlCTime; + + if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) { + // Second Ctrl+C within 1 second - exit + showExitMessage = false; + if (tuiUnmount) { + tuiUnmount(); + } + await sentryService.flush(); + process.exit(0); + } else { + // First Ctrl+C or too much time elapsed - show exit message + lastCtrlCTime = now; + showExitMessage = true; + if (exitMessageCallback) { + exitMessageCallback(); + } + + // Hide message after 1 second + setTimeout(() => { + showExitMessage = false; + if (exitMessageCallback) { + exitMessageCallback(); + } + }, 1000); + } }); process.on("SIGTERM", async () => { diff --git a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx index d23cfceba..19fc8ca5d 100644 --- a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx +++ b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx @@ -130,6 +130,18 @@ const FreeTrialTransitionUI: React.FC = ({ const hasOrganizations = organizations && organizations.length > 0; useInput((input, key) => { + // Allow Escape to cancel immediately, but Ctrl+C uses two-stage exit + if (key.escape) { + closeCurrentScreen(); + return; + } + + // Handle Ctrl+C with two-stage exit (delegates to main process) + if (key.ctrl && input === "c") { + process.kill(process.pid, "SIGINT"); + return; + } + if (currentStep === "choice") { handleChoiceInput({ input, diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index 80c52f6e5..a06372fec 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -216,13 +216,14 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const maxIndex = Math.max(0, items.length - 1); useInput(async (input, key) => { - if (isLoading) return; - - if (key.escape) { + // Always allow escape/Ctrl+C so users can cancel even when loading + if (key.escape || (key.ctrl && input === "c")) { handleBack(); return; } + if (isLoading) return; + if (key.upArrow) { setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1); return; diff --git a/extensions/cli/src/ui/Selector.tsx b/extensions/cli/src/ui/Selector.tsx index 3c76446df..b8ba5f4c4 100644 --- a/extensions/cli/src/ui/Selector.tsx +++ b/extensions/cli/src/ui/Selector.tsx @@ -40,8 +40,20 @@ export function Selector({ onNavigate, renderOption, }: SelectorProps) { + // Handle input for loading and error states useInput((input, key) => { - if (key.escape) { + if (loading || error) { + if (key.escape || (key.ctrl && input === "c")) { + onCancel(); + return; + } + } + }); + + useInput((input, key) => { + if (loading || error) return; // Skip normal input handling during loading/error + + if (key.escape || (key.ctrl && input === "c")) { onCancel(); return; } @@ -84,7 +96,7 @@ export function Selector({ {error} - Press Escape to cancel + Press Esc to cancel ); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 0ebfc2858..466d8b421 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -62,6 +62,13 @@ const UserInput: React.FC = ({ const [inputText, setInputText] = useState(""); const [cursorPosition, setCursorPosition] = useState(0); const [showSlashCommands, setShowSlashCommands] = useState(false); + + // Clear input function for Ctrl+C + const clearInput = useCallback(() => { + textBuffer.clear(); + setInputText(""); + setCursorPosition(0); + }, [textBuffer]); const [slashCommandFilter, setSlashCommandFilter] = useState(""); const [selectedCommandIndex, setSelectedCommandIndex] = useState(0); const [showFileSearch, setShowFileSearch] = useState(false); @@ -427,6 +434,7 @@ const UserInput: React.FC = ({ showSlashCommands, showFileSearch, cycleModes, + clearInput, }) ) { return; diff --git a/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx new file mode 100644 index 000000000..8088b4aa5 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx @@ -0,0 +1,63 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { BottomStatusBar } from "../components/BottomStatusBar.js"; + +// Mock the index module functions +vi.mock("../../index.js", () => ({ + shouldShowExitMessage: vi.fn(() => false), + setExitMessageCallback: vi.fn(), +})); + +describe("BottomStatusBar Ctrl+C message", () => { + const defaultProps = { + currentMode: "normal" as const, + repoURLText: "github.com/user/repo", + isRemoteMode: false, + services: { model: { model: null } }, + navState: { currentScreen: "chat" }, + navigateTo: vi.fn(), + closeCurrentScreen: vi.fn(), + contextPercentage: undefined, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + // Reset mocks to default state + const indexModule = await vi.importMock("../../index.js") as any; + indexModule.shouldShowExitMessage.mockReturnValue(false); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("shows repo URL when not in exit message mode", async () => { + const indexModule = await vi.importMock("../../index.js") as any; + indexModule.shouldShowExitMessage.mockReturnValue(false); + + const { lastFrame } = render(); + + expect(lastFrame()).toContain("github.com/user/repo"); + expect(lastFrame()).not.toContain("ctrl+c to exit"); + }); + + it("shows exit message when shouldShowExitMessage returns true", async () => { + const indexModule = await vi.importMock("../../index.js") as any; + indexModule.shouldShowExitMessage.mockReturnValue(true); + + const { lastFrame } = render(); + + expect(lastFrame()).toContain("ctrl+c to exit"); + expect(lastFrame()).not.toContain("github.com/user/repo"); + }); + + it("registers exit message callback on mount", async () => { + const indexModule = await vi.importMock("../../index.js") as any; + + render(); + + expect(indexModule.setExitMessageCallback).toHaveBeenCalledWith(expect.any(Function)); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/__tests__/CtrlC.test.tsx b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx new file mode 100644 index 000000000..9051d3849 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx @@ -0,0 +1,119 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { Selector } from "../Selector.js"; +import { MCPSelector } from "../MCPSelector.js"; +import { ConfigSelector } from "../ConfigSelector.js"; + +describe("Ctrl+C behavior", () => { + let mockOnCancel: ReturnType; + let mockOnSelect: ReturnType; + let mockProcess: any; + + beforeEach(() => { + mockOnCancel = vi.fn(); + mockOnSelect = vi.fn(); + + // Mock process.exit for testing + mockProcess = { + exit: vi.fn(), + kill: vi.fn(), + }; + vi.stubGlobal("process", mockProcess); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); + }); + + describe("Selector component", () => { + it("calls onCancel when Ctrl+C is pressed", () => { + const options = [ + { id: "1", name: "Option 1" }, + { id: "2", name: "Option 2" } + ]; + + const { stdin } = render( + + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + expect(mockOnSelect).not.toHaveBeenCalled(); + }); + + it("calls onCancel when Ctrl+C is pressed during loading", () => { + const options: any[] = []; + + const { stdin } = render( + + ); + + // Simulate Ctrl+C during loading + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + + it("calls onCancel when Ctrl+C is pressed during error state", () => { + const options: any[] = []; + + const { stdin } = render( + + ); + + // Simulate Ctrl+C during error + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + }); + + describe("ConfigSelector component", () => { + it("calls onCancel when Ctrl+C is pressed", () => { + const { stdin } = render( + + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx new file mode 100644 index 000000000..d79c49306 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx @@ -0,0 +1,63 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { UserInput } from "../UserInput.js"; + +describe("Ctrl+C input clearing", () => { + let mockOnSubmit: ReturnType; + let mockProcess: any; + + beforeEach(() => { + mockOnSubmit = vi.fn(); + + // Mock process.kill for SIGINT simulation + mockProcess = { + kill: vi.fn(), + pid: 12345, + }; + vi.stubGlobal("process", mockProcess); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); + }); + + it("sends SIGINT when Ctrl+C is pressed (input clearing tested implicitly)", () => { + const { stdin } = render( + + ); + + // Type some text first + stdin.write("hello world"); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + // Should send SIGINT to process (which handles the two-stage exit) + expect(mockProcess.kill).toHaveBeenCalledWith(12345, "SIGINT"); + }); + + it("sends SIGINT to main process for two-stage exit handling", () => { + const { stdin } = render( + + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + // Should delegate to main process SIGINT handler + expect(mockProcess.kill).toHaveBeenCalledWith(12345, "SIGINT"); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index c46bd2059..da4094b08 100644 --- a/extensions/cli/src/ui/components/BottomStatusBar.tsx +++ b/extensions/cli/src/ui/components/BottomStatusBar.tsx @@ -1,6 +1,7 @@ import { Box, Text } from "ink"; -import React from "react"; +import React, { useEffect, useState } from "react"; +import { setExitMessageCallback, shouldShowExitMessage } from "../../index.js"; import type { PermissionMode } from "../../permissions/types.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { FreeTrialStatus } from "../FreeTrialStatus.js"; @@ -29,42 +30,57 @@ export const BottomStatusBar: React.FC = ({ navigateTo, closeCurrentScreen, contextPercentage, -}) => ( - - - {currentMode === "normal" && ( - - - {repoURLText} - - - - )} - - {contextPercentage !== undefined && contextPercentage > 75 && ( - - • - - - )} +}) => { + const [refreshTrigger, setRefreshTrigger] = useState(0); + + useEffect(() => { + setExitMessageCallback(() => { + setRefreshTrigger((prev) => prev + 1); + }); + }, []); + + const showingExitMessage = shouldShowExitMessage(); + + return ( + + + {currentMode === "normal" && ( + + + {showingExitMessage ? "ctrl+c to exit" : repoURLText} + + + + )} + + {contextPercentage !== undefined && contextPercentage > 75 && ( + + • + + + )} + + + {!isRemoteMode && services.model?.model && ( + { + if (shouldShow && navState.currentScreen === "chat") { + navigateTo("free-trial"); + } else if ( + !shouldShow && + navState.currentScreen === "free-trial" + ) { + closeCurrentScreen(); + } + }} + /> + )} + + + + - - {!isRemoteMode && services.model?.model && ( - { - if (shouldShow && navState.currentScreen === "chat") { - navigateTo("free-trial"); - } else if (!shouldShow && navState.currentScreen === "free-trial") { - closeCurrentScreen(); - } - }} - /> - )} - - - - - -); + ); +}; diff --git a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx index c4b93ab35..15154b7b4 100644 --- a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx +++ b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx @@ -79,8 +79,8 @@ export const ToolPermissionSelector: React.FC = ({ return; } - // Escape to reject with stop stream - if (key.escape) { + // Escape or Ctrl+C to reject with stop stream + if (key.escape || (key.ctrl && input === "c")) { onResponse(requestId, false, false, true); return; } diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index ae0dea719..3aa349f85 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -9,14 +9,25 @@ interface ControlKeysOptions { showSlashCommands: boolean; showFileSearch: boolean; cycleModes: () => Promise; + clearInput?: () => void; } export function handleControlKeys(options: ControlKeysOptions): boolean { - const { input, key, exit, showSlashCommands, showFileSearch, cycleModes } = + const { input, key, exit, showSlashCommands, showFileSearch, cycleModes, clearInput } = options; - // Handle Ctrl+C and Ctrl+D - if (key.ctrl && (input === "c" || input === "d")) { + // Handle Ctrl+C with two-stage exit, Ctrl+D immediately exits + if (key.ctrl && input === "c") { + // Clear input box if clearInput function is provided + if (clearInput) { + clearInput(); + } + // Let the main process SIGINT handler handle Ctrl+C logic + process.kill(process.pid, "SIGINT"); + return true; + } + + if (key.ctrl && input === "d") { exit(); return true; } diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index e75f9aa91..55dc236eb 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -1,9 +1,10 @@ -import { render } from "ink"; +import { render, RenderOptions } 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 { setTUIUnmount } from "../index.js"; import { AppRoot } from "./AppRoot.js"; @@ -52,7 +53,9 @@ export async function startTUIChat( // Use static imports since we're always loading TUI when there's piped input // Start the TUI immediately - it will handle loading states - const renderOptions: any = {}; + const renderOptions: RenderOptions = { + exitOnCtrlC: false, // Disable Ink's default Ctrl+C handling so we can implement two-stage exit + }; if (customStdin) { renderOptions.stdin = customStdin; } @@ -69,11 +72,8 @@ export async function startTUIChat( renderOptions, ); - // Handle cleanup - process.on("SIGINT", () => { - unmount(); - process.exit(0); - }); + // Register unmount function with main process for two-stage Ctrl+C exit + setTUIUnmount(unmount); return { unmount }; } @@ -92,11 +92,8 @@ export async function startRemoteTUIChat( }), ); - // Handle cleanup - process.on("SIGINT", () => { - unmount(); - process.exit(0); - }); + // Register unmount function with main process for two-stage Ctrl+C exit + setTUIUnmount(unmount); return { unmount }; }