Merge pull request #4 from continuedev/nate/ink-tui
feat: basic ink tui
This commit is contained in:
commit
350cc09597
13 changed files with 1875 additions and 42 deletions
67
AGENTS.md
Normal file
67
AGENTS.md
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Development Commands
|
||||
|
||||
- **Build**: `npm run build` - Compiles TypeScript to JavaScript in dist/
|
||||
- **Test**: `npm test` - Runs Jest tests with ESM support
|
||||
- **Type Check**: `npm run lint` - Runs TypeScript compiler without emitting files for type checking
|
||||
- **Start**: `npm start` - Runs the built CLI from dist/index.js
|
||||
- **Development**: After building, test locally with `node dist/index.js`
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
This is a CLI tool for Continue Dev that provides an interactive AI-assisted development experience. The architecture consists of:
|
||||
|
||||
### Core Components
|
||||
|
||||
1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes:
|
||||
- **Headless mode**: Non-interactive mode for automation/CI
|
||||
- **TUI mode**: Terminal User Interface using Ink/React
|
||||
- **Standard mode**: Traditional readline-based chat interface
|
||||
|
||||
2. **Authentication** (`src/auth/`): WorkOS-based authentication system
|
||||
- `ensureAuth.ts`: Handles authentication flow
|
||||
- `workos.ts`: WorkOS configuration and token management
|
||||
|
||||
3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with:
|
||||
- API key authentication
|
||||
- Assistant configuration (slug-based)
|
||||
- Organization support
|
||||
|
||||
4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components
|
||||
- `TUIChat.tsx`: Main chat interface component
|
||||
- `UserInput.tsx`: Input handling with multi-line support
|
||||
- `TextBuffer.ts`: Text display utilities
|
||||
|
||||
5. **Tools System** (`src/tools/`): Built-in development tools including:
|
||||
- File operations (read, write, list)
|
||||
- Code search functionality
|
||||
- Terminal command execution
|
||||
- Diff viewing
|
||||
- Exit tool (headless mode only)
|
||||
|
||||
6. **MCP Integration** (`src/mcp.ts`): Model Context Protocol service for extended tool capabilities
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Streaming Responses**: Real-time AI response streaming (`streamChatResponse.ts`)
|
||||
- **Slash Commands**: Built-in commands like `/help`, `/exit` (`slashCommands.ts`)
|
||||
- **Multi-mode Operation**: Supports TUI, headless, and standard chat modes
|
||||
- **Tool Integration**: Extensible tool system for development tasks
|
||||
|
||||
### Testing Setup
|
||||
|
||||
- Uses Jest with TypeScript and ESM support
|
||||
- Configuration in `jest.config.mjs`
|
||||
- Tests should be written with `.test.ts` extension
|
||||
- No existing test files found - tests should be added when writing new functionality
|
||||
|
||||
### Build System
|
||||
|
||||
- TypeScript compilation with declaration files
|
||||
- ESNext target with NodeNext module resolution
|
||||
- Outputs to `dist/` directory
|
||||
- Source maps and inline sources enabled
|
||||
- JSX support for React components
|
||||
|
|
@ -5,6 +5,7 @@ A command-line interface for Continue Dev that provides an interactive AI-assist
|
|||
## Features
|
||||
|
||||
- 🤖 Interactive AI Assistant Chat
|
||||
- 🎨 Beautiful Terminal User Interface (TUI)
|
||||
- 🔐 Secure Authentication via WorkOS
|
||||
- 🛠️ Built-in Development Tools
|
||||
- ⚡ Real-time Response Streaming
|
||||
|
|
@ -87,6 +88,7 @@ npm test
|
|||
src/
|
||||
├── auth/ # Authentication implementation
|
||||
├── tools/ # CLI tools and utilities
|
||||
├── ui/ # Terminal User Interface components
|
||||
├── index.ts # Main entry point
|
||||
├── args.ts # Command line argument parsing
|
||||
├── client.ts # Client implementation
|
||||
|
|
@ -99,6 +101,7 @@ src/
|
|||
- `@continuedev/*` packages for core functionality
|
||||
- `@workos-inc/node` for authentication
|
||||
- `openai` for AI capabilities
|
||||
- `ink` and `react` for Terminal UI
|
||||
- Various utility packages (chalk, axios, etc.)
|
||||
|
||||
## License
|
||||
|
|
@ -111,4 +114,4 @@ Contributions are welcome! Please feel free to submit a Pull Request.
|
|||
|
||||
## Support
|
||||
|
||||
For issues and feature requests, please use the GitHub issue tracker.
|
||||
For issues and feature requests, please use the GitHub issue tracker.
|
||||
1100
package-lock.json
generated
1100
package-lock.json
generated
File diff suppressed because it is too large
Load diff
10
package.json
10
package.json
|
|
@ -12,8 +12,10 @@
|
|||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx src/index.ts",
|
||||
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
|
||||
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml"
|
||||
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
|
||||
"lint": "tsc --noEmit"
|
||||
},
|
||||
"author": "Continue Dev, Inc.",
|
||||
"license": "Apache-2.0",
|
||||
|
|
@ -21,12 +23,15 @@
|
|||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@continuedev/sdk": "^0.0.12",
|
||||
"@modelcontextprotocol/sdk": "^1.9.0",
|
||||
"@types/react": "^19.1.8",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"axios": "^1.8.4",
|
||||
"chalk": "^5.4.1",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"ink": "^6.0.1",
|
||||
"open": "^10.1.0",
|
||||
"react": "^19.1.0",
|
||||
"readline-sync": "^1.4.10",
|
||||
"uuid": "^9.0.1"
|
||||
},
|
||||
|
|
@ -38,6 +43,7 @@
|
|||
"cross-env": "^7.0.3",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2"
|
||||
"ts-node": "^10.9.2",
|
||||
"tsx": "^4.20.3"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
export interface CommandLineArgs {
|
||||
isHeadless: boolean;
|
||||
configPath: string;
|
||||
|
|
@ -17,7 +14,7 @@ export function parseArgs(): CommandLineArgs {
|
|||
// Default values
|
||||
const result: CommandLineArgs = {
|
||||
isHeadless: false,
|
||||
configPath: path.join(os.homedir(), ".continue", "config.yaml"),
|
||||
configPath: "nate/default-assistant",
|
||||
};
|
||||
|
||||
// Parse flags
|
||||
|
|
|
|||
29
src/index.ts
29
src/index.ts
|
|
@ -13,6 +13,7 @@ import { configureLogger } from "./logger.js";
|
|||
import { MCPService } from "./mcp.js";
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { startTUIChat } from "./ui/index.js";
|
||||
|
||||
// Parse command line arguments
|
||||
const args = parseArgs();
|
||||
|
|
@ -30,10 +31,6 @@ async function chat() {
|
|||
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
// Check if the assistant path is a file or a slug
|
||||
let assistant: ContinueClient["assistant"];
|
||||
let client: ContinueClient["client"];
|
||||
|
||||
// This was the previous default behavior, but currently the SDK
|
||||
// only supports slugs, so we've disabled reading local assistant files
|
||||
|
||||
|
|
@ -62,14 +59,20 @@ async function chat() {
|
|||
// }
|
||||
// }
|
||||
|
||||
// Initialize ContinueSDK and MCPService once
|
||||
let assistant: ContinueClient["assistant"];
|
||||
let client: ContinueClient["client"];
|
||||
let mcpService: MCPService;
|
||||
|
||||
try {
|
||||
let continueSdk = await initializeContinueSDK(
|
||||
const continueSdk = await initializeContinueSDK(
|
||||
authConfig.accessToken,
|
||||
args.configPath
|
||||
);
|
||||
|
||||
assistant = continueSdk.assistant;
|
||||
client = continueSdk.client;
|
||||
mcpService = await MCPService.create(assistant.config);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
chalk.red(`Error loading assistant ${args.configPath}:`),
|
||||
|
|
@ -78,16 +81,18 @@ async function chat() {
|
|||
throw error;
|
||||
}
|
||||
|
||||
const mcpService = await MCPService.create(assistant!.config);
|
||||
|
||||
// Only show intro message if not in headless mode
|
||||
// If not in headless mode, start the TUI chat (default)
|
||||
if (!args.isHeadless) {
|
||||
introMessage(assistant!, mcpService);
|
||||
await startTUIChat(assistant, client, mcpService, args.prompt);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show intro message for headless mode
|
||||
introMessage(assistant, mcpService);
|
||||
|
||||
// Rules
|
||||
const chatHistory: ChatCompletionMessageParam[] = [];
|
||||
const systemMessage = assistant!.systemMessage;
|
||||
const systemMessage = assistant.systemMessage;
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
|
@ -108,7 +113,7 @@ async function chat() {
|
|||
isFirstMessage = false;
|
||||
|
||||
// Handle slash commands
|
||||
const commandResult = handleSlashCommands(userInput, assistant!.config);
|
||||
const commandResult = handleSlashCommands(userInput, assistant.config);
|
||||
if (commandResult) {
|
||||
if (commandResult.exit) {
|
||||
break;
|
||||
|
|
@ -133,7 +138,7 @@ async function chat() {
|
|||
}
|
||||
|
||||
try {
|
||||
await streamChatResponse(chatHistory, assistant!, client!);
|
||||
await streamChatResponse(chatHistory, assistant, client);
|
||||
} catch (e: any) {
|
||||
console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
|
||||
console.info(
|
||||
|
|
|
|||
|
|
@ -50,11 +50,19 @@ export function getAllTools() {
|
|||
|
||||
type TODO = any;
|
||||
|
||||
export interface StreamCallbacks {
|
||||
onContent?: (content: string) => void;
|
||||
onToolStart?: (toolName: string) => void;
|
||||
onToolResult?: (result: string) => void;
|
||||
onToolError?: (error: string) => void;
|
||||
}
|
||||
|
||||
// Define a function to handle streaming responses with tool calling
|
||||
export async function streamChatResponse(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
assistant: ContinueClient["assistant"],
|
||||
client: ContinueClient["client"]
|
||||
client: ContinueClient["client"],
|
||||
callbacks?: StreamCallbacks
|
||||
) {
|
||||
// Prepare tools for the API call
|
||||
const toolsForRequest = getAllTools();
|
||||
|
|
@ -94,7 +102,11 @@ export async function streamChatResponse(
|
|||
// Handle regular content
|
||||
if (chunk.choices[0].delta.content) {
|
||||
const content = chunk.choices[0].delta.content;
|
||||
process.stdout.write(chalk.white(content));
|
||||
if (callbacks?.onContent) {
|
||||
callbacks.onContent(content);
|
||||
} else {
|
||||
process.stdout.write(chalk.white(content));
|
||||
}
|
||||
aiResponse += content;
|
||||
}
|
||||
|
||||
|
|
@ -121,11 +133,15 @@ export async function streamChatResponse(
|
|||
if (toolCall) {
|
||||
if (!toolCall.name) {
|
||||
toolCall.name = toolCallDelta.function.name;
|
||||
process.stdout.write(
|
||||
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
|
||||
toolCall.name
|
||||
)}${chalk.yellow("]")}`
|
||||
);
|
||||
if (callbacks?.onToolStart) {
|
||||
callbacks.onToolStart(toolCall.name);
|
||||
} else {
|
||||
process.stdout.write(
|
||||
`\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold(
|
||||
toolCall.name
|
||||
)}${chalk.yellow("]")}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -152,7 +168,9 @@ export async function streamChatResponse(
|
|||
}
|
||||
}
|
||||
|
||||
console.info(); // Add a newline after the response
|
||||
if (!callbacks?.onContent) {
|
||||
console.info(); // Add a newline after the response
|
||||
}
|
||||
|
||||
// Add the assistant's response to chat history if there's content or tool calls
|
||||
if (currentToolCalls.length > 0) {
|
||||
|
|
@ -193,7 +211,11 @@ export async function streamChatResponse(
|
|||
content: toolResult,
|
||||
});
|
||||
|
||||
console.info(chalk.green(toolResult) + "\n");
|
||||
if (callbacks?.onToolResult) {
|
||||
callbacks.onToolResult(toolResult);
|
||||
} else {
|
||||
console.info(chalk.green(toolResult) + "\n");
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = `Error executing tool ${toolCall.name}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
|
|
@ -203,11 +225,15 @@ export async function streamChatResponse(
|
|||
tool_call_id: toolCall.id,
|
||||
content: errorMessage,
|
||||
});
|
||||
console.info(
|
||||
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(
|
||||
")"
|
||||
)}`
|
||||
);
|
||||
if (callbacks?.onToolError) {
|
||||
callbacks.onToolError(errorMessage);
|
||||
} else {
|
||||
console.info(
|
||||
`${chalk.red("[Tool error:")} ${chalk.red(errorMessage)}${chalk.red(
|
||||
")"
|
||||
)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { Tool, ToolParameters } from "./types.js";
|
|||
import { viewDiffTool } from "./viewDiff.js";
|
||||
import { writeFileTool } from "./writeFile.js";
|
||||
|
||||
export { Tool } from "./types.js";
|
||||
export { Tool, ToolParameters };
|
||||
|
||||
export const BUILTIN_TOOLS: Tool[] = [
|
||||
readFileTool,
|
||||
|
|
|
|||
207
src/ui/TUIChat.tsx
Normal file
207
src/ui/TUIChat.tsx
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { ContinueClient } from "@continuedev/sdk";
|
||||
import { Box, Text, useApp } from "ink";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { handleSlashCommands } from "../slashCommands.js";
|
||||
import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js";
|
||||
import UserInput from "./UserInput.js";
|
||||
|
||||
interface TUIChatProps {
|
||||
assistant: ContinueClient["assistant"];
|
||||
client: ContinueClient["client"];
|
||||
initialPrompt?: string;
|
||||
}
|
||||
|
||||
interface DisplayMessage {
|
||||
role: string;
|
||||
content: string;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
const TUIChat: React.FC<TUIChatProps> = ({
|
||||
assistant,
|
||||
client,
|
||||
initialPrompt,
|
||||
}) => {
|
||||
const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>(
|
||||
() => {
|
||||
const history: ChatCompletionMessageParam[] = [];
|
||||
const systemMessage = assistant.systemMessage;
|
||||
if (systemMessage) {
|
||||
history.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
return history;
|
||||
}
|
||||
);
|
||||
|
||||
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
|
||||
const [messages, setMessages] = useState<DisplayMessage[]>([]);
|
||||
const [inputMode, setInputMode] = useState(true);
|
||||
const { exit } = useApp();
|
||||
|
||||
// Handle initial prompt
|
||||
useEffect(() => {
|
||||
if (initialPrompt) {
|
||||
handleUserMessage(initialPrompt);
|
||||
}
|
||||
}, [initialPrompt]);
|
||||
|
||||
const handleUserMessage = async (message: string) => {
|
||||
// Handle slash commands
|
||||
const commandResult = handleSlashCommands(message, assistant.config);
|
||||
if (commandResult) {
|
||||
if (commandResult.exit) {
|
||||
exit();
|
||||
return;
|
||||
}
|
||||
|
||||
// Add command output to messages
|
||||
if (commandResult.output) {
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: "system", content: commandResult.output! },
|
||||
]);
|
||||
}
|
||||
|
||||
if (commandResult.newInput) {
|
||||
message = commandResult.newInput;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add user message to history and display
|
||||
const newUserMessage: ChatCompletionMessageParam = {
|
||||
role: "user",
|
||||
content: message,
|
||||
};
|
||||
setChatHistory((prev) => [...prev, newUserMessage]);
|
||||
setMessages((prev) => [...prev, { role: "user", content: message }]);
|
||||
|
||||
// Start streaming response
|
||||
setIsWaitingForResponse(true);
|
||||
setInputMode(false);
|
||||
|
||||
// Add placeholder for streaming message
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: "assistant", content: "", isStreaming: true },
|
||||
]);
|
||||
|
||||
try {
|
||||
const newHistory = [...chatHistory, newUserMessage];
|
||||
let assistantResponse = "";
|
||||
|
||||
// Create callbacks to handle streaming updates
|
||||
const streamCallbacks: StreamCallbacks = {
|
||||
onContent: (content: string) => {
|
||||
assistantResponse += content;
|
||||
setMessages((prev) => {
|
||||
const newMessages = [...prev];
|
||||
const lastMessage = newMessages[newMessages.length - 1];
|
||||
if (lastMessage.isStreaming) {
|
||||
lastMessage.content += content;
|
||||
}
|
||||
return newMessages;
|
||||
});
|
||||
},
|
||||
onToolStart: (toolName: string) => {
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: "system", content: `[Using tool: ${toolName}]` },
|
||||
]);
|
||||
},
|
||||
onToolResult: (result: string) => {
|
||||
setMessages((prev) => [...prev, { role: "system", content: result }]);
|
||||
},
|
||||
onToolError: (error: string) => {
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: "system", content: `[Tool error: ${error}]` },
|
||||
]);
|
||||
},
|
||||
};
|
||||
|
||||
await streamChatResponse(newHistory, assistant, client, streamCallbacks);
|
||||
|
||||
// Finalize the assistant message
|
||||
const finalAssistantMessage: ChatCompletionMessageParam = {
|
||||
role: "assistant",
|
||||
content: assistantResponse,
|
||||
};
|
||||
setChatHistory((prev) => [...prev, finalAssistantMessage]);
|
||||
|
||||
// Update messages to remove streaming flag
|
||||
setMessages((prev) => {
|
||||
const newMessages = [...prev];
|
||||
const lastMessage = newMessages[newMessages.length - 1];
|
||||
if (lastMessage.isStreaming) {
|
||||
lastMessage.isStreaming = false;
|
||||
}
|
||||
return newMessages;
|
||||
});
|
||||
} catch (error: any) {
|
||||
const errorMessage = `Error: ${error.message}`;
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: "system", content: errorMessage },
|
||||
]);
|
||||
} finally {
|
||||
setIsWaitingForResponse(false);
|
||||
setInputMode(true);
|
||||
}
|
||||
};
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box key={index} marginBottom={1}>
|
||||
<Text color={isUser ? "green" : "blue"} bold>
|
||||
●
|
||||
</Text>
|
||||
<Text> {message.content}</Text>
|
||||
{message.isStreaming && <Text color="gray">▋</Text>}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" height="100%">
|
||||
{/* Chat history - takes up all available space above input */}
|
||||
<Box flexDirection="column" flexGrow={1} paddingX={1} overflow="hidden">
|
||||
{messages.map(renderMessage)}
|
||||
</Box>
|
||||
|
||||
{/* Fixed bottom section */}
|
||||
<Box flexDirection="column" flexShrink={0}>
|
||||
{/* Status */}
|
||||
{isWaitingForResponse && (
|
||||
<Box paddingX={1}>
|
||||
<Text color="gray">esc to interrupt</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Input area - always at bottom */}
|
||||
<UserInput
|
||||
onSubmit={handleUserMessage}
|
||||
isWaitingForResponse={isWaitingForResponse}
|
||||
inputMode={inputMode}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default TUIChat;
|
||||
258
src/ui/TextBuffer.ts
Normal file
258
src/ui/TextBuffer.ts
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { Key } from "ink";
|
||||
|
||||
export class TextBuffer {
|
||||
private _text: string = "";
|
||||
private _cursor: number = 0;
|
||||
|
||||
constructor(initialText: string = "") {
|
||||
this._text = initialText;
|
||||
this._cursor = initialText.length;
|
||||
}
|
||||
|
||||
get text(): string {
|
||||
return this._text;
|
||||
}
|
||||
|
||||
get cursor(): number {
|
||||
return this._cursor;
|
||||
}
|
||||
|
||||
setText(text: string): void {
|
||||
this._text = text;
|
||||
this._cursor = Math.min(this._cursor, text.length);
|
||||
}
|
||||
|
||||
setCursor(position: number): void {
|
||||
this._cursor = Math.max(0, Math.min(position, this._text.length));
|
||||
}
|
||||
|
||||
insertText(text: string): void {
|
||||
this._text =
|
||||
this._text.slice(0, this._cursor) + text + this._text.slice(this._cursor);
|
||||
this._cursor += text.length;
|
||||
}
|
||||
|
||||
deleteCharAt(position: number): void {
|
||||
if (position >= 0 && position < this._text.length) {
|
||||
this._text =
|
||||
this._text.slice(0, position) + this._text.slice(position + 1);
|
||||
if (this._cursor > position) {
|
||||
this._cursor--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deleteBackward(): void {
|
||||
if (this._cursor > 0) {
|
||||
this.deleteCharAt(this._cursor - 1);
|
||||
}
|
||||
}
|
||||
|
||||
deleteForward(): void {
|
||||
if (this._cursor < this._text.length) {
|
||||
this.deleteCharAt(this._cursor);
|
||||
}
|
||||
}
|
||||
|
||||
private findWordBoundary(
|
||||
position: number,
|
||||
direction: "left" | "right"
|
||||
): number {
|
||||
if (direction === "left") {
|
||||
// Find start of current word or previous word
|
||||
let pos = Math.max(0, position - 1);
|
||||
|
||||
// Skip whitespace
|
||||
while (pos > 0 && /\s/.test(this._text[pos])) {
|
||||
pos--;
|
||||
}
|
||||
|
||||
// Find word boundary
|
||||
while (pos > 0 && !/\s/.test(this._text[pos - 1])) {
|
||||
pos--;
|
||||
}
|
||||
|
||||
return pos;
|
||||
} else {
|
||||
// Find end of current word or next word
|
||||
let pos = position;
|
||||
|
||||
// Skip whitespace
|
||||
while (pos < this._text.length && /\s/.test(this._text[pos])) {
|
||||
pos++;
|
||||
}
|
||||
|
||||
// Find word boundary
|
||||
while (pos < this._text.length && !/\s/.test(this._text[pos])) {
|
||||
pos++;
|
||||
}
|
||||
|
||||
return pos;
|
||||
}
|
||||
}
|
||||
|
||||
moveWordLeft(): void {
|
||||
this._cursor = this.findWordBoundary(this._cursor, "left");
|
||||
}
|
||||
|
||||
moveWordRight(): void {
|
||||
this._cursor = this.findWordBoundary(this._cursor, "right");
|
||||
}
|
||||
|
||||
deleteWordBackward(): void {
|
||||
const wordStart = this.findWordBoundary(this._cursor, "left");
|
||||
if (wordStart < this._cursor) {
|
||||
this._text =
|
||||
this._text.slice(0, wordStart) + this._text.slice(this._cursor);
|
||||
this._cursor = wordStart;
|
||||
}
|
||||
}
|
||||
|
||||
deleteWordForward(): void {
|
||||
const wordEnd = this.findWordBoundary(this._cursor, "right");
|
||||
if (wordEnd > this._cursor) {
|
||||
this._text =
|
||||
this._text.slice(0, this._cursor) + this._text.slice(wordEnd);
|
||||
}
|
||||
}
|
||||
|
||||
moveToStart(): void {
|
||||
this._cursor = 0;
|
||||
}
|
||||
|
||||
moveToEnd(): void {
|
||||
this._cursor = this._text.length;
|
||||
}
|
||||
|
||||
moveLeft(): void {
|
||||
this._cursor = Math.max(0, this._cursor - 1);
|
||||
}
|
||||
|
||||
moveRight(): void {
|
||||
this._cursor = Math.min(this._text.length, this._cursor + 1);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this._text = "";
|
||||
this._cursor = 0;
|
||||
}
|
||||
|
||||
handleInput(input: string, key: Key): boolean {
|
||||
// Detect option key combinations through escape sequences
|
||||
const isOptionKey = input.startsWith("\u001b") && input.length > 1;
|
||||
|
||||
// Handle option key combinations (detected through escape sequences)
|
||||
if (isOptionKey) {
|
||||
const sequence = input.slice(1);
|
||||
|
||||
// Option + backspace (usually \u001b\u0008 or \u001b\u007f)
|
||||
if (sequence === "\u0008" || sequence === "\u007f") {
|
||||
this.deleteWordBackward();
|
||||
return true;
|
||||
}
|
||||
|
||||
return true; // Consume other option sequences
|
||||
}
|
||||
|
||||
// Handle special key combinations based on input character
|
||||
if (key.ctrl) {
|
||||
switch (input) {
|
||||
case "a":
|
||||
this.moveToStart();
|
||||
return true;
|
||||
case "e":
|
||||
this.moveToEnd();
|
||||
return true;
|
||||
case "u":
|
||||
// Delete from cursor to start of line
|
||||
this._text = this._text.slice(this._cursor);
|
||||
this._cursor = 0;
|
||||
return true;
|
||||
case "k":
|
||||
// Delete from cursor to end of line
|
||||
this._text = this._text.slice(0, this._cursor);
|
||||
return true;
|
||||
case "w":
|
||||
this.deleteWordBackward();
|
||||
return true;
|
||||
case "d":
|
||||
this.deleteWordForward();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle meta key combinations (cmd on Mac)
|
||||
if (key.meta) {
|
||||
if (key.backspace) {
|
||||
this.deleteWordBackward();
|
||||
return true;
|
||||
}
|
||||
if (key.delete) {
|
||||
this.deleteWordBackward();
|
||||
return true;
|
||||
}
|
||||
if (key.leftArrow) {
|
||||
this.moveWordLeft();
|
||||
return true;
|
||||
}
|
||||
if (key.rightArrow) {
|
||||
this.moveWordRight();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle option+left/right as characters (on Mac, option+arrow sends character codes)
|
||||
if (input === "b") {
|
||||
this.moveWordLeft();
|
||||
return true;
|
||||
}
|
||||
if (input === "f") {
|
||||
this.moveWordRight();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle arrow keys
|
||||
if (key.leftArrow && !key.meta) {
|
||||
this.moveLeft();
|
||||
return true;
|
||||
}
|
||||
if (key.rightArrow && !key.meta) {
|
||||
this.moveRight();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle backspace/delete
|
||||
// On Mac, backspace key registers as key.delete, so treat it as backward deletion
|
||||
if (key.delete && !key.meta) {
|
||||
this.deleteBackward();
|
||||
return true;
|
||||
}
|
||||
if (key.backspace && !key.meta) {
|
||||
this.deleteBackward();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle regular character input (including paste - multi-character input)
|
||||
if (input && input.length >= 1 && !key.ctrl && !key.meta && !isOptionKey) {
|
||||
this.insertText(input);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Helper method to render text with cursor
|
||||
renderWithCursor(placeholder?: string): {
|
||||
text: string;
|
||||
cursorPosition: number;
|
||||
} {
|
||||
if (this._text.length === 0 && placeholder) {
|
||||
return { text: placeholder, cursorPosition: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
text: this._text,
|
||||
cursorPosition: this._cursor,
|
||||
};
|
||||
}
|
||||
}
|
||||
144
src/ui/UserInput.tsx
Normal file
144
src/ui/UserInput.tsx
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import { Box, Text, useApp, useInput } from "ink";
|
||||
import React, { useState } from "react";
|
||||
import { TextBuffer } from "./TextBuffer.js";
|
||||
|
||||
interface UserInputProps {
|
||||
onSubmit: (message: string) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
inputMode: boolean;
|
||||
}
|
||||
|
||||
const UserInput: React.FC<UserInputProps> = ({
|
||||
onSubmit,
|
||||
isWaitingForResponse,
|
||||
inputMode,
|
||||
}) => {
|
||||
const [textBuffer] = useState(() => new TextBuffer());
|
||||
const [inputText, setInputText] = useState("");
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const { exit } = useApp();
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.ctrl && (input === "c" || input === "d")) {
|
||||
exit();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!inputMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Enter key (regular enter for submit)
|
||||
if (key.return && !key.shift) {
|
||||
if (textBuffer.text.trim() && !isWaitingForResponse) {
|
||||
onSubmit(textBuffer.text.trim());
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Shift+Enter (carriage return character) for new line
|
||||
if (input === "\r" || input === "\\\r") {
|
||||
const handled = textBuffer.handleInput("\n", key);
|
||||
if (handled) {
|
||||
setInputText(textBuffer.text);
|
||||
setCursorPosition(textBuffer.cursor);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Let TextBuffer handle the input
|
||||
const handled = textBuffer.handleInput(input, key);
|
||||
|
||||
// Update React state to trigger re-render
|
||||
if (handled) {
|
||||
setInputText(textBuffer.text);
|
||||
setCursorPosition(textBuffer.cursor);
|
||||
}
|
||||
});
|
||||
|
||||
const renderInputText = () => {
|
||||
if (inputText.length === 0) {
|
||||
return (
|
||||
<>
|
||||
{inputMode && !isWaitingForResponse && (
|
||||
<Text color="gray">▋Type your message...</Text>
|
||||
)}
|
||||
{(!inputMode || isWaitingForResponse) && (
|
||||
<Text color="gray">Type your message...</Text>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (inputMode && !isWaitingForResponse) {
|
||||
// Handle multi-line text with cursor
|
||||
const lines = inputText.split("\n");
|
||||
let charCount = 0;
|
||||
let cursorLine = 0;
|
||||
let cursorCol = 0;
|
||||
|
||||
// Find which line and column the cursor is on
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (cursorPosition <= charCount + lines[i].length) {
|
||||
cursorLine = i;
|
||||
cursorCol = cursorPosition - charCount;
|
||||
break;
|
||||
}
|
||||
charCount += lines[i].length + 1; // +1 for the newline character
|
||||
}
|
||||
|
||||
// Handle cursor at the very end
|
||||
if (cursorPosition >= inputText.length) {
|
||||
cursorLine = lines.length - 1;
|
||||
cursorCol = lines[cursorLine].length;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{lines.map((line, lineIndex) => {
|
||||
if (lineIndex === cursorLine) {
|
||||
// Line with cursor
|
||||
const beforeCursor = line.slice(0, cursorCol);
|
||||
const atCursor = line.slice(cursorCol, cursorCol + 1);
|
||||
const afterCursor = line.slice(cursorCol + 1);
|
||||
|
||||
return (
|
||||
<Text key={lineIndex}>
|
||||
{beforeCursor}
|
||||
<Text inverse>{atCursor || " "}</Text>
|
||||
{afterCursor}
|
||||
</Text>
|
||||
);
|
||||
} else {
|
||||
// Regular line - ensure empty lines still render
|
||||
return <Text key={lineIndex}>{line || " "}</Text>;
|
||||
}
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
} else {
|
||||
// Not in input mode, just display the text
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{inputText.split("\n").map((line, index) => (
|
||||
<Text key={index}>{line || " "}</Text>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box borderStyle="round" borderTop={true} paddingX={1}>
|
||||
<Text color="green" bold>
|
||||
●{" "}
|
||||
</Text>
|
||||
{renderInputText()}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserInput;
|
||||
33
src/ui/index.ts
Normal file
33
src/ui/index.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { ContinueClient } from "@continuedev/sdk";
|
||||
import { render } from "ink";
|
||||
import React from "react";
|
||||
import { introMessage } from "../intro.js";
|
||||
import { MCPService } from "../mcp.js";
|
||||
import TUIChat from "./TUIChat.js";
|
||||
|
||||
export async function startTUIChat(
|
||||
assistant: ContinueClient["assistant"],
|
||||
client: ContinueClient["client"],
|
||||
mcpService: MCPService,
|
||||
initialPrompt?: string
|
||||
) {
|
||||
// Show intro message before starting TUI
|
||||
introMessage(assistant, mcpService);
|
||||
|
||||
// Start the TUI
|
||||
const { unmount } = render(
|
||||
React.createElement(TUIChat, {
|
||||
assistant,
|
||||
client,
|
||||
initialPrompt,
|
||||
})
|
||||
);
|
||||
|
||||
// Handle cleanup
|
||||
process.on("SIGINT", () => {
|
||||
unmount();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
return { unmount };
|
||||
}
|
||||
|
|
@ -18,7 +18,8 @@
|
|||
"outDir": "dist",
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true
|
||||
"inlineSources": true,
|
||||
"jsx": "react"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue