Elffuss BraidHub

kikocis/continue public

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