-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathinput_section.rs
More file actions
1348 lines (1226 loc) · 64.2 KB
/
input_section.rs
File metadata and controls
1348 lines (1226 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Input section component
//!
//! This module provides the input section component that handles
//! user input and displays the status bar.
use crate::interactive::file_search::{
extract_existing_file_references, extract_search_query, should_show_file_search,
};
use crate::interactive::file_search::{
DefaultFileSearchProvider, FileSearchProvider, FileSearchResult,
};
use crate::interactive::input_history::InputHistory;
use crate::interactive::message_handler::AppMessage;
use coro_core::ResolvedLlmConfig;
use coro_router::use_router;
use iocraft::prelude::*;
use std::cmp::min;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{broadcast, Mutex};
use unicode_width::UnicodeWidthStr;
/// Find the nearest character boundary at or before the given byte position
/// This ensures we don't slice in the middle of a UTF-8 character
fn find_char_boundary(text: &str, byte_pos: usize) -> usize {
if byte_pos >= text.len() {
return text.len();
}
// Find the nearest character boundary at or before byte_pos
text.char_indices()
.map(|(i, _)| i)
.filter(|&i| i <= byte_pos)
.next_back()
.unwrap_or(0)
}
/// Calculate cursor position (line, column) from text and byte position
/// Returns (line_number, column_number) where both are 1-based
fn calculate_cursor_position(text: &str, byte_pos: usize) -> (usize, usize) {
if text.is_empty() {
return (1, 1);
}
// Ensure we're at a valid character boundary
let safe_pos = find_char_boundary(text, byte_pos);
let text_before_cursor = &text[..safe_pos];
// Count lines (number of newlines + 1)
let line_number = text_before_cursor.matches('\n').count() + 1;
// Find the start of the current line
let current_line_start = text_before_cursor.rfind('\n').map(|i| i + 1).unwrap_or(0);
let current_line_text = &text_before_cursor[current_line_start..];
// Count characters in current line (not bytes)
let column_number = current_line_text.chars().count() + 1;
(line_number, column_number)
}
/// Calculate cursor display position for rendering with soft-wrapping awareness
/// Returns (display_line, display_column) where both are 0-based for UI positioning
fn calculate_cursor_display_position(
text: &str,
byte_pos: usize,
max_width: usize,
) -> (usize, usize) {
if text.is_empty() {
return (0, 0);
}
let safe_pos = byte_pos.min(text.len());
// Traverse characters up to the cursor and simulate wrapping using display width
let mut display_line = 0usize;
let mut current_line_width = 0usize;
let iter = text.char_indices().peekable();
for (idx, ch) in iter {
if idx >= safe_pos {
break;
}
if ch == '\n' {
// Hard line break
display_line += 1;
current_line_width = 0;
continue;
}
let char_width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
// If adding this char would exceed the width and we already have something on this line, wrap before it
if max_width > 0 && current_line_width > 0 && current_line_width + char_width > max_width {
display_line += 1;
current_line_width = 0;
}
current_line_width += char_width;
}
(display_line, current_line_width)
}
#[derive(Clone, Props)]
pub struct InputSectionProps {
pub context: InputSectionContext,
}
impl Default for InputSectionProps {
fn default() -> Self {
Self {
context: InputSectionContext {
llm_config: ResolvedLlmConfig::new(
coro_core::Protocol::OpenAICompat,
"https://api.openai.com".to_string(),
"test-key".to_string(),
"gpt-4o".to_string(),
),
project_path: PathBuf::new(),
ui_sender: tokio::sync::broadcast::channel(1).0,
agent: Arc::new(Mutex::new(None)),
},
}
}
}
/// Context for the input section component
#[derive(Clone)]
pub struct InputSectionContext {
pub llm_config: ResolvedLlmConfig,
pub project_path: PathBuf,
pub ui_sender: broadcast::Sender<AppMessage>,
pub agent: Arc<Mutex<Option<coro_core::agent::AgentCore>>>,
}
/// Enhanced text input component that wraps iocraft's TextInput with submit handling
#[derive(Props)]
pub struct EnhancedTextInputProps {
pub value: String,
pub has_focus: bool,
pub on_change: Handler<'static, String>,
pub on_submit: Handler<'static, String>,
pub on_cursor_position_change: Handler<'static, (usize, usize)>, // (line, column)
pub on_file_list_state_change: Handler<'static, bool>, // Track file list visibility
pub width: u16,
pub placeholder: String,
pub color: Option<Color>,
pub cursor_color: Option<Color>,
pub project_path: PathBuf,
}
impl Default for EnhancedTextInputProps {
fn default() -> Self {
Self {
value: String::new(),
has_focus: false,
on_change: Handler::default(),
on_submit: Handler::default(),
on_cursor_position_change: Handler::default(),
on_file_list_state_change: Handler::default(),
width: 80,
placeholder: String::new(),
color: None,
cursor_color: None,
project_path: PathBuf::new(),
}
}
}
/// Simple multiline text input component without internal scrolling
#[component]
pub fn EnhancedTextInput(
mut hooks: Hooks,
props: &mut EnhancedTextInputProps,
) -> impl Into<AnyElement<'static>> {
let has_focus = props.has_focus;
let width = props.width;
let project_path = props.project_path.clone();
// Local state for cursor position
let cursor_pos = hooks.use_state(|| props.value.len());
// State for file search popup
let show_file_list = hooks.use_state(|| false);
let search_results = hooks.use_state(Vec::<FileSearchResult>::new);
let selected_file_index = hooks.use_state(|| 0usize);
let current_query = hooks.use_state(String::new);
// Track last text input time to disambiguate paste vs. manual Enter
let last_text_time = hooks.use_state(|| Instant::now() - Duration::from_secs(10));
// Cache for existing file references to avoid repeated parsing
let cached_existing_refs = hooks.use_state(Vec::<String>::new);
let last_input_for_refs = hooks.use_state(String::new);
// Initialize search provider
let search_provider =
hooks.use_state(|| DefaultFileSearchProvider::new(project_path.clone()).ok());
// Handle keyboard input
hooks.use_terminal_events({
let mut on_change = props.on_change.take();
let mut on_submit = props.on_submit.take();
let mut on_cursor_position_change = props.on_cursor_position_change.take();
let mut on_file_list_state_change = props.on_file_list_state_change.take();
let mut value = props.value.clone();
let mut cursor_pos = cursor_pos;
let mut show_file_list = show_file_list;
let mut search_results = search_results;
let mut selected_file_index = selected_file_index;
let mut current_query = current_query;
let _project_path = project_path.clone();
let mut cached_existing_refs = cached_existing_refs;
let mut last_input_for_refs = last_input_for_refs;
let mut last_text_time = last_text_time;
move |event| {
if !has_focus {
return;
}
match event {
TerminalEvent::Key(KeyEvent {
code,
modifiers,
kind,
..
}) if kind != KeyEventKind::Release => {
let mut pos = cursor_pos.get();
let mut changed = false;
// Handle file list navigation when it's shown
if *show_file_list.read() {
match code {
KeyCode::Up => {
let current = selected_file_index.get();
if current > 0 {
selected_file_index.set(current - 1);
}
return;
}
KeyCode::Down => {
let current = selected_file_index.get();
let max_index = search_results.read().len().saturating_sub(1);
if current < max_index {
selected_file_index.set(current + 1);
}
return;
}
KeyCode::Char('p') if modifiers.contains(KeyModifiers::CONTROL) => {
// Ctrl+P: Move up (previous)
let current = selected_file_index.get();
if current > 0 {
selected_file_index.set(current - 1);
}
return;
}
KeyCode::Char('n') if modifiers.contains(KeyModifiers::CONTROL) => {
// Ctrl+N: Move down (next)
let current = selected_file_index.get();
let max_index = search_results.read().len().saturating_sub(1);
if current < max_index {
selected_file_index.set(current + 1);
}
return;
}
KeyCode::Enter | KeyCode::Tab => {
// If this Enter comes immediately after burst typing/paste, treat as newline (not file pick)
let recent_text = Instant::now()
.duration_since(*last_text_time.read())
<= Duration::from_millis(10);
if recent_text && matches!(code, KeyCode::Enter) {
// Close popup and let the general handler below process Enter as newline
show_file_list.set(false);
on_file_list_state_change(false);
// fallthrough to general handling by not returning
} else {
// Insert selected file
if let Some(selected_result) =
search_results.read().get(selected_file_index.get())
{
// Find the @ position and replace the entire @search_term with @absolute_path + space
if let Some(query) = extract_search_query(&value, pos) {
if let Some(at_pos) = value.rfind('@') {
// Find the end of the search term
let search_end = at_pos + 1 + query.len();
let before_at = &value[..at_pos];
let after_search = &value[search_end..];
// Create replacement: @absolute_path + space
let replacement =
format!("@{} ", selected_result.insertion_path);
value = format!(
"{}{}{}",
before_at, replacement, after_search
);
pos = at_pos + replacement.len();
cursor_pos.set(pos);
on_change(value.clone());
// Update cursor position
let (line, col) =
calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
}
}
}
show_file_list.set(false);
on_file_list_state_change(false);
return;
}
}
KeyCode::Esc => {
show_file_list.set(false);
on_file_list_state_change(false);
return;
}
_ => {}
}
}
match code {
KeyCode::Char(c) => {
// Record time of recent text input
last_text_time.set(Instant::now());
// Ensure we're at a character boundary before inserting
let safe_pos = find_char_boundary(&value, pos);
let char_pos = value[..safe_pos].chars().count();
let mut chars: Vec<char> = value.chars().collect();
chars.insert(char_pos, c);
value = chars.into_iter().collect();
// Update position to after the inserted character
pos = value
.char_indices()
.nth(char_pos + 1)
.map(|(i, _)| i)
.unwrap_or(value.len());
changed = true;
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
// Check if we should show/update/hide file list after character input
let should_show = should_show_file_search(&value, pos);
if should_show {
if let Some(query) = extract_search_query(&value, pos) {
// Show list and update search if needed
if !*show_file_list.read() || query != *current_query.read() {
if let Some(search_provider) =
search_provider.read().as_ref()
{
// Get cached existing file references to exclude them
let existing_refs = if value
!= *last_input_for_refs.read()
{
let refs =
extract_existing_file_references(&value, pos);
cached_existing_refs.set(refs.clone());
last_input_for_refs.set(value.clone());
refs
} else {
cached_existing_refs.read().clone()
};
let exclude_paths: Vec<&str> =
existing_refs.iter().map(|s| s.as_str()).collect();
let results = if query.is_empty() {
search_provider
.get_all_files_with_exclusions(&exclude_paths)
} else {
search_provider
.search_with_exclusions(&query, &exclude_paths)
};
search_results.set(results);
selected_file_index.set(0);
current_query.set(query);
show_file_list.set(true);
on_file_list_state_change(true);
}
}
}
} else {
// Should not show list, hide it
show_file_list.set(false);
on_file_list_state_change(false);
}
}
KeyCode::Backspace => {
if pos > 0 {
// Find the start of the previous character
let safe_pos = find_char_boundary(&value, pos);
let char_start = value[..safe_pos]
.char_indices()
.last()
.map(|(i, _)| i)
.unwrap_or(0);
// Convert to chars, remove the previous character, and rebuild string
let mut chars: Vec<char> = value.chars().collect();
let char_pos = value[..safe_pos].chars().count();
if char_pos > 0 {
chars.remove(char_pos - 1);
value = chars.into_iter().collect();
pos = char_start;
changed = true;
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
// Check if we should show/update/hide file list after backspace
let should_show = should_show_file_search(&value, pos);
if should_show {
if let Some(query) = extract_search_query(&value, pos) {
// Show list and update search if needed
if !*show_file_list.read()
|| query != *current_query.read()
{
if let Some(search_provider) =
search_provider.read().as_ref()
{
// Get cached existing file references to exclude them
let existing_refs = if value
!= *last_input_for_refs.read()
{
let refs = extract_existing_file_references(
&value, pos,
);
cached_existing_refs.set(refs.clone());
last_input_for_refs.set(value.clone());
refs
} else {
cached_existing_refs.read().clone()
};
let exclude_paths: Vec<&str> = existing_refs
.iter()
.map(|s| s.as_str())
.collect();
let results = if query.is_empty() {
search_provider
.get_all_files_with_exclusions(
&exclude_paths,
)
} else {
search_provider.search_with_exclusions(
&query,
&exclude_paths,
)
};
search_results.set(results);
selected_file_index.set(0);
current_query.set(query);
show_file_list.set(true);
on_file_list_state_change(true);
}
}
}
} else {
// Should not show list, hide it
show_file_list.set(false);
on_file_list_state_change(false);
}
}
}
}
KeyCode::Delete => {
if pos < value.len() {
// Find the next character boundary to delete safely
if value[pos..].chars().next().is_some() {
// Convert to chars, remove one, and rebuild string
let mut chars: Vec<char> = value.chars().collect();
let safe_pos = find_char_boundary(&value, pos);
let char_pos = value[..safe_pos].chars().count();
if char_pos < chars.len() {
chars.remove(char_pos);
value = chars.into_iter().collect();
changed = true;
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
// Update search or hide file list
if *show_file_list.read() {
if let Some(query) = extract_search_query(&value, pos) {
if query != *current_query.read() {
if let Some(search_provider) =
search_provider.read().as_ref()
{
// Get cached existing file references to exclude them
let existing_refs = if value
!= *last_input_for_refs.read()
{
let refs =
extract_existing_file_references(
&value, pos,
);
cached_existing_refs.set(refs.clone());
last_input_for_refs.set(value.clone());
refs
} else {
cached_existing_refs.read().clone()
};
let exclude_paths: Vec<&str> =
existing_refs
.iter()
.map(|s| s.as_str())
.collect();
let results = if query.is_empty() {
search_provider
.get_all_files_with_exclusions(
&exclude_paths,
)
} else {
search_provider.search_with_exclusions(
&query,
&exclude_paths,
)
};
search_results.set(results);
selected_file_index.set(0);
current_query.set(query);
}
}
} else {
// No valid query found, hide the list
show_file_list.set(false);
on_file_list_state_change(false);
}
}
}
}
}
}
KeyCode::Enter => {
// Check if current line ends with backslash
let current_line_end_with_backslash = {
// Find the current line by looking backwards from cursor position
let safe_pos = find_char_boundary(&value, pos);
let before_cursor = &value[..safe_pos];
let current_line_start =
before_cursor.rfind('\n').map(|i| i + 1).unwrap_or(0);
// Find the end of current line by looking forward from cursor
let after_cursor = &value[pos..];
let current_line_end = after_cursor
.find('\n')
.map(|i| pos + i)
.unwrap_or(value.len());
// Get the current line content
let current_line = &value[current_line_start..current_line_end];
current_line.trim_end().ends_with('\\')
};
if current_line_end_with_backslash {
// Remove the trailing backslash and add newline
let safe_pos = find_char_boundary(&value, pos);
let before_cursor = &value[..safe_pos];
let current_line_start =
before_cursor.rfind('\n').map(|i| i + 1).unwrap_or(0);
let after_cursor = &value[pos..];
let current_line_end = after_cursor
.find('\n')
.map(|i| pos + i)
.unwrap_or(value.len());
let current_line = &value[current_line_start..current_line_end];
let trimmed_line = current_line.trim_end();
if let Some(backslash_pos) = trimmed_line.rfind('\\') {
// Create new string parts to avoid borrowing conflicts
let new_line = trimmed_line[..backslash_pos].to_string();
let before_line = value[..current_line_start].to_string();
let after_line = value[current_line_end..].to_string();
value = format!("{}{}\n{}", before_line, new_line, after_line);
pos = current_line_start + new_line.len() + 1; // Position after newline
changed = true;
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
}
} else {
// Heuristic: if Enter comes right after a burst of text input (e.g., from a paste),
// treat it as a newline instead of submit.
let recent_text = Instant::now()
.duration_since(*last_text_time.read())
<= Duration::from_millis(10);
if modifiers.contains(KeyModifiers::SHIFT) || recent_text {
// Insert newline - use safe character insertion
let safe_pos = find_char_boundary(&value, pos);
let char_pos = value[..safe_pos].chars().count();
let mut chars: Vec<char> = value.chars().collect();
chars.insert(char_pos, '\n');
value = chars.into_iter().collect();
// Update position to after the inserted newline
pos = value
.char_indices()
.nth(char_pos + 1)
.map(|(i, _)| i)
.unwrap_or(value.len());
changed = true;
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
// Update recent text time since we effectively inserted text
last_text_time.set(Instant::now());
} else {
// Regular Enter submits
on_submit(value.clone());
return;
}
}
}
KeyCode::Left => {
if pos > 0 {
let safe_pos = find_char_boundary(&value, pos);
let char_start = value[..safe_pos]
.char_indices()
.last()
.map(|(i, _)| i)
.unwrap_or(0);
pos = char_start;
cursor_pos.set(pos);
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
}
}
KeyCode::Right => {
if pos < value.len() {
let char_end = value[pos..]
.char_indices()
.nth(1)
.map(|(i, _)| pos + i)
.unwrap_or(value.len());
pos = char_end;
cursor_pos.set(pos);
// Update cursor position
let (line, col) = calculate_cursor_position(&value, pos);
on_cursor_position_change((line, col));
}
}
KeyCode::Up => {
// History navigation will be handled in InputSection
// For now, just handle normal text navigation
}
KeyCode::Down => {
// History navigation will be handled in InputSection
// For now, just handle normal text navigation
}
_ => {}
}
if changed {
cursor_pos.set(pos);
on_change(value.clone());
}
}
_ => {}
}
}
});
// Split text into display lines with wrapping
let effective_width = (width as usize).saturating_sub(4); // Account for borders and padding
let display_lines = if props.value.is_empty() {
vec![String::new()]
} else {
let mut lines = Vec::new();
for line in props.value.lines() {
if line.is_empty() {
lines.push(String::new());
} else {
// Simple wrapping: split long lines
let line_width = UnicodeWidthStr::width(line);
if line_width <= effective_width {
lines.push(line.to_string());
} else {
// Need to wrap this line
let mut current_line = String::new();
let mut current_width = 0;
for ch in line.chars() {
let char_width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if current_width + char_width > effective_width && !current_line.is_empty()
{
lines.push(current_line);
current_line = String::new();
current_width = 0;
}
current_line.push(ch);
current_width += char_width;
}
if !current_line.is_empty() {
lines.push(current_line);
}
}
}
}
if props.value.ends_with('\n') {
lines.push(String::new());
}
lines
};
let total_height = (display_lines.len() + 2) as u16; // +2 for borders
element! {
View(
flex_direction: FlexDirection::Column,
position: Position::Relative,
) {
// Input box
View(
width: width,
height: total_height,
border_style: BorderStyle::Round,
padding_left: 1,
padding_right: 1,
position: Position::Relative,
) {
// Content area with cursor
View(
flex_direction: FlexDirection::Column,
width: 100pct,
height: 100pct,
position: Position::Relative,
) {
#(display_lines.iter().enumerate().map(|(line_idx, line)| {
element! {
View(
key: format!("line-{}", line_idx),
height: 1,
width: 100pct,
position: Position::Relative,
) {
#(if line.is_empty() && line_idx == 0 && props.value.is_empty() && !props.placeholder.is_empty() {
Some(element! {
Text(
content: &props.placeholder,
color: Color::DarkGrey,
)
})
} else {
Some(element! {
Text(
content: line,
color: props.color.unwrap_or(Color::White),
)
})
})
}
}
}))
// Render cursor if component has focus
#(if props.has_focus {
// Calculate cursor position in display coordinates (wrap-aware)
let cursor_pos = cursor_pos.get();
let (cursor_line, cursor_col) = calculate_cursor_display_position(&props.value, cursor_pos, effective_width);
// Clamp left within the drawable area to avoid off-by-one overflow
let clamped_left = min(cursor_col, effective_width.saturating_sub(1)) as u16;
// Get the character at cursor position for semi-transparent effect
let cursor_char = if props.value.is_empty() && !props.placeholder.is_empty() {
// Show placeholder character at cursor position with different styling
props.placeholder.chars().nth(cursor_col).unwrap_or(' ')
} else {
// Show space or character at cursor position
let chars: Vec<char> = props.value.chars().collect();
// Convert byte index to char index safely
// First, ensure cursor_pos is at a valid character boundary
let safe_cursor_pos = find_char_boundary(&props.value, cursor_pos);
let char_idx = props.value[..safe_cursor_pos].chars().count();
if char_idx < chars.len() {
chars[char_idx]
} else {
' '
}
};
Some(element! {
View(
key: "cursor",
position: Position::Absolute,
top: cursor_line as u16,
left: clamped_left,
width: 1,
height: 1,
background_color: props.cursor_color.unwrap_or(Color::Rgb { r: 200, g: 200, b: 200 }), // Light grey background
) {
Text(
content: cursor_char.to_string(),
color: Color::Rgb { r: 80, g: 80, b: 80 }, // Dark text for contrast
)
}
})
} else {
None
})
}
}
// File list popup
#(if *show_file_list.read() {
let results = search_results.read();
let selected_index = selected_file_index.get();
let max_display_files = 10;
let display_results: Vec<_> = results.iter().take(max_display_files).enumerate().collect();
Some(element! {
View(
key: "file-list",
width: width,
height: min(results.len(), max_display_files) as u16,
position: Position::Relative,
) {
View(
flex_direction: FlexDirection::Column,
width: 100pct,
height: 100pct,
padding_left: 2,
padding_right: 2,
) {
#(display_results.iter().map(|(idx, result)| {
let is_selected = *idx == selected_index;
element! {
View(
key: format!("file-{}", idx),
height: 1,
width: 100pct,
) {
Text(
content: result.display_name.clone(),
color: if is_selected {
Color::Rgb { r: 100, g: 149, b: 237 }
} else {
Color::DarkGrey
},
)
}
}
}))
}
}
})
} else {
None
})
}
}
}
/// Spawn agent task execution and broadcast UI events
pub fn spawn_ui_agent_task(
input: String,
llm_config: ResolvedLlmConfig,
project_path: PathBuf,
ui_sender: broadcast::Sender<AppMessage>,
) {
use crate::interactive::message_handler::get_random_status_word;
use crate::interactive::task_executor::execute_agent_task;
// Start with a random status word
let _ = ui_sender.send(AppMessage::AgentTaskStarted {
operation: get_random_status_word(),
});
// Create a cancellation token for the timer
let (cancel_sender, mut cancel_receiver) = tokio::sync::oneshot::channel::<()>();
// Change status word once after 1 second (unless cancelled)
let ui_sender_timer = ui_sender.clone();
tokio::spawn(async move {
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_secs(1)) => {
let _ = ui_sender_timer.send(AppMessage::AgentTaskStarted {
operation: get_random_status_word(),
});
}
_ = &mut cancel_receiver => {
// Timer cancelled, do nothing
}
}
});
// Execute agent task
tokio::spawn(async move {
match execute_agent_task(input, llm_config, project_path, ui_sender.clone()).await {
Ok(_) => {
let _ = cancel_sender.send(()); // Cancel the timer
let _ = ui_sender.send(AppMessage::AgentExecutionCompleted);
}
Err(e) => {
let _ = cancel_sender.send(()); // Cancel the timer
// Check if it's an interruption error
if e.to_string().contains("Task interrupted by user") {
// Don't show error message for user interruptions
} else {
let _ = ui_sender.send(AppMessage::SystemMessage(format!("Error: {}", e)));
}
let _ = ui_sender.send(AppMessage::AgentExecutionCompleted);
}
}
});
}
/// Spawn agent task execution with persistent agent for conversation continuity
pub fn spawn_ui_agent_task_with_context(
input: String,
llm_config: ResolvedLlmConfig,
project_path: PathBuf,
ui_sender: broadcast::Sender<AppMessage>,
agent: Arc<Mutex<Option<coro_core::agent::AgentCore>>>,
) {
use crate::interactive::message_handler::get_random_status_word;
use crate::interactive::task_executor::execute_agent_task_with_context;
// Start with a random status word
let _ = ui_sender.send(AppMessage::AgentTaskStarted {
operation: get_random_status_word(),
});
// Create a cancellation token for the timer
let (cancel_sender, mut cancel_receiver) = tokio::sync::oneshot::channel::<()>();
// Change status word once after 1 second (unless cancelled)
let ui_sender_timer = ui_sender.clone();
tokio::spawn(async move {
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_secs(1)) => {
let _ = ui_sender_timer.send(AppMessage::AgentTaskStarted {
operation: get_random_status_word(),
});
}
_ = &mut cancel_receiver => {
// Timer cancelled, do nothing
}
}
});
// Execute agent task with persistent context
tokio::spawn(async move {
match execute_agent_task_with_context(
input,
llm_config,
project_path,
ui_sender.clone(),
agent,
)
.await
{
Ok(_) => {
let _ = cancel_sender.send(()); // Cancel the timer
let _ = ui_sender.send(AppMessage::AgentExecutionCompleted);
}
Err(e) => {
let _ = cancel_sender.send(()); // Cancel the timer
// Check if it's an interruption error
if e.to_string().contains("Task interrupted by user") {
// Don't show error message for user interruptions
} else {
let _ = ui_sender.send(AppMessage::SystemMessage(format!("Error: {}", e)));
}
let _ = ui_sender.send(AppMessage::AgentExecutionCompleted);
}
}
});
}
/// Input Section Component - Fixed bottom area for input and status
#[component]
pub fn InputSection(mut hooks: Hooks, props: &InputSectionProps) -> impl Into<AnyElement<'static>> {
// Subscribe to keyboard and dispatch events
let context = &props.context;
// Get terminal width for fixed input width
let (terminal_width, _height) = hooks.use_terminal_size();
let input_width = if terminal_width > 6 {