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