-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.rs
More file actions
1408 lines (1257 loc) · 43.2 KB
/
app.rs
File metadata and controls
1408 lines (1257 loc) · 43.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
use crate::permissions::PermissionMode;
use crate::question::QuestionState;
use crate::selection::TextSelection;
use crate::views::tool_call::{ContentSegment, ToolCallDisplay, ToolResultDisplay, ToolStatus};
use crate::widgets::ToastManager;
use cortex_core::{
animation::{Pulse, Spinner, Typewriter},
widgets::{CortexInput, Message},
};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use uuid::Uuid;
/// The current view/screen being displayed
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AppView {
#[default]
Session,
Approval,
Questions,
Settings,
Help,
}
/// Which UI element currently has focus
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FocusTarget {
#[default]
Input,
Chat,
Sidebar,
Modal,
}
/// State for streaming responses
#[derive(Debug, Clone, Default)]
pub struct StreamingState {
pub is_streaming: bool,
pub current_tool: Option<String>,
pub tool_status: Option<String>,
pub thinking: bool,
/// When the current task started (for elapsed time display)
pub task_started_at: Option<Instant>,
/// Name of the tool currently executing in background (for visual indicator)
pub executing_tool: Option<String>,
/// When the tool started executing (for elapsed time display)
pub tool_started_at: Option<Instant>,
}
impl StreamingState {
pub fn start(&mut self, tool: Option<String>) {
self.is_streaming = true;
self.thinking = true;
self.current_tool = tool;
self.task_started_at = Some(Instant::now());
}
/// Get the elapsed seconds since the task started
pub fn elapsed_seconds(&self) -> u64 {
self.task_started_at
.map(|t| t.elapsed().as_secs())
.unwrap_or(0)
}
/// Reset streaming state when task completes
pub fn stop(&mut self) {
self.is_streaming = false;
self.thinking = false;
self.current_tool = None;
self.tool_status = None;
self.task_started_at = None;
}
/// Start tool execution in background
pub fn start_tool_execution(&mut self, tool_name: String) {
self.executing_tool = Some(tool_name);
self.tool_started_at = Some(Instant::now());
}
/// Clear tool execution state
pub fn stop_tool_execution(&mut self) {
self.executing_tool = None;
self.tool_started_at = None;
}
/// Check if a tool is currently executing
pub fn is_tool_executing(&self) -> bool {
self.executing_tool.is_some()
}
/// Get the elapsed seconds since tool started executing
pub fn tool_elapsed_seconds(&self) -> u64 {
self.tool_started_at
.map(|t| t.elapsed().as_secs())
.unwrap_or(0)
}
}
/// Mode for tool approval
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ApprovalMode {
#[default]
Ask,
AllowSession,
AllowAlways,
}
/// State for pending tool approval
#[derive(Debug, Clone, Default)]
pub struct ApprovalState {
/// Unique ID for this tool call (from the LLM)
pub tool_call_id: String,
pub tool_name: String,
pub tool_args: String,
/// Parsed arguments for execution
pub tool_args_json: Option<serde_json::Value>,
pub diff_preview: Option<String>,
pub approval_mode: ApprovalMode,
}
impl ApprovalState {
/// Creates a new ApprovalState with the given tool name and arguments.
pub fn new(tool_name: String, tool_args: serde_json::Value) -> Self {
Self {
tool_call_id: String::new(),
tool_name,
tool_args: serde_json::to_string_pretty(&tool_args).unwrap_or_default(),
tool_args_json: Some(tool_args),
diff_preview: None,
approval_mode: ApprovalMode::default(),
}
}
/// Creates an ApprovalState with a specific tool call ID.
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.tool_call_id = id.into();
self
}
/// Adds a diff preview to the approval state.
pub fn with_diff(mut self, diff: String) -> Self {
self.diff_preview = Some(diff);
self
}
}
/// State for a pending tool execution waiting for continuation
#[derive(Debug, Clone)]
pub struct PendingToolResult {
/// Tool call ID from the LLM
pub tool_call_id: String,
/// Tool name
pub tool_name: String,
/// Tool output/result
pub output: String,
/// Whether the tool succeeded
pub success: bool,
}
// ============================================================================
// SUBAGENT TASK DISPLAY
// ============================================================================
/// Display state for an active subagent task.
#[derive(Debug, Clone)]
pub struct SubagentTaskDisplay {
/// Subagent session ID.
pub session_id: String,
/// Original tool call ID (for matching response).
pub tool_call_id: String,
/// Task description.
pub description: String,
/// Subagent type (code, research, etc.).
pub agent_type: String,
/// Current status.
pub status: SubagentDisplayStatus,
/// Spinner frame (0-3 for animation).
pub spinner_frame: usize,
/// Current activity description.
pub current_activity: String,
/// Tool calls made by this subagent: (name, success).
pub tool_calls: Vec<(String, bool)>,
/// Last output preview (first 200 chars).
pub output_preview: String,
/// Start time.
pub started_at: Instant,
}
impl SubagentTaskDisplay {
/// Create a new subagent task display.
pub fn new(
session_id: impl Into<String>,
tool_call_id: impl Into<String>,
description: impl Into<String>,
agent_type: impl Into<String>,
) -> Self {
Self {
session_id: session_id.into(),
tool_call_id: tool_call_id.into(),
description: description.into(),
agent_type: agent_type.into(),
status: SubagentDisplayStatus::Starting,
spinner_frame: 0,
current_activity: "Initializing...".to_string(),
tool_calls: Vec::new(),
output_preview: String::new(),
started_at: Instant::now(),
}
}
/// Get elapsed time since start.
pub fn elapsed(&self) -> Duration {
self.started_at.elapsed()
}
}
/// Status of a subagent task for display.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubagentDisplayStatus {
/// Subagent is initializing.
Starting,
/// Subagent is thinking/generating.
Thinking,
/// Subagent is executing a tool.
ExecutingTool(String),
/// Subagent completed successfully.
Completed,
/// Subagent failed.
Failed,
}
impl SubagentDisplayStatus {
/// Get a short description of the status.
pub fn description(&self) -> String {
match self {
Self::Starting => "Starting...".to_string(),
Self::Thinking => "Thinking...".to_string(),
Self::ExecutingTool(name) => format!("Running {}", name),
Self::Completed => "Completed".to_string(),
Self::Failed => "Failed".to_string(),
}
}
/// Check if this is a terminal status.
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Completed | Self::Failed)
}
}
/// Trigger type for autocomplete
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutocompleteTrigger {
Command,
Mention,
}
/// An item in the autocomplete list
#[derive(Debug, Clone)]
pub struct AutocompleteItem {
pub value: String,
pub label: String,
pub description: String,
pub icon: char,
pub category: String,
}
impl AutocompleteItem {
pub fn new(
value: impl Into<String>,
label: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self {
value: value.into(),
label: label.into(),
description: description.into(),
icon: ' ',
category: String::new(),
}
}
pub fn with_icon(mut self, icon: char) -> Self {
self.icon = icon;
self
}
pub fn with_category(mut self, category: impl Into<String>) -> Self {
self.category = category.into();
self
}
}
/// State for the autocomplete popup
#[derive(Debug, Clone, Default)]
pub struct AutocompleteState {
pub visible: bool,
pub trigger: Option<AutocompleteTrigger>,
pub query: String,
pub trigger_position: usize,
pub items: Vec<AutocompleteItem>,
pub selected: usize,
pub max_visible: usize,
pub scroll_offset: usize,
}
impl AutocompleteState {
pub fn new() -> Self {
Self {
visible: false,
trigger: None,
query: String::new(),
trigger_position: 0,
items: Vec::new(),
selected: 0,
max_visible: 8,
scroll_offset: 0,
}
}
/// Select the previous item in the list
pub fn select_prev(&mut self) {
if self.items.is_empty() {
return;
}
if self.selected == 0 {
// Wrap to end
self.selected = self.items.len() - 1;
// Scroll to show the last items
if self.items.len() > self.max_visible {
self.scroll_offset = self.items.len() - self.max_visible;
}
} else {
self.selected -= 1;
// Adjust scroll offset to keep selected item visible
if self.selected < self.scroll_offset {
self.scroll_offset = self.selected;
}
}
}
/// Select the next item in the list
pub fn select_next(&mut self) {
if self.items.is_empty() {
return;
}
self.selected = (self.selected + 1) % self.items.len();
// Adjust scroll offset to keep selected item visible
if self.selected == 0 {
// Wrapped around to start
self.scroll_offset = 0;
} else if self.selected >= self.scroll_offset + self.max_visible {
self.scroll_offset = self.selected - self.max_visible + 1;
}
}
/// Get the completion text for the currently selected item
pub fn completion_text(&self) -> Option<&str> {
self.items
.get(self.selected)
.map(|item| item.value.as_str())
}
/// Hide the autocomplete popup and reset state
pub fn hide(&mut self) {
self.visible = false;
self.items.clear();
self.selected = 0;
self.scroll_offset = 0;
self.query.clear();
self.trigger = None;
}
/// Check if there are any items in the list
pub fn has_items(&self) -> bool {
!self.items.is_empty()
}
/// Get the currently visible items based on scroll offset
pub fn visible_items(&self) -> &[AutocompleteItem] {
let start = self.scroll_offset;
let end = (start + self.max_visible).min(self.items.len());
&self.items[start..end]
}
/// Show the autocomplete popup with a trigger
pub fn show(&mut self, trigger: AutocompleteTrigger, position: usize) {
self.visible = true;
self.trigger = Some(trigger);
self.trigger_position = position;
self.query.clear();
self.selected = 0;
self.scroll_offset = 0;
}
/// Set the filter query
pub fn set_query(&mut self, query: &str) {
self.query = query.to_string();
self.selected = 0;
self.scroll_offset = 0;
}
/// Set the list of items
pub fn set_items(&mut self, items: Vec<AutocompleteItem>) {
self.items = items;
self.selected = 0;
self.scroll_offset = 0;
}
}
/// Summary of a session for the sidebar
#[derive(Debug, Clone)]
pub struct SessionSummary {
pub id: Uuid,
pub title: String,
pub last_message: String,
pub timestamp: chrono::DateTime<chrono::Utc>,
pub message_count: usize,
}
impl SessionSummary {
/// Create a new session summary with minimal info
pub fn new(id: Uuid, title: String) -> Self {
Self {
id,
title,
last_message: String::new(),
timestamp: chrono::Utc::now(),
message_count: 0,
}
}
/// Get a human-readable relative time string
pub fn relative_time(&self) -> String {
cortex_protocol::num_format::format_relative_time_compact(self.timestamp)
}
pub fn with_message_count(mut self, count: usize) -> Self {
self.message_count = count;
self
}
pub fn with_timestamp(mut self, timestamp: chrono::DateTime<chrono::Utc>) -> Self {
self.timestamp = timestamp;
self
}
/// Sets the last message preview.
pub fn with_last_message(mut self, message: impl Into<String>) -> Self {
self.last_message = message.into();
self
}
}
/// Currently active modal dialog
#[derive(Debug, Clone)]
pub enum ActiveModal {
Form(crate::widgets::FormState),
ProviderPicker,
ModelPicker,
CommandPalette,
Export,
Fork,
}
/// Main application state
pub struct AppState {
pub view: AppView,
pub previous_view: Option<AppView>,
pub focus: FocusTarget,
pub session_id: Option<Uuid>,
pub messages: Vec<Message>,
pub model: String,
pub provider: String,
pub system_prompt: Option<String>,
pub sidebar_visible: bool,
pub sidebar_width: u16,
pub chat_scroll: usize,
pub sidebar_scroll: usize,
pub scrollbar_visible_until: Option<Instant>,
pub chat_scroll_pinned_bottom: bool,
pub input: CortexInput<'static>,
pub autocomplete: AutocompleteState,
pub streaming: StreamingState,
pub typewriter: Option<Typewriter>,
pub brain_pulse: Pulse,
pub spinner: Spinner,
pub brain_frame: u64,
pub pending_approval: Option<ApprovalState>,
pub session_history: Vec<SessionSummary>,
pub terminal_size: (u16, u16),
pub running: bool,
pub last_ctrl_c: Option<Instant>,
pub active_modal: Option<ActiveModal>,
pub provider_picker: crate::widgets::ProviderPickerState,
pub model_picker: crate::widgets::ModelPickerState,
pub text_selection: TextSelection,
pub toasts: ToastManager,
/// Current permission mode for tool execution
pub permission_mode: PermissionMode,
/// Tool calls being displayed
pub tool_calls: Vec<ToolCallDisplay>,
/// Pending tool results that need to be sent back to the LLM
pub pending_tool_results: Vec<PendingToolResult>,
/// Current thinking budget level (for models that support it)
pub thinking_budget: Option<String>,
/// Event sequence counter for ordering tool calls by arrival
pub event_sequence: u64,
/// Content segments for interleaved text/tool display during streaming
pub content_segments: Vec<ContentSegment>,
/// Accumulated text before the next tool call (for segment creation)
pub pending_text_segment: String,
/// Active question prompt state
pub question_state: Option<QuestionState>,
/// Hovered option in question prompt (for mouse support)
pub question_hovered_option: Option<usize>,
/// Hovered tab in question prompt (for mouse support)
pub question_hovered_tab: Option<usize>,
/// Queue of pending user messages (sent together when system becomes available)
pub message_queue: VecDeque<String>,
/// Active subagent tasks being displayed.
pub active_subagents: Vec<SubagentTaskDisplay>,
/// MCP servers list for management
pub mcp_servers: Vec<crate::modal::mcp_manager::McpServerInfo>,
/// Context files added to the session
pub context_files: Vec<std::path::PathBuf>,
/// Current log level setting
pub log_level: String,
/// Generic settings storage
pub settings: std::collections::HashMap<String, String>,
/// Diff scroll position for approval view
pub diff_scroll: i32,
/// Input mode (normal text input or interactive selection)
pub input_mode: crate::interactive::InputMode,
/// Compact display mode
pub compact_mode: bool,
/// Debug mode enabled
pub debug_mode: bool,
/// Sandbox mode (restricted execution)
pub sandbox_mode: bool,
/// Temperature for model sampling
pub temperature: f32,
/// Max tokens for model output
pub max_tokens: Option<u32>,
/// Command history for /history
pub command_history: Vec<String>,
// Extended settings
/// Show timestamps on messages
pub timestamps_enabled: bool,
/// Show line numbers in code blocks
pub line_numbers_enabled: bool,
/// Word wrap enabled
pub word_wrap_enabled: bool,
/// Syntax highlighting enabled
pub syntax_highlight_enabled: bool,
/// Auto scroll to new messages
pub auto_scroll_enabled: bool,
/// Sound notifications enabled
pub sound_enabled: bool,
/// Context-aware mode (include open files)
pub context_aware_enabled: bool,
/// Add as co-author on commits
pub co_author_enabled: bool,
/// Auto-suggest commits after changes
pub auto_commit_enabled: bool,
/// Sign commits with GPG
pub sign_commits_enabled: bool,
/// Cloud sync for sessions
pub cloud_sync_enabled: bool,
/// Auto-save sessions
pub auto_save_enabled: bool,
/// Keep session history
pub session_history_enabled: bool,
/// Telemetry enabled
pub telemetry_enabled: bool,
/// Analytics enabled
pub analytics_enabled: bool,
}
impl AppState {
/// Create a new AppState with default values
pub fn new() -> Self {
Self {
view: AppView::default(),
previous_view: None,
focus: FocusTarget::default(),
session_id: None,
messages: Vec::new(),
model: String::from("gpt-4"),
provider: String::from("openai"),
system_prompt: None,
sidebar_visible: true,
sidebar_width: 30,
chat_scroll: 0,
sidebar_scroll: 0,
scrollbar_visible_until: None,
chat_scroll_pinned_bottom: true,
input: CortexInput::new(),
autocomplete: AutocompleteState::new(),
streaming: StreamingState::default(),
typewriter: None,
brain_pulse: Pulse::new(2000),
spinner: Spinner::dots(),
brain_frame: 0,
pending_approval: None,
session_history: Vec::new(),
terminal_size: (80, 24),
running: true,
last_ctrl_c: None,
active_modal: None,
provider_picker: crate::widgets::ProviderPickerState::new(),
model_picker: crate::widgets::ModelPickerState::new(),
text_selection: TextSelection::new(),
toasts: ToastManager::new(),
permission_mode: PermissionMode::default(),
tool_calls: Vec::new(),
pending_tool_results: Vec::new(),
thinking_budget: None,
event_sequence: 0,
content_segments: Vec::new(),
pending_text_segment: String::new(),
question_state: None,
question_hovered_option: None,
question_hovered_tab: None,
message_queue: VecDeque::new(),
active_subagents: Vec::new(),
mcp_servers: Vec::new(),
context_files: Vec::new(),
log_level: String::from("info"),
settings: std::collections::HashMap::new(),
diff_scroll: 0,
input_mode: crate::interactive::InputMode::Normal,
compact_mode: false,
debug_mode: false,
sandbox_mode: false,
temperature: 0.7,
max_tokens: None,
command_history: Vec::new(),
// Extended settings with sensible defaults
timestamps_enabled: false,
line_numbers_enabled: true,
word_wrap_enabled: true,
syntax_highlight_enabled: true,
auto_scroll_enabled: true,
sound_enabled: false,
context_aware_enabled: true,
co_author_enabled: true,
auto_commit_enabled: false,
sign_commits_enabled: false,
cloud_sync_enabled: false,
auto_save_enabled: true,
session_history_enabled: true,
telemetry_enabled: false,
analytics_enabled: false,
}
}
/// Create AppState with a specific model
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
/// Create AppState with a specific provider
pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
self.provider = provider.into();
self
}
/// Create AppState with a system prompt
pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.system_prompt = Some(prompt.into());
self
}
/// Create AppState with terminal size
pub fn with_terminal_size(mut self, width: u16, height: u16) -> Self {
self.terminal_size = (width, height);
self
}
/// Set the current view
pub fn set_view(&mut self, view: AppView) {
self.previous_view = Some(self.view);
self.view = view;
}
/// Go back to the previous view
pub fn go_back(&mut self) {
if let Some(prev) = self.previous_view.take() {
self.view = prev;
}
}
/// Add a message to the chat
pub fn add_message(&mut self, message: Message) {
self.messages.push(message);
if self.chat_scroll_pinned_bottom {
self.scroll_chat_to_bottom();
}
}
/// Start streaming a response
pub fn start_streaming(&mut self, tool: Option<String>) {
self.streaming.start(tool);
// Use dynamic typewriter that adapts to stream speed
self.typewriter = Some(Typewriter::dynamic(String::new(), 500.0));
}
/// Stop streaming
pub fn stop_streaming(&mut self) {
self.streaming.stop();
}
/// Append content to the last streaming message
pub fn append_streaming_content(&mut self, content: &str) {
if let Some(msg) = self.messages.last_mut() {
msg.content.push_str(content);
}
self.streaming.thinking = false;
}
/// Get the last message
pub fn last_message(&self) -> Option<&Message> {
self.messages.last()
}
/// Get mutable reference to the last message
pub fn last_message_mut(&mut self) -> Option<&mut Message> {
self.messages.last_mut()
}
/// Clear all messages
pub fn clear_messages(&mut self) {
self.messages.clear();
self.chat_scroll = 0;
}
/// Set the focus target
pub fn set_focus(&mut self, focus: FocusTarget) {
self.focus = focus;
}
/// Move focus to the next element
pub fn focus_next(&mut self) {
self.focus = match self.focus {
FocusTarget::Input => FocusTarget::Chat,
FocusTarget::Chat => {
if self.sidebar_visible {
FocusTarget::Sidebar
} else {
FocusTarget::Input
}
}
FocusTarget::Sidebar => FocusTarget::Input,
FocusTarget::Modal => FocusTarget::Modal,
};
}
/// Move focus to the previous element
pub fn focus_prev(&mut self) {
self.focus = match self.focus {
FocusTarget::Input => {
if self.sidebar_visible {
FocusTarget::Sidebar
} else {
FocusTarget::Chat
}
}
FocusTarget::Chat => FocusTarget::Input,
FocusTarget::Sidebar => FocusTarget::Chat,
FocusTarget::Modal => FocusTarget::Modal,
};
}
/// Scroll the chat by a delta amount
pub fn scroll_chat(&mut self, delta: i32) {
if delta < 0 {
self.chat_scroll = self
.chat_scroll
.saturating_sub(delta.unsigned_abs() as usize);
} else {
self.chat_scroll = self.chat_scroll.saturating_add(delta as usize);
}
self.chat_scroll_pinned_bottom = false;
self.show_scrollbar();
}
/// Scroll to the bottom of the chat
pub fn scroll_chat_to_bottom(&mut self) {
self.chat_scroll = 0; // 0 = at bottom (showing newest messages)
self.chat_scroll_pinned_bottom = true;
self.show_scrollbar();
}
/// Scroll to the top of the chat
pub fn scroll_chat_to_top(&mut self) {
self.chat_scroll = usize::MAX; // Large value = scrolled up (showing oldest messages)
self.chat_scroll_pinned_bottom = false;
self.show_scrollbar();
}
/// Check if chat is scrolled to the bottom
pub fn is_chat_at_bottom(&self) -> bool {
self.chat_scroll_pinned_bottom
}
/// Show the scrollbar temporarily
pub fn show_scrollbar(&mut self) {
self.scrollbar_visible_until = Some(Instant::now() + Duration::from_secs(2));
}
/// Check if the scrollbar should be visible
pub fn is_scrollbar_visible(&self) -> bool {
self.scrollbar_visible_until
.map(|until| Instant::now() < until)
.unwrap_or(false)
}
/// Get the scrollbar opacity (for fade effect)
pub fn scrollbar_opacity(&self) -> f32 {
self.scrollbar_visible_until
.map(|until| {
let remaining = until.saturating_duration_since(Instant::now());
let fade_start = Duration::from_millis(500);
if remaining > fade_start {
1.0
} else {
remaining.as_secs_f32() / fade_start.as_secs_f32()
}
})
.unwrap_or(0.0)
}
/// Tick the scrollbar visibility timer
pub fn tick_scrollbar(&mut self) {
if let Some(until) = self.scrollbar_visible_until
&& Instant::now() >= until
{
self.scrollbar_visible_until = None;
}
}
/// Scroll the sidebar
pub fn scroll_sidebar(&mut self, delta: i32) {
if delta < 0 {
self.sidebar_scroll = self
.sidebar_scroll
.saturating_sub(delta.unsigned_abs() as usize);
} else {
self.sidebar_scroll = self.sidebar_scroll.saturating_add(delta as usize);
}
}
/// Toggle sidebar visibility
pub fn toggle_sidebar(&mut self) {
self.sidebar_visible = !self.sidebar_visible;
if !self.sidebar_visible && self.focus == FocusTarget::Sidebar {
self.focus = FocusTarget::Input;
}
}
/// Request approval for a tool
pub fn request_approval(
&mut self,
tool_name: String,
tool_args: String,
diff_preview: Option<String>,
) {
// Try to parse the args as JSON
let tool_args_json = serde_json::from_str(&tool_args).ok();
self.pending_approval = Some(ApprovalState {
tool_call_id: String::new(),
tool_name,
tool_args,
tool_args_json,
diff_preview,
approval_mode: ApprovalMode::Ask,
});
self.set_view(AppView::Approval);
}
/// Request approval for a tool with full details
pub fn request_tool_approval(
&mut self,
tool_call_id: String,
tool_name: String,
tool_args: serde_json::Value,
diff_preview: Option<String>,
) {
self.pending_approval = Some(ApprovalState {
tool_call_id,
tool_name,
tool_args: serde_json::to_string_pretty(&tool_args).unwrap_or_default(),
tool_args_json: Some(tool_args),
diff_preview,
approval_mode: ApprovalMode::Ask,
});
self.set_view(AppView::Approval);
}
/// Approve the pending tool
pub fn approve(&mut self) -> Option<ApprovalState> {
let approval = self.pending_approval.take();
self.go_back();
approval
}
/// Reject the pending tool
pub fn reject(&mut self) -> Option<ApprovalState> {
let approval = self.pending_approval.take();
self.go_back();
approval
}
/// Check if there's a pending approval
pub fn has_pending_approval(&self) -> bool {
self.pending_approval.is_some()
}
/// Start a new session
pub fn new_session(&mut self) {
self.session_id = Some(Uuid::new_v4());
self.clear_messages();
self.set_view(AppView::Session);
}
/// Load an existing session
pub fn load_session(&mut self, session_id: Uuid) {
self.session_id = Some(session_id);
self.set_view(AppView::Session);
}
/// Tick animations and timers
pub fn tick(&mut self) {
self.brain_pulse.tick();
self.spinner.tick();
self.brain_frame = self.brain_frame.wrapping_add(1);
self.tick_scrollbar();
if let Some(ref mut typewriter) = self.typewriter {
typewriter.tick();
}
}
/// Check if currently streaming
pub fn is_streaming(&self) -> bool {
self.streaming.is_streaming
}
/// Check if the system is busy (streaming, executing tool, has pending tool results, or running subagents)
/// Used to determine if new messages should be queued
pub fn is_busy(&self) -> bool {
self.streaming.is_streaming
|| self.streaming.is_tool_executing()
|| !self.pending_tool_results.is_empty()
|| self.has_active_subagents()
}
/// Add a message to the queue
pub fn queue_message(&mut self, message: String) {
if !message.trim().is_empty() {
self.message_queue.push_back(message);
}
}
/// Get number of queued messages
pub fn queued_count(&self) -> usize {
self.message_queue.len()
}
/// Check if there are queued messages
pub fn has_queued_messages(&self) -> bool {
!self.message_queue.is_empty()
}
/// Take all queued messages and combine into one
/// Messages are joined with double newlines
pub fn take_queued_messages(&mut self) -> Option<String> {
if self.message_queue.is_empty() {
return None;
}
let messages: Vec<String> = self.message_queue.drain(..).collect();
Some(messages.join("\n\n"))
}
/// Clear the message queue (for cancellation)
pub fn clear_message_queue(&mut self) {
self.message_queue.clear();
}
/// Get the display name for the current model
pub fn model_display(&self) -> String {
format!("{}/{}", self.provider, self.model)
}
/// Set the terminal size
pub fn set_terminal_size(&mut self, width: u16, height: u16) {
self.terminal_size = (width, height);
}