Elffuss BraidHub

kikocis/continue public

9a76840d7230 · 17.6 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 // Show selector for partial matches
156 setShowSlashCommands(true);
157 setSlashCommandFilter(afterSlash);
158 setSelectedCommandIndex(0);
159 setShowFileSearch(false);
160 };
161
162 // Update file search UI state based on input
163 const updateFileSearchState = (text: string, cursor: number) => {
164 // Don't show file search in remote mode
165 if (isRemoteMode) {
166 setShowFileSearch(false);
167 return;
168 }
169
170 // Check if we're in a file search context
171 const beforeCursor = text.slice(0, cursor);
172 const lastAtIndex = beforeCursor.lastIndexOf("@");
173
174 if (lastAtIndex === -1) {
175 setShowFileSearch(false);
176 } else {
177 // Check if there's any whitespace between the last @ and cursor
178 const afterAt = beforeCursor.slice(lastAtIndex + 1);
179
180 if (afterAt.includes(" ") || afterAt.includes("\n")) {
181 setShowFileSearch(false);
182 } else {
183 // We're in a file search context
184 setShowFileSearch(true);
185 setFileSearchFilter(afterAt);
186 setSelectedFileIndex(0);
187 setShowSlashCommands(false);
188 }
189 }
190 };
191
192 // Get filtered commands for navigation - using the same sorting logic as SlashCommandUI
193 const getFilteredCommands = () => {
194 const allCommands = getSlashCommands();
195 return allCommands
196 .filter((cmd) =>
197 cmd.name.toLowerCase().includes(slashCommandFilter.toLowerCase()),
198 )
199 .sort((a, b) => {
200 const aStartsWith = a.name
201 .toLowerCase()
202 .startsWith(slashCommandFilter.toLowerCase());
203 const bStartsWith = b.name
204 .toLowerCase()
205 .startsWith(slashCommandFilter.toLowerCase());
206
207 if (aStartsWith && !bStartsWith) return -1;
208 if (!aStartsWith && bStartsWith) return 1;
209
210 return a.name.localeCompare(b.name);
211 });
212 };
213
214 // Handle slash command selection
215 const selectSlashCommand = (commandName: string) => {
216 const beforeCursor = inputText.slice(0, cursorPosition);
217 const lastSlashIndex = beforeCursor.lastIndexOf("/");
218
219 if (lastSlashIndex !== -1) {
220 const beforeSlash = inputText.slice(0, lastSlashIndex);
221 const afterCursor = inputText.slice(cursorPosition);
222
223 // Replace the partial command with the full command
224 const newText = beforeSlash + "/" + commandName + " " + afterCursor;
225 const newCursorPos = lastSlashIndex + 1 + commandName.length + 1;
226
227 textBuffer.setText(newText);
228 textBuffer.setCursor(newCursorPos);
229 setInputText(newText);
230 setCursorPosition(newCursorPos);
231 setShowSlashCommands(false);
232 }
233 };
234
235 // Handle file selection
236 const selectFile = async (filePath: string) => {
237 const beforeCursor = inputText.slice(0, cursorPosition);
238 const lastAtIndex = beforeCursor.lastIndexOf("@");
239
240 if (lastAtIndex !== -1) {
241 const beforeAt = inputText.slice(0, lastAtIndex);
242 const afterCursor = inputText.slice(cursorPosition);
243
244 // Replace the partial file reference with the full file path
245 const newText = beforeAt + "@" + filePath + " " + afterCursor;
246 const newCursorPos = lastAtIndex + 1 + filePath.length + 1;
247
248 textBuffer.setText(newText);
249 textBuffer.setCursor(newCursorPos);
250 setInputText(newText);
251 setCursorPosition(newCursorPos);
252 setShowFileSearch(false);
253
254 // Read the file content and notify parent component
255 if (onFileAttached) {
256 try {
257 const fs = await import("fs/promises");
258 const content = await fs.readFile(filePath, "utf-8");
259 onFileAttached(filePath, content);
260 } catch (error) {
261 console.error(`Error reading file ${filePath}:`, error);
262 }
263 }
264 }
265 };
266
267 const handleSlashCommandNavigation = (key: any): boolean => {
268 const filteredCommands = getFilteredCommands();
269
270 if (key.upArrow) {
271 setSelectedCommandIndex((prev) =>
272 prev > 0 ? prev - 1 : filteredCommands.length - 1,
273 );
274 return true;
275 }
276
277 if (key.downArrow) {
278 setSelectedCommandIndex((prev) =>
279 prev < filteredCommands.length - 1 ? prev + 1 : 0,
280 );
281 return true;
282 }
283
284 if ((key.return && !key.shift) || key.tab) {
285 if (filteredCommands.length > 0) {
286 selectSlashCommand(filteredCommands[selectedCommandIndex].name);
287 }
288 return true;
289 }
290
291 return false;
292 };
293
294 const handleFileSearchNavigation = (key: any): boolean => {
295 if (key.upArrow) {
296 setSelectedFileIndex((prev) =>
297 prev > 0 ? prev - 1 : Math.max(0, Math.min(currentFiles.length - 1, 9)),
298 );
299 return true;
300 }
301
302 if (key.downArrow) {
303 setSelectedFileIndex((prev) =>
304 prev < Math.min(currentFiles.length - 1, 9) ? prev + 1 : 0,
305 );
306 return true;
307 }
308
309 if ((key.return && !key.shift) || key.tab) {
310 if (currentFiles.length > 0 && selectedFileIndex < currentFiles.length) {
311 selectFile(currentFiles[selectedFileIndex].path);
312 }
313 return true;
314 }
315
316 return false;
317 };
318
319 const handleHistoryNavigation = (key: any): boolean => {
320 if (!showSlashCommands && !showFileSearch) {
321 if (key.upArrow) {
322 const historyEntry = inputHistory.navigateUp(inputText);
323 if (historyEntry !== null) {
324 textBuffer.setText(historyEntry);
325 textBuffer.setCursor(historyEntry.length);
326 setInputText(historyEntry);
327 setCursorPosition(historyEntry.length);
328 }
329 return true;
330 }
331
332 if (key.downArrow) {
333 const historyEntry = inputHistory.navigateDown();
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 return false;
344 };
345
346 const handleEnterKey = (key: any): boolean => {
347 if (key.return && !key.shift) {
348 if (textBuffer.text.trim() && !isWaitingForResponse) {
349 // Expand all paste blocks before submitting
350 textBuffer.expandAllPasteBlocks();
351 const submittedText = textBuffer.text.trim();
352 inputHistory.addEntry(submittedText);
353 onSubmit(submittedText);
354 textBuffer.clear();
355 setInputText("");
356 setCursorPosition(0);
357 setShowSlashCommands(false);
358 }
359 return true;
360 }
361 return false;
362 };
363
364 const handleNewLine = (input: string, key: any): boolean => {
365 if (input === "\r" || input === "\\\r") {
366 const handled = textBuffer.handleInput("\n", key);
367 if (handled) {
368 const newText = textBuffer.text;
369 const newCursor = textBuffer.cursor;
370 setInputText(newText);
371 setCursorPosition(newCursor);
372 updateSlashCommandState(newText, newCursor);
373 updateFileSearchState(newText, newCursor);
374 }
375 return true;
376 }
377 return false;
378 };
379
380 const handleEscapeKey = (key: any): boolean => {
381 if (!key.escape) return false;
382
383 // Handle escape key to interrupt streaming
384 if (isWaitingForResponse && onInterrupt) {
385 onInterrupt();
386 return true;
387 }
388
389 // Handle escape key to close slash command UI
390 if (showSlashCommands && inputMode) {
391 setShowSlashCommands(false);
392 return true;
393 }
394
395 // Handle escape key to close file search UI
396 if (showFileSearch && inputMode) {
397 setShowFileSearch(false);
398 return true;
399 }
400
401 return false;
402 };
403
404 useInput((input, key) => {
405 // Don't handle any input when disabled
406 if (disabled) {
407 return;
408 }
409
410 // Handle control keys
411 if (
412 handleControlKeys({
413 input,
414 key,
415 exit,
416 showSlashCommands,
417 showFileSearch,
418 cycleModes,
419 })
420 ) {
421 return;
422 }
423
424 // Handle escape key variations
425 if (handleEscapeKey(key)) {
426 return;
427 }
428
429 // Allow typing during streaming, but block submission
430 if (!inputMode) {
431 // Block only Enter key submission during streaming
432 if (key.return && !key.shift) {
433 return;
434 }
435 // Allow all other input (typing, navigation, etc.)
436 }
437
438 // Handle slash command navigation
439 if (showSlashCommands) {
440 if (handleSlashCommandNavigation(key)) {
441 return;
442 }
443 }
444
445 // Handle file search navigation
446 if (showFileSearch) {
447 if (handleFileSearchNavigation(key)) {
448 return;
449 }
450 }
451
452 // Handle input history navigation
453 if (handleHistoryNavigation(key)) {
454 return;
455 }
456
457 // Handle Enter key
458 if (handleEnterKey(key)) {
459 return;
460 }
461
462 // Handle Shift+Enter (new line)
463 if (handleNewLine(input, key)) {
464 return;
465 }
466
467 // Let TextBuffer handle the input
468 const handled = textBuffer.handleInput(input, key);
469
470 // Update React state to trigger re-render
471 updateTextBufferState({
472 handled,
473 textBuffer,
474 setInputText,
475 setCursorPosition,
476 updateSlashCommandState,
477 updateFileSearchState,
478 inputHistory,
479 });
480 });
481
482 const renderInputText = () => {
483 const placeholderText = isRemoteMode
484 ? "Ask anything, / for slash commands"
485 : placeholder || "Ask anything, @ for context, / for slash commands";
486 if (inputText.length === 0) {
487 return (
488 <>
489 {(inputMode || isWaitingForResponse) && (
490 <Text italic color="gray">
491 ▋{placeholderText}
492 </Text>
493 )}
494 {!inputMode && !isWaitingForResponse && (
495 <Text italic color="gray">
496 {placeholderText}
497 </Text>
498 )}
499 </>
500 );
501 }
502
503 if (inputMode || isWaitingForResponse) {
504 // Handle multi-line text with cursor
505 const lines = inputText.split("\n");
506 let charCount = 0;
507 let cursorLine = 0;
508 let cursorCol = 0;
509
510 // Find which line and column the cursor is on
511 for (let i = 0; i < lines.length; i++) {
512 if (cursorPosition <= charCount + lines[i].length) {
513 cursorLine = i;
514 cursorCol = cursorPosition - charCount;
515 break;
516 }
517 charCount += lines[i].length + 1; // +1 for the newline character
518 }
519
520 // Handle cursor at the very end
521 if (cursorPosition >= inputText.length) {
522 cursorLine = lines.length - 1;
523 cursorCol = lines[cursorLine].length;
524 }
525
526 return (
527 <Box flexDirection="column">
528 {lines.map((line, lineIndex) => {
529 if (lineIndex === cursorLine) {
530 // Line with cursor
531 const beforeCursor = line.slice(0, cursorCol);
532 const atCursor = line.slice(cursorCol, cursorCol + 1);
533 const afterCursor = line.slice(cursorCol + 1);
534
535 return (
536 <Text key={lineIndex}>
537 {beforeCursor}
538 <Text inverse>{atCursor || " "}</Text>
539 {afterCursor}
540 </Text>
541 );
542 } else {
543 // Regular line - ensure empty lines still render
544 return <Text key={lineIndex}>{line || " "}</Text>;
545 }
546 })}
547 </Box>
548 );
549 } else {
550 // Not in input mode, just display the text
551 return (
552 <Box flexDirection="column">
553 {inputText.split("\n").map((line, index) => (
554 <Text key={index}>{line || " "}</Text>
555 ))}
556 </Box>
557 );
558 }
559 };
560
561 // Don't render anything when disabled
562 if (disabled) {
563 return null;
564 }
565
566 return (
567 <Box flexDirection="column">
568 {/* Input box */}
569 <Box
570 borderStyle="round"
571 borderTop={true}
572 paddingX={1}
573 borderColor={isRemoteMode ? "cyan" : "gray"}
574 >
575 <Text color={isRemoteMode ? "cyan" : "green"} bold>
576 {isRemoteMode ? "◉" : "●"}{" "}
577 </Text>
578 {renderInputText()}
579 </Box>
580
581 {/* Slash command UI - show in remote mode OR when assistant is available */}
582 {showSlashCommands &&
583 inputMode &&
584 !hideNormalUI &&
585 (isRemoteMode || assistant) && (
586 <SlashCommandUI
587 assistant={assistant}
588 filter={slashCommandFilter}
589 selectedIndex={selectedCommandIndex}
590 isRemoteMode={isRemoteMode}
591 />
592 )}
593
594 {/* File search UI - only show in local mode */}
595 {showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && (
596 <FileSearchUI
597 filter={fileSearchFilter}
598 selectedIndex={selectedFileIndex}
599 onSelect={selectFile}
600 onFilesUpdated={setCurrentFiles}
601 />
602 )}
603 </Box>
604 );
605};
606
607export { UserInput };