Merge pull request #5 from continuedev/nate/ui-improvements

feat: esc to interrupt
This commit is contained in:
Nate Sesti 2025-07-13 19:05:10 -07:00 • committed by GitHub
commit 431d3147a2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 603 additions and 60 deletions

View file

@ -1,9 +1,8 @@
import { Assistant, type AssistantConfig } from "@continuedev/sdk";
import chalk from "chalk";
import * as fs from "fs";
import { CONTINUE_ASCII_ART } from "./asciiArt.js";
import { MCPService } from "./mcp.js";
import { getAllTools } from "./streamChatResponse.js";
import { Assistant, type AssistantConfig } from "@continuedev/sdk";
export function loadSystemMessage(
assistant: AssistantConfig
@ -22,10 +21,10 @@ export function introMessage(assistant: Assistant, mcpService: MCPService) {
console.info(chalk.cyan(CONTINUE_ASCII_ART));
console.info(`\n${chalk.bold.blue(`Assistant: ${assistantConfig.name}`)}`);
console.info(`${chalk.blue(`Model: ${assistant.getModel()}`)}\n`);
console.info(`\n${chalk.bold.blue(`Agent: ${assistantConfig.name}\n`)}`);
console.info(`${chalk.yellow("Model:")} ${assistant.getModel()}\n`);
console.info(chalk.yellow("Available tools:"));
console.info(chalk.yellow("Tools:"));
getAllTools().forEach((tool) => {
console.info(
`- ${chalk.green(tool.function.name)}: ${tool.function.description ?? ""}`
@ -36,14 +35,16 @@ export function introMessage(assistant: Assistant, mcpService: MCPService) {
});
console.info("");
console.info(chalk.yellow("\nAvailable slash commands:"));
console.info("- /exit: Exit the chat");
console.info("- /clear: Clear the chat history");
console.info("- /help: Show help message");
console.info("- /models: Show available models");
console.info("- /login: Authenticate with your account");
console.info("- /logout: Sign out of your current session");
console.info("- /whoami: Check who you're currently logged in as");
console.info(chalk.yellow("Slash commands:"));
console.info(`- ${chalk.green("/exit")}: Exit the chat`);
console.info(`- ${chalk.green("/clear")}: Clear the chat history`);
console.info(`- ${chalk.green("/help")}: Show help message`);
console.info(`- ${chalk.green("/models")}: Show available models`);
console.info(`- ${chalk.green("/login")}: Authenticate with your account`);
console.info(`- ${chalk.green("/logout")}: Sign out of your current session`);
console.info(
`- ${chalk.green("/whoami")}: Check who you're currently logged in as`
);
for (const prompt of assistantConfig.prompts ?? []) {
console.info(`- /${prompt?.name}: ${prompt?.description}`);
}

View file

@ -52,9 +52,9 @@ type TODO = any;
export interface StreamCallbacks {
onContent?: (content: string) => void;
onToolStart?: (toolName: string) => void;
onToolResult?: (result: string) => void;
onToolError?: (error: string) => void;
onToolStart?: (toolName: string, toolArgs?: any) => void;
onToolResult?: (result: string, toolName: string) => void;
onToolError?: (error: string, toolName?: string) => void;
}
// Define a function to handle streaming responses with tool calling
@ -62,7 +62,8 @@ export async function streamChatResponse(
chatHistory: ChatCompletionMessageParam[],
assistant: ContinueClient["assistant"],
client: ContinueClient["client"],
callbacks?: StreamCallbacks
callbacks?: StreamCallbacks,
abortController?: AbortController
) {
// Prepare tools for the API call
const toolsForRequest = getAllTools();
@ -84,6 +85,8 @@ export async function streamChatResponse(
messages: chatHistory,
stream: true,
tools: toolsForRequest,
}, {
signal: abortController?.signal,
});
} catch (error: any) {
console.error(
@ -99,6 +102,11 @@ export async function streamChatResponse(
let toolArguments = "";
for await (const chunk of stream) {
// Check if we should abort
if (abortController?.signal.aborted) {
break;
}
// Handle regular content
if (chunk.choices[0].delta.content) {
const content = chunk.choices[0].delta.content;
@ -120,6 +128,7 @@ export async function streamChatResponse(
id: toolCallDelta.id,
name: "",
arguments: {},
startNotified: false,
};
}
currentToolCallId = toolCallDelta.id;
@ -133,15 +142,7 @@ export async function streamChatResponse(
if (toolCall) {
if (!toolCall.name) {
toolCall.name = toolCallDelta.function.name;
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name);
} else {
process.stdout.write(
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
toolCall.name
)}${chalk.yellow("]")}`
);
}
toolCall.startNotified = false;
}
}
}
@ -159,6 +160,20 @@ export async function streamChatResponse(
// Try to parse complete JSON
const parsed = JSON.parse(toolArguments);
toolCall.arguments = parsed;
// Notify start if we haven't already and have both name and args
if (toolCall.name && !toolCall.startNotified) {
toolCall.startNotified = true;
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name, toolCall.arguments);
} else {
process.stdout.write(
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
toolCall.name
)}${chalk.yellow("]")}`
);
}
}
} catch (e) {
// Not complete JSON yet, continue collecting
}
@ -212,7 +227,7 @@ export async function streamChatResponse(
});
if (callbacks?.onToolResult) {
callbacks.onToolResult(toolResult);
callbacks.onToolResult(toolResult, toolCall.name);
} else {
console.info(chalk.green(toolResult) + "\n");
}
@ -226,7 +241,7 @@ export async function streamChatResponse(
content: errorMessage,
});
if (callbacks?.onToolError) {
callbacks.onToolError(errorMessage);
callbacks.onToolError(errorMessage, toolCall.name);
} else {
console.info(
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(

View file

@ -3,6 +3,7 @@ import {
executeToolCall,
extractToolCalls,
getToolsDescription,
getToolDisplayName,
Tool,
} from "./tools/index.js";
@ -11,6 +12,7 @@ export {
executeToolCall,
extractToolCalls,
getToolsDescription,
getToolDisplayName,
Tool,
BUILTIN_TOOLS as tools,
};

View file

@ -2,6 +2,7 @@ import { Tool } from "./types.js";
export const exitTool: Tool = {
name: "exit",
displayName: "Exit",
description:
"Exit the current process with status code 1, indicating a failure or error",
parameters: {},

View file

@ -22,6 +22,11 @@ export const BUILTIN_TOOLS: Tool[] = [
...(parseArgs().isHeadless ? [exitTool] : []),
];
export function getToolDisplayName(toolName: string): string {
const tool = BUILTIN_TOOLS.find(t => t.name === toolName);
return tool?.displayName || toolName;
}
export function getToolsDescription(): string {
return BUILTIN_TOOLS.map((tool) => {
const params = Object.entries(tool.parameters)
@ -99,6 +104,7 @@ export async function executeToolCall(toolCall: {
?.getTools()
.map((t) => ({
name: t.name,
displayName: t.name.replace("mcp__", "").replace("ide__", ""),
description: t.description ?? "",
parameters: convertInputSchemaToParameters(t.inputSchema),
run: async (args: any) => {

View file

@ -5,6 +5,7 @@ import { Tool } from "./types.js";
// List files in a directory
export const listFilesTool: Tool = {
name: "list_files",
displayName: "List",
description: "List files in a directory",
parameters: {
dirpath: {

View file

@ -3,6 +3,7 @@ import { Tool } from "./types.js";
export const readFileTool: Tool = {
name: "read_file",
displayName: "Read",
description: "Read the contents of a file at the specified path",
parameters: {
filepath: {

View file

@ -3,6 +3,7 @@ import { exec } from "child_process";
export const runTerminalCommandTool: Tool = {
name: "run_terminal_command",
displayName: "Terminal",
description: "Executes a terminal command and returns the output.",
parameters: {
command: {

View file

@ -7,6 +7,7 @@ const execPromise = util.promisify(child_process.exec);
export const searchCodeTool: Tool = {
name: "search_code",
displayName: "Search",
description: "Search the codebase using ripgrep (rg) for a specific pattern",
parameters: {
pattern: {

View file

@ -9,6 +9,7 @@ export type ToolParameters = Record<
export interface Tool {
name: string;
displayName: string;
description: string;
parameters: ToolParameters;
run: (args: any) => Promise<string>;

View file

@ -7,6 +7,7 @@ const execPromise = util.promisify(child_process.exec);
export const viewDiffTool: Tool = {
name: "view_diff",
displayName: "Diff",
description: "View all uncommitted changes in the git repository",
parameters: {
path: {

View file

@ -4,6 +4,7 @@ import { Tool } from "./types.js";
export const writeFileTool: Tool = {
name: "write_file",
displayName: "Write",
description: "Write content to a file at the specified path",
parameters: {
filepath: {

View file

@ -0,0 +1,63 @@
import { Text } from "ink";
import React, { useEffect, useState } from "react";
const SPINNER_BARS = "▁▂▃▄▅▆▇█▇▆▅▄▃▁";
const SPINNER_BLOCKS = "▉▊▋▌▍▎▏▎▍▌▋▊▉";
const SPINNER_CORNERS = "▖▘▝▗";
const SPINNER_CLASSIC = "-/|\\-/|";
const SPINNER_BOX = "┤┘┴└├┌┬┐";
const SPINNER_DOUBLE_BARS = [
"▁▁",
"▁▂",
"▁▃",
"▁▄",
"▁▅",
"▁▆",
"▁▇",
"▁█",
"▂▇",
"▃▆",
"▄▅",
"▅▄",
"▆▃",
"▇▂",
"█▁",
"▇▁",
"▆▁",
"▅▁",
"▄▁",
"▃▁",
"▂▁",
];
const SPINNER: string | string[] = SPINNER_CORNERS;
interface LoadingAnimationProps {
visible?: boolean;
color?: string;
}
const LoadingAnimation: React.FC<LoadingAnimationProps> = ({
visible = true,
color = "blue",
}) => {
const [currentIndex, setCurrentIndex] = useState(0);
const animationChars =
typeof SPINNER === "string" ? (SPINNER as string).split("") : SPINNER;
useEffect(() => {
if (!visible) return;
const interval = setInterval(() => {
setCurrentIndex((prev) => (prev + 1) % animationChars.length);
}, 150);
return () => clearInterval(interval);
}, [visible, animationChars.length]);
if (!visible) return null;
return <Text color={color}>{animationChars[currentIndex]}</Text>;
};
export default LoadingAnimation;

108
src/ui/SlashCommandUI.tsx Normal file
View file

@ -0,0 +1,108 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Box, Text } from "ink";
import React from "react";
interface SlashCommandUIProps {
assistant: AssistantConfig;
filter: string;
selectedIndex: number;
onSelect: (command: string) => void;
}
interface SlashCommand {
name: string;
description: string;
category: "system" | "assistant";
}
const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
assistant,
filter,
selectedIndex,
onSelect,
}) => {
// Get all available slash commands
const getSlashCommands = (): SlashCommand[] => {
const systemCommands: SlashCommand[] = [
{ name: "help", description: "Show help message", category: "system" },
{ name: "exit", description: "Exit the chat", category: "system" },
{
name: "login",
description: "Authenticate with your account",
category: "system",
},
{
name: "logout",
description: "Sign out of your current session",
category: "system",
},
{
name: "whoami",
description: "Check who you're currently logged in as",
category: "system",
},
{
name: "models",
description: "List available AI models",
category: "system",
},
];
const assistantCommands: SlashCommand[] =
assistant.prompts?.map((prompt) => ({
name: prompt?.name || "",
description: prompt?.description || "",
category: "assistant" as const,
})) || [];
return [...systemCommands, ...assistantCommands];
};
const allCommands = getSlashCommands();
// Filter commands based on the current filter
const filteredCommands = allCommands
.filter((cmd) => cmd.name.toLowerCase().includes(filter.toLowerCase()))
.sort((a, b) => {
const aStartsWith = a.name.toLowerCase().startsWith(filter.toLowerCase());
const bStartsWith = b.name.toLowerCase().startsWith(filter.toLowerCase());
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
return a.name.localeCompare(b.name);
});
if (filteredCommands.length === 0) {
return (
<Box paddingX={1} marginX={1} marginBottom={1}>
<Text color="gray">No matching commands found</Text>
</Box>
);
}
return (
<Box paddingX={1} marginX={1} marginBottom={1} flexDirection="column">
{filteredCommands.map((command, index) => {
const isSelected = index === selectedIndex;
return (
<Box key={command.name}>
<Text color="white" bold={isSelected}>
{" "}
<Text color="green">/{command.name}</Text>
<Text color="gray"> - {command.description}</Text>
</Text>
</Box>
);
})}
<Box marginTop={1}>
<Text color="gray" dimColor>
Use ↑/↓ to navigate, Enter to select, Tab to complete
</Text>
</Box>
</Box>
);
};
export default SlashCommandUI;

View file

@ -4,6 +4,9 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs";
import React, { useEffect, useState } from "react";
import { handleSlashCommands } from "../slashCommands.js";
import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js";
import { getToolDisplayName } from "../tools.js";
import LoadingAnimation from "./LoadingAnimation.js";
import ToolResultSummary from "./ToolResultSummary.js";
import UserInput from "./UserInput.js";
interface TUIChatProps {
@ -16,6 +19,9 @@ interface DisplayMessage {
role: string;
content: string;
isStreaming?: boolean;
messageType?: "tool-start" | "tool-result" | "tool-error" | "system";
toolName?: string;
toolResult?: string;
}
const TUIChat: React.FC<TUIChatProps> = ({
@ -37,6 +43,8 @@ const TUIChat: React.FC<TUIChatProps> = ({
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
const [messages, setMessages] = useState<DisplayMessage[]>([]);
const [inputMode, setInputMode] = useState(true);
const [abortController, setAbortController] =
useState<AbortController | null>(null);
const { exit } = useApp();
// Handle initial prompt
@ -59,7 +67,11 @@ const TUIChat: React.FC<TUIChatProps> = ({
if (commandResult.output) {
setMessages((prev) => [
...prev,
{ role: "system", content: commandResult.output! },
{
role: "system",
content: commandResult.output!,
messageType: "system",
},
]);
}
@ -79,6 +91,8 @@ const TUIChat: React.FC<TUIChatProps> = ({
setMessages((prev) => [...prev, { role: "user", content: message }]);
// Start streaming response
const controller = new AbortController();
setAbortController(controller);
setIsWaitingForResponse(true);
setInputMode(false);
@ -105,24 +119,66 @@ const TUIChat: React.FC<TUIChatProps> = ({
return newMessages;
});
},
onToolStart: (toolName: string) => {
onToolStart: (toolName: string, toolArgs?: any) => {
const formatToolCall = (name: string, args: any) => {
const displayName = getToolDisplayName(name);
if (!args) return displayName;
// Get the first parameter value for display
const firstValue = Object.values(args)[0];
return `${displayName}(${firstValue || ""})`;
};
setMessages((prev) => [
...prev,
{ role: "system", content: `[Using tool: ${toolName}]` },
{
role: "system",
content: formatToolCall(toolName, toolArgs),
messageType: "tool-start",
toolName,
},
]);
},
onToolResult: (result: string) => {
setMessages((prev) => [...prev, { role: "system", content: result }]);
onToolResult: (result: string, toolName: string) => {
setMessages((prev) => {
const newMessages = [...prev];
// Find the last tool-start message for this tool and replace it
for (let i = newMessages.length - 1; i >= 0; i--) {
if (
newMessages[i].messageType === "tool-start" &&
newMessages[i].toolName === toolName
) {
newMessages[i] = {
...newMessages[i],
messageType: "tool-result",
toolResult: result, // Store the actual result separately
};
break;
}
}
return newMessages;
});
},
onToolError: (error: string) => {
onToolError: (error: string, toolName?: string) => {
setMessages((prev) => [
...prev,
{ role: "system", content: `[Tool error: ${error}]` },
{
role: "system",
content: error,
messageType: "tool-error",
toolName,
},
]);
},
};
await streamChatResponse(newHistory, assistant, client, streamCallbacks);
await streamChatResponse(
newHistory,
assistant,
client,
streamCallbacks,
controller
);
// Finalize the assistant message
const finalAssistantMessage: ChatCompletionMessageParam = {
@ -144,33 +200,84 @@ const TUIChat: React.FC<TUIChatProps> = ({
const errorMessage = `Error: ${error.message}`;
setMessages((prev) => [
...prev,
{ role: "system", content: errorMessage },
{ role: "system", content: errorMessage, messageType: "system" },
]);
} finally {
setAbortController(null);
setIsWaitingForResponse(false);
setInputMode(true);
}
};
const handleInterrupt = () => {
if (abortController && isWaitingForResponse) {
abortController.abort();
setMessages((prev) => [
...prev,
{
role: "system",
content: "[Interrupted by user]",
messageType: "system",
},
]);
}
};
const renderMessage = (message: DisplayMessage, index: number) => {
const isUser = message.role === "user";
const isSystem = message.role === "system";
if (isSystem) {
return (
<Box key={index} marginBottom={1}>
<Text color="gray" italic>
{message.content}
</Text>
</Box>
);
// Handle different types of system messages
switch (message.messageType) {
case "tool-start":
return (
<Box key={index} marginBottom={1}>
<Text color="white">○ {message.content}</Text>
</Box>
);
case "tool-result":
return (
<Box key={index} marginBottom={1} flexDirection="column">
<Box>
<Text color="green">●</Text>
<Text> {message.content}</Text>
</Box>
<Box marginLeft={2}>
<ToolResultSummary
toolName={message.toolName}
content={message.toolResult || ""}
/>
</Box>
</Box>
);
case "tool-error":
return (
<Box key={index} marginBottom={1}>
<Text color="red" bold>
✗{" "}
</Text>
<Text color="red">Tool error: {message.content}</Text>
</Box>
);
default:
// Regular system messages
return (
<Box key={index} marginBottom={1}>
<Text color="gray" italic>
{message.content}
</Text>
</Box>
);
}
}
return (
<Box key={index} marginBottom={1}>
<Text color={isUser ? "green" : "blue"} bold>
●
</Text>
<Text color={isUser ? "green" : "blue"}>●</Text>
<Text> {message.content}</Text>
{message.isStreaming && <Text color="gray">▋</Text>}
</Box>
@ -188,7 +295,8 @@ const TUIChat: React.FC<TUIChatProps> = ({
<Box flexDirection="column" flexShrink={0}>
{/* Status */}
{isWaitingForResponse && (
<Box paddingX={1}>
<Box paddingX={1} flexDirection="row" gap={1}>
<LoadingAnimation visible={isWaitingForResponse} />
<Text color="gray">esc to interrupt</Text>
</Box>
)}
@ -198,10 +306,15 @@ const TUIChat: React.FC<TUIChatProps> = ({
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant.config}
/>
<Box marginRight={2} justifyContent="flex-end">
<Text color="gray">● Continue CLI</Text>
</Box>
</Box>
</Box>
);
};
export default TUIChat;
export default TUIChat;

View file

@ -0,0 +1,67 @@
import { Box, Text } from "ink";
import React from "react";
import { getToolDisplayName } from "../tools.js";
interface ToolResultSummaryProps {
toolName?: string;
content: string;
}
const ToolResultSummary: React.FC<ToolResultSummaryProps> = ({
toolName,
content,
}) => {
const getSummary = () => {
if (!content) return "No output";
const lines = content.split("\n").length;
const chars = content.length;
const displayName = toolName ? getToolDisplayName(toolName) : "Tool";
// Handle specific tool output formatting
switch (toolName) {
case "read_file":
// Try to extract file path from content if it contains line numbers
if (content.includes("→")) {
const pathMatch = content.match(/^(.+?):/);
const filePath = pathMatch ? pathMatch[1] : "file";
return `${displayName} ${filePath} (${lines} lines)`;
}
return `${displayName} tool output (${lines} lines)`;
case "write_file":
return "File written successfully";
case "list_files":
return `Listed ${lines} ${lines === 1 ? "item" : "items"}`;
case "search_code":
return `Found ${lines} ${lines === 1 ? "match" : "matches"}`;
case "run_terminal_command":
return `Command output (${lines} lines)`;
case "view_diff":
return `Diff output (${lines} lines)`;
default:
// Fallback for all tools using display name
if (chars > 1000) {
return `${displayName} output: ${lines} lines, ${chars} characters`;
} else if (lines > 10) {
return `${displayName} output: ${lines} lines`;
} else {
return content.slice(0, 100) + (content.length > 100 ? "..." : "");
}
}
};
return (
<Box>
<Text color="gray">⎿ </Text>
<Text color="gray"> {getSummary()}</Text>
</Box>
);
};
export default ToolResultSummary;

View file

@ -1,33 +1,172 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Box, Text, useApp, useInput } from "ink";
import React, { useState } from "react";
import SlashCommandUI from "./SlashCommandUI.js";
import { TextBuffer } from "./TextBuffer.js";
interface UserInputProps {
onSubmit: (message: string) => void;
isWaitingForResponse: boolean;
inputMode: boolean;
onInterrupt?: () => void;
assistant: AssistantConfig;
}
const UserInput: React.FC<UserInputProps> = ({
onSubmit,
isWaitingForResponse,
inputMode,
onInterrupt,
assistant,
}) => {
const [textBuffer] = useState(() => new TextBuffer());
const [inputText, setInputText] = useState("");
const [cursorPosition, setCursorPosition] = useState(0);
const [showSlashCommands, setShowSlashCommands] = useState(false);
const [slashCommandFilter, setSlashCommandFilter] = useState("");
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const { exit } = useApp();
// Get all available slash commands
const getSlashCommands = () => {
const systemCommands = [
{ name: "help", description: "Show help message" },
{ name: "exit", description: "Exit the chat" },
{ name: "login", description: "Authenticate with your account" },
{ name: "logout", description: "Sign out of your current session" },
{
name: "whoami",
description: "Check who you're currently logged in as",
},
{ name: "models", description: "List available AI models" },
];
const assistantCommands =
assistant.prompts?.map((prompt) => ({
name: prompt?.name || "",
description: prompt?.description || "",
})) || [];
return [...systemCommands, ...assistantCommands];
};
// Update slash command UI state based on input
const updateSlashCommandState = (text: string, cursor: number) => {
// Check if we're in a slash command context
const beforeCursor = text.slice(0, cursor);
const lastSlashIndex = beforeCursor.lastIndexOf("/");
if (lastSlashIndex !== -1) {
// Check if there's any whitespace between the last slash and cursor
const afterSlash = beforeCursor.slice(lastSlashIndex + 1);
if (!afterSlash.includes(" ") && !afterSlash.includes("\n")) {
// We're in a slash command context
setShowSlashCommands(true);
setSlashCommandFilter(afterSlash);
setSelectedCommandIndex(0);
} else {
setShowSlashCommands(false);
}
} else {
setShowSlashCommands(false);
}
};
// Get filtered commands for navigation - using the same sorting logic as SlashCommandUI
const getFilteredCommands = () => {
const allCommands = getSlashCommands();
return allCommands
.filter((cmd) =>
cmd.name.toLowerCase().includes(slashCommandFilter.toLowerCase())
)
.sort((a, b) => {
const aStartsWith = a.name.toLowerCase().startsWith(slashCommandFilter.toLowerCase());
const bStartsWith = b.name.toLowerCase().startsWith(slashCommandFilter.toLowerCase());
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
return a.name.localeCompare(b.name);
});
};
// Handle slash command selection
const selectSlashCommand = (commandName: string) => {
const beforeCursor = inputText.slice(0, cursorPosition);
const lastSlashIndex = beforeCursor.lastIndexOf("/");
if (lastSlashIndex !== -1) {
const beforeSlash = inputText.slice(0, lastSlashIndex);
const afterCursor = inputText.slice(cursorPosition);
// Replace the partial command with the full command
const newText = beforeSlash + "/" + commandName + " " + afterCursor;
const newCursorPos = lastSlashIndex + 1 + commandName.length + 1;
textBuffer.setText(newText);
textBuffer.setCursor(newCursorPos);
setInputText(newText);
setCursorPosition(newCursorPos);
setShowSlashCommands(false);
}
};
useInput((input, key) => {
if (key.ctrl && (input === "c" || input === "d")) {
exit();
return;
}
// Handle escape key to interrupt streaming
if (key.escape && isWaitingForResponse && onInterrupt) {
onInterrupt();
return;
}
// Handle escape key to close slash command UI
if (key.escape && showSlashCommands && inputMode) {
setShowSlashCommands(false);
return;
}
if (!inputMode) {
return;
}
// Handle slash command navigation
if (showSlashCommands) {
const filteredCommands = getFilteredCommands();
if (key.upArrow) {
setSelectedCommandIndex((prev) =>
prev > 0 ? prev - 1 : filteredCommands.length - 1
);
return;
}
if (key.downArrow) {
setSelectedCommandIndex((prev) =>
prev < filteredCommands.length - 1 ? prev + 1 : 0
);
return;
}
if (key.return && !key.shift) {
if (filteredCommands.length > 0) {
selectSlashCommand(filteredCommands[selectedCommandIndex].name);
}
return;
}
if (key.tab) {
if (filteredCommands.length > 0) {
selectSlashCommand(filteredCommands[selectedCommandIndex].name);
}
return;
}
}
// Handle Enter key (regular enter for submit)
if (key.return && !key.shift) {
if (textBuffer.text.trim() && !isWaitingForResponse) {
@ -35,6 +174,7 @@ const UserInput: React.FC<UserInputProps> = ({
textBuffer.clear();
setInputText("");
setCursorPosition(0);
setShowSlashCommands(false);
}
return;
}
@ -43,8 +183,11 @@ const UserInput: React.FC<UserInputProps> = ({
if (input === "\r" || input === "\\\r") {
const handled = textBuffer.handleInput("\n", key);
if (handled) {
setInputText(textBuffer.text);
setCursorPosition(textBuffer.cursor);
const newText = textBuffer.text;
const newCursor = textBuffer.cursor;
setInputText(newText);
setCursorPosition(newCursor);
updateSlashCommandState(newText, newCursor);
}
return;
}
@ -54,20 +197,24 @@ const UserInput: React.FC<UserInputProps> = ({
// Update React state to trigger re-render
if (handled) {
setInputText(textBuffer.text);
setCursorPosition(textBuffer.cursor);
const newText = textBuffer.text;
const newCursor = textBuffer.cursor;
setInputText(newText);
setCursorPosition(newCursor);
updateSlashCommandState(newText, newCursor);
}
});
const renderInputText = () => {
const placeholderText = "Ask anything, @ for context, / for slash commands";
if (inputText.length === 0) {
return (
<>
{inputMode && !isWaitingForResponse && (
<Text color="gray">▋Type your message...</Text>
<Text color="gray">▋{placeholderText}</Text>
)}
{(!inputMode || isWaitingForResponse) && (
<Text color="gray">Type your message...</Text>
<Text color="gray">{placeholderText}</Text>
)}
</>
);
@ -132,11 +279,24 @@ const UserInput: React.FC<UserInputProps> = ({
};
return (
<Box borderStyle="round" borderTop={true} paddingX={1}>
<Text color="green" bold>
●{" "}
</Text>
{renderInputText()}
<Box flexDirection="column">
{/* Input box */}
<Box borderStyle="round" borderTop={true} paddingX={1} borderColor="gray">
<Text color="green" bold>
●{" "}
</Text>
{renderInputText()}
</Box>
{/* Slash command UI */}
{showSlashCommands && inputMode && (
<SlashCommandUI
assistant={assistant}
filter={slashCommandFilter}
selectedIndex={selectedCommandIndex}
onSelect={selectSlashCommand}
/>
)}
</Box>
);
};