Elffuss BraidHub

kikocis/continue public

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