Elffuss BraidHub

kikocis/continue public

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