diff --git a/extensions/cli/spec/ctrl-c-behavior.md b/extensions/cli/spec/ctrl-c-behavior.md new file mode 100644 index 000000000..9d11f26ab --- /dev/null +++ b/extensions/cli/spec/ctrl-c-behavior.md @@ -0,0 +1,32 @@ +# 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..563efbbe9 --- /dev/null +++ b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } 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"); + }); +}); diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 91b5a6c78..784dbe09b 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 }); @@ -265,10 +294,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/ConfigSelector.tsx b/extensions/cli/src/ui/ConfigSelector.tsx index f47a97b1b..8c8d2ae55 100644 --- a/extensions/cli/src/ui/ConfigSelector.tsx +++ b/extensions/cli/src/ui/ConfigSelector.tsx @@ -12,6 +12,7 @@ import { } from "../auth/workos.js"; import { getApiClient } from "../config.js"; import { env } from "../env.js"; +import { services } from "../services/index.js"; import { Selector, SelectorOption } from "./Selector.js"; @@ -118,8 +119,10 @@ const ConfigSelector: React.FC = ({ displaySuffix: " (opens web)", }); - // Determine current config by checking auth config + // Determine current config by checking both auth config and service state const assistantSlug = getAssistantSlug(authConfig); + const currentConfigState = services.config.getState(); + if (assistantSlug) { // Find the matching config by slug and organization const matchingConfig = options.find( @@ -129,8 +132,12 @@ const ConfigSelector: React.FC = ({ opt.organizationId === currentOrganizationId, ); currentId = matchingConfig?.id || null; - } else if (fs.existsSync(CONFIG_PATH)) { - // No assistant slug means local config is current + } else if ( + currentConfigState.configPath === CONFIG_PATH && + fs.existsSync(CONFIG_PATH) + ) { + // Only mark local config as current if it's actually the active config path in the service + // This ensures we don't show a green checkmark for first-time users just because the file exists currentId = "local"; } diff --git a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx index 5a4638e2e..0943d8015 100644 --- a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx +++ b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx @@ -15,6 +15,7 @@ import { import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; import { useNavigation } from "./context/NavigationContext.js"; +import { defaultBoxStyles } from "./styles.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); @@ -130,6 +131,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, @@ -215,39 +228,38 @@ const FreeTrialTransitionUI: React.FC = ({ }; if (currentStep === "choice") { + const options = [ + { num: 1, text: "💳 Sign up for models add-on (recommended)" }, + { num: 2, text: "🔑 Enter your Anthropic API key" }, + { num: 3, text: "⚙️ Switch to a different configuration" }, + ]; + + if (hasOrganizations) { + options.push({ + num: 4, + text: "🏢 Switch to organization configuration", + }); + } + return ( - + 🚀 Free trial limit reached! Choose how you'd like to continue: - - {selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on - (recommended) - - - {selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API - key - - - {selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different - configuration - - {hasOrganizations && ( - - {selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization - configuration + {options.map((option) => ( + + {selectedOption === option.num ? "➤ " : " "} + {option.num}. {option.text} - )} + ))} - Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, + ↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, Enter to confirm @@ -256,12 +268,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "enterApiKey") { return ( - + Enter your Anthropic API key @@ -278,12 +285,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "processing") { return ( - + Processing... @@ -294,12 +296,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "success") { return ( - + Success! @@ -316,12 +313,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "error") { return ( - + Error diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index fb84a4c60..f9db017ef 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -3,11 +3,18 @@ import React, { useState } from "react"; import { quote } from "shell-quote"; import { useServices } from "../hooks/useService.js"; -import { MCPServiceState, SERVICE_NAMES } from "../services/types.js"; +import { + MCPConnectionInfo, + MCPServerStatus, + MCPServiceState, + SERVICE_NAMES, +} from "../services/types.js"; import { logger } from "../util/logger.js"; +import { defaultBoxStyles } from "./styles.js"; + // Utility function to get status icon and color based on server connection -const getServerStatusDisplay = (conn: any) => { +const getServerStatusDisplay = (conn: MCPConnectionInfo) => { let icon = "⚪️"; // note, white circle causes extra blank line bug let color: "green" | "yellow" | "red" | "white" | "dim" = "white"; let statusText = conn.status; @@ -22,7 +29,7 @@ const getServerStatusDisplay = (conn: any) => { if (conn.warnings && conn.warnings.length > 0) { icon = "🟡"; color = "yellow"; - statusText = "connected (with warnings)"; + statusText = "connected (with warnings)" as MCPServerStatus; } else { icon = "🟢"; color = "green"; @@ -170,7 +177,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {/* Add prompts if any */} {serverInfo.prompts.length > 0 && ( - 📝 Prompts: {serverInfo.prompts.length} + 📝 Prompts: {serverInfo.prompts.length} {serverInfo.prompts.map((prompt, index) => ( • {prompt.name} @@ -182,7 +189,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {/* Add tools if any */} {serverInfo.tools.length > 0 && ( - 🔧 Tools: {serverInfo.tools.length} + 🔧 Tools: {serverInfo.tools.length} {serverInfo.tools.map((tool, index) => ( • {tool.name} @@ -210,13 +217,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; @@ -302,7 +310,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const renderHeader = () => { return ( - + {menuState === "server-detail" && selectedServer ? `Server: ${selectedServer}` : "MCP Servers"} @@ -336,13 +344,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { }; return ( - + {renderHeader()} {message && ( @@ -369,9 +371,8 @@ export const MCPSelector: React.FC = ({ onCancel }) => { key={`${item.value}-${index}`} color={isSelected ? "blue" : "white"} bold={isSelected} - inverse={isSelected} > - {isSelected ? "> " : " "} + {isSelected ? "➤ " : " "} {item.label} ); @@ -381,7 +382,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { - Use ↑/↓ to navigate, Enter to select, Esc to go back + ↑/↓ to navigate, Enter to select, Esc to go back diff --git a/extensions/cli/src/ui/Selector.tsx b/extensions/cli/src/ui/Selector.tsx index 6d00660f0..3e01a37e2 100644 --- a/extensions/cli/src/ui/Selector.tsx +++ b/extensions/cli/src/ui/Selector.tsx @@ -1,20 +1,14 @@ import { Box, Text, useInput } from "ink"; import React, { ReactNode } from "react"; +import { defaultBoxStyles } from "./styles.js"; + export interface SelectorOption { id: string; name: string; displaySuffix?: string; } -const boxStyles: React.ComponentProps = { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - borderStyle: "round", - borderColor: "blue", -}; - interface SelectorProps { title: string; options: T[]; @@ -46,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; } @@ -70,7 +76,7 @@ export function Selector({ if (loading) { return ( - + {title} @@ -84,13 +90,13 @@ export function Selector({ if (error) { return ( - + Error {error} - Press Escape to cancel + Press Esc to cancel ); @@ -106,7 +112,7 @@ export function Selector({ color={isSelected ? "blue" : isCurrent ? "green" : "white"} bold={isSelected} > - {isSelected ? "→ " : " "} + {isSelected ? "➤ " : " "} {option.name} {option.displaySuffix || ""} @@ -119,7 +125,7 @@ export function Selector({ ); return ( - + {title} @@ -136,7 +142,7 @@ export function Selector({ - ↑/↓ to navigate, Enter to select, Escape to cancel + ↑/↓ to navigate, Enter to select, Esc to cancel diff --git a/extensions/cli/src/ui/ServiceDebugger.tsx b/extensions/cli/src/ui/ServiceDebugger.tsx index 1f121bd0a..e10786dc5 100644 --- a/extensions/cli/src/ui/ServiceDebugger.tsx +++ b/extensions/cli/src/ui/ServiceDebugger.tsx @@ -9,6 +9,8 @@ import { ModelServiceState, } from "../services/types.js"; +import { defaultBoxStyles } from "./styles.js"; + interface ServiceDebuggerProps { services: { auth?: AuthServiceState; @@ -60,13 +62,7 @@ const ServiceDebugger: React.FC = ({ }; return ( - + 🔧 Service Debug Info diff --git a/extensions/cli/src/ui/SessionSelector.tsx b/extensions/cli/src/ui/SessionSelector.tsx index 670ebf01d..2cf4927a4 100644 --- a/extensions/cli/src/ui/SessionSelector.tsx +++ b/extensions/cli/src/ui/SessionSelector.tsx @@ -1,10 +1,11 @@ -import { format, isToday, isYesterday, isThisWeek, isThisYear } from "date-fns"; +import { format, isThisWeek, isThisYear, isToday, isYesterday } from "date-fns"; import { Box, Text, useInput } from "ink"; import React, { useMemo, useState } from "react"; import { SessionMetadata } from "../session.js"; import { useTerminalSize } from "./hooks/useTerminalSize.js"; +import { defaultBoxStyles } from "./styles.js"; interface SessionSelectorProps { sessions: SessionMetadata[]; @@ -70,33 +71,31 @@ export function SessionSelector({ if (sessions.length === 0) { return ( - + No previous sessions found. Start a new conversation with: cn - Press ESC or Ctrl+D to exit + Press Esc to exit ); } return ( - + Recent Sessions - - Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit - + ↑/↓ to navigate, Enter to select, Esc to exit {displaySessions.map((session, index) => { const isSelected = index === selectedIndex; - const indicator = isSelected ? "► " : " "; - const color = isSelected ? "cyan" : "white"; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "blue" : "white"; return ( - + {indicator} {formatMessage(session.title)} diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index b4852933f..15d88bf29 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -73,7 +73,7 @@ const SlashCommandUI: React.FC = ({ {" "} {paddedCommandName} - {" "} + {" "} {command.description} diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index b60013046..ea48988d9 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -70,6 +70,16 @@ 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); + setShowSlashCommands(false); + setShowFileSearch(false); + inputHistory.resetNavigation(); + }, [textBuffer]); const [slashCommandFilter, setSlashCommandFilter] = useState(""); const [selectedCommandIndex, setSelectedCommandIndex] = useState(0); const [showFileSearch, setShowFileSearch] = useState(false); @@ -141,13 +151,8 @@ const UserInput: React.FC = ({ return; } - const afterSlash = beforeCursor.slice(1); - - // Check if we have whitespace in the command - if (afterSlash.includes(" ") || afterSlash.includes("\n")) { - setShowSlashCommands(false); - return; - } + // Get the complete slash command, not just the part before cursor + const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0]; // We're in a slash command context - check if it's a complete command const allCommands = getSlashCommands(); @@ -478,16 +483,6 @@ const UserInput: React.FC = ({ return false; }; - // Clear input function - const clearInput = () => { - textBuffer.clear(); - setInputText(""); - setCursorPosition(0); - setShowSlashCommands(false); - setShowFileSearch(false); - inputHistory.resetNavigation(); - }; - // Handle text buffer updates for async operations like image pasting const handleTextBufferUpdate = () => { const newText = textBuffer.text; 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..897228a96 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx @@ -0,0 +1,65 @@ +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), + ); + }); +}); 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..f05154977 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx @@ -0,0 +1,115 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { ConfigSelector } from "../ConfigSelector.js"; +import { Selector } from "../Selector.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); + }); + }); +}); 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..f40dd1414 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx @@ -0,0 +1,61 @@ +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 mockProcessKill: any; + + beforeEach(() => { + mockOnSubmit = vi.fn(); + + // Mock process.kill using vi.spyOn + mockProcessKill = vi.spyOn(process, "kill").mockImplementation(() => { + return true; + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.restoreAllMocks(); + }); + + 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 using raw character code (like other tests in codebase) + stdin.write("\u0003"); + + // Should send SIGINT to process (which handles the two-stage exit) + expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT"); + }); + + it("sends SIGINT to main process for two-stage exit handling", () => { + const { stdin } = render( + , + ); + + // Simulate Ctrl+C using raw character code (like other tests in codebase) + stdin.write("\u0003"); + + // Should delegate to main process SIGINT handler + expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT"); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx index 1fea1b3fb..dfb3b59ce 100644 --- a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx +++ b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx @@ -37,7 +37,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { expect(frame).toContain("1. 💳 Sign up for models add-on"); expect(frame).toContain("2. 🔑 Enter your Anthropic API key"); expect(frame).toContain("3. ⚙️ Switch to a different configuration"); - expect(frame).toContain("Use ↑↓ arrows or 1/2/3 to select"); + expect(frame).toContain("↑/↓ to navigate or 1/2/3 to select"); }); it("highlights first option by default", () => { @@ -46,10 +46,10 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { ); const frame = lastFrame(); - expect(frame).toContain("▶ 1. 💳 Sign up for models add-on"); - expect(frame).not.toContain("▶ 2. 🔑 Enter your Anthropic API key"); + expect(frame).toContain("➤ 1. 💳 Sign up for models add-on"); + expect(frame).not.toContain("➤ 2. 🔑 Enter your Anthropic API key"); expect(frame).not.toContain( - "▶ 3. ⚙️ Switch to a different configuration", + "➤ 3. ⚙️ Switch to a different configuration", ); }); @@ -85,7 +85,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { const frame = lastFrame(); expect(frame).toContain("Choose how you'd like to continue:"); expect(frame).toContain( - "Use ↑↓ arrows or 1/2/3 to select, Enter to confirm", + "↑/↓ to navigate or 1/2/3 to select, Enter to confirm", ); }); @@ -155,9 +155,9 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { line.includes("Switch to a different configuration"), ); - expect(modelsLine).toContain("▶"); - expect(apiKeyLine).not.toContain("▶"); - expect(configLine).not.toContain("▶"); + expect(modelsLine).toContain("➤"); + expect(apiKeyLine).not.toContain("➤"); + expect(configLine).not.toContain("➤"); }); }); diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index d31095f77..c780af456 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"; @@ -31,51 +32,66 @@ export const BottomStatusBar: React.FC = ({ closeCurrentScreen, contextPercentage, hasImageInClipboard, -}) => ( - - - {currentMode === "normal" && ( - - {hasImageInClipboard ? ( - - Press Ctrl+V to paste image +}) => { + const [_refreshTrigger, setRefreshTrigger] = useState(0); + + useEffect(() => { + setExitMessageCallback(() => { + setRefreshTrigger((prev) => prev + 1); + }); + }, []); + + const showingExitMessage = shouldShowExitMessage(); + + return ( + + + {currentMode === "normal" && ( + + {hasImageInClipboard ? ( + + Press Ctrl+V to paste image + + ) : ( + + {showingExitMessage ? "ctrl+c to exit" : repoURLText} + + )} + + + )} + + {contextPercentage !== undefined && contextPercentage > 75 && ( + + + {" "} + •{" "} - ) : ( - - {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 46abde7d2..66d88de42 100644 --- a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx +++ b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx @@ -4,6 +4,7 @@ import React, { useState } from "react"; import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; import { ToolCallPreview } from "../../tools/types.js"; +import { defaultBoxStyles } from "../styles.js"; import { ToolPreview } from "./ToolPreview.js"; @@ -80,8 +81,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; } @@ -103,12 +104,7 @@ export const ToolPermissionSelector: React.FC = ({ }); return ( - + diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index c0d641b01..b1a09ae43 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -32,9 +32,14 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { onTextBufferUpdate, } = options; - // Handle Ctrl+C to clear input - if (key.ctrl && input === "c" && clearInput) { - clearInput(); + // 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; } diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index 3b4edece4..e9333155f 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -1,6 +1,7 @@ -import { render } from "ink"; +import { render, RenderOptions } from "ink"; import React from "react"; +import { setTUIUnmount } from "../index.js"; import { PermissionMode } from "../permissions/types.js"; import { initializeServices } from "../services/index.js"; import { ServiceContainerProvider } from "../services/ServiceContainerContext.js"; @@ -54,7 +55,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; } @@ -73,11 +76,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 }; } @@ -96,11 +96,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 }; } diff --git a/extensions/cli/src/ui/styles.ts b/extensions/cli/src/ui/styles.ts new file mode 100644 index 000000000..4e767b0b8 --- /dev/null +++ b/extensions/cli/src/ui/styles.ts @@ -0,0 +1,17 @@ +import { Box } from "ink"; + +export const baseBoxStyles: React.ComponentProps = { + flexDirection: "column", + paddingX: 2, + paddingY: 1, + borderStyle: "round", +}; + +export const defaultBoxStyles = ( + borderColor: string, + overrides?: Partial>, +): React.ComponentProps => ({ + ...baseBoxStyles, + borderColor, + ...overrides, +});