Elffuss BraidHub

kikocis/continue public

4b606125a269 · 19.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) => 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 if (textBuffer.text.trim() && !isWaitingForResponse) {
390 // Expand all paste blocks before submitting
391 textBuffer.expandAllPasteBlocks();
392 const submittedText = textBuffer.text.trim();
393 inputHistory.addEntry(submittedText);
394 onSubmit(submittedText);
395 textBuffer.clear();
396 setInputText("");
397 setCursorPosition(0);
398 setShowSlashCommands(false);
399 }
400 return true;
401 }
402 return false;
403 };
404
405 const handleNewLine = (input: string, key: any): boolean => {
406 if (input === "\r" || input === "\\\r") {
407 const handled = textBuffer.handleInput("\n", key);
408 if (handled) {
409 const newText = textBuffer.text;
410 const newCursor = textBuffer.cursor;
411 setInputText(newText);
412 setCursorPosition(newCursor);
413 updateSlashCommandState(newText, newCursor);
414 updateFileSearchState(newText, newCursor);
415 }
416 return true;
417 }
418 return false;
419 };
420
421 const handleEscapeKey = (key: any): boolean => {
422 if (!key.escape) return false;
423
424 // Handle escape key to interrupt streaming
425 if (isWaitingForResponse && onInterrupt) {
426 onInterrupt();
427 return true;
428 }
429
430 // Handle escape key to close slash command UI
431 if (showSlashCommands && inputMode) {
432 setShowSlashCommands(false);
433 return true;
434 }
435
436 // Handle escape key to close file search UI
437 if (showFileSearch && inputMode) {
438 setShowFileSearch(false);
439 return true;
440 }
441
442 return false;
443 };
444
445 // Clear input function
446 const clearInput = () => {
447 textBuffer.clear();
448 setInputText("");
449 setCursorPosition(0);
450 setShowSlashCommands(false);
451 setShowFileSearch(false);
452 inputHistory.resetNavigation();
453 };
454
455 useInput((input, key) => {
456 // Don't handle any input when disabled
457 if (disabled) {
458 return;
459 }
460
461 // Handle control keys
462 if (
463 handleControlKeys({
464 input,
465 key,
466 exit,
467 showSlashCommands,
468 showFileSearch,
469 cycleModes,
470 clearInput,
471 })
472 ) {
473 return;
474 }
475
476 // Handle escape key variations
477 if (handleEscapeKey(key)) {
478 return;
479 }
480
481 // Allow typing during streaming, but block submission
482 if (!inputMode) {
483 // Block only Enter key submission during streaming
484 if (key.return && !key.shift) {
485 return;
486 }
487 // Allow all other input (typing, navigation, etc.)
488 }
489
490 // Handle slash command navigation
491 if (showSlashCommands) {
492 if (handleSlashCommandNavigation(key)) {
493 return;
494 }
495 }
496
497 // Handle file search navigation
498 if (showFileSearch) {
499 if (handleFileSearchNavigation(key)) {
500 return;
501 }
502 }
503
504 // Handle input history navigation
505 if (handleHistoryNavigation(key)) {
506 return;
507 }
508
509 // Handle Enter key
510 if (handleEnterKey(key)) {
511 return;
512 }
513
514 // Handle Shift+Enter (new line)
515 if (handleNewLine(input, key)) {
516 return;
517 }
518
519 // Let TextBuffer handle the input
520 const handled = textBuffer.handleInput(input, key);
521
522 // Update React state to trigger re-render
523 updateTextBufferState({
524 handled,
525 textBuffer,
526 setInputText,
527 setCursorPosition,
528 updateSlashCommandState,
529 updateFileSearchState,
530 inputHistory,
531 });
532 });
533
534 const renderInputText = () => {
535 const placeholderText = isRemoteMode
536 ? "Ask anything, / for slash commands"
537 : placeholder || "Ask anything, @ for context, / for slash commands";
538 if (inputText.length === 0) {
539 return (
540 <>
541 {(inputMode || isWaitingForResponse) && (
542 <Text italic color="gray">
543 ▋{placeholderText}
544 </Text>
545 )}
546 {!inputMode && !isWaitingForResponse && (
547 <Text italic color="gray">
548 {placeholderText}
549 </Text>
550 )}
551 </>
552 );
553 }
554
555 if (inputMode || isWaitingForResponse) {
556 // Handle multi-line text with cursor
557 const lines = inputText.split("\n");
558 let charCount = 0;
559 let cursorLine = 0;
560 let cursorCol = 0;
561
562 // Find which line and column the cursor is on
563 for (let i = 0; i < lines.length; i++) {
564 if (cursorPosition <= charCount + lines[i].length) {
565 cursorLine = i;
566 cursorCol = cursorPosition - charCount;
567 break;
568 }
569 charCount += lines[i].length + 1; // +1 for the newline character
570 }
571
572 // Handle cursor at the very end
573 if (cursorPosition >= inputText.length) {
574 cursorLine = lines.length - 1;
575 cursorCol = lines[cursorLine].length;
576 }
577
578 return (
579 <Box flexDirection="column">
580 {lines.map((line, lineIndex) => {
581 if (lineIndex === cursorLine) {
582 // Line with cursor
583 const beforeCursor = line.slice(0, cursorCol);
584 const atCursor = line.slice(cursorCol, cursorCol + 1);
585 const afterCursor = line.slice(cursorCol + 1);
586
587 return (
588 <Text key={lineIndex}>
589 {beforeCursor}
590 <Text inverse>{atCursor || " "}</Text>
591 {afterCursor}
592 </Text>
593 );
594 } else {
595 // Regular line - ensure empty lines still render
596 return <Text key={lineIndex}>{line || " "}</Text>;
597 }
598 })}
599 </Box>
600 );
601 } else {
602 // Not in input mode, just display the text
603 return (
604 <Box flexDirection="column">
605 {inputText.split("\n").map((line, index) => (
606 <Text key={index}>{line || " "}</Text>
607 ))}
608 </Box>
609 );
610 }
611 };
612
613 // Don't render anything when disabled
614 if (disabled) {
615 return null;
616 }
617
618 return (
619 <Box flexDirection="column">
620 {/* Input box */}
621 <Box
622 borderStyle="round"
623 borderTop={true}
624 paddingX={1}
625 borderColor={isRemoteMode ? "cyan" : "gray"}
626 >
627 <Text color={isRemoteMode ? "cyan" : "blue"} bold>
628 {isRemoteMode ? "◉" : "●"}{" "}
629 </Text>
630 {renderInputText()}
631 </Box>
632
633 {/* Slash command UI - show in remote mode OR when assistant is available */}
634 {showSlashCommands &&
635 inputMode &&
636 !hideNormalUI &&
637 (isRemoteMode || assistant) && (
638 <SlashCommandUI
639 assistant={assistant}
640 filter={slashCommandFilter}
641 selectedIndex={selectedCommandIndex}
642 isRemoteMode={isRemoteMode}
643 />
644 )}
645
646 {/* File search UI - only show in local mode */}
647 {showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && (
648 <FileSearchUI
649 filter={fileSearchFilter}
650 selectedIndex={selectedFileIndex}
651 onSelect={selectFile}
652 onFilesUpdated={setCurrentFiles}
653 />
654 )}
655 </Box>
656 );
657};
658
659export { UserInput };