Merge pull request #7378 from continuedev/tingwai/ctrl-c-and-refactoring

feat: ctrl+c once to clear input, twice to exit. Refactoring, bug fixes
This commit is contained in:
Nate Sesti 2025-09-03 17:41:56 -07:00 • committed by GitHub
commit 7dc08233dc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 571 additions and 201 deletions

View file

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

View file

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

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

View file

@ -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<ConfigSelectorProps> = ({
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<ConfigSelectorProps> = ({
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";
}

View file

@ -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<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,
@ -215,39 +228,38 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
};
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 (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="yellow"
>
<Box {...defaultBoxStyles("yellow")}>
<Text bold color="yellow">
🚀 Free trial limit reached!
</Text>
<Text>Choose how you'd like to continue:</Text>
<Text></Text>
<Text color={selectedOption === 1 ? "cyan" : "white"}>
{selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on
(recommended)
</Text>
<Text color={selectedOption === 2 ? "cyan" : "white"}>
{selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API
key
</Text>
<Text color={selectedOption === 3 ? "cyan" : "white"}>
{selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different
configuration
</Text>
{hasOrganizations && (
<Text color={selectedOption === 4 ? "cyan" : "white"}>
{selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization
configuration
{options.map((option) => (
<Text
key={option.num}
color={selectedOption === option.num ? "cyan" : "white"}
>
{selectedOption === option.num ? "➤ " : " "}
{option.num}. {option.text}
</Text>
)}
))}
<Text></Text>
<Text color="gray">
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
</Text>
</Box>
@ -256,12 +268,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
if (currentStep === "enterApiKey") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="yellow"
>
<Box {...defaultBoxStyles("yellow")}>
<Text bold color="yellow">
Enter your Anthropic API key
</Text>
@ -278,12 +285,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
if (currentStep === "processing") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Box {...defaultBoxStyles("blue")}>
<Text bold color="blue">
Processing...
</Text>
@ -294,12 +296,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
if (currentStep === "success") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="green"
>
<Box {...defaultBoxStyles("green")}>
<Text bold color="green">
Success!
</Text>
@ -316,12 +313,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
if (currentStep === "error") {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="red"
>
<Box {...defaultBoxStyles("red")}>
<Text bold color="red">
Error
</Text>

View file

@ -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<MCPSelectorProps> = ({ onCancel }) => {
{/* Add prompts if any */}
{serverInfo.prompts.length > 0 && (
<Box flexDirection="column" marginBottom={1}>
<Text color="cyan">📝 Prompts: {serverInfo.prompts.length}</Text>
<Text color="blue">📝 Prompts: {serverInfo.prompts.length}</Text>
{serverInfo.prompts.map((prompt, index) => (
<Text key={index} color="dim">
• {prompt.name}
@ -182,7 +189,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
{/* Add tools if any */}
{serverInfo.tools.length > 0 && (
<Box flexDirection="column" marginBottom={1}>
<Text color="cyan">🔧 Tools: {serverInfo.tools.length}</Text>
<Text color="blue">🔧 Tools: {serverInfo.tools.length}</Text>
{serverInfo.tools.map((tool, index) => (
<Text key={index} color="dim">
• {tool.name}
@ -210,13 +217,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;
@ -302,7 +310,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
const renderHeader = () => {
return (
<Box flexDirection="column" marginBottom={1}>
<Text bold color="cyan">
<Text bold color="blue">
{menuState === "server-detail" && selectedServer
? `Server: ${selectedServer}`
: "MCP Servers"}
@ -336,13 +344,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
};
return (
<Box
flexDirection="column"
borderStyle="round"
borderColor="cyan"
padding={1}
minHeight={10}
>
<Box {...defaultBoxStyles("blue", { minHeight: 10 })}>
{renderHeader()}
{message && (
@ -369,9 +371,8 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
key={`${item.value}-${index}`}
color={isSelected ? "blue" : "white"}
bold={isSelected}
inverse={isSelected}
>
{isSelected ? "> " : " "}
{isSelected ? "➤ " : " "}
{item.label}
</Text>
);
@ -381,7 +382,7 @@ export const MCPSelector: React.FC<MCPSelectorProps> = ({ onCancel }) => {
<Box marginTop={1}>
<Text color="dim">
Use ↑/↓ to navigate, Enter to select, Esc to go back
↑/↓ to navigate, Enter to select, Esc to go back
</Text>
</Box>
</Box>

View file

@ -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<typeof Box> = {
flexDirection: "column",
paddingX: 2,
paddingY: 1,
borderStyle: "round",
borderColor: "blue",
};
interface SelectorProps<T extends SelectorOption> {
title: string;
options: T[];
@ -46,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;
}
@ -70,7 +76,7 @@ export function Selector<T extends SelectorOption>({
if (loading) {
return (
<Box {...boxStyles}>
<Box {...defaultBoxStyles("blue")}>
<Text color="blue" bold>
{title}
</Text>
@ -84,13 +90,13 @@ export function Selector<T extends SelectorOption>({
if (error) {
return (
<Box {...boxStyles}>
<Box {...defaultBoxStyles("blue")}>
<Text color="red" bold>
Error
</Text>
<Text color="red">{error}</Text>
<Text color="gray" dimColor>
Press Escape to cancel
Press Esc to cancel
</Text>
</Box>
);
@ -106,7 +112,7 @@ export function Selector<T extends SelectorOption>({
color={isSelected ? "blue" : isCurrent ? "green" : "white"}
bold={isSelected}
>
{isSelected ? "→ " : " "}
{isSelected ? "➤ " : " "}
{option.name}
{option.displaySuffix || ""}
</Text>
@ -119,7 +125,7 @@ export function Selector<T extends SelectorOption>({
);
return (
<Box {...boxStyles}>
<Box {...defaultBoxStyles("blue")}>
<Text color="blue" bold>
{title}
</Text>
@ -136,7 +142,7 @@ export function Selector<T extends SelectorOption>({
</Box>
<Box marginTop={1}>
<Text color="gray" dimColor>
↑/↓ to navigate, Enter to select, Escape to cancel
↑/↓ to navigate, Enter to select, Esc to cancel
</Text>
</Box>
</Box>

View file

@ -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<ServiceDebuggerProps> = ({
};
return (
<Box
flexDirection="column"
paddingX={1}
paddingY={1}
borderStyle="round"
borderColor="cyan"
>
<Box {...defaultBoxStyles("cyan")}>
<Text bold color="cyan">
🔧 Service Debug Info
</Text>

View file

@ -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 (
<Box flexDirection="column" padding={1}>
<Box {...defaultBoxStyles("blue")}>
<Text color="yellow">No previous sessions found.</Text>
<Text color="gray">Start a new conversation with: cn</Text>
<Text color="gray">Press ESC or Ctrl+D to exit</Text>
<Text color="gray">Press Esc to exit</Text>
</Box>
);
}
return (
<Box flexDirection="column" padding={1}>
<Box {...defaultBoxStyles("blue")}>
<Text color="blue" bold>
Recent Sessions
</Text>
<Text color="gray">
Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit
</Text>
<Text color="gray">↑/↓ to navigate, Enter to select, Esc to exit</Text>
<Text> </Text>
{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 (
<Box key={session.sessionId} flexDirection="column">
<Box paddingRight={3}>
<Text color={color} wrap="truncate-end">
<Text bold={isSelected} color={color} wrap="truncate-end">
{indicator}
{formatMessage(session.title)}
</Text>

View file

@ -73,7 +73,7 @@ const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
{" "}
{paddedCommandName}
<Text color={isSelected ? "blue" : "gray"}>
{" "}
{" "}
{command.description}
</Text>
</Text>

View file

@ -70,6 +70,16 @@ 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);
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<UserInputProps> = ({
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<UserInputProps> = ({
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;

View file

@ -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(<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,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<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,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<typeof vi.fn>;
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(
<UserInput
onSubmit={mockOnSubmit}
inputMode={true}
disabled={false}
isWaitingForResponse={false}
/>,
);
// 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(
<UserInput
onSubmit={mockOnSubmit}
inputMode={true}
disabled={false}
isWaitingForResponse={false}
/>,
);
// 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");
});
});

View file

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

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";
@ -31,51 +32,66 @@ export const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
closeCurrentScreen,
contextPercentage,
hasImageInClipboard,
}) => (
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
<Box marginLeft={2} flexDirection="row" alignItems="center">
{currentMode === "normal" && (
<React.Fragment>
{hasImageInClipboard ? (
<Text key="image-paste-hint" color="cyan" wrap="truncate-start">
Press Ctrl+V to paste image
}) => {
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>
{hasImageInClipboard ? (
<Text key="image-paste-hint" color="cyan" wrap="truncate-start">
Press Ctrl+V to paste image
</Text>
) : (
<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" color="dim">
{" "}
•{" "}
</Text>
) : (
<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" color="dim">
{" "}
•{" "}
</Text>
<ContextPercentageDisplay percentage={contextPercentage} />
</React.Fragment>
)}
<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

@ -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<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;
}
@ -103,12 +104,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
});
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="magenta"
>
<Box {...defaultBoxStyles("magenta")}>
<Text color="magenta" bold>
<ToolCallTitle toolName={toolName} args={toolArgs} />
</Text>

View file

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

View file

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

View file

@ -0,0 +1,17 @@
import { Box } from "ink";
export const baseBoxStyles: React.ComponentProps<typeof Box> = {
flexDirection: "column",
paddingX: 2,
paddingY: 1,
borderStyle: "round",
};
export const defaultBoxStyles = (
borderColor: string,
overrides?: Partial<React.ComponentProps<typeof Box>>,
): React.ComponentProps<typeof Box> => ({
...baseBoxStyles,
borderColor,
...overrides,
});