Elffuss BraidHub

kikocis/continue public

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