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