feat: ctrl+c once to clear input, twice to exit

This commit is contained in:
Ting-Wai To 2025-08-23 02:49:20 -07:00
parent ce3c2068c6
commit 2c95e2c322
14 changed files with 464 additions and 64 deletions

View file

@ -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.

View file

@ -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");
});
});

View file

@ -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 () => {

View file

@ -130,6 +130,18 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
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,

View file

@ -216,13 +216,14 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ 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;

View file

@ -40,8 +40,20 @@ export function Selector<T extends SelectorOption>({
onNavigate,
renderOption,
}: SelectorProps<T>) {
// 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<T extends SelectorOption>({
</Text>
<Text color="red">{error}</Text>
<Text color="gray" dimColor>
Press Escape to cancel
Press Esc to cancel
</Text>
</Box>
);

View file

@ -62,6 +62,13 @@ const UserInput: React.FC<UserInputProps> = ({
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<UserInputProps> = ({
showSlashCommands,
showFileSearch,
cycleModes,
clearInput,
})
) {
return;

View file

@ -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(<BottomStatusBar {...defaultProps} />);
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(<BottomStatusBar {...defaultProps} />);
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(<BottomStatusBar {...defaultProps} />);
expect(indexModule.setExitMessageCallback).toHaveBeenCalledWith(expect.any(Function));
});
});

View file

@ -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<typeof vi.fn>;
let mockOnSelect: ReturnType<typeof vi.fn>;
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(
<Selector
title="Test"
options={options}
selectedIndex={0}
loading={false}
error={null}
onSelect={mockOnSelect}
onCancel={mockOnCancel}
onNavigate={vi.fn()}
/>
);
// 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(
<Selector
title="Loading Test"
options={options}
selectedIndex={0}
loading={true}
error={null}
loadingMessage="Loading..."
onSelect={mockOnSelect}
onCancel={mockOnCancel}
onNavigate={vi.fn()}
/>
);
// 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(
<Selector
title="Error Test"
options={options}
selectedIndex={0}
loading={false}
error="Something went wrong"
onSelect={mockOnSelect}
onCancel={mockOnCancel}
onNavigate={vi.fn()}
/>
);
// 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(
<ConfigSelector
onSelect={mockOnSelect}
onCancel={mockOnCancel}
/>
);
// Simulate Ctrl+C
stdin.write("\u0003");
expect(mockOnCancel).toHaveBeenCalledTimes(1);
});
});
});

View file

@ -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<typeof vi.fn>;
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(
<UserInput
onSubmit={mockOnSubmit}
onExit={vi.fn()}
disabled={false}
isWaitingForResponse={false}
/>
);
// 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(
<UserInput
onSubmit={mockOnSubmit}
onExit={vi.fn()}
disabled={false}
isWaitingForResponse={false}
/>
);
// Simulate Ctrl+C
stdin.write("\u0003");
// Should delegate to main process SIGINT handler
expect(mockProcess.kill).toHaveBeenCalledWith(12345, "SIGINT");
});
});

View file

@ -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<BottomStatusBarProps> = ({
navigateTo,
closeCurrentScreen,
contextPercentage,
}) => (
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
<Box marginLeft={2} flexDirection="row" alignItems="center">
{currentMode === "normal" && (
<React.Fragment>
<Text key="repo-url" color="dim" wrap="truncate-start">
{repoURLText}
</Text>
<Text key="repo-separator"> </Text>
</React.Fragment>
)}
<ModeIndicator />
{contextPercentage !== undefined && contextPercentage > 75 && (
<React.Fragment>
<Text key="context-separator"> • </Text>
<ContextPercentageDisplay percentage={contextPercentage} />
</React.Fragment>
)}
}) => {
const [refreshTrigger, setRefreshTrigger] = useState(0);
useEffect(() => {
setExitMessageCallback(() => {
setRefreshTrigger((prev) => prev + 1);
});
}, []);
const showingExitMessage = shouldShowExitMessage();
return (
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
<Box marginLeft={2} flexDirection="row" alignItems="center">
{currentMode === "normal" && (
<React.Fragment>
<Text key="repo-url" color="dim" wrap="truncate-start">
{showingExitMessage ? "ctrl+c to exit" : repoURLText}
</Text>
<Text key="repo-separator"> </Text>
</React.Fragment>
)}
<ModeIndicator />
{contextPercentage !== undefined && contextPercentage > 75 && (
<React.Fragment>
<Text key="context-separator"> • </Text>
<ContextPercentageDisplay percentage={contextPercentage} />
</React.Fragment>
)}
</Box>
<Box>
{!isRemoteMode && services.model?.model && (
<FreeTrialStatus
apiClient={services.apiClient?.apiClient || undefined}
model={services.model.model}
onTransitionStateChange={(shouldShow) => {
if (shouldShow && navState.currentScreen === "chat") {
navigateTo("free-trial");
} else if (
!shouldShow &&
navState.currentScreen === "free-trial"
) {
closeCurrentScreen();
}
}}
/>
)}
</Box>
<Box marginRight={2} marginLeft={2}>
<UpdateNotification isRemoteMode={isRemoteMode} />
</Box>
</Box>
<Box>
{!isRemoteMode && services.model?.model && (
<FreeTrialStatus
apiClient={services.apiClient?.apiClient || undefined}
model={services.model.model}
onTransitionStateChange={(shouldShow) => {
if (shouldShow && navState.currentScreen === "chat") {
navigateTo("free-trial");
} else if (!shouldShow && navState.currentScreen === "free-trial") {
closeCurrentScreen();
}
}}
/>
)}
</Box>
<Box marginRight={2} marginLeft={2}>
<UpdateNotification isRemoteMode={isRemoteMode} />
</Box>
</Box>
);
);
};

View file

@ -79,8 +79,8 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
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;
}

View file

@ -9,14 +9,25 @@ interface ControlKeysOptions {
showSlashCommands: boolean;
showFileSearch: boolean;
cycleModes: () => Promise<PermissionMode>;
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;
}

View file

@ -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 };
}