| 1 | /* eslint-disable max-lines */ |
| 2 | import { type AssistantConfig } from "@continuedev/sdk"; |
| 3 | import { Box, Text, useApp, useInput } from "ink"; |
| 4 | import React, { useCallback, useState } from "react"; |
| 5 | |
| 6 | import { getAllSlashCommands } from "../commands/commands.js"; |
| 7 | import { useServices } from "../hooks/useService.js"; |
| 8 | import type { PermissionMode } from "../permissions/types.js"; |
| 9 | import type { FileIndexServiceState } from "../services/FileIndexService.js"; |
| 10 | import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; |
| 11 | import { modeService } from "../services/ModeService.js"; |
| 12 | import { InputHistory } from "../util/inputHistory.js"; |
| 13 | |
| 14 | import { FileSearchUI } from "./FileSearchUI.js"; |
| 15 | import { useClipboardMonitor } from "./hooks/useClipboardMonitor.js"; |
| 16 | import { |
| 17 | handleControlKeys, |
| 18 | updateTextBufferState, |
| 19 | } from "./hooks/useUserInput.js"; |
| 20 | import { SlashCommandUI } from "./SlashCommandUI.js"; |
| 21 | import { TextBuffer } from "./TextBuffer.js"; |
| 22 | |
| 23 | interface UserInputProps { |
| 24 | onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void; |
| 25 | isWaitingForResponse: boolean; |
| 26 | inputMode: boolean; |
| 27 | onInterrupt?: () => void; |
| 28 | assistant?: AssistantConfig; |
| 29 | wasInterrupted?: boolean; |
| 30 | onFileAttached?: (filePath: string, content: string) => void; |
| 31 | disabled?: boolean; |
| 32 | placeholder?: string; |
| 33 | hideNormalUI?: boolean; |
| 34 | isRemoteMode?: boolean; |
| 35 | onImageInClipboardChange?: (hasImage: boolean) => void; |
| 36 | } |
| 37 | |
| 38 | const UserInput: React.FC<UserInputProps> = ({ |
| 39 | onSubmit, |
| 40 | isWaitingForResponse, |
| 41 | inputMode, |
| 42 | onInterrupt, |
| 43 | assistant, |
| 44 | wasInterrupted = false, |
| 45 | onFileAttached, |
| 46 | disabled = false, |
| 47 | placeholder, |
| 48 | hideNormalUI = false, |
| 49 | isRemoteMode = false, |
| 50 | onImageInClipboardChange, |
| 51 | }) => { |
| 52 | const [textBuffer] = useState(() => new TextBuffer()); |
| 53 | const [inputHistory] = useState(() => new InputHistory()); |
| 54 | |
| 55 | // Stable callback for TextBuffer state changes to prevent race conditions |
| 56 | const onStateChange = useCallback(() => { |
| 57 | setInputText(textBuffer.text); |
| 58 | setCursorPosition(textBuffer.cursor); |
| 59 | }, [textBuffer]); |
| 60 | |
| 61 | // Set up callback for when TextBuffer state changes (e.g., rapid input finalized) |
| 62 | React.useEffect(() => { |
| 63 | textBuffer.setStateChangeCallback(onStateChange); |
| 64 | |
| 65 | // Cleanup on unmount: clear any pending timers |
| 66 | return () => { |
| 67 | textBuffer.clear(); |
| 68 | }; |
| 69 | }, [textBuffer, onStateChange]); |
| 70 | const [inputText, setInputText] = useState(""); |
| 71 | const [cursorPosition, setCursorPosition] = useState(0); |
| 72 | const [showSlashCommands, setShowSlashCommands] = useState(false); |
| 73 | |
| 74 | // Clear input function for Ctrl+C |
| 75 | const clearInput = useCallback(() => { |
| 76 | textBuffer.clear(); |
| 77 | setInputText(""); |
| 78 | setCursorPosition(0); |
| 79 | setShowSlashCommands(false); |
| 80 | setShowFileSearch(false); |
| 81 | inputHistory.resetNavigation(); |
| 82 | }, [textBuffer]); |
| 83 | const [slashCommandFilter, setSlashCommandFilter] = useState(""); |
| 84 | const [selectedCommandIndex, setSelectedCommandIndex] = useState(0); |
| 85 | const [showFileSearch, setShowFileSearch] = useState(false); |
| 86 | const [fileSearchFilter, setFileSearchFilter] = useState(""); |
| 87 | const [selectedFileIndex, setSelectedFileIndex] = useState(0); |
| 88 | const [currentFiles, setCurrentFiles] = useState< |
| 89 | Array<{ path: string; displayName: string }> |
| 90 | >([]); |
| 91 | const { exit } = useApp(); |
| 92 | |
| 93 | // Get file index service |
| 94 | const { services } = useServices<{ |
| 95 | fileIndex: FileIndexServiceState; |
| 96 | }>(["fileIndex"]); |
| 97 | |
| 98 | const getSlashCommands = () => { |
| 99 | if (assistant || isRemoteMode) { |
| 100 | return getAllSlashCommands(assistant || ({} as AssistantConfig), { |
| 101 | isRemoteMode, |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | // Fallback - basic commands without assistant |
| 106 | return [ |
| 107 | { name: "help", description: "Show help message" }, |
| 108 | { name: "clear", description: "Clear the chat history" }, |
| 109 | { name: "exit", description: "Exit the chat" }, |
| 110 | ]; |
| 111 | }; |
| 112 | |
| 113 | // Cycle through permission modes |
| 114 | const cycleModes = async () => { |
| 115 | const modes: PermissionMode[] = ["normal", "plan", "auto"]; |
| 116 | const currentMode = modeService.getCurrentMode(); |
| 117 | const currentIndex = modes.indexOf(currentMode); |
| 118 | const nextIndex = (currentIndex + 1) % modes.length; |
| 119 | const nextMode = modes[nextIndex]; |
| 120 | |
| 121 | modeService.switchMode(nextMode); |
| 122 | |
| 123 | // Update the service container with the new tool permissions state |
| 124 | // Since TOOL_PERMISSIONS was registered with registerValue(), we need to |
| 125 | // update its value directly rather than reloading from a factory |
| 126 | const updatedState = modeService.getToolPermissionService().getState(); |
| 127 | serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); |
| 128 | |
| 129 | // Show a brief indicator of the mode change |
| 130 | // This will be reflected in the ModeIndicator component |
| 131 | return nextMode; |
| 132 | }; |
| 133 | |
| 134 | // Update slash command UI state based on input |
| 135 | const updateSlashCommandState = (text: string, cursor: number) => { |
| 136 | // Only show slash commands if slash is the very first character |
| 137 | if (!text.trimStart().startsWith("/")) { |
| 138 | setShowSlashCommands(false); |
| 139 | return; |
| 140 | } |
| 141 | |
| 142 | const trimmedText = text.trimStart(); |
| 143 | const beforeCursor = trimmedText.slice( |
| 144 | 0, |
| 145 | cursor - (text.length - trimmedText.length), |
| 146 | ); |
| 147 | |
| 148 | // Only show if cursor is after the slash and before any whitespace |
| 149 | if (beforeCursor.length === 0 || !beforeCursor.startsWith("/")) { |
| 150 | setShowSlashCommands(false); |
| 151 | return; |
| 152 | } |
| 153 | |
| 154 | // Get the complete slash command, not just the part before cursor |
| 155 | const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0]; |
| 156 | |
| 157 | // We're in a slash command context - check if it's a complete command |
| 158 | const allCommands = getSlashCommands(); |
| 159 | const exactMatch = allCommands.find((cmd) => cmd.name === afterSlash); |
| 160 | |
| 161 | // Hide selector if we have an exact match and there's a space after cursor |
| 162 | if (exactMatch) { |
| 163 | const restOfText = text.slice(cursor); |
| 164 | // Only hide if there's a space or newline immediately after cursor |
| 165 | const shouldHide = |
| 166 | restOfText.startsWith(" ") || restOfText.startsWith("\n"); |
| 167 | if (shouldHide) { |
| 168 | setShowSlashCommands(false); |
| 169 | return; |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | // Check if there are any matching commands |
| 174 | const filteredCommands = allCommands.filter((cmd) => |
| 175 | cmd.name.toLowerCase().includes(afterSlash.toLowerCase()), |
| 176 | ); |
| 177 | |
| 178 | // If no commands match, hide the dropdown to allow normal Enter behavior |
| 179 | if (filteredCommands.length === 0) { |
| 180 | setShowSlashCommands(false); |
| 181 | return; |
| 182 | } |
| 183 | |
| 184 | // Show selector for partial matches |
| 185 | setShowSlashCommands(true); |
| 186 | setSlashCommandFilter(afterSlash); |
| 187 | setSelectedCommandIndex(0); |
| 188 | setShowFileSearch(false); |
| 189 | }; |
| 190 | |
| 191 | // Update file search UI state based on input |
| 192 | const updateFileSearchState = (text: string, cursor: number) => { |
| 193 | // Don't show file search in remote mode |
| 194 | if (isRemoteMode) { |
| 195 | setShowFileSearch(false); |
| 196 | return; |
| 197 | } |
| 198 | |
| 199 | // Check if we're in a file search context |
| 200 | const beforeCursor = text.slice(0, cursor); |
| 201 | const lastAtIndex = beforeCursor.lastIndexOf("@"); |
| 202 | |
| 203 | if (lastAtIndex === -1) { |
| 204 | setShowFileSearch(false); |
| 205 | } else { |
| 206 | // Check if there's any whitespace between the last @ and cursor |
| 207 | const afterAt = beforeCursor.slice(lastAtIndex + 1); |
| 208 | |
| 209 | if (afterAt.includes(" ") || afterAt.includes("\n")) { |
| 210 | setShowFileSearch(false); |
| 211 | } else { |
| 212 | // We're in a file search context - check if there are matching files |
| 213 | const fileIndexService = services.fileIndex; |
| 214 | if (fileIndexService) { |
| 215 | const filteredFiles = fileIndexService.files.filter((file) => { |
| 216 | if (afterAt.length === 0) { |
| 217 | return true; |
| 218 | } |
| 219 | const lowerFilter = afterAt.toLowerCase(); |
| 220 | return ( |
| 221 | file.displayName.toLowerCase().includes(lowerFilter) || |
| 222 | file.path.toLowerCase().includes(lowerFilter) |
| 223 | ); |
| 224 | }); |
| 225 | |
| 226 | // If no files match, hide the dropdown to allow normal Enter behavior |
| 227 | if (filteredFiles.length === 0 && afterAt.length > 0) { |
| 228 | setShowFileSearch(false); |
| 229 | return; |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | setShowFileSearch(true); |
| 234 | setFileSearchFilter(afterAt); |
| 235 | setSelectedFileIndex(0); |
| 236 | setShowSlashCommands(false); |
| 237 | } |
| 238 | } |
| 239 | }; |
| 240 | |
| 241 | // Get filtered commands for navigation - using the same sorting logic as SlashCommandUI |
| 242 | const getFilteredCommands = () => { |
| 243 | const allCommands = getSlashCommands(); |
| 244 | return allCommands |
| 245 | .filter((cmd) => |
| 246 | cmd.name.toLowerCase().includes(slashCommandFilter.toLowerCase()), |
| 247 | ) |
| 248 | .sort((a, b) => { |
| 249 | const aStartsWith = a.name |
| 250 | .toLowerCase() |
| 251 | .startsWith(slashCommandFilter.toLowerCase()); |
| 252 | const bStartsWith = b.name |
| 253 | .toLowerCase() |
| 254 | .startsWith(slashCommandFilter.toLowerCase()); |
| 255 | |
| 256 | if (aStartsWith && !bStartsWith) return -1; |
| 257 | if (!aStartsWith && bStartsWith) return 1; |
| 258 | |
| 259 | return a.name.localeCompare(b.name); |
| 260 | }); |
| 261 | }; |
| 262 | |
| 263 | // Handle slash command selection |
| 264 | const selectSlashCommand = (commandName: string) => { |
| 265 | const beforeCursor = inputText.slice(0, cursorPosition); |
| 266 | const lastSlashIndex = beforeCursor.lastIndexOf("/"); |
| 267 | |
| 268 | if (lastSlashIndex !== -1) { |
| 269 | const beforeSlash = inputText.slice(0, lastSlashIndex); |
| 270 | const afterCursor = inputText.slice(cursorPosition); |
| 271 | |
| 272 | // Replace the partial command with the full command |
| 273 | const newText = beforeSlash + "/" + commandName + " " + afterCursor; |
| 274 | const newCursorPos = lastSlashIndex + 1 + commandName.length + 1; |
| 275 | |
| 276 | textBuffer.setText(newText); |
| 277 | textBuffer.setCursor(newCursorPos); |
| 278 | setInputText(newText); |
| 279 | setCursorPosition(newCursorPos); |
| 280 | setShowSlashCommands(false); |
| 281 | } |
| 282 | }; |
| 283 | |
| 284 | // Handle file selection |
| 285 | const selectFile = async (filePath: string) => { |
| 286 | const beforeCursor = inputText.slice(0, cursorPosition); |
| 287 | const lastAtIndex = beforeCursor.lastIndexOf("@"); |
| 288 | |
| 289 | if (lastAtIndex !== -1) { |
| 290 | const beforeAt = inputText.slice(0, lastAtIndex); |
| 291 | const afterCursor = inputText.slice(cursorPosition); |
| 292 | |
| 293 | // Replace the partial file reference with the full file path |
| 294 | const newText = beforeAt + "@" + filePath + " " + afterCursor; |
| 295 | const newCursorPos = lastAtIndex + 1 + filePath.length + 1; |
| 296 | |
| 297 | textBuffer.setText(newText); |
| 298 | textBuffer.setCursor(newCursorPos); |
| 299 | setInputText(newText); |
| 300 | setCursorPosition(newCursorPos); |
| 301 | setShowFileSearch(false); |
| 302 | |
| 303 | // Read the file content and notify parent component |
| 304 | if (onFileAttached) { |
| 305 | try { |
| 306 | const fs = await import("fs/promises"); |
| 307 | const path = await import("path"); |
| 308 | const absolutePath = path.resolve(filePath); |
| 309 | const content = await fs.readFile(absolutePath, "utf-8"); |
| 310 | onFileAttached(absolutePath, content); |
| 311 | } catch (error) { |
| 312 | console.error(`Error reading file ${filePath}:`, error); |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | }; |
| 317 | |
| 318 | const handleSlashCommandNavigation = (key: any): boolean => { |
| 319 | const filteredCommands = getFilteredCommands(); |
| 320 | |
| 321 | if (key.upArrow) { |
| 322 | setSelectedCommandIndex((prev) => |
| 323 | prev > 0 ? prev - 1 : filteredCommands.length - 1, |
| 324 | ); |
| 325 | return true; |
| 326 | } |
| 327 | |
| 328 | if (key.downArrow) { |
| 329 | setSelectedCommandIndex((prev) => |
| 330 | prev < filteredCommands.length - 1 ? prev + 1 : 0, |
| 331 | ); |
| 332 | return true; |
| 333 | } |
| 334 | |
| 335 | if ((key.return && !key.shift) || key.tab) { |
| 336 | if (filteredCommands.length > 0) { |
| 337 | selectSlashCommand(filteredCommands[selectedCommandIndex].name); |
| 338 | } |
| 339 | return true; |
| 340 | } |
| 341 | |
| 342 | return false; |
| 343 | }; |
| 344 | |
| 345 | const handleFileSearchNavigation = (key: any): boolean => { |
| 346 | if (key.upArrow) { |
| 347 | setSelectedFileIndex((prev) => |
| 348 | prev > 0 ? prev - 1 : Math.max(0, Math.min(currentFiles.length - 1, 9)), |
| 349 | ); |
| 350 | return true; |
| 351 | } |
| 352 | |
| 353 | if (key.downArrow) { |
| 354 | setSelectedFileIndex((prev) => |
| 355 | prev < Math.min(currentFiles.length - 1, 9) ? prev + 1 : 0, |
| 356 | ); |
| 357 | return true; |
| 358 | } |
| 359 | |
| 360 | if ((key.return && !key.shift) || key.tab) { |
| 361 | if (currentFiles.length > 0 && selectedFileIndex < currentFiles.length) { |
| 362 | selectFile(currentFiles[selectedFileIndex].path); |
| 363 | } |
| 364 | return true; |
| 365 | } |
| 366 | |
| 367 | return false; |
| 368 | }; |
| 369 | |
| 370 | const handleHistoryNavigation = (key: any): boolean => { |
| 371 | if (!showSlashCommands && !showFileSearch) { |
| 372 | if (key.upArrow) { |
| 373 | const historyEntry = inputHistory.navigateUp(inputText); |
| 374 | if (historyEntry !== null) { |
| 375 | textBuffer.setText(historyEntry); |
| 376 | textBuffer.setCursor(historyEntry.length); |
| 377 | setInputText(historyEntry); |
| 378 | setCursorPosition(historyEntry.length); |
| 379 | } |
| 380 | return true; |
| 381 | } |
| 382 | |
| 383 | if (key.downArrow) { |
| 384 | const historyEntry = inputHistory.navigateDown(); |
| 385 | if (historyEntry !== null) { |
| 386 | textBuffer.setText(historyEntry); |
| 387 | textBuffer.setCursor(historyEntry.length); |
| 388 | setInputText(historyEntry); |
| 389 | setCursorPosition(historyEntry.length); |
| 390 | } |
| 391 | return true; |
| 392 | } |
| 393 | } |
| 394 | return false; |
| 395 | }; |
| 396 | |
| 397 | const handleEnterKey = (key: any): boolean => { |
| 398 | if (key.return && !key.shift) { |
| 399 | // Check for backslash continuation |
| 400 | const beforeCursor = textBuffer.text.slice(0, cursorPosition); |
| 401 | const trimmedBeforeCursor = beforeCursor.trimEnd(); |
| 402 | |
| 403 | if (trimmedBeforeCursor.endsWith("\\")) { |
| 404 | // Handle backslash continuation: remove the trailing "\" and add newline |
| 405 | const beforeBackslash = trimmedBeforeCursor.slice(0, -1); |
| 406 | const afterCursor = textBuffer.text.slice(cursorPosition); |
| 407 | const newText = beforeBackslash + "\n" + afterCursor; |
| 408 | const newCursorPos = beforeBackslash.length + 1; |
| 409 | |
| 410 | textBuffer.setText(newText); |
| 411 | textBuffer.setCursor(newCursorPos); |
| 412 | setInputText(newText); |
| 413 | setCursorPosition(newCursorPos); |
| 414 | updateSlashCommandState(newText, newCursorPos); |
| 415 | updateFileSearchState(newText, newCursorPos); |
| 416 | return true; |
| 417 | } |
| 418 | |
| 419 | // Normal Enter behavior - submit if there's content |
| 420 | if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) { |
| 421 | // Get images before expanding paste blocks |
| 422 | const imageMap = textBuffer.getAllImages(); |
| 423 | |
| 424 | // Expand all paste blocks before submitting |
| 425 | textBuffer.expandAllPasteBlocks(); |
| 426 | const submittedText = textBuffer.text.trim(); |
| 427 | |
| 428 | // Only add to history if there's actual text (not when resuming) |
| 429 | if (submittedText) { |
| 430 | inputHistory.addEntry(submittedText); |
| 431 | } |
| 432 | |
| 433 | // Submit with images |
| 434 | onSubmit(submittedText, imageMap); |
| 435 | |
| 436 | textBuffer.clear(); |
| 437 | setInputText(""); |
| 438 | setCursorPosition(0); |
| 439 | setShowSlashCommands(false); |
| 440 | } |
| 441 | return true; |
| 442 | } |
| 443 | return false; |
| 444 | }; |
| 445 | |
| 446 | const handleNewLine = (input: string, key: any): boolean => { |
| 447 | if (input === "\r" || input === "\\\r") { |
| 448 | const handled = textBuffer.handleInput("\n", key); |
| 449 | if (handled) { |
| 450 | const newText = textBuffer.text; |
| 451 | const newCursor = textBuffer.cursor; |
| 452 | setInputText(newText); |
| 453 | setCursorPosition(newCursor); |
| 454 | updateSlashCommandState(newText, newCursor); |
| 455 | updateFileSearchState(newText, newCursor); |
| 456 | } |
| 457 | return true; |
| 458 | } |
| 459 | return false; |
| 460 | }; |
| 461 | |
| 462 | const handleEscapeKey = (key: any): boolean => { |
| 463 | if (!key.escape) return false; |
| 464 | |
| 465 | // Handle escape key to interrupt streaming |
| 466 | if (isWaitingForResponse && onInterrupt) { |
| 467 | onInterrupt(); |
| 468 | return true; |
| 469 | } |
| 470 | |
| 471 | // Handle escape key to close slash command UI |
| 472 | if (showSlashCommands && inputMode) { |
| 473 | setShowSlashCommands(false); |
| 474 | return true; |
| 475 | } |
| 476 | |
| 477 | // Handle escape key to close file search UI |
| 478 | if (showFileSearch && inputMode) { |
| 479 | setShowFileSearch(false); |
| 480 | return true; |
| 481 | } |
| 482 | |
| 483 | return false; |
| 484 | }; |
| 485 | |
| 486 | // Handle text buffer updates for async operations like image pasting |
| 487 | const handleTextBufferUpdate = () => { |
| 488 | const newText = textBuffer.text; |
| 489 | const newCursor = textBuffer.cursor; |
| 490 | setInputText(newText); |
| 491 | setCursorPosition(newCursor); |
| 492 | updateSlashCommandState(newText, newCursor); |
| 493 | updateFileSearchState(newText, newCursor); |
| 494 | inputHistory.resetNavigation(); |
| 495 | }; |
| 496 | |
| 497 | // State for showing image paste hint |
| 498 | const [_hasImageInClipboard, _setHasImageInClipboard] = useState(false); |
| 499 | |
| 500 | // Monitor clipboard for images and show helpful hints |
| 501 | const { checkNow: _checkClipboardNow } = useClipboardMonitor({ |
| 502 | onImageStatusChange: (hasImage) => { |
| 503 | _setHasImageInClipboard(hasImage); |
| 504 | // Also notify parent component |
| 505 | if (onImageInClipboardChange) { |
| 506 | onImageInClipboardChange(hasImage); |
| 507 | } |
| 508 | }, |
| 509 | enabled: !disabled && inputMode, |
| 510 | pollInterval: 2000, |
| 511 | }); |
| 512 | |
| 513 | useInput((input, key) => { |
| 514 | // Don't handle any input when disabled |
| 515 | if (disabled) { |
| 516 | return; |
| 517 | } |
| 518 | |
| 519 | // Handle control keys |
| 520 | if ( |
| 521 | handleControlKeys({ |
| 522 | input, |
| 523 | key, |
| 524 | exit, |
| 525 | showSlashCommands, |
| 526 | showFileSearch, |
| 527 | cycleModes, |
| 528 | clearInput, |
| 529 | textBuffer, |
| 530 | onTextBufferUpdate: handleTextBufferUpdate, |
| 531 | }) |
| 532 | ) { |
| 533 | return; |
| 534 | } |
| 535 | |
| 536 | // Handle escape key variations |
| 537 | if (handleEscapeKey(key)) { |
| 538 | return; |
| 539 | } |
| 540 | |
| 541 | // Allow typing during streaming, but block submission |
| 542 | if (!inputMode) { |
| 543 | // Block only Enter key submission during streaming |
| 544 | if (key.return && !key.shift) { |
| 545 | return; |
| 546 | } |
| 547 | // Allow all other input (typing, navigation, etc.) |
| 548 | } |
| 549 | |
| 550 | // Handle slash command navigation |
| 551 | if (showSlashCommands) { |
| 552 | if (handleSlashCommandNavigation(key)) { |
| 553 | return; |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | // Handle file search navigation |
| 558 | if (showFileSearch) { |
| 559 | if (handleFileSearchNavigation(key)) { |
| 560 | return; |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | // Handle input history navigation |
| 565 | if (handleHistoryNavigation(key)) { |
| 566 | return; |
| 567 | } |
| 568 | |
| 569 | // Handle Enter key |
| 570 | if (handleEnterKey(key)) { |
| 571 | return; |
| 572 | } |
| 573 | |
| 574 | // Handle Shift+Enter (new line) |
| 575 | if (handleNewLine(input, key)) { |
| 576 | return; |
| 577 | } |
| 578 | |
| 579 | // Let TextBuffer handle the input |
| 580 | const handled = textBuffer.handleInput(input, key); |
| 581 | |
| 582 | // Update React state to trigger re-render |
| 583 | updateTextBufferState({ |
| 584 | handled, |
| 585 | textBuffer, |
| 586 | setInputText, |
| 587 | setCursorPosition, |
| 588 | updateSlashCommandState, |
| 589 | updateFileSearchState, |
| 590 | inputHistory, |
| 591 | }); |
| 592 | }); |
| 593 | |
| 594 | const renderInputText = () => { |
| 595 | const placeholderText = isRemoteMode |
| 596 | ? "Ask anything, / for slash commands" |
| 597 | : placeholder || "Ask anything, @ for context, / for slash commands"; |
| 598 | if (inputText.length === 0) { |
| 599 | return ( |
| 600 | <> |
| 601 | {(inputMode || isWaitingForResponse) && ( |
| 602 | <Text italic color="gray"> |
| 603 | ▋{placeholderText} |
| 604 | </Text> |
| 605 | )} |
| 606 | {!inputMode && !isWaitingForResponse && ( |
| 607 | <Text italic color="gray"> |
| 608 | {placeholderText} |
| 609 | </Text> |
| 610 | )} |
| 611 | </> |
| 612 | ); |
| 613 | } |
| 614 | |
| 615 | if (inputMode || isWaitingForResponse) { |
| 616 | // Handle multi-line text with cursor |
| 617 | const lines = inputText.split("\n"); |
| 618 | let charCount = 0; |
| 619 | let cursorLine = 0; |
| 620 | let cursorCol = 0; |
| 621 | |
| 622 | // Find which line and column the cursor is on |
| 623 | for (let i = 0; i < lines.length; i++) { |
| 624 | if (cursorPosition <= charCount + lines[i].length) { |
| 625 | cursorLine = i; |
| 626 | cursorCol = cursorPosition - charCount; |
| 627 | break; |
| 628 | } |
| 629 | charCount += lines[i].length + 1; // +1 for the newline character |
| 630 | } |
| 631 | |
| 632 | // Handle cursor at the very end |
| 633 | if (cursorPosition >= inputText.length) { |
| 634 | cursorLine = lines.length - 1; |
| 635 | cursorCol = lines[cursorLine].length; |
| 636 | } |
| 637 | |
| 638 | return ( |
| 639 | <Box flexDirection="column"> |
| 640 | {lines.map((line, lineIndex) => { |
| 641 | if (lineIndex === cursorLine) { |
| 642 | // Line with cursor |
| 643 | const beforeCursor = line.slice(0, cursorCol); |
| 644 | const atCursor = line.slice(cursorCol, cursorCol + 1); |
| 645 | const afterCursor = line.slice(cursorCol + 1); |
| 646 | |
| 647 | return ( |
| 648 | <Text key={lineIndex}> |
| 649 | {beforeCursor} |
| 650 | <Text inverse>{atCursor || " "}</Text> |
| 651 | {afterCursor} |
| 652 | </Text> |
| 653 | ); |
| 654 | } else { |
| 655 | // Regular line - ensure empty lines still render |
| 656 | return <Text key={lineIndex}>{line || " "}</Text>; |
| 657 | } |
| 658 | })} |
| 659 | </Box> |
| 660 | ); |
| 661 | } else { |
| 662 | // Not in input mode, just display the text |
| 663 | return ( |
| 664 | <Box flexDirection="column"> |
| 665 | {inputText.split("\n").map((line, index) => ( |
| 666 | <Text key={index}>{line || " "}</Text> |
| 667 | ))} |
| 668 | </Box> |
| 669 | ); |
| 670 | } |
| 671 | }; |
| 672 | |
| 673 | // Don't render anything when disabled |
| 674 | if (disabled) { |
| 675 | return null; |
| 676 | } |
| 677 | |
| 678 | return ( |
| 679 | <Box flexDirection="column"> |
| 680 | {/* Interruption message - shown just above the input box */} |
| 681 | {wasInterrupted && ( |
| 682 | <Box paddingX={1} marginBottom={0}> |
| 683 | <Text color="yellow"> |
| 684 | ⚠ Interrupted by user - Press enter to resume |
| 685 | </Text> |
| 686 | </Box> |
| 687 | )} |
| 688 | |
| 689 | {/* Input box */} |
| 690 | <Box |
| 691 | borderStyle="round" |
| 692 | borderTop={true} |
| 693 | paddingX={1} |
| 694 | borderColor={isRemoteMode ? "cyan" : "gray"} |
| 695 | > |
| 696 | <Text color={isRemoteMode ? "cyan" : "blue"} bold> |
| 697 | {isRemoteMode ? "◉" : "●"}{" "} |
| 698 | </Text> |
| 699 | {renderInputText()} |
| 700 | </Box> |
| 701 | |
| 702 | {/* Slash command UI - show in remote mode OR when assistant is available */} |
| 703 | {showSlashCommands && |
| 704 | inputMode && |
| 705 | !hideNormalUI && |
| 706 | (isRemoteMode || assistant) && ( |
| 707 | <SlashCommandUI |
| 708 | assistant={assistant} |
| 709 | filter={slashCommandFilter} |
| 710 | selectedIndex={selectedCommandIndex} |
| 711 | isRemoteMode={isRemoteMode} |
| 712 | /> |
| 713 | )} |
| 714 | |
| 715 | {/* File search UI - only show in local mode */} |
| 716 | {showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && ( |
| 717 | <FileSearchUI |
| 718 | filter={fileSearchFilter} |
| 719 | selectedIndex={selectedFileIndex} |
| 720 | onSelect={selectFile} |
| 721 | onFilesUpdated={setCurrentFiles} |
| 722 | /> |
| 723 | )} |
| 724 | </Box> |
| 725 | ); |
| 726 | }; |
| 727 | |
| 728 | export { UserInput }; |