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