wave-code 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/components/InputBox.d.ts.map +1 -1
  2. package/dist/components/InputBox.js +69 -95
  3. package/dist/components/MessageList.d.ts.map +1 -1
  4. package/dist/components/MessageList.js +2 -1
  5. package/dist/components/SubagentBlock.d.ts +1 -1
  6. package/dist/components/SubagentBlock.d.ts.map +1 -1
  7. package/dist/components/SubagentBlock.js +12 -2
  8. package/dist/components/ToolResultDisplay.js +1 -1
  9. package/dist/contexts/useChat.d.ts +2 -1
  10. package/dist/contexts/useChat.d.ts.map +1 -1
  11. package/dist/contexts/useChat.js +18 -0
  12. package/dist/hooks/useInputManager.d.ts +91 -0
  13. package/dist/hooks/useInputManager.d.ts.map +1 -0
  14. package/dist/hooks/useInputManager.js +319 -0
  15. package/dist/index.js +9 -9
  16. package/dist/managers/InputManager.d.ts +169 -0
  17. package/dist/managers/InputManager.d.ts.map +1 -0
  18. package/dist/managers/InputManager.js +806 -0
  19. package/dist/print-cli.d.ts +7 -0
  20. package/dist/print-cli.d.ts.map +1 -0
  21. package/dist/{plain-cli.js → print-cli.js} +21 -2
  22. package/dist/utils/constants.d.ts +1 -1
  23. package/dist/utils/constants.js +1 -1
  24. package/dist/utils/fileSearch.d.ts +20 -0
  25. package/dist/utils/fileSearch.d.ts.map +1 -0
  26. package/dist/utils/fileSearch.js +102 -0
  27. package/dist/utils/logger.js +3 -3
  28. package/dist/utils/usageSummary.d.ts +27 -0
  29. package/dist/utils/usageSummary.d.ts.map +1 -0
  30. package/dist/utils/usageSummary.js +82 -0
  31. package/package.json +2 -2
  32. package/src/components/InputBox.tsx +114 -153
  33. package/src/components/MessageList.tsx +14 -10
  34. package/src/components/SubagentBlock.tsx +14 -3
  35. package/src/components/ToolResultDisplay.tsx +1 -1
  36. package/src/contexts/useChat.tsx +23 -0
  37. package/src/hooks/useInputManager.ts +443 -0
  38. package/src/index.ts +9 -9
  39. package/src/managers/InputManager.ts +1102 -0
  40. package/src/{plain-cli.ts → print-cli.ts} +21 -3
  41. package/src/utils/constants.ts +1 -1
  42. package/src/utils/fileSearch.ts +133 -0
  43. package/src/utils/logger.ts +3 -3
  44. package/src/utils/usageSummary.ts +125 -0
  45. package/dist/hooks/useBashHistorySelector.d.ts +0 -15
  46. package/dist/hooks/useBashHistorySelector.d.ts.map +0 -1
  47. package/dist/hooks/useBashHistorySelector.js +0 -61
  48. package/dist/hooks/useCommandSelector.d.ts +0 -24
  49. package/dist/hooks/useCommandSelector.d.ts.map +0 -1
  50. package/dist/hooks/useCommandSelector.js +0 -98
  51. package/dist/hooks/useFileSelector.d.ts +0 -16
  52. package/dist/hooks/useFileSelector.d.ts.map +0 -1
  53. package/dist/hooks/useFileSelector.js +0 -174
  54. package/dist/hooks/useImageManager.d.ts +0 -13
  55. package/dist/hooks/useImageManager.d.ts.map +0 -1
  56. package/dist/hooks/useImageManager.js +0 -46
  57. package/dist/hooks/useInputHistory.d.ts +0 -11
  58. package/dist/hooks/useInputHistory.d.ts.map +0 -1
  59. package/dist/hooks/useInputHistory.js +0 -64
  60. package/dist/hooks/useInputKeyboardHandler.d.ts +0 -83
  61. package/dist/hooks/useInputKeyboardHandler.d.ts.map +0 -1
  62. package/dist/hooks/useInputKeyboardHandler.js +0 -507
  63. package/dist/hooks/useInputState.d.ts +0 -14
  64. package/dist/hooks/useInputState.d.ts.map +0 -1
  65. package/dist/hooks/useInputState.js +0 -57
  66. package/dist/hooks/useMemoryTypeSelector.d.ts +0 -9
  67. package/dist/hooks/useMemoryTypeSelector.d.ts.map +0 -1
  68. package/dist/hooks/useMemoryTypeSelector.js +0 -27
  69. package/dist/plain-cli.d.ts +0 -7
  70. package/dist/plain-cli.d.ts.map +0 -1
  71. package/src/hooks/useBashHistorySelector.ts +0 -77
  72. package/src/hooks/useCommandSelector.ts +0 -131
  73. package/src/hooks/useFileSelector.ts +0 -227
  74. package/src/hooks/useImageManager.ts +0 -64
  75. package/src/hooks/useInputHistory.ts +0 -74
  76. package/src/hooks/useInputKeyboardHandler.ts +0 -778
  77. package/src/hooks/useInputState.ts +0 -66
  78. package/src/hooks/useMemoryTypeSelector.ts +0 -40
