-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminimal_session.rs
More file actions
1690 lines (1467 loc) · 63.8 KB
/
minimal_session.rs
File metadata and controls
1690 lines (1467 loc) · 63.8 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
//! Minimalist Session View
//!
//! A terminal-style chat interface inspired by Codex CLI.
//! This view provides a clean, minimal UI with:
//! - Chat history as simple terminal scrollback
//! - Status indicator with shimmer animation
//! - Simple input line with prompt
//! - Contextual key hints at the bottom
use std::time::{SystemTime, UNIX_EPOCH};
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Widget,
};
use cortex_core::widgets::{Brain, Message, MessageRole};
use cortex_tui_components::welcome_card::{InfoCard, InfoCardPair, ToLines, WelcomeCard};
use crate::app::{AppState, SubagentDisplayStatus, SubagentTaskDisplay};
use crate::ui::colors::AdaptiveColors;
use crate::ui::consts::{CURSOR_BLINK_INTERVAL_MS, border};
use crate::views::tool_call::{ContentSegment, ToolCallDisplay, ToolStatus};
use crate::widgets::{AutocompletePopup, HintContext, KeyHints, StatusIndicator};
/// Application version
const VERSION: &str = env!("CARGO_PKG_VERSION");
// Re-export for convenience
pub use cortex_core::widgets::Message as ChatMessage;
// ============================================================
// MINIMAL SESSION VIEW
// ============================================================
/// Minimalist session view for the chat interface.
///
/// Layout:
/// ```text
/// ┌─────────────────────────────────────────────────────────┐
/// │ > You: Hello, how are you? │
/// │ │
/// │ Assistant: I'm doing well! How can I help you today? │
/// │ │
/// │ ⠹ Working · Analyzing code... (12s • Esc to interrupt) │
/// ├─────────────────────────────────────────────────────────┤
/// │ > _ │
/// ├─────────────────────────────────────────────────────────┤
/// │ Enter submit · Ctrl+K palette · Ctrl+M model · ? help │
/// └─────────────────────────────────────────────────────────┘
/// ```
pub struct MinimalSessionView<'a> {
/// Reference to the application state
app_state: &'a AppState,
/// Color palette
colors: AdaptiveColors,
}
impl<'a> MinimalSessionView<'a> {
/// Creates a new minimal session view.
pub fn new(app_state: &'a AppState) -> Self {
Self {
app_state,
colors: AdaptiveColors::default(),
}
}
/// Wraps text to fit within a maximum width.
///
/// This function performs word wrapping, breaking lines at word boundaries
/// when possible. Very long words that exceed the width are broken mid-word.
fn wrap_text(text: &str, max_width: usize) -> Vec<String> {
if max_width == 0 {
return vec![text.to_string()];
}
let mut result = Vec::new();
for line in text.lines() {
if line.is_empty() {
result.push(String::new());
continue;
}
// Check if line fits as-is (fast path)
if line.chars().count() <= max_width {
result.push(line.to_string());
continue;
}
// Word wrap the line
let mut current_line = String::new();
let mut current_width = 0;
for word in line.split_whitespace() {
let word_width = word.chars().count();
if current_line.is_empty() {
// First word on line
if word_width <= max_width {
current_line = word.to_string();
current_width = word_width;
} else {
// Word is too long - break it
let mut chars = word.chars().peekable();
while chars.peek().is_some() {
let chunk: String = chars.by_ref().take(max_width).collect();
if !chunk.is_empty() {
result.push(chunk);
}
}
}
} else if current_width + 1 + word_width <= max_width {
// Word fits on current line
current_line.push(' ');
current_line.push_str(word);
current_width += 1 + word_width;
} else {
// Word doesn't fit - start new line
result.push(current_line);
if word_width <= max_width {
current_line = word.to_string();
current_width = word_width;
} else {
// Word is too long - break it
current_line = String::new();
current_width = 0;
let mut chars = word.chars().peekable();
while chars.peek().is_some() {
let chunk: String = chars.by_ref().take(max_width).collect();
let chunk_len = chunk.chars().count();
if chunk_len == max_width {
result.push(chunk);
} else {
// Last chunk - keep for next word
current_line = chunk;
current_width = chunk_len;
}
}
}
}
}
if !current_line.is_empty() {
result.push(current_line);
}
}
// Ensure we have at least one line (for empty input)
if result.is_empty() {
result.push(String::new());
}
result
}
/// Renders a single message to lines.
fn render_message(&self, msg: &Message, width: u16) -> Vec<Line<'static>> {
let mut lines = Vec::new();
// Colors for user messages
let light_green = Color::Rgb(0x80, 0xFF, 0xD0); // Vert clair pour texte utilisateur
match msg.role {
MessageRole::User => {
// "> message" - prefix vert accent, texte vert clair
let prefix = Span::styled("> ", Style::default().fg(self.colors.accent));
// Calculate available width for text (after "> " prefix)
let text_width = (width as usize).saturating_sub(3); // "> " + margin
// Wrap text and render each line
let wrapped_lines = Self::wrap_text(&msg.content, text_width);
for (i, line_content) in wrapped_lines.iter().enumerate() {
if i == 0 {
lines.push(Line::from(vec![
prefix.clone(),
Span::styled(line_content.clone(), Style::default().fg(light_green)),
]));
} else {
lines.push(Line::from(vec![
Span::raw(" "), // Indent continuation (2 spaces = "> " length)
Span::styled(line_content.clone(), Style::default().fg(light_green)),
]));
}
}
}
MessageRole::Assistant => {
// Use full markdown renderer
use cortex_core::markdown::MarkdownRenderer;
// Create renderer with width
let content_width = width.saturating_sub(4) as u16; // Leave margin
let renderer = MarkdownRenderer::new().with_width(content_width);
// Render markdown content
let mut rendered_lines = renderer.render(&msg.content);
// Add streaming cursor if still streaming
if msg.is_streaming {
if let Some(last) = rendered_lines.last_mut() {
last.spans
.push(Span::styled("▌", Style::default().fg(self.colors.accent)));
}
}
lines.extend(rendered_lines);
}
MessageRole::System => {
// Detect error messages - no prefix, show in error color
let is_error = msg.content.contains("Check your")
|| msg.content.contains("Access denied")
|| msg.content.contains("timed out")
|| msg.content.contains("failed")
|| msg.content.contains("Invalid")
|| msg.content.contains("limit")
|| msg.content.starts_with("Error:");
let (prefix, text_color) = if is_error {
// Error messages: no prefix, use error color
(Span::raw(""), self.colors.error)
} else {
// Info messages: [i] prefix, use muted color
(
Span::styled("[i] ", Style::default().fg(self.colors.text_muted)),
self.colors.text_muted,
)
};
// Calculate available width for text
let prefix_width = if is_error { 0 } else { 2 };
let text_width = (width as usize).saturating_sub(prefix_width + 1);
// Wrap text and render each line
let wrapped_lines = Self::wrap_text(&msg.content, text_width);
for (i, line_content) in wrapped_lines.iter().enumerate() {
if i == 0 {
let mut spans = Vec::new();
if !is_error {
spans.push(prefix.clone());
}
spans.push(Span::styled(
line_content.clone(),
Style::default().fg(text_color),
));
lines.push(Line::from(spans));
} else {
let indent = if is_error { "" } else { " " };
lines.push(Line::from(vec![
Span::raw(indent.to_string()),
Span::styled(line_content.clone(), Style::default().fg(text_color)),
]));
}
}
}
MessageRole::Tool => {
// "[>] tool_name: result"
let prefix = Span::styled("[>] ", Style::default().fg(self.colors.accent));
let tool_name = msg.tool_name.as_deref().unwrap_or("tool");
let name_span = Span::styled(
format!("{}: ", tool_name),
Style::default().fg(self.colors.text_dim),
);
// Truncate content for tool results
let max_content = 100;
let content = if msg.content.len() > max_content {
format!("{}...", &msg.content[..max_content])
} else {
msg.content.clone()
};
lines.push(Line::from(vec![
prefix,
name_span,
Span::styled(content, Style::default().fg(self.colors.text_muted)),
]));
}
}
// Add blank line after each message for spacing
lines.push(Line::from(""));
lines
}
/// Renders a single tool call with status indicator
fn render_tool_call(&self, call: &ToolCallDisplay) -> Vec<Line<'static>> {
use crate::ui::consts::TOOL_SPINNER_FRAMES;
let mut lines = Vec::new();
// Status indicator with color - animated spinner for Running status
let (dot, dot_color) = match call.status {
ToolStatus::Pending => ("○".to_string(), self.colors.warning),
ToolStatus::Running => {
// Animated spinner using half-circle frames
let frame = TOOL_SPINNER_FRAMES[call.spinner_frame % TOOL_SPINNER_FRAMES.len()];
(frame.to_string(), self.colors.accent)
}
ToolStatus::Completed => ("●".to_string(), self.colors.success),
ToolStatus::Failed => ("●".to_string(), self.colors.error),
};
// Line 1: ◐ ToolName summary_args (truncate summary to avoid overflow)
let summary = crate::views::tool_call::format_tool_summary(&call.name, &call.arguments);
let max_summary = 60_usize.saturating_sub(call.name.len());
let summary_truncated = if summary.len() > max_summary {
format!(
"{}...",
&summary
.chars()
.take(max_summary.saturating_sub(3))
.collect::<String>()
)
} else {
summary
};
lines.push(Line::from(vec![
Span::styled(dot, Style::default().fg(dot_color)),
Span::raw(" "),
Span::styled(
call.name.clone(),
Style::default()
.fg(self.colors.accent)
.add_modifier(Modifier::BOLD),
),
Span::raw(" "),
Span::styled(summary_truncated, Style::default().fg(self.colors.text_dim)),
]));
// Live output lines (for Running status with output)
if call.status == ToolStatus::Running && !call.live_output.is_empty() {
for output_line in &call.live_output {
// Truncate long lines to fit display
let truncated = if output_line.len() > 70 {
format!("{}...", &output_line.chars().take(67).collect::<String>())
} else {
output_line.clone()
};
lines.push(Line::from(vec![
Span::styled(" │ ", Style::default().fg(self.colors.text_muted)),
Span::styled(truncated, Style::default().fg(self.colors.text_dim)),
]));
}
}
// Result summary line (if completed/failed) - truncate to avoid overflow
if let Some(ref result) = call.result {
let result_color = if result.success {
self.colors.text_dim
} else {
self.colors.error
};
let summary_truncated = if result.summary.len() > 70 {
format!(
"{}...",
&result.summary.chars().take(67).collect::<String>()
)
} else {
result.summary.clone()
};
lines.push(Line::from(vec![
Span::raw(" ⎿ "),
Span::styled(summary_truncated, Style::default().fg(result_color)),
]));
// If error and not collapsed, show full error
if !result.success && !call.collapsed {
for err_line in result.output.lines().take(5) {
lines.push(Line::from(vec![
Span::raw(" "),
Span::styled(err_line.to_string(), Style::default().fg(self.colors.error)),
]));
}
}
}
// Expanded view (if not collapsed and has result)
if !call.collapsed && call.result.is_some() {
// Show arguments
lines.push(Line::from(Span::styled(
" Arguments:",
Style::default().fg(self.colors.text_dim),
)));
if let Ok(args_str) = serde_json::to_string_pretty(&call.arguments) {
for arg_line in args_str.lines().take(10) {
lines.push(Line::from(vec![
Span::raw(" "),
Span::styled(arg_line.to_string(), Style::default().fg(self.colors.text)),
]));
}
}
}
lines.push(Line::from("")); // Spacing
lines
}
/// Renders a subagent task with todos in Factory-style format
///
/// Format:
/// ```text
/// ● Task {agent_type}
/// ⎿ [pending] task1
/// [in_progress] task2
/// [completed] task3
/// ```
fn render_subagent(&self, task: &SubagentTaskDisplay) -> Vec<Line<'static>> {
use crate::app::SubagentTodoStatus;
let mut lines = Vec::new();
// Status indicator with color
let (indicator, indicator_color) = match &task.status {
SubagentDisplayStatus::Starting
| SubagentDisplayStatus::Thinking
| SubagentDisplayStatus::ExecutingTool(_) => ("●", self.colors.accent),
SubagentDisplayStatus::Completed => ("●", self.colors.success),
SubagentDisplayStatus::Failed => ("●", self.colors.error),
};
// Line 1: ● Task {agent_type}
lines.push(Line::from(vec![
Span::styled(indicator, Style::default().fg(indicator_color)),
Span::raw(" "),
Span::styled(
format!("Task {}", task.agent_type),
Style::default()
.fg(self.colors.accent)
.add_modifier(Modifier::BOLD),
),
]));
// Display error message if task failed
if task.status == SubagentDisplayStatus::Failed {
if let Some(ref error_msg) = task.error_message {
lines.push(Line::from(vec![
Span::styled(" ⎿ ", Style::default().fg(self.colors.text_muted)),
Span::styled("Error: ", Style::default().fg(self.colors.error)),
]));
// Display error message, truncate if too long
for (i, err_line) in error_msg.lines().take(5).enumerate() {
let truncated = if err_line.len() > 70 {
format!("{}...", &err_line.chars().take(67).collect::<String>())
} else {
err_line.to_string()
};
let prefix = if i == 0 { " " } else { " " };
lines.push(Line::from(vec![
Span::styled(prefix, Style::default().fg(self.colors.text_muted)),
Span::styled(truncated, Style::default().fg(self.colors.error)),
]));
}
} else {
// Fallback: no error message provided
lines.push(Line::from(vec![
Span::styled(" ⎿ ", Style::default().fg(self.colors.text_muted)),
Span::styled("Task failed", Style::default().fg(self.colors.error)),
]));
}
} else if !task.todos.is_empty() {
// Display todos if any - use ⎿ prefix for first, space for rest
for (i, todo) in task.todos.iter().enumerate() {
let (status_text, status_color) = match todo.status {
SubagentTodoStatus::Completed => ("[completed]", self.colors.success),
SubagentTodoStatus::InProgress => ("[in_progress]", self.colors.accent),
SubagentTodoStatus::Pending => ("[pending]", self.colors.text_muted),
};
// Truncate long todo content
let content = if todo.content.len() > 50 {
format!("{}...", &todo.content.chars().take(47).collect::<String>())
} else {
todo.content.clone()
};
// First line uses ⎿, rest use indentation
let prefix = if i == 0 { " ⎿ " } else { " " };
lines.push(Line::from(vec![
Span::styled(prefix, Style::default().fg(self.colors.text_muted)),
Span::styled(status_text, Style::default().fg(status_color)),
Span::styled(" ", Style::default()),
Span::styled(content, Style::default().fg(self.colors.text_dim)),
]));
}
} else {
// No todos yet - show current activity with ⎿ (truncate if too long)
let activity = if task.current_activity.is_empty() {
"Initializing...".to_string()
} else if task.current_activity.len() > 70 {
format!(
"{}...",
&task.current_activity.chars().take(67).collect::<String>()
)
} else {
task.current_activity.clone()
};
lines.push(Line::from(vec![
Span::styled(" ⎿ ", Style::default().fg(self.colors.text_muted)),
Span::styled(activity, Style::default().fg(self.colors.text_dim)),
]));
}
lines.push(Line::from("")); // Spacing
lines
}
/// Renders the chat area with welcome cards as part of scrollable content.
fn render_chat_with_welcome(&self, area: Rect, buf: &mut Buffer) {
if area.is_empty() {
return;
}
// Welcome card heights: 1 (top margin) + 11 (welcome card) + 1 (gap) + 5 (info cards) = 18
let welcome_height = 18_u16;
// Calculate total content height: welcome cards + messages
let has_messages =
!self.app_state.messages.is_empty() || self.app_state.streaming.is_streaming;
if !has_messages {
// Only welcome cards, render them at top with 1 line margin
let welcome_area = Rect::new(
area.x,
area.y + 1,
area.width,
welcome_height.min(area.height.saturating_sub(1)),
);
self.render_motd(welcome_area, buf);
return;
}
// We have messages - render welcome cards first, then messages below
// For now, render welcome cards at top, messages below
// TODO: implement proper scrolling through welcome + messages
let scroll_offset = self.app_state.chat_scroll;
// If scrolled past welcome cards, only show messages
if scroll_offset > 0 {
// Render only messages (welcome cards scrolled out of view)
self.render_messages_only(area, buf);
} else {
// Show welcome cards at top, messages below
let welcome_area = Rect::new(
area.x,
area.y + 1,
area.width,
welcome_height.min(area.height.saturating_sub(1)),
);
self.render_motd(welcome_area, buf);
// Render messages below welcome cards
let messages_y = area.y + 1 + welcome_height + 1; // 1 margin + welcome + 1 gap
if messages_y < area.y + area.height {
let messages_area = Rect::new(
area.x,
messages_y,
area.width,
area.height.saturating_sub(welcome_height + 2),
);
self.render_messages_only(messages_area, buf);
}
}
}
/// Renders all scrollable content (welcome cards + messages) as unified lines.
/// Returns the actual content height rendered (for dynamic input positioning).
fn render_scrollable_content(&self, area: Rect, buf: &mut Buffer, _welcome_height: u16) -> u16 {
if area.is_empty() || area.height == 0 {
return 0;
}
let mut all_lines: Vec<Line<'static>> = Vec::new();
// 1. Generate welcome card lines (same visual style as render_motd)
all_lines.extend(self.generate_welcome_lines(area.width));
// 2. Gap after welcome
all_lines.push(Line::from(""));
all_lines.push(Line::from(""));
// 3. Generate message lines
all_lines.extend(self.generate_message_lines(area.width));
let total_lines = all_lines.len();
let visible_lines = area.height as usize;
// Calculate scroll bounds
let max_scroll = total_lines.saturating_sub(visible_lines);
let scroll_offset = self.app_state.chat_scroll.min(max_scroll);
// Calculate visible window
let start = if total_lines > visible_lines {
total_lines - visible_lines - scroll_offset
} else {
0
};
let end = (start + visible_lines).min(total_lines);
// Render the visible portion
let visible: Vec<Line<'static>> = all_lines[start..end].to_vec();
let paragraph = Paragraph::new(visible);
paragraph.render(area, buf);
// Render scrollbar if needed
if total_lines > visible_lines {
self.render_scrollbar(
area,
buf,
total_lines,
scroll_offset,
max_scroll,
visible_lines,
);
}
// Render "go to bottom" indicator if not at bottom
if !self.app_state.is_chat_at_bottom() && total_lines > visible_lines {
self.render_scroll_to_bottom_hint(area, buf);
}
// Return actual content height (capped at area height)
(total_lines as u16).min(area.height)
}
/// Generates welcome card as styled lines using TUI components.
fn generate_welcome_lines(&self, width: u16) -> Vec<Line<'static>> {
let mut lines: Vec<Line<'static>> = Vec::new();
// Get user info
let user_name = self.app_state.user_name.as_deref().unwrap_or("User");
let org_name = self.app_state.org_name.as_deref().unwrap_or("Personal");
let cwd = std::env::current_dir()
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "~/".to_string());
// Create welcome card using component
let welcome_card = WelcomeCard::new()
.user_name(user_name)
.subtitle("Your AI-powered coding assistant.")
.version(VERSION)
.tips(&[
"Send /help for available commands.",
"Use Tab for autocomplete. Press Esc to cancel.",
])
.accent_color(self.colors.accent)
.text_color(self.colors.text)
.dim_color(self.colors.text_dim)
.border_color(self.colors.accent);
// Generate lines from welcome card
lines.extend(welcome_card.to_lines(width));
// Gap between cards
lines.push(Line::from(""));
// Create info cards using components
let left_card = InfoCard::new()
.add("Directory", &cwd)
.add("Org", org_name)
.dim_color(self.colors.text_dim)
.text_color(self.colors.text)
.border_color(self.colors.accent);
let right_card = InfoCard::new()
.add("Plan", "Pro")
.add("", "")
.dim_color(self.colors.text_dim)
.text_color(self.colors.text)
.border_color(self.colors.accent);
let info_cards = InfoCardPair::new(left_card, right_card)
.gap(2)
.right_width(25);
// Generate lines from info cards
lines.extend(info_cards.to_lines(width));
lines
}
/// Generates message lines for scrollable content.
fn generate_message_lines(&self, width: u16) -> Vec<Line<'static>> {
let mut all_lines: Vec<Line<'static>> = Vec::new();
if self.app_state.messages.is_empty()
&& !self.app_state.streaming.is_streaming
&& self.app_state.content_segments.is_empty()
{
return all_lines;
}
// Determine what content we have for display
let has_tool_calls = !self.app_state.tool_calls.is_empty();
let has_content_segments = !self.app_state.content_segments.is_empty();
let last_is_assistant = self
.app_state
.messages
.last()
.map(|m| m.role == cortex_core::widgets::MessageRole::Assistant)
.unwrap_or(false);
// If we have content segments, skip the last assistant message (it's in the segments)
let messages_to_render = if has_content_segments && last_is_assistant {
let len = self.app_state.messages.len();
&self.app_state.messages[..len.saturating_sub(1)]
} else {
&self.app_state.messages[..]
};
for msg in messages_to_render.iter() {
all_lines.extend(self.render_message(msg, width));
}
// Get streaming content if any
let streaming_content = if self.app_state.streaming.is_streaming {
self.app_state
.typewriter
.as_ref()
.map(|tw| tw.visible_text().to_string())
.filter(|s| !s.is_empty())
} else {
None
};
// Render content segments (interleaved text and tool calls)
if has_content_segments {
let mut sorted_segments: Vec<_> = self.app_state.content_segments.iter().collect();
sorted_segments.sort_by_key(|s| s.sequence());
for segment in sorted_segments {
match segment {
ContentSegment::Text { content, .. } => {
all_lines.extend(self.render_text_content(content, width));
}
ContentSegment::ToolCall { tool_call_id, .. } => {
if let Some(call) = self
.app_state
.tool_calls
.iter()
.find(|c| &c.id == tool_call_id)
{
all_lines.extend(self.render_tool_call(call));
}
}
}
}
if self.app_state.streaming.is_streaming {
let pending_text = &self.app_state.pending_text_segment;
if !pending_text.is_empty() {
all_lines.extend(self.render_streaming_content(pending_text, width));
}
}
} else if has_tool_calls {
let mut sorted_calls: Vec<_> = self.app_state.tool_calls.iter().collect();
sorted_calls.sort_by_key(|c| c.sequence);
if let Some(ref content) = streaming_content {
all_lines.extend(self.render_streaming_content(content, width));
}
for call in &sorted_calls {
all_lines.extend(self.render_tool_call(call));
}
} else if let Some(ref content) = streaming_content {
all_lines.extend(self.render_streaming_content(content, width));
}
// Render active subagents
for task in &self.app_state.active_subagents {
all_lines.extend(self.render_subagent(task));
}
all_lines
}
/// Renders only the chat messages (no welcome cards) - legacy function for compatibility.
fn render_messages_only(&self, area: Rect, buf: &mut Buffer) {
if area.is_empty() || area.height == 0 {
return;
}
let all_lines = self.generate_message_lines(area.width);
let total_lines = all_lines.len();
let visible_lines = area.height as usize;
if total_lines == 0 {
return;
}
let max_scroll = total_lines.saturating_sub(visible_lines);
let scroll_offset = self.app_state.chat_scroll.min(max_scroll);
let start = if total_lines > visible_lines {
total_lines - visible_lines - scroll_offset
} else {
0
};
let end = (start + visible_lines).min(total_lines);
// Render the visible portion
let visible: Vec<Line<'static>> = all_lines[start..end].to_vec();
let paragraph = Paragraph::new(visible);
paragraph.render(area, buf);
// Note: Selection highlight is now applied globally in event_loop.rs
// to support selection across the entire screen, not just chat area.
// Render scrollbar if visible (with fade effect)
// Pass scroll_offset and max_scroll for correct thumb position
self.render_scrollbar(
area,
buf,
total_lines,
scroll_offset,
max_scroll,
visible_lines,
);
// Render "go to bottom" indicator if not at bottom
if !self.app_state.is_chat_at_bottom() && total_lines > visible_lines {
self.render_scroll_to_bottom_hint(area, buf);
}
}
/// Renders the input area.
fn render_input(&self, area: Rect, buf: &mut Buffer) {
if area.is_empty() || area.height < 3 {
return;
}
let dim_style = Style::default().fg(self.colors.text_dim);
// Draw top border
buf.get_mut(area.x, area.y)
.set_char(border::TOP_LEFT)
.set_style(dim_style);
buf.get_mut(area.right() - 1, area.y)
.set_char(border::TOP_RIGHT)
.set_style(dim_style);
for x in (area.x + 1)..(area.right() - 1) {
buf.get_mut(x, area.y)
.set_char(border::HORIZONTAL)
.set_style(dim_style);
}
// Show queue indicator if there are pending messages
let queue_count = self.app_state.queued_count();
if queue_count > 0 {
let indicator = format!("[{} pending]", queue_count);
let indicator_x = area.right().saturating_sub(indicator.len() as u16 + 2);
if indicator_x > area.x + 1 {
buf.set_string(
indicator_x,
area.y,
&indicator,
Style::default().fg(self.colors.warning),
);
}
}
// Draw bottom border
buf.get_mut(area.x, area.bottom() - 1)
.set_char(border::BOTTOM_LEFT)
.set_style(dim_style);
buf.get_mut(area.right() - 1, area.bottom() - 1)
.set_char(border::BOTTOM_RIGHT)
.set_style(dim_style);
for x in (area.x + 1)..(area.right() - 1) {
buf.get_mut(x, area.bottom() - 1)
.set_char(border::HORIZONTAL)
.set_style(dim_style);
}
// Draw side borders
buf.get_mut(area.x, area.y + 1)
.set_char(border::VERTICAL)
.set_style(dim_style);
buf.get_mut(area.right() - 1, area.y + 1)
.set_char(border::VERTICAL)
.set_style(dim_style);
// Get input text from app_state
let input_text = self.app_state.input.text();
// Calculate cursor visibility
let show_cursor = (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
/ CURSOR_BLINK_INTERVAL_MS)
% 2
== 0;
// Content area is inside the box (1 char padding on left/right + 1 space padding)
// Layout: "│ > content ▌ │"
// Start x = area.x + 2 (border + space)
let content_x = area.x + 2;
let content_y = area.y + 1;
let content_width = area.width.saturating_sub(4); // 2 borders + 2 spaces padding
// Simple prompt: "> "
let prompt_span = Span::styled("> ", Style::default().fg(self.colors.accent));
let text_span = Span::styled(
input_text.to_string(),
Style::default().fg(self.colors.text),
);
let mut spans = vec![prompt_span, text_span];
if show_cursor {
spans.push(Span::styled("▌", Style::default().fg(self.colors.accent)));
}
let line = Line::from(spans);
// Use paragraph to render text inside the box
// We only show the visible part if it overflows
// For simplicity, we just render it. A proper text input widget would handle scrolling.
// Assuming CortexInput handles some of this, but here we just render the string.
// To prevent overflow rendering over the right border, we might need to truncate or scroll manually?
// But for now, let's just render it. The paragraph will clip if we set the area correctly.
let text_area = Rect::new(content_x, content_y, content_width, 1);
let paragraph = Paragraph::new(line);
paragraph.render(text_area, buf);
}
/// Returns the cursor position for the input field.
pub fn cursor_position(&self, input_area: Rect) -> Option<(u16, u16)> {
// Cursor is after "> " prefix (2 chars) plus the input text
// Input starts at input_area.x + 2 (border + space)
// Text starts after prompt "> " (length 2)
// So cursor is at input_area.x + 2 + 2 + cursor_pos
let cursor_pos = self.app_state.input.cursor_pos();
// x = area.x + border(1) + space(1) + prompt(2) + cursor_pos
let x = input_area.x + 4 + cursor_pos as u16;
let y = input_area.y + 1; // Middle line
if x < input_area.right() - 2 {
// Ensure inside right border
Some((x, y))
} else {
None
}
}
/// Returns whether a task is currently running.
fn is_task_running(&self) -> bool {
self.app_state.streaming.is_streaming
|| self.app_state.streaming.is_tool_executing()
|| self.app_state.streaming.is_delegating
|| self.app_state.has_active_subagents()
}
/// Returns the status header text based on current state.
fn status_header(&self) -> String {
// Check for delegation/subagent first (highest priority)
if self.app_state.streaming.is_delegating || self.app_state.has_active_subagents() {
"Delegation".to_string()
} else if self.app_state.streaming.is_tool_executing() {
let tool_name = self
.app_state
.streaming
.executing_tool
.as_deref()
.unwrap_or("tool");
format!("Executing {}", tool_name)
} else if self.app_state.streaming.thinking && self.app_state.thinking_budget.is_some() {
"Thinking".to_string()
} else if self.app_state.streaming.is_streaming {
"Working".to_string()
} else {
"Idle".to_string()
}
}
/// Renders a thin scrollbar on the right side with fade effect.
fn render_scrollbar(
&self,
area: Rect,
buf: &mut Buffer,
total_lines: usize,
scroll_offset: usize,
max_scroll: usize,
visible_lines: usize,
) {
// Get opacity for fade effect
let opacity = self.app_state.scrollbar_opacity();
if opacity <= 0.0 {
return;
}
// No scrollbar needed if content fits
if total_lines <= visible_lines || max_scroll == 0 {