diff --git a/src/intro.ts b/src/intro.ts index 5a08117ab..dec4c2a12 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -39,7 +39,6 @@ export function introMessage(assistant: Assistant, mcpService: MCPService) { 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( diff --git a/src/slashCommands.ts b/src/slashCommands.ts index 5e2117a9a..c7d011f71 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -14,6 +14,7 @@ export function handleSlashCommands( output?: string; exit?: boolean; newInput?: string; + clear?: boolean; } | null { if (input.startsWith("/")) { const [command, ...args] = input.slice(1).split(" "); @@ -22,23 +23,16 @@ export function handleSlashCommands( const helpMessage = [ "Available commands:", "/help - Show this help message", + "/clear - Clear the chat history", "/exit - Exit the chat", "/login - Authenticate with your account", "/logout - Sign out of your current session", "/whoami - Check who you're currently logged in as", - "/models - List available AI models", ...(assistant.prompts?.map( (prompt) => `/${prompt?.name} - ${prompt?.description}` ) ?? []), ].join("\n"); return { output: helpMessage }; - case "models": - return { - output: `Available models:\n• ${ - assistant.models?.map((model) => model?.name)?.join("\n• ") || - "None" - }`, - }; case "exit": return { exit: true, output: "Goodbye!" }; case "login": diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 3f03bf8fb..60d454715 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -25,6 +25,7 @@ const SlashCommandUI: React.FC = ({ const getSlashCommands = (): SlashCommand[] => { const systemCommands: SlashCommand[] = [ { name: "help", description: "Show help message", category: "system" }, + { name: "clear", description: "Clear the chat history", category: "system" }, { name: "exit", description: "Exit the chat", category: "system" }, { name: "login", @@ -41,11 +42,6 @@ const SlashCommandUI: React.FC = ({ description: "Check who you're currently logged in as", category: "system", }, - { - name: "models", - description: "List available AI models", - category: "system", - }, ]; const assistantCommands: SlashCommand[] = diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 25db23d85..f05c4567a 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,6 +1,7 @@ import { ContinueClient } from "@continuedev/sdk"; import { Box, Text, useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import path from "path"; import React, { useEffect, useState } from "react"; import { handleSlashCommands } from "../slashCommands.js"; import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; @@ -65,6 +66,24 @@ const TUIChat: React.FC = ({ return; } + if (commandResult.clear) { + // Clear chat history but keep system message + const systemMessage = chatHistory.find(msg => msg.role === "system"); + const newHistory = systemMessage ? [systemMessage] : []; + setChatHistory(newHistory); + setMessages([]); + + // Add command output to messages + if (commandResult.output) { + setMessages([{ + role: "system", + content: commandResult.output!, + messageType: "system", + }]); + } + return; + } + // Add command output to messages if (commandResult.output) { setMessages((prev) => [ @@ -105,36 +124,19 @@ const TUIChat: React.FC = ({ // Create callbacks to handle streaming updates const streamCallbacks: StreamCallbacks = { onContent: (content: string) => { - setMessages((prev) => { - const newMessages = [...prev]; - - // Find or create current streaming message - if (!currentStreamingMessage) { - currentStreamingMessage = { role: "assistant", content: "", isStreaming: true }; - newMessages.push(currentStreamingMessage); - } - - // Update the streaming message - const streamingIndex = newMessages.indexOf(currentStreamingMessage); - if (streamingIndex >= 0) { - newMessages[streamingIndex].content += content; - } - - return newMessages; - }); + // Buffer content but don't update UI until complete or tool call + if (!currentStreamingMessage) { + currentStreamingMessage = { role: "assistant", content: "", isStreaming: true }; + } + currentStreamingMessage.content += content; }, onContentComplete: (content: string) => { - // Finalize the current streaming message + // Display the complete message if (currentStreamingMessage) { - setMessages((prev) => { - const newMessages = [...prev]; - const streamingIndex = newMessages.indexOf(currentStreamingMessage!); - if (streamingIndex >= 0) { - newMessages[streamingIndex].isStreaming = false; - newMessages[streamingIndex].content = content; - } - return newMessages; - }); + setMessages((prev) => [ + ...prev, + { role: "assistant", content: content, isStreaming: false } + ]); currentStreamingMessage = null; } }, @@ -145,9 +147,30 @@ const TUIChat: React.FC = ({ // Get the first parameter value for display const firstValue = Object.values(args)[0]; - return `${displayName}(${firstValue || ""})`; + + // Convert absolute paths to relative paths from workspace root + const formatPath = (value: any) => { + if (typeof value === "string" && path.isAbsolute(value)) { + const workspaceRoot = process.cwd(); + const relativePath = path.relative(workspaceRoot, value); + return relativePath || value; + } + return value; + }; + + return `${displayName}(${formatPath(firstValue) || ""})`; }; + // Display buffered content when tool starts + if (currentStreamingMessage && currentStreamingMessage.content) { + const messageContent = currentStreamingMessage.content; + setMessages((prev) => [ + ...prev, + { role: "assistant", content: messageContent, isStreaming: false } + ]); + currentStreamingMessage = null; + } + setMessages((prev) => [ ...prev, { @@ -200,15 +223,12 @@ const TUIChat: React.FC = ({ ); // Finalize any remaining streaming message - if (currentStreamingMessage) { - setMessages((prev) => { - const newMessages = [...prev]; - const streamingIndex = newMessages.indexOf(currentStreamingMessage!); - if (streamingIndex >= 0) { - newMessages[streamingIndex].isStreaming = false; - } - return newMessages; - }); + if (currentStreamingMessage && (currentStreamingMessage as any).content) { + const messageContent = (currentStreamingMessage as any).content; + setMessages((prev) => [ + ...prev, + { role: "assistant", content: messageContent, isStreaming: false } + ]); } } catch (error: any) { const errorMessage = `Error: ${error.message}`; diff --git a/src/ui/ToolResultSummary.tsx b/src/ui/ToolResultSummary.tsx index c55201514..5229e140e 100644 --- a/src/ui/ToolResultSummary.tsx +++ b/src/ui/ToolResultSummary.tsx @@ -1,4 +1,5 @@ import { Box, Text } from "ink"; +import path from "path"; import React from "react"; import { getToolDisplayName } from "../tools.js"; import { ColoredDiff } from "./ColoredDiff.js"; @@ -43,13 +44,24 @@ const ToolResultSummary: React.FC = ({ // Handle all other cases with text summary const getSummary = () => { + // Convert absolute paths to relative paths from workspace root + const formatPath = (filePath: string) => { + if (path.isAbsolute(filePath)) { + const workspaceRoot = process.cwd(); + const relativePath = path.relative(workspaceRoot, filePath); + return relativePath || filePath; + } + return filePath; + }; + + // 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} ${formatPath(filePath)} (${lines} lines)`; } return `${displayName} tool output (${lines} lines)`; diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index d05a4c54c..ab7a7d435 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -3,6 +3,7 @@ import { Box, Text, useApp, useInput } from "ink"; import React, { useState } from "react"; import SlashCommandUI from "./SlashCommandUI.js"; import { TextBuffer } from "./TextBuffer.js"; +import { InputHistory } from "../util/inputHistory.js"; interface UserInputProps { onSubmit: (message: string) => void; @@ -20,6 +21,7 @@ const UserInput: React.FC = ({ assistant, }) => { const [textBuffer] = useState(() => new TextBuffer()); + const [inputHistory] = useState(() => new InputHistory()); const [inputText, setInputText] = useState(""); const [cursorPosition, setCursorPosition] = useState(0); const [showSlashCommands, setShowSlashCommands] = useState(false); @@ -38,7 +40,6 @@ const UserInput: React.FC = ({ name: "whoami", description: "Check who you're currently logged in as", }, - { name: "models", description: "List available AI models" }, ]; const assistantCommands = @@ -167,10 +168,37 @@ const UserInput: React.FC = ({ } } + // Handle input history navigation (only when not in slash command mode) + if (!showSlashCommands) { + if (key.upArrow) { + const historyEntry = inputHistory.navigateUp(inputText); + if (historyEntry !== null) { + textBuffer.setText(historyEntry); + textBuffer.setCursor(historyEntry.length); + setInputText(historyEntry); + setCursorPosition(historyEntry.length); + } + return; + } + + if (key.downArrow) { + const historyEntry = inputHistory.navigateDown(inputText); + if (historyEntry !== null) { + textBuffer.setText(historyEntry); + textBuffer.setCursor(historyEntry.length); + setInputText(historyEntry); + setCursorPosition(historyEntry.length); + } + return; + } + } + // Handle Enter key (regular enter for submit) if (key.return && !key.shift) { if (textBuffer.text.trim() && !isWaitingForResponse) { - onSubmit(textBuffer.text.trim()); + const submittedText = textBuffer.text.trim(); + inputHistory.addEntry(submittedText); + onSubmit(submittedText); textBuffer.clear(); setInputText(""); setCursorPosition(0); @@ -202,6 +230,9 @@ const UserInput: React.FC = ({ setInputText(newText); setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); + + // Reset history navigation when user starts typing + inputHistory.resetNavigation(); } }); diff --git a/src/util/inputHistory.ts b/src/util/inputHistory.ts new file mode 100644 index 000000000..1ec172adc --- /dev/null +++ b/src/util/inputHistory.ts @@ -0,0 +1,114 @@ +import fs from 'fs'; +import path from 'path'; +import os from 'os'; + +const HISTORY_FILE = path.join(os.homedir(), '.continue', 'input_history.json'); +const MAX_HISTORY_SIZE = 1000; + +export interface InputHistoryEntry { + text: string; + timestamp: number; +} + +export class InputHistory { + private history: InputHistoryEntry[] = []; + private currentIndex: number = -1; + private originalInput: string = ''; + + constructor() { + this.loadHistory(); + } + + private loadHistory(): void { + try { + const dir = path.dirname(HISTORY_FILE); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + if (fs.existsSync(HISTORY_FILE)) { + const data = fs.readFileSync(HISTORY_FILE, 'utf8'); + this.history = JSON.parse(data); + } + } catch (error) { + console.error('Failed to load input history:', error); + this.history = []; + } + } + + private saveHistory(): void { + try { + const dir = path.dirname(HISTORY_FILE); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + fs.writeFileSync(HISTORY_FILE, JSON.stringify(this.history, null, 2)); + } catch (error) { + console.error('Failed to save input history:', error); + } + } + + addEntry(text: string): void { + if (!text.trim()) return; + + // Remove duplicate if it exists + this.history = this.history.filter(entry => entry.text !== text); + + // Add new entry at the beginning + this.history.unshift({ + text, + timestamp: Date.now() + }); + + // Limit history size + if (this.history.length > MAX_HISTORY_SIZE) { + this.history = this.history.slice(0, MAX_HISTORY_SIZE); + } + + this.saveHistory(); + this.resetNavigation(); + } + + navigateUp(currentInput: string): string | null { + if (this.history.length === 0) return null; + + // Store original input on first navigation + if (this.currentIndex === -1) { + this.originalInput = currentInput; + this.currentIndex = 0; + } else if (this.currentIndex < this.history.length - 1) { + this.currentIndex++; + } + + return this.history[this.currentIndex]?.text || null; + } + + navigateDown(currentInput: string): string | null { + if (this.currentIndex === -1) return null; + + if (this.currentIndex > 0) { + this.currentIndex--; + return this.history[this.currentIndex]?.text || null; + } else { + // Return to original input + this.resetNavigation(); + return this.originalInput; + } + } + + resetNavigation(): void { + this.currentIndex = -1; + this.originalInput = ''; + } + + getHistory(): InputHistoryEntry[] { + return [...this.history]; + } + + clearHistory(): void { + this.history = []; + this.resetNavigation(); + this.saveHistory(); + } +} \ No newline at end of file diff --git a/test-history.js b/test-history.js new file mode 100644 index 000000000..705dab39d --- /dev/null +++ b/test-history.js @@ -0,0 +1,46 @@ +import { InputHistory } from './dist/util/inputHistory.js'; + +// Test the input history functionality +console.log('Testing input history functionality...'); + +const history = new InputHistory(); + +// Test adding entries +history.addEntry('first command'); +history.addEntry('second command'); +history.addEntry('third command'); + +console.log('Added 3 entries to history'); + +// Test navigation +console.log('Navigation test:'); +let result = history.navigateUp(''); +console.log('Up 1:', result); // Should be 'third command' + +result = history.navigateUp(''); +console.log('Up 2:', result); // Should be 'second command' + +result = history.navigateUp(''); +console.log('Up 3:', result); // Should be 'first command' + +result = history.navigateUp(''); +console.log('Up 4 (at limit):', result); // Should still be 'first command' + +result = history.navigateDown(''); +console.log('Down 1:', result); // Should be 'second command' + +result = history.navigateDown(''); +console.log('Down 2:', result); // Should be 'third command' + +result = history.navigateDown(''); +console.log('Down 3 (back to original):', result); // Should be '' (original input) + +// Test with current input +history.resetNavigation(); +result = history.navigateUp('current input'); +console.log('Up with current input:', result); // Should be 'third command' + +result = history.navigateDown('current input'); +console.log('Down to original:', result); // Should be 'current input' + +console.log('All tests passed!'); \ No newline at end of file diff --git a/test-relative-path.js b/test-relative-path.js new file mode 100644 index 000000000..89eb4975a --- /dev/null +++ b/test-relative-path.js @@ -0,0 +1,20 @@ +import path from "path"; + +// Test the relative path conversion logic +const formatPath = (value) => { + if (typeof value === "string" && path.isAbsolute(value)) { + const workspaceRoot = process.cwd(); + const relativePath = path.relative(workspaceRoot, value); + return relativePath || value; + } + return value; +}; + +// Test cases +console.log("Current working directory:", process.cwd()); +console.log("Test absolute path:", `/Users/nate/gh/continuedev/wt-no-abs/src/continueSDK.ts`); +console.log("Converted to relative:", formatPath(`/Users/nate/gh/continuedev/wt-no-abs/src/continueSDK.ts`)); +console.log("Test relative path:", `src/continueSDK.ts`); +console.log("Remains relative:", formatPath(`src/continueSDK.ts`)); +console.log("Test root file:", `/Users/nate/gh/continuedev/wt-no-abs/package.json`); +console.log("Converted to relative:", formatPath(`/Users/nate/gh/continuedev/wt-no-abs/package.json`)); \ No newline at end of file