diff --git a/src/intro.ts b/src/intro.ts index 44fc37f81..5a08117ab 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -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}`); } diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index ad1b73b90..3ac1e5649 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -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( diff --git a/src/tools.ts b/src/tools.ts index a9b7a7b5e..f2aeb341e 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -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, }; diff --git a/src/tools/exit.ts b/src/tools/exit.ts index 5f884a919..999600d6a 100644 --- a/src/tools/exit.ts +++ b/src/tools/exit.ts @@ -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: {}, diff --git a/src/tools/index.ts b/src/tools/index.ts index 3ee6972c2..2340b6db3 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -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) => { diff --git a/src/tools/listFiles.ts b/src/tools/listFiles.ts index bcd6df4d2..80010e58d 100644 --- a/src/tools/listFiles.ts +++ b/src/tools/listFiles.ts @@ -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: { diff --git a/src/tools/readFile.ts b/src/tools/readFile.ts index 2ea6bf5de..45ed8aa5b 100644 --- a/src/tools/readFile.ts +++ b/src/tools/readFile.ts @@ -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: { diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index 176f669e8..e753e8a31 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -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: { diff --git a/src/tools/searchCode.ts b/src/tools/searchCode.ts index 1b53b0c3f..fe6073203 100644 --- a/src/tools/searchCode.ts +++ b/src/tools/searchCode.ts @@ -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: { diff --git a/src/tools/types.ts b/src/tools/types.ts index 45ca005a3..86074f13b 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -9,6 +9,7 @@ export type ToolParameters = Record< export interface Tool { name: string; + displayName: string; description: string; parameters: ToolParameters; run: (args: any) => Promise; diff --git a/src/tools/viewDiff.ts b/src/tools/viewDiff.ts index b16eb861b..ebc9abab2 100644 --- a/src/tools/viewDiff.ts +++ b/src/tools/viewDiff.ts @@ -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: { diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index 54c1bc221..2ab64799f 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -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: { diff --git a/src/ui/LoadingAnimation.tsx b/src/ui/LoadingAnimation.tsx new file mode 100644 index 000000000..dc19f6da4 --- /dev/null +++ b/src/ui/LoadingAnimation.tsx @@ -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 = ({ + 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 {animationChars[currentIndex]}; +}; + +export default LoadingAnimation; diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx new file mode 100644 index 000000000..3f03bf8fb --- /dev/null +++ b/src/ui/SlashCommandUI.tsx @@ -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 = ({ + 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 ( + + No matching commands found + + ); + } + + return ( + + {filteredCommands.map((command, index) => { + const isSelected = index === selectedIndex; + + return ( + + + {" "} + /{command.name} + - {command.description} + + + ); + })} + + + + Use ↑/↓ to navigate, Enter to select, Tab to complete + + + + ); +}; + +export default SlashCommandUI; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 550cd7c1f..60d579dd2 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -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 = ({ @@ -37,6 +43,8 @@ const TUIChat: React.FC = ({ const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); const [messages, setMessages] = useState([]); const [inputMode, setInputMode] = useState(true); + const [abortController, setAbortController] = + useState(null); const { exit } = useApp(); // Handle initial prompt @@ -59,7 +67,11 @@ const TUIChat: React.FC = ({ 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 = ({ 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 = ({ 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 = ({ 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 ( - - - {message.content} - - - ); + // Handle different types of system messages + switch (message.messageType) { + case "tool-start": + return ( + + ○ {message.content} + + ); + + case "tool-result": + return ( + + + ● + {message.content} + + + + + + ); + + case "tool-error": + return ( + + + ✗{" "} + + Tool error: {message.content} + + ); + + default: + // Regular system messages + return ( + + + {message.content} + + + ); + } } return ( - - ● - + ● {message.content} {message.isStreaming && ▋} @@ -188,7 +295,8 @@ const TUIChat: React.FC = ({ {/* Status */} {isWaitingForResponse && ( - + + esc to interrupt )} @@ -198,10 +306,15 @@ const TUIChat: React.FC = ({ onSubmit={handleUserMessage} isWaitingForResponse={isWaitingForResponse} inputMode={inputMode} + onInterrupt={handleInterrupt} + assistant={assistant.config} /> + + ● Continue CLI + ); }; -export default TUIChat; +export default TUIChat; \ No newline at end of file diff --git a/src/ui/ToolResultSummary.tsx b/src/ui/ToolResultSummary.tsx new file mode 100644 index 000000000..c360f9f0b --- /dev/null +++ b/src/ui/ToolResultSummary.tsx @@ -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 = ({ + 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 ( + + ⎿ + {getSummary()} + + ); +}; + +export default ToolResultSummary; diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 00496634c..d05a4c54c 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -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 = ({ 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 = ({ textBuffer.clear(); setInputText(""); setCursorPosition(0); + setShowSlashCommands(false); } return; } @@ -43,8 +183,11 @@ const UserInput: React.FC = ({ 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 = ({ // 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 && ( - ▋Type your message... + ▋{placeholderText} )} {(!inputMode || isWaitingForResponse) && ( - Type your message... + {placeholderText} )} ); @@ -132,11 +279,24 @@ const UserInput: React.FC = ({ }; return ( - - - ●{" "} - - {renderInputText()} + + {/* Input box */} + + + ●{" "} + + {renderInputText()} + + + {/* Slash command UI */} + {showSlashCommands && inputMode && ( + + )} ); };