Elffuss BraidHub

kikocis/continue public

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