@@ -0,0 +1,1102 @@
1
+ import { FileItem } from "../components/FileSelector.js";
2
+ import { searchFiles as searchFilesUtil } from "../utils/fileSearch.js";
3
+ import { readClipboardImage } from "../utils/clipboard.js";
4
+ import type { Key } from "ink";
5
+
6
+ export interface AttachedImage {
7
+ id: number;
8
+ path: string;
9
+ mimeType: string;
10
+ }
11
+
12
+ export interface InputManagerCallbacks {
13
+ onInputTextChange?: (text: string) => void;
14
+ onCursorPositionChange?: (position: number) => void;
15
+ onFileSelectorStateChange?: (
16
+ show: boolean,
17
+ files: FileItem[],
18
+ query: string,
19
+ position: number,
20
+ ) => void;
21
+ onCommandSelectorStateChange?: (
22
+ show: boolean,
23
+ query: string,
24
+ position: number,
25
+ ) => void;
26
+ onBashHistorySelectorStateChange?: (
27
+ show: boolean,
28
+ query: string,
29
+ position: number,
30
+ ) => void;
31
+ onMemoryTypeSelectorStateChange?: (show: boolean, message: string) => void;
32
+ onShowBashManager?: () => void;
33
+ onShowMcpManager?: () => void;
34
+ onBashManagerStateChange?: (show: boolean) => void;
35
+ onMcpManagerStateChange?: (show: boolean) => void;
36
+ onImagesStateChange?: (images: AttachedImage[]) => void;
37
+ onSendMessage?: (
38
+ content: string,
39
+ images?: Array<{ path: string; mimeType: string }>,
40
+ ) => void | Promise<void>;
41
+ onHasSlashCommand?: (commandId: string) => boolean;
42
+ onSaveMemory?: (message: string, type: "project" | "user") => Promise<void>;
43
+ onAbortMessage?: () => void;
44
+ onResetHistoryNavigation?: () => void;
45
+ }
46
+
47
+ export class InputManager {
48
+ // Core input state
49
+ private inputText: string = "";
50
+ private cursorPosition: number = 0;
51
+
52
+ // File selector state
53
+ private showFileSelector: boolean = false;
54
+ private atPosition: number = -1;
55
+ private fileSearchQuery: string = "";
56
+ private filteredFiles: FileItem[] = [];
57
+ private fileSearchDebounceTimer: NodeJS.Timeout | null = null;
58
+
59
+ // Command selector state
60
+ private showCommandSelector: boolean = false;
61
+ private slashPosition: number = -1;
62
+ private commandSearchQuery: string = "";
63
+
64
+ // Bash history selector state
65
+ private showBashHistorySelector: boolean = false;
66
+ private exclamationPosition: number = -1;
67
+ private bashHistorySearchQuery: string = "";
68
+
69
+ // Memory type selector state
70
+ private showMemoryTypeSelector: boolean = false;
71
+ private memoryMessage: string = "";
72
+
73
+ // Input history state
74
+ private userInputHistory: string[] = [];
75
+ private historyIndex: number = -1;
76
+ private historyBuffer: string = "";
77
+
78
+ // Paste debounce state
79
+ private pasteDebounceTimer: NodeJS.Timeout | null = null;
80
+ private pasteBuffer: string = "";
81
+ private initialPasteCursorPosition: number = 0;
82
+ private isPasting: boolean = false;
83
+
84
+ // Long text compression state
85
+ private longTextCounter: number = 0;
86
+ private longTextMap: Map<string, string> = new Map();
87
+
88
+ // Image management state
89
+ private attachedImages: AttachedImage[] = [];
90
+ private imageIdCounter: number = 1;
91
+
92
+ // Additional UI state
93
+ private showBashManager: boolean = false;
94
+ private showMcpManager: boolean = false;
95
+
96
+ // Flag to prevent handleInput conflicts when selector selection occurs
97
+ private selectorJustUsed: boolean = false;
98
+
99
+ private callbacks: InputManagerCallbacks;
100
+
101
+ constructor(callbacks: InputManagerCallbacks = {}) {
102
+ this.callbacks = callbacks;
103
+ }
104
+
105
+ // Update callbacks
106
+ updateCallbacks(callbacks: Partial<InputManagerCallbacks>) {
107
+ this.callbacks = { ...this.callbacks, ...callbacks };
108
+ }
109
+
110
+ // Core input methods
111
+ getInputText(): string {
112
+ return this.inputText;
113
+ }
114
+
115
+ setInputText(text: string): void {
116
+ this.inputText = text;
117
+ this.callbacks.onInputTextChange?.(text);
118
+ }
119
+
120
+ getCursorPosition(): number {
121
+ return this.cursorPosition;
122
+ }
123
+
124
+ setCursorPosition(position: number): void {
125
+ this.cursorPosition = Math.max(
126
+ 0,
127
+ Math.min(this.inputText.length, position),
128
+ );
129
+ this.callbacks.onCursorPositionChange?.(this.cursorPosition);
130
+ }
131
+
132
+ insertTextAtCursor(
133
+ text: string,
134
+ callback?: (newText: string, newCursorPosition: number) => void,
135
+ ): void {
136
+ const beforeCursor = this.inputText.substring(0, this.cursorPosition);
137
+ const afterCursor = this.inputText.substring(this.cursorPosition);
138
+ const newText = beforeCursor + text + afterCursor;
139
+ const newCursorPosition = this.cursorPosition + text.length;
140
+
141
+ this.inputText = newText;
142
+ this.cursorPosition = newCursorPosition;
143
+
144
+ this.callbacks.onInputTextChange?.(newText);
145
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
146
+
147
+ callback?.(newText, newCursorPosition);
148
+ }
149
+
150
+ deleteCharAtCursor(
151
+ callback?: (newText: string, newCursorPosition: number) => void,
152
+ ): void {
153
+ if (this.cursorPosition > 0) {
154
+ const beforeCursor = this.inputText.substring(0, this.cursorPosition - 1);
155
+ const afterCursor = this.inputText.substring(this.cursorPosition);
156
+ const newText = beforeCursor + afterCursor;
157
+ const newCursorPosition = this.cursorPosition - 1;
158
+
159
+ this.inputText = newText;
160
+ this.cursorPosition = newCursorPosition;
161
+
162
+ this.callbacks.onInputTextChange?.(newText);
163
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
164
+
165
+ callback?.(newText, newCursorPosition);
166
+ }
167
+ }
168
+
169
+ clearInput(): void {
170
+ this.inputText = "";
171
+ this.cursorPosition = 0;
172
+ this.callbacks.onInputTextChange?.("");
173
+ this.callbacks.onCursorPositionChange?.(0);
174
+ }
175
+
176
+ moveCursorLeft(): void {
177
+ this.setCursorPosition(this.cursorPosition - 1);
178
+ }
179
+
180
+ moveCursorRight(): void {
181
+ this.setCursorPosition(this.cursorPosition + 1);
182
+ }
183
+
184
+ moveCursorToStart(): void {
185
+ this.setCursorPosition(0);
186
+ }
187
+
188
+ moveCursorToEnd(): void {
189
+ this.setCursorPosition(this.inputText.length);
190
+ }
191
+
192
+ // File selector methods
193
+ private async searchFiles(query: string): Promise<void> {
194
+ try {
195
+ const fileItems = await searchFilesUtil(query);
196
+ this.filteredFiles = fileItems;
197
+ this.callbacks.onFileSelectorStateChange?.(
198
+ this.showFileSelector,
199
+ this.filteredFiles,
200
+ this.fileSearchQuery,
201
+ this.atPosition,
202
+ );
203
+ } catch (error) {
204
+ console.error("File search error:", error);
205
+ this.filteredFiles = [];
206
+ this.callbacks.onFileSelectorStateChange?.(
207
+ this.showFileSelector,
208
+ [],
209
+ this.fileSearchQuery,
210
+ this.atPosition,
211
+ );
212
+ }
213
+ }
214
+
215
+ private debouncedSearchFiles(query: string): void {
216
+ if (this.fileSearchDebounceTimer) {
217
+ clearTimeout(this.fileSearchDebounceTimer);
218
+ }
219
+
220
+ const debounceDelay = parseInt(
221
+ process.env.FILE_SELECTOR_DEBOUNCE_MS || "300",
222
+ 10,
223
+ );
224
+ this.fileSearchDebounceTimer = setTimeout(() => {
225
+ this.searchFiles(query);
226
+ }, debounceDelay);
227
+ }
228
+
229
+ activateFileSelector(position: number): void {
230
+ this.showFileSelector = true;
231
+ this.atPosition = position;
232
+ this.fileSearchQuery = "";
233
+ this.filteredFiles = [];
234
+
235
+ // Immediately trigger search to display initial file list
236
+ this.searchFiles("");
237
+
238
+ this.callbacks.onFileSelectorStateChange?.(
239
+ true,
240
+ this.filteredFiles,
241
+ "",
242
+ position,
243
+ );
244
+ }
245
+
246
+ updateFileSearchQuery(query: string): void {
247
+ this.fileSearchQuery = query;
248
+ this.debouncedSearchFiles(query);
249
+ }
250
+
251
+ handleFileSelect(filePath: string): {
252
+ newInput: string;
253
+ newCursorPosition: number;
254
+ } {
255
+ if (this.atPosition >= 0) {
256
+ const beforeAt = this.inputText.substring(0, this.atPosition);
257
+ const afterQuery = this.inputText.substring(this.cursorPosition);
258
+ const newInput = beforeAt + `${filePath} ` + afterQuery;
259
+ const newCursorPosition = beforeAt.length + filePath.length + 1;
260
+
261
+ this.inputText = newInput;
262
+ this.cursorPosition = newCursorPosition;
263
+
264
+ this.callbacks.onInputTextChange?.(newInput);
265
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
266
+
267
+ // Cancel file selector AFTER updating the input
268
+ this.handleCancelFileSelect();
269
+
270
+ // Set flag to prevent handleInput from processing the same Enter key
271
+ this.selectorJustUsed = true;
272
+ // Reset flag after a short delay
273
+ setTimeout(() => {
274
+ this.selectorJustUsed = false;
275
+ }, 0);
276
+
277
+ return { newInput, newCursorPosition };
278
+ }
279
+ return { newInput: this.inputText, newCursorPosition: this.cursorPosition };
280
+ }
281
+
282
+ handleCancelFileSelect(): void {
283
+ this.showFileSelector = false;
284
+ this.atPosition = -1;
285
+ this.fileSearchQuery = "";
286
+ this.filteredFiles = [];
287
+
288
+ this.callbacks.onFileSelectorStateChange?.(false, [], "", -1);
289
+ }
290
+
291
+ checkForAtDeletion(cursorPosition: number): boolean {
292
+ if (this.showFileSelector && cursorPosition <= this.atPosition) {
293
+ this.handleCancelFileSelect();
294
+ return true;
295
+ }
296
+ return false;
297
+ }
298
+
299
+ // Command selector methods
300
+ activateCommandSelector(position: number): void {
301
+ this.showCommandSelector = true;
302
+ this.slashPosition = position;
303
+ this.commandSearchQuery = "";
304
+
305
+ this.callbacks.onCommandSelectorStateChange?.(true, "", position);
306
+ }
307
+
308
+ updateCommandSearchQuery(query: string): void {
309
+ this.commandSearchQuery = query;
310
+ this.callbacks.onCommandSelectorStateChange?.(
311
+ this.showCommandSelector,
312
+ query,
313
+ this.slashPosition,
314
+ );
315
+ }
316
+
317
+ handleCommandSelect(command: string): {
318
+ newInput: string;
319
+ newCursorPosition: number;
320
+ } {
321
+ if (this.slashPosition >= 0) {
322
+ // Replace command part, keep other content
323
+ const beforeSlash = this.inputText.substring(0, this.slashPosition);
324
+ const afterQuery = this.inputText.substring(this.cursorPosition);
325
+ const newInput = beforeSlash + afterQuery;
326
+ const newCursorPosition = beforeSlash.length;
327
+
328
+ this.inputText = newInput;
329
+ this.cursorPosition = newCursorPosition;
330
+
331
+ // Execute command asynchronously
332
+ (async () => {
333
+ // First check if it's an agent command
334
+ let commandExecuted = false;
335
+ if (
336
+ this.callbacks.onSendMessage &&
337
+ this.callbacks.onHasSlashCommand?.(command)
338
+ ) {
339
+ // Execute complete command (replace partial input with complete command name)
340
+ const fullCommand = `/${command}`;
341
+ try {
342
+ await this.callbacks.onSendMessage(fullCommand);
343
+ commandExecuted = true;
344
+ } catch (error) {
345
+ console.error("Failed to execute slash command:", error);
346
+ }
347
+ }
348
+
349
+ // If not an agent command or execution failed, check local commands
350
+ if (!commandExecuted) {
351
+ if (command === "bashes" && this.callbacks.onShowBashManager) {
352
+ this.callbacks.onShowBashManager();
353
+ commandExecuted = true;
354
+ } else if (command === "mcp" && this.callbacks.onShowMcpManager) {
355
+ this.callbacks.onShowMcpManager();
356
+ commandExecuted = true;
357
+ }
358
+ }
359
+ })();
360
+
361
+ this.handleCancelCommandSelect();
362
+
363
+ // Set flag to prevent handleInput from processing the same Enter key
364
+ this.selectorJustUsed = true;
365
+ setTimeout(() => {
366
+ this.selectorJustUsed = false;
367
+ }, 0);
368
+
369
+ this.callbacks.onInputTextChange?.(newInput);
370
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
371
+
372
+ return { newInput, newCursorPosition };
373
+ }
374
+ return { newInput: this.inputText, newCursorPosition: this.cursorPosition };
375
+ }
376
+
377
+ handleCommandInsert(command: string): {
378
+ newInput: string;
379
+ newCursorPosition: number;
380
+ } {
381
+ if (this.slashPosition >= 0) {
382
+ const beforeSlash = this.inputText.substring(0, this.slashPosition);
383
+ const afterQuery = this.inputText.substring(this.cursorPosition);
384
+ const newInput = beforeSlash + `/${command} ` + afterQuery;
385
+ const newCursorPosition = beforeSlash.length + command.length + 2;
386
+
387
+ this.inputText = newInput;
388
+ this.cursorPosition = newCursorPosition;
389
+
390
+ this.handleCancelCommandSelect();
391
+
392
+ // Set flag to prevent handleInput from processing the same Enter key
393
+ this.selectorJustUsed = true;
394
+ setTimeout(() => {
395
+ this.selectorJustUsed = false;
396
+ }, 0);
397
+
398
+ this.callbacks.onInputTextChange?.(newInput);
399
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
400
+
401
+ return { newInput, newCursorPosition };
402
+ }
403
+ return { newInput: this.inputText, newCursorPosition: this.cursorPosition };
404
+ }
405
+
406
+ handleCancelCommandSelect(): void {
407
+ this.showCommandSelector = false;
408
+ this.slashPosition = -1;
409
+ this.commandSearchQuery = "";
410
+
411
+ this.callbacks.onCommandSelectorStateChange?.(false, "", -1);
412
+ }
413
+
414
+ checkForSlashDeletion(cursorPosition: number): boolean {
415
+ if (this.showCommandSelector && cursorPosition <= this.slashPosition) {
416
+ this.handleCancelCommandSelect();
417
+ return true;
418
+ }
419
+ return false;
420
+ }
421
+
422
+ // Bash history selector methods
423
+ activateBashHistorySelector(position: number): void {
424
+ this.showBashHistorySelector = true;
425
+ this.exclamationPosition = position;
426
+ this.bashHistorySearchQuery = "";
427
+
428
+ this.callbacks.onBashHistorySelectorStateChange?.(true, "", position);
429
+ }
430
+
431
+ updateBashHistorySearchQuery(query: string): void {
432
+ this.bashHistorySearchQuery = query;
433
+ this.callbacks.onBashHistorySelectorStateChange?.(
434
+ this.showBashHistorySelector,
435
+ query,
436
+ this.exclamationPosition,
437
+ );
438
+ }
439
+
440
+ handleBashHistorySelect(command: string): {
441
+ newInput: string;
442
+ newCursorPosition: number;
443
+ } {
444
+ if (this.exclamationPosition >= 0) {
445
+ const beforeExclamation = this.inputText.substring(
446
+ 0,
447
+ this.exclamationPosition,
448
+ );
449
+ const afterQuery = this.inputText.substring(this.cursorPosition);
450
+ const newInput = beforeExclamation + `!${command}` + afterQuery;
451
+ const newCursorPosition = beforeExclamation.length + command.length + 1;
452
+
453
+ this.inputText = newInput;
454
+ this.cursorPosition = newCursorPosition;
455
+
456
+ this.handleCancelBashHistorySelect();
457
+
458
+ // Set flag to prevent handleInput from processing the same Enter key
459
+ this.selectorJustUsed = true;
460
+ setTimeout(() => {
461
+ this.selectorJustUsed = false;
462
+ }, 0);
463
+
464
+ this.callbacks.onInputTextChange?.(newInput);
465
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
466
+
467
+ return { newInput, newCursorPosition };
468
+ }
469
+ return { newInput: this.inputText, newCursorPosition: this.cursorPosition };
470
+ }
471
+
472
+ handleCancelBashHistorySelect(): void {
473
+ this.showBashHistorySelector = false;
474
+ this.exclamationPosition = -1;
475
+ this.bashHistorySearchQuery = "";
476
+
477
+ this.callbacks.onBashHistorySelectorStateChange?.(false, "", -1);
478
+ }
479
+
480
+ handleBashHistoryExecute(command: string): string {
481
+ this.showBashHistorySelector = false;
482
+ this.exclamationPosition = -1;
483
+ this.bashHistorySearchQuery = "";
484
+
485
+ this.callbacks.onBashHistorySelectorStateChange?.(false, "", -1);
486
+
487
+ return command; // Return command to execute
488
+ }
489
+
490
+ checkForExclamationDeletion(cursorPosition: number): boolean {
491
+ if (
492
+ this.showBashHistorySelector &&
493
+ cursorPosition <= this.exclamationPosition
494
+ ) {
495
+ this.handleCancelBashHistorySelect();
496
+ return true;
497
+ }
498
+ return false;
499
+ }
500
+
501
+ // Memory type selector methods
502
+ activateMemoryTypeSelector(message: string): void {
503
+ this.showMemoryTypeSelector = true;
504
+ this.memoryMessage = message;
505
+
506
+ this.callbacks.onMemoryTypeSelectorStateChange?.(true, message);
507
+ }
508
+
509
+ handleMemoryTypeSelect(type: "project" | "user"): void {
510
+ // Note: type parameter will be used in future for different handling logic
511
+ console.debug(`Memory type selected: ${type}`);
512
+ this.showMemoryTypeSelector = false;
513
+ this.memoryMessage = "";
514
+
515
+ this.callbacks.onMemoryTypeSelectorStateChange?.(false, "");
516
+ }
517
+
518
+ handleCancelMemoryTypeSelect(): void {
519
+ this.showMemoryTypeSelector = false;
520
+ this.memoryMessage = "";
521
+
522
+ this.callbacks.onMemoryTypeSelectorStateChange?.(false, "");
523
+ }
524
+
525
+ // Input history methods
526
+ setUserInputHistory(history: string[]): void {
527
+ this.userInputHistory = history;
528
+ }
529
+
530
+ navigateHistory(
531
+ direction: "up" | "down",
532
+ currentInput: string,
533
+ ): { newInput: string; newCursorPosition: number } {
534
+ if (this.historyIndex === -1) {
535
+ this.historyBuffer = currentInput;
536
+ }
537
+
538
+ if (direction === "up") {
539
+ if (this.historyIndex < this.userInputHistory.length - 1) {
540
+ this.historyIndex++;
541
+ }
542
+ } else {
543
+ // Down direction
544
+ if (this.historyIndex > 0) {
545
+ this.historyIndex--;
546
+ } else if (this.historyIndex === 0) {
547
+ // Go from first history item to draft
548
+ this.historyIndex = -1;
549
+ } else if (this.historyIndex === -1) {
550
+ // Go from draft to empty (beyond history bottom)
551
+ this.historyIndex = -2;
552
+ }
553
+ }
554
+
555
+ let newInput: string;
556
+ if (this.historyIndex === -1) {
557
+ newInput = this.historyBuffer;
558
+ } else if (this.historyIndex === -2) {
559
+ // Beyond history bottom, clear input
560
+ newInput = "";
561
+ } else {
562
+ const historyItem =
563
+ this.userInputHistory[
564
+ this.userInputHistory.length - 1 - this.historyIndex
565
+ ];
566
+ newInput = historyItem || "";
567
+ }
568
+
569
+ const newCursorPosition = newInput.length;
570
+
571
+ this.inputText = newInput;
572
+ this.cursorPosition = newCursorPosition;
573
+
574
+ this.callbacks.onInputTextChange?.(newInput);
575
+ this.callbacks.onCursorPositionChange?.(newCursorPosition);
576
+
577
+ return { newInput, newCursorPosition };
578
+ }
579
+
580
+ resetHistoryNavigation(): void {
581
+ this.historyIndex = -1;
582
+ this.historyBuffer = "";
583
+ }
584
+
585
+ // Getter methods for state
586
+ isFileSelectorActive(): boolean {
587
+ return this.showFileSelector;
588
+ }
589
+
590
+ isCommandSelectorActive(): boolean {
591
+ return this.showCommandSelector;
592
+ }
593
+
594
+ isBashHistorySelectorActive(): boolean {
595
+ return this.showBashHistorySelector;
596
+ }
597
+
598
+ isMemoryTypeSelectorActive(): boolean {
599
+ return this.showMemoryTypeSelector;
600
+ }
601
+
602
+ getFileSelectorState() {
603
+ return {
604
+ show: this.showFileSelector,
605
+ files: this.filteredFiles,
606
+ query: this.fileSearchQuery,
607
+ position: this.atPosition,
608
+ };
609
+ }
610
+
611
+ getCommandSelectorState() {
612
+ return {
613
+ show: this.showCommandSelector,
614
+ query: this.commandSearchQuery,
615
+ position: this.slashPosition,
616
+ };
617
+ }
618
+
619
+ getBashHistorySelectorState() {
620
+ return {
621
+ show: this.showBashHistorySelector,
622
+ query: this.bashHistorySearchQuery,
623
+ position: this.exclamationPosition,
624
+ };
625
+ }
626
+
627
+ getMemoryTypeSelectorState() {
628
+ return {
629
+ show: this.showMemoryTypeSelector,
630
+ message: this.memoryMessage,
631
+ };
632
+ }
633
+
634
+ // Handle special character input that might trigger selectors
635
+ handleSpecialCharInput(char: string): void {
636
+ if (char === "@") {
637
+ this.activateFileSelector(this.cursorPosition - 1);
638
+ } else if (char === "/" && !this.showFileSelector) {
639
+ // Don't activate command selector when file selector is active
640
+ this.activateCommandSelector(this.cursorPosition - 1);
641
+ } else if (char === "!" && this.cursorPosition === 1) {
642
+ this.activateBashHistorySelector(0);
643
+ } else if (char === "#" && this.cursorPosition === 1) {
644
+ // Memory message detection will be handled in submit
645
+ } else {
646
+ // Update search queries for active selectors
647
+ if (this.showFileSelector && this.atPosition >= 0) {
648
+ const queryStart = this.atPosition + 1;
649
+ const queryEnd = this.cursorPosition;
650
+ const newQuery = this.inputText.substring(queryStart, queryEnd);
651
+ this.updateFileSearchQuery(newQuery);
652
+ } else if (this.showCommandSelector && this.slashPosition >= 0) {
653
+ const queryStart = this.slashPosition + 1;
654
+ const queryEnd = this.cursorPosition;
655
+ const newQuery = this.inputText.substring(queryStart, queryEnd);
656
+ this.updateCommandSearchQuery(newQuery);
657
+ } else if (
658
+ this.showBashHistorySelector &&
659
+ this.exclamationPosition >= 0
660
+ ) {
661
+ const queryStart = this.exclamationPosition + 1;
662
+ const queryEnd = this.cursorPosition;
663
+ const newQuery = this.inputText.substring(queryStart, queryEnd);
664
+ this.updateBashHistorySearchQuery(newQuery);
665
+ }
666
+ }
667
+ }
668
+
669
+ // Long text compression methods
670
+ generateCompressedText(originalText: string): string {
671
+ this.longTextCounter += 1;
672
+ const compressedLabel = `[LongText#${this.longTextCounter}]`;
673
+ this.longTextMap.set(compressedLabel, originalText);
674
+ return compressedLabel;
675
+ }
676
+
677
+ expandLongTextPlaceholders(text: string): string {
678
+ let expandedText = text;
679
+ const longTextRegex = /\[LongText#(\d+)\]/g;
680
+ const matches = [...text.matchAll(longTextRegex)];
681
+
682
+ for (const match of matches) {
683
+ const placeholder = match[0];
684
+ const originalText = this.longTextMap.get(placeholder);
685
+ if (originalText) {
686
+ expandedText = expandedText.replace(placeholder, originalText);
687
+ }
688
+ }
689
+
690
+ return expandedText;
691
+ }
692
+
693
+ clearLongTextMap(): void {
694
+ this.longTextMap.clear();
695
+ }
696
+
697
+ // Paste handling methods
698
+ handlePasteInput(input: string): void {
699
+ const inputString = input;
700
+
701
+ // Detect if it's a paste operation (input contains multiple characters or newlines)
702
+ const isPasteOperation =
703
+ inputString.length > 1 ||
704
+ inputString.includes("\n") ||
705
+ inputString.includes("\r");
706
+
707
+ if (isPasteOperation) {
708
+ // Start or continue the debounce handling for paste operation
709
+ if (!this.isPasting) {
710
+ // Start new paste operation
711
+ this.isPasting = true;
712
+ this.pasteBuffer = inputString;
713
+ this.initialPasteCursorPosition = this.cursorPosition;
714
+ } else {
715
+ // Continue paste operation, add new input to buffer
716
+ this.pasteBuffer += inputString;
717
+ }
718
+
719
+ // Clear previous timer
720
+ if (this.pasteDebounceTimer) {
721
+ clearTimeout(this.pasteDebounceTimer);
722
+ }
723
+
724
+ // Set new timer, support environment variable configuration
725
+ const pasteDebounceDelay = parseInt(
726
+ process.env.PASTE_DEBOUNCE_MS || "30",
727
+ 10,
728
+ );
729
+ this.pasteDebounceTimer = setTimeout(() => {
730
+ // Process all paste content in buffer
731
+ let processedInput = this.pasteBuffer.replace(/\r/g, "\n");
732
+
733
+ // Check if long text compression is needed (over 200 characters)
734
+ if (processedInput.length > 200) {
735
+ const originalText = processedInput;
736
+ const compressedLabel = this.generateCompressedText(originalText);
737
+ processedInput = compressedLabel;
738
+ }
739
+
740
+ this.insertTextAtCursor(processedInput);
741
+ this.callbacks.onResetHistoryNavigation?.();
742
+
743
+ // Reset paste state
744
+ this.isPasting = false;
745
+ this.pasteBuffer = "";
746
+ this.pasteDebounceTimer = null;
747
+ }, pasteDebounceDelay);
748
+ } else {
749
+ // Handle single character input
750
+ let char = inputString;
751
+
752
+ // Check if it's Chinese exclamation mark, convert to English if at beginning
753
+ if (char === "!" && this.cursorPosition === 0) {
754
+ char = "!";
755
+ }
756
+
757
+ this.callbacks.onResetHistoryNavigation?.();
758
+ this.insertTextAtCursor(char, () => {
759
+ // Handle special character input - this will manage all selectors
760
+ this.handleSpecialCharInput(char);
761
+ });
762
+ }
763
+ }
764
+
765
+ // Image management methods
766
+ addImage(imagePath: string, mimeType: string): AttachedImage {
767
+ const newImage: AttachedImage = {
768
+ id: this.imageIdCounter,
769
+ path: imagePath,
770
+ mimeType,
771
+ };
772
+ this.attachedImages = [...this.attachedImages, newImage];
773
+ this.imageIdCounter++;
774
+ this.callbacks.onImagesStateChange?.(this.attachedImages);
775
+ return newImage;
776
+ }
777
+
778
+ removeImage(imageId: number): void {
779
+ this.attachedImages = this.attachedImages.filter(
780
+ (img) => img.id !== imageId,
781
+ );
782
+ this.callbacks.onImagesStateChange?.(this.attachedImages);
783
+ }
784
+
785
+ clearImages(): void {
786
+ this.attachedImages = [];
787
+ this.callbacks.onImagesStateChange?.(this.attachedImages);
788
+ }
789
+
790
+ getAttachedImages(): AttachedImage[] {
791
+ return this.attachedImages;
792
+ }
793
+
794
+ async handlePasteImage(): Promise<boolean> {
795
+ try {
796
+ const result = await readClipboardImage();
797
+
798
+ if (result.success && result.imagePath && result.mimeType) {
799
+ // Add image to manager
800
+ const attachedImage = this.addImage(result.imagePath, result.mimeType);
801
+
802
+ // Insert image placeholder at cursor position
803
+ this.insertTextAtCursor(`[Image #${attachedImage.id}]`);
804
+
805
+ return true;
806
+ }
807
+
808
+ return false;
809
+ } catch (error) {
810
+ console.warn("Failed to paste image from clipboard:", error);
811
+ return false;
812
+ }
813
+ }
814
+
815
+ // Bash/MCP manager state methods
816
+ getShowBashManager(): boolean {
817
+ return this.showBashManager;
818
+ }
819
+
820
+ setShowBashManager(show: boolean): void {
821
+ this.showBashManager = show;
822
+ this.callbacks.onBashManagerStateChange?.(show);
823
+ }
824
+
825
+ getShowMcpManager(): boolean {
826
+ return this.showMcpManager;
827
+ }
828
+
829
+ setShowMcpManager(show: boolean): void {
830
+ this.showMcpManager = show;
831
+ this.callbacks.onMcpManagerStateChange?.(show);
832
+ }
833
+
834
+ // Handle submit logic
835
+ async handleSubmit(
836
+ attachedImages: Array<{ id: number; path: string; mimeType: string }>,
837
+ isLoading: boolean = false,
838
+ isCommandRunning: boolean = false,
839
+ ): Promise<void> {
840
+ // Prevent submission during loading or command execution
841
+ if (isLoading || isCommandRunning) {
842
+ return;
843
+ }
844
+
845
+ if (this.inputText.trim()) {
846
+ const trimmedInput = this.inputText.trim();
847
+
848
+ // Check if it's a memory message (starts with # and only one line)
849
+ if (trimmedInput.startsWith("#") && !trimmedInput.includes("\n")) {
850
+ // Activate memory type selector
851
+ this.activateMemoryTypeSelector(trimmedInput);
852
+ return;
853
+ }
854
+
855
+ // Extract image information
856
+ const imageRegex = /\[Image #(\d+)\]/g;
857
+ const matches = [...this.inputText.matchAll(imageRegex)];
858
+ const referencedImages = matches
859
+ .map((match) => {
860
+ const imageId = parseInt(match[1], 10);
861
+ return attachedImages.find((img) => img.id === imageId);
862
+ })
863
+ .filter(
864
+ (img): img is { id: number; path: string; mimeType: string } =>
865
+ img !== undefined,
866
+ )
867
+ .map((img) => ({ path: img.path, mimeType: img.mimeType }));
868
+
869
+ // Remove image placeholders, expand long text placeholders, send message
870
+ let cleanContent = this.inputText.replace(imageRegex, "").trim();
871
+ cleanContent = this.expandLongTextPlaceholders(cleanContent);
872
+
873
+ this.callbacks.onSendMessage?.(
874
+ cleanContent,
875
+ referencedImages.length > 0 ? referencedImages : undefined,
876
+ );
877
+ this.clearInput();
878
+ this.callbacks.onResetHistoryNavigation?.();
879
+
880
+ // Clear long text mapping
881
+ this.clearLongTextMap();
882
+ }
883
+ }
884
+
885
+ // Handle selector input (when any selector is active)
886
+ handleSelectorInput(input: string, key: Key): boolean {
887
+ if (key.backspace || key.delete) {
888
+ if (this.cursorPosition > 0) {
889
+ this.deleteCharAtCursor((newInput, newCursorPosition) => {
890
+ // Check for special character deletion
891
+ this.checkForAtDeletion(newCursorPosition);
892
+ this.checkForSlashDeletion(newCursorPosition);
893
+ this.checkForExclamationDeletion(newCursorPosition);
894
+ });
895
+ }
896
+ return true;
897
+ }
898
+
899
+ // Arrow keys and Enter should be handled by selector components
900
+ if (key.upArrow || key.downArrow || key.return) {
901
+ // Let selector component handle these keys, but prevent further processing
902
+ // by returning true (indicating we've handled the input)
903
+ return true;
904
+ }
905
+
906
+ if (
907
+ input &&
908
+ !key.ctrl &&
909
+ !("alt" in key && key.alt) &&
910
+ !key.meta &&
911
+ !key.return &&
912
+ !key.escape &&
913
+ !key.leftArrow &&
914
+ !key.rightArrow &&
915
+ !("home" in key && key.home) &&
916
+ !("end" in key && key.end)
917
+ ) {
918
+ // Handle character input for search
919
+ this.insertTextAtCursor(input, () => {
920
+ // Special character handling is now managed by InputManager
921
+ this.handleSpecialCharInput(input);
922
+ });
923
+ return true;
924
+ }
925
+
926
+ return false;
927
+ }
928
+
929
+ // Handle normal input (when no selector is active)
930
+ async handleNormalInput(
931
+ input: string,
932
+ key: Key,
933
+ attachedImages: Array<{ id: number; path: string; mimeType: string }>,
934
+ isLoading: boolean = false,
935
+ isCommandRunning: boolean = false,
936
+ clearImages?: () => void,
937
+ ): Promise<boolean> {
938
+ if (key.return) {
939
+ await this.handleSubmit(attachedImages, isLoading, isCommandRunning);
940
+ clearImages?.();
941
+ return true;
942
+ }
943
+
944
+ if (key.escape) {
945
+ if (this.showFileSelector) {
946
+ this.handleCancelFileSelect();
947
+ } else if (this.showCommandSelector) {
948
+ this.handleCancelCommandSelect();
949
+ } else if (this.showBashHistorySelector) {
950
+ this.handleCancelBashHistorySelect();
951
+ }
952
+ return true;
953
+ }
954
+
955
+ if (key.backspace || key.delete) {
956
+ if (this.cursorPosition > 0) {
957
+ this.deleteCharAtCursor();
958
+ this.callbacks.onResetHistoryNavigation?.();
959
+
960
+ // Check if we deleted any special characters
961
+ const newCursorPosition = this.cursorPosition - 1;
962
+ this.checkForAtDeletion(newCursorPosition);
963
+ this.checkForSlashDeletion(newCursorPosition);
964
+ this.checkForExclamationDeletion(newCursorPosition);
965
+ }
966
+ return true;
967
+ }
968
+
969
+ if (key.leftArrow) {
970
+ this.moveCursorLeft();
971
+ return true;
972
+ }
973
+
974
+ if (key.rightArrow) {
975
+ this.moveCursorRight();
976
+ return true;
977
+ }
978
+
979
+ if (("home" in key && key.home) || (key.ctrl && input === "a")) {
980
+ this.moveCursorToStart();
981
+ return true;
982
+ }
983
+
984
+ if (("end" in key && key.end) || (key.ctrl && input === "e")) {
985
+ this.moveCursorToEnd();
986
+ return true;
987
+ }
988
+
989
+ // Handle Ctrl+V for pasting images
990
+ if (key.ctrl && input === "v") {
991
+ this.handlePasteImage().catch((error) => {
992
+ console.warn("Failed to handle paste image:", error);
993
+ });
994
+ return true;
995
+ }
996
+
997
+ // Handle up/down keys for history navigation (only when no selector is active)
998
+ if (
999
+ key.upArrow &&
1000
+ !this.showFileSelector &&
1001
+ !this.showCommandSelector &&
1002
+ !this.showBashHistorySelector
1003
+ ) {
1004
+ this.navigateHistory("up", this.inputText);
1005
+ return true;
1006
+ }
1007
+
1008
+ if (
1009
+ key.downArrow &&
1010
+ !this.showFileSelector &&
1011
+ !this.showCommandSelector &&
1012
+ !this.showBashHistorySelector
1013
+ ) {
1014
+ this.navigateHistory("down", this.inputText);
1015
+ return true;
1016
+ }
1017
+
1018
+ // Handle typing input
1019
+ if (
1020
+ input &&
1021
+ !key.ctrl &&
1022
+ !("alt" in key && key.alt) &&
1023
+ !key.meta &&
1024
+ !key.return &&
1025
+ !key.escape &&
1026
+ !key.backspace &&
1027
+ !key.delete &&
1028
+ !key.leftArrow &&
1029
+ !key.rightArrow &&
1030
+ !("home" in key && key.home) &&
1031
+ !("end" in key && key.end)
1032
+ ) {
1033
+ this.handlePasteInput(input);
1034
+ return true;
1035
+ }
1036
+
1037
+ return false;
1038
+ }
1039
+
1040
+ // Main input handler - routes to appropriate handler based on state
1041
+ async handleInput(
1042
+ input: string,
1043
+ key: Key,
1044
+ attachedImages: Array<{ id: number; path: string; mimeType: string }>,
1045
+ isLoading: boolean = false,
1046
+ isCommandRunning: boolean = false,
1047
+ clearImages?: () => void,
1048
+ ): Promise<boolean> {
1049
+ // If selector was just used, ignore this input to prevent conflicts
1050
+ if (this.selectorJustUsed) {
1051
+ return true;
1052
+ }
1053
+
1054
+ // Handle interrupt request - use Esc key to interrupt AI request or command
1055
+ if (key.escape && (isLoading || isCommandRunning)) {
1056
+ // Unified interrupt for AI message generation and command execution
1057
+ this.callbacks.onAbortMessage?.();
1058
+ return true;
1059
+ }
1060
+
1061
+ // Check if any selector is active
1062
+ if (
1063
+ this.showFileSelector ||
1064
+ this.showCommandSelector ||
1065
+ this.showBashHistorySelector ||
1066
+ this.showMemoryTypeSelector ||
1067
+ this.showBashManager ||
1068
+ this.showMcpManager
1069
+ ) {
1070
+ if (
1071
+ this.showMemoryTypeSelector ||
1072
+ this.showBashManager ||
1073
+ this.showMcpManager
1074
+ ) {
1075
+ // Memory type selector, bash manager and MCP manager don't need to handle input, handled by component itself
1076
+ return false;
1077
+ }
1078
+ return this.handleSelectorInput(input, key);
1079
+ } else {
1080
+ return await this.handleNormalInput(
1081
+ input,
1082
+ key,
1083
+ attachedImages,
1084
+ isLoading,
1085
+ isCommandRunning,
1086
+ clearImages,
1087
+ );
1088
+ }
1089
+ }
1090
+
1091
+ // Cleanup method
1092
+ destroy(): void {
1093
+ if (this.fileSearchDebounceTimer) {
1094
+ clearTimeout(this.fileSearchDebounceTimer);
1095
+ this.fileSearchDebounceTimer = null;
1096
+ }
1097
+ if (this.pasteDebounceTimer) {
1098
+ clearTimeout(this.pasteDebounceTimer);
1099
+ this.pasteDebounceTimer = null;
1100
+ }
1101
+ }
1102
+ }