aethershell 0.3.1

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//! Main TUI Application State and Logic

use anyhow::Result;
use ratatui::widgets::ListState;
use serde::{Deserialize, Serialize};
use tui_input::Input;
use uuid::Uuid;

use super::distributed::DistributedSwarm;
use super::media::MediaFile;
use super::reasoning::{
    GoalSpecification, PlanningGoal, ReasoningCoordinator, ReasoningEngine, TaskPlanner,
};
use crate::ai::a2ui::{A2UIEvent, A2UIEventType, NotificationLevel, A2UI_CHANNEL};
use crate::{ai, env::Env};

#[derive(Debug, Clone, PartialEq)]
pub enum AppMode {
    Chat,
    AgentSwarm,
    MediaBrowser,
    Settings,
    DistributedAgents,
    AdvancedReasoning,
    Search,
}

#[derive(Debug, Clone, PartialEq)]
pub enum InputMode {
    Normal,
    Editing,
}

#[derive(Debug, Clone)]
pub struct ChatMessage {
    pub id: Uuid,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub role: MessageRole,
    pub content: String,
    pub media_attachments: Vec<MediaFile>,
    pub model: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum MessageRole {
    User,
    Assistant,
    System,
}

#[derive(Debug, Clone)]
pub struct AgentInfo {
    pub id: Uuid,
    pub name: String,
    pub model: String,
    pub status: AgentStatus,
    pub current_task: Option<String>,
    pub tools: Vec<String>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub last_activity: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AgentStatus {
    Idle,
    Working,
    Waiting,
    Error(String),
}

/// A2UI notification to display in TUI
#[derive(Debug, Clone)]
pub struct A2UINotification {
    pub id: Uuid,
    pub message: String,
    pub level: NotificationLevel,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub duration_ms: Option<u64>,
}

/// Progress indicator state
#[derive(Debug, Clone)]
pub struct ProgressIndicator {
    pub id: Uuid,
    pub label: String,
    pub current: u64,
    pub total: u64,
    pub message: Option<String>,
}

pub struct App {
    pub should_quit: bool,
    pub mode: AppMode,
    pub input_mode: InputMode,

    // UI State
    pub input: Input,
    pub messages: Vec<ChatMessage>,
    pub agents: Vec<AgentInfo>,
    pub media_files: Vec<MediaFile>,

    // List states for navigation
    pub message_list_state: ListState,
    pub agent_list_state: ListState,
    pub media_list_state: ListState,
    pub tab_index: usize,

    // AetherShell environment
    pub env: Env,

    // Configuration
    pub config: AppConfig,

    // Current selections
    pub selected_media: Vec<usize>, // Indices into media_files
    pub current_model: String,

    // Search state
    pub search_query: String,
    pub search_results: Vec<usize>,
    pub search_result_index: usize,

    // Distributed agents and advanced reasoning
    pub distributed_swarm: Option<DistributedSwarm>,
    pub reasoning_coordinator: ReasoningCoordinator,
    pub active_planning_goal: Option<PlanningGoal>,

    // A2UI State
    pub notifications: Vec<A2UINotification>,
    pub progress_indicators: std::collections::HashMap<Uuid, ProgressIndicator>,
    pub status_bar_text: Option<String>,
    pub pending_prompts: Vec<(Uuid, String, crate::ai::a2ui::PromptType)>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
    pub default_model: String,
    pub max_messages: usize,
    pub auto_scroll: bool,
    pub show_timestamps: bool,
    pub enable_media_preview: bool,
    pub agent_update_interval: u64, // milliseconds
}

impl Default for AppConfig {
    fn default() -> Self {
        // Use configured AI provider or show warning
        let default_model = std::env::var("AETHER_AI").unwrap_or_else(|_| {
            eprintln!("Warning: AETHER_AI not set. AI features will not work.");
            eprintln!("Set AETHER_AI=openai|ollama|compat to enable AI.");
            String::new()
        });

        Self {
            default_model: default_model.clone(),
            max_messages: 1000,
            auto_scroll: true,
            show_timestamps: true,
            enable_media_preview: true,
            agent_update_interval: 1000,
        }
    }
}

impl App {
    pub fn new() -> Result<Self> {
        let mut message_list_state = ListState::default();
        message_list_state.select(Some(0));

        let mut agent_list_state = ListState::default();
        agent_list_state.select(Some(0));

        let mut media_list_state = ListState::default();
        media_list_state.select(Some(0));

        // Get current model from env
        let current_model = std::env::var("AETHER_AI").unwrap_or_default();

        Ok(App {
            should_quit: false,
            mode: AppMode::Chat,
            input_mode: InputMode::Normal,
            input: Input::default(),
            messages: Vec::new(),
            agents: Vec::new(),
            media_files: Vec::new(),
            message_list_state,
            agent_list_state,
            media_list_state,
            tab_index: 0,
            env: Env::new(),
            config: AppConfig::default(),
            selected_media: Vec::new(),
            current_model,
            search_query: String::new(),
            search_results: Vec::new(),
            search_result_index: 0,
            distributed_swarm: None,
            reasoning_coordinator: ReasoningCoordinator {
                reasoning_engine: ReasoningEngine::new(),
                task_planner: TaskPlanner {
                    goal: PlanningGoal {
                        description: "Default planning goal".to_string(),
                        input_data: ai::MultiModalMessage {
                            role: "user".to_string(),
                            content: vec![],
                        },
                        desired_output: GoalSpecification {
                            output_modalities: vec![],
                            quality_requirements: std::collections::HashMap::new(),
                            success_criteria: vec![],
                        },
                        constraints: vec![],
                        deadline: None,
                    },
                    available_agents: vec![],
                    planning_strategy: super::reasoning::PlanningStrategy::ForwardChaining,
                    execution_plan: None,
                },
                active_reasoning_sessions: std::collections::HashMap::new(),
            },
            active_planning_goal: None,
            // A2UI state
            notifications: Vec::new(),
            progress_indicators: std::collections::HashMap::new(),
            status_bar_text: None,
            pending_prompts: Vec::new(),
        })
    }

    pub fn quit(&mut self) {
        self.should_quit = true;
    }

    pub fn switch_mode(&mut self, mode: AppMode) {
        self.mode = mode;
        self.input_mode = InputMode::Normal;
    }

    pub fn next_tab(&mut self) {
        self.tab_index = (self.tab_index + 1) % 7; // 7 modes
        self.mode = match self.tab_index {
            0 => AppMode::Chat,
            1 => AppMode::AgentSwarm,
            2 => AppMode::MediaBrowser,
            3 => AppMode::Settings,
            4 => AppMode::DistributedAgents,
            5 => AppMode::AdvancedReasoning,
            6 => AppMode::Search,
            _ => AppMode::Chat,
        };
    }

    pub fn previous_tab(&mut self) {
        if self.tab_index == 0 {
            self.tab_index = 6;
        } else {
            self.tab_index -= 1;
        }
        self.mode = match self.tab_index {
            0 => AppMode::Chat,
            1 => AppMode::AgentSwarm,
            2 => AppMode::MediaBrowser,
            3 => AppMode::Settings,
            4 => AppMode::DistributedAgents,
            5 => AppMode::AdvancedReasoning,
            6 => AppMode::Search,
            _ => AppMode::Chat,
        };
    }

    pub fn add_message(&mut self, role: MessageRole, content: String) {
        let message = ChatMessage {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            role,
            content,
            media_attachments: self.get_selected_media_files(),
            model: Some(self.current_model.clone()),
        };

        self.messages.push(message);

        // Auto-scroll to latest message
        if self.config.auto_scroll {
            let index = self.messages.len().saturating_sub(1);
            self.message_list_state.select(Some(index));
        }

        // Limit message history
        if self.messages.len() > self.config.max_messages {
            self.messages.remove(0);
        }
    }

    pub fn send_message(&mut self) -> Result<()> {
        if self.input.value().trim().is_empty() {
            return Ok(());
        }

        let user_input = self.input.value().to_string();
        self.input.reset();

        // Add user message
        self.add_message(MessageRole::User, user_input.clone());

        // Check if AI is configured
        if self.current_model.is_empty() {
            self.add_message(
                MessageRole::Assistant,
                "⚠️ AI not configured.\n\n\
                Set environment variables and restart:\n\
                • OpenAI: $env:AETHER_AI=\"openai\"; $env:OPENAI_API_KEY=\"sk-...\"\n\
                • Ollama: $env:AETHER_AI=\"ollama\" (run 'ollama serve' first)\n\
                • Compatible: $env:AETHER_AI=\"compat\"; $env:AETHER_COMPAT_BASE=\"http://...\""
                    .to_string(),
            );
            return Ok(());
        }

        // Process with AI
        let response = match ai::complete_sync_router(&user_input) {
            Ok(r) => r,
            Err(e) => format!("⚠️ AI Error: {}", e),
        };

        // Add AI response
        self.add_message(MessageRole::Assistant, response);

        // Clear selected media after sending
        self.selected_media.clear();

        Ok(())
    }

    pub fn add_agent(&mut self, name: String, model: String, tools: Vec<String>) {
        let agent = AgentInfo {
            id: Uuid::new_v4(),
            name,
            model,
            status: AgentStatus::Idle,
            current_task: None,
            tools,
            created_at: chrono::Utc::now(),
            last_activity: chrono::Utc::now(),
        };

        self.agents.push(agent);
    }

    pub fn remove_selected_agent(&mut self) {
        if let Some(selected) = self.agent_list_state.selected() {
            if selected < self.agents.len() {
                self.agents.remove(selected);

                // Adjust selection
                if self.agents.is_empty() {
                    self.agent_list_state.select(None);
                } else if selected >= self.agents.len() {
                    self.agent_list_state.select(Some(self.agents.len() - 1));
                }
            }
        }
    }

    pub fn add_media_file(&mut self, file: MediaFile) {
        self.media_files.push(file);
    }

    pub fn toggle_media_selection(&mut self) {
        if let Some(selected) = self.media_list_state.selected() {
            if selected < self.media_files.len() {
                if let Some(pos) = self.selected_media.iter().position(|&x| x == selected) {
                    self.selected_media.remove(pos);
                } else {
                    self.selected_media.push(selected);
                }
            }
        }
    }

    pub fn get_selected_media_files(&self) -> Vec<MediaFile> {
        self.selected_media
            .iter()
            .filter_map(|&idx| self.media_files.get(idx).cloned())
            .collect()
    }

    pub fn clear_media_selection(&mut self) {
        self.selected_media.clear();
    }

    pub fn start_agent_task(&mut self, task: String) -> Result<()> {
        if let Some(selected) = self.agent_list_state.selected() {
            if let Some(agent) = self.agents.get_mut(selected) {
                let agent_name = agent.name.clone();
                agent.status = AgentStatus::Working;
                agent.current_task = Some(task.clone());
                agent.last_activity = chrono::Utc::now();

                // Add system message
                self.add_message(
                    MessageRole::System,
                    format!("Agent '{}' started task: {}", agent_name, task),
                );
            }
        }
        Ok(())
    }

    pub fn get_tab_titles(&self) -> Vec<&'static str> {
        vec![
            "Chat",
            "Agents",
            "Media",
            "Settings",
            "Distributed",
            "Reasoning",
            "Search",
        ]
    }

    pub fn move_list_up(&mut self) {
        match self.mode {
            AppMode::Chat => {
                let i = match self.message_list_state.selected() {
                    Some(i) => {
                        if i == 0 {
                            self.messages.len().saturating_sub(1)
                        } else {
                            i - 1
                        }
                    }
                    None => 0,
                };
                self.message_list_state.select(Some(i));
            }
            AppMode::AgentSwarm => {
                let i = match self.agent_list_state.selected() {
                    Some(i) => {
                        if i == 0 {
                            self.agents.len().saturating_sub(1)
                        } else {
                            i - 1
                        }
                    }
                    None => 0,
                };
                self.agent_list_state.select(Some(i));
            }
            AppMode::MediaBrowser => {
                let i = match self.media_list_state.selected() {
                    Some(i) => {
                        if i == 0 {
                            self.media_files.len().saturating_sub(1)
                        } else {
                            i - 1
                        }
                    }
                    None => 0,
                };
                self.media_list_state.select(Some(i));
            }
            _ => {}
        }
    }

    pub fn move_list_down(&mut self) {
        match self.mode {
            AppMode::Chat => {
                let i = match self.message_list_state.selected() {
                    Some(i) => {
                        if i >= self.messages.len().saturating_sub(1) {
                            0
                        } else {
                            i + 1
                        }
                    }
                    None => 0,
                };
                self.message_list_state.select(Some(i));
            }
            AppMode::AgentSwarm => {
                let i = match self.agent_list_state.selected() {
                    Some(i) => {
                        if i >= self.agents.len().saturating_sub(1) {
                            0
                        } else {
                            i + 1
                        }
                    }
                    None => 0,
                };
                self.agent_list_state.select(Some(i));
            }
            AppMode::MediaBrowser => {
                let i = match self.media_list_state.selected() {
                    Some(i) => {
                        if i >= self.media_files.len().saturating_sub(1) {
                            0
                        } else {
                            i + 1
                        }
                    }
                    None => 0,
                };
                self.media_list_state.select(Some(i));
            }
            _ => {}
        }
    }

    /// Start a distributed agent swarm
    pub async fn start_distributed_swarm(&mut self, listen_addr: &str) -> Result<()> {
        let addr: std::net::SocketAddr = listen_addr.parse()?;
        let swarm = DistributedSwarm::new(addr).await?;
        self.distributed_swarm = Some(swarm);
        Ok(())
    }

    /// Stop the distributed agent swarm
    pub async fn stop_distributed_swarm(&mut self) -> Result<()> {
        if let Some(mut swarm) = self.distributed_swarm.take() {
            swarm.shutdown().await?;
        }
        Ok(())
    }

    /// Start an advanced reasoning session
    pub async fn start_reasoning_session(&mut self, goal: PlanningGoal) -> Result<Uuid> {
        let _session_result = self
            .reasoning_coordinator
            .reasoning_engine
            .reason(&goal)
            .await?;
        self.active_planning_goal = Some(goal);
        Ok(Uuid::new_v4()) // Return a session ID
    }

    /// Get the status of distributed agents
    pub fn get_distributed_agent_status(&self) -> Vec<String> {
        if let Some(_swarm) = &self.distributed_swarm {
            vec!["Distributed swarm active".to_string()]
        } else {
            vec!["No distributed swarm running".to_string()]
        }
    }

    /// Get active reasoning sessions
    pub fn get_active_reasoning_sessions(&self) -> Vec<String> {
        self.reasoning_coordinator
            .active_reasoning_sessions
            .iter()
            .map(|(id, session)| format!("{}: {}", id, session.goal.description))
            .collect()
    }

    /// Export conversation to markdown format
    pub fn export_to_markdown(&self) -> String {
        let mut output = String::new();
        output.push_str("# AetherShell Conversation Export\n\n");
        output.push_str(&format!(
            "**Exported:** {}\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
        ));
        output.push_str(&format!("**Model:** {}\n", self.current_model));
        output.push_str(&format!("**Total Messages:** {}\n\n", self.messages.len()));
        output.push_str("---\n\n");

        for msg in &self.messages {
            let role = match msg.role {
                MessageRole::User => "👤 User",
                MessageRole::Assistant => "🤖 Assistant",
                MessageRole::System => "⚙️ System",
            };

            output.push_str(&format!(
                "## {} ({})\n\n",
                role,
                msg.timestamp.format("%H:%M:%S")
            ));

            if let Some(model) = &msg.model {
                output.push_str(&format!("*Model: {}*\n\n", model));
            }

            output.push_str(&msg.content);
            output.push_str("\n\n");

            if !msg.media_attachments.is_empty() {
                output.push_str("**Attachments:**\n");
                for media in &msg.media_attachments {
                    output.push_str(&format!("- {} ({:?})\n", media.path, media.media_type));
                }
                output.push_str("\n");
            }

            output.push_str("---\n\n");
        }

        output
    }

    /// Export conversation to JSON format
    pub fn export_to_json(&self) -> Result<String> {
        #[derive(Serialize)]
        struct ExportData {
            exported_at: String,
            model: String,
            total_messages: usize,
            messages: Vec<ExportMessage>,
        }

        #[derive(Serialize)]
        struct ExportMessage {
            timestamp: String,
            role: String,
            content: String,
            model: Option<String>,
            media_count: usize,
        }

        let export = ExportData {
            exported_at: chrono::Utc::now().to_rfc3339(),
            model: self.current_model.clone(),
            total_messages: self.messages.len(),
            messages: self
                .messages
                .iter()
                .map(|msg| ExportMessage {
                    timestamp: msg.timestamp.to_rfc3339(),
                    role: format!("{:?}", msg.role),
                    content: msg.content.clone(),
                    model: msg.model.clone(),
                    media_count: msg.media_attachments.len(),
                })
                .collect(),
        };

        serde_json::to_string_pretty(&export)
            .map_err(|e| anyhow::anyhow!("JSON export failed: {}", e))
    }

    /// Search messages by content
    pub fn search_messages(&self, query: &str) -> Vec<usize> {
        let query_lower = query.to_lowercase();
        self.messages
            .iter()
            .enumerate()
            .filter(|(_, msg)| msg.content.to_lowercase().contains(&query_lower))
            .map(|(idx, _)| idx)
            .collect()
    }

    /// Filter messages by role
    pub fn filter_by_role(&self, role: MessageRole) -> Vec<usize> {
        self.messages
            .iter()
            .enumerate()
            .filter(|(_, msg)| msg.role == role)
            .map(|(idx, _)| idx)
            .collect()
    }

    /// Execute search and update search state
    pub fn execute_search(&mut self) {
        if self.search_query.is_empty() {
            self.search_results.clear();
            self.search_result_index = 0;
        } else {
            self.search_results = self.search_messages(&self.search_query.clone());
            self.search_result_index = 0;
        }
    }

    /// Navigate to next search result
    pub fn next_search_result(&mut self) {
        if !self.search_results.is_empty() {
            self.search_result_index = (self.search_result_index + 1) % self.search_results.len();
        }
    }

    /// Navigate to previous search result
    pub fn previous_search_result(&mut self) {
        if !self.search_results.is_empty() {
            if self.search_result_index == 0 {
                self.search_result_index = self.search_results.len() - 1;
            } else {
                self.search_result_index -= 1;
            }
        }
    }

    /// Clear search and return to chat mode
    pub fn clear_search(&mut self) {
        self.search_query.clear();
        self.search_results.clear();
        self.search_result_index = 0;
        self.mode = AppMode::Chat;
    }

    /// Get conversation statistics
    pub fn get_stats(&self) -> ConversationStats {
        let user_msgs = self
            .messages
            .iter()
            .filter(|m| m.role == MessageRole::User)
            .count();
        let assistant_msgs = self
            .messages
            .iter()
            .filter(|m| m.role == MessageRole::Assistant)
            .count();
        let system_msgs = self
            .messages
            .iter()
            .filter(|m| m.role == MessageRole::System)
            .count();

        let total_chars: usize = self.messages.iter().map(|m| m.content.len()).sum();
        let avg_msg_length = if !self.messages.is_empty() {
            total_chars / self.messages.len()
        } else {
            0
        };

        let total_media = self
            .messages
            .iter()
            .map(|m| m.media_attachments.len())
            .sum();

        ConversationStats {
            total_messages: self.messages.len(),
            user_messages: user_msgs,
            assistant_messages: assistant_msgs,
            system_messages: system_msgs,
            total_characters: total_chars,
            avg_message_length: avg_msg_length,
            total_media_attachments: total_media,
            active_agents: self.agents.len(),
        }
    }

    /// Clear all messages
    pub fn clear_conversation(&mut self) {
        self.messages.clear();
        self.message_list_state.select(Some(0));
    }

    /// Get context window (last N messages)
    pub fn get_context_window(&self, window_size: usize) -> Vec<&ChatMessage> {
        let start = if self.messages.len() > window_size {
            self.messages.len() - window_size
        } else {
            0
        };
        self.messages[start..].iter().collect()
    }

    /// Calculate estimated tokens (rough approximation)
    pub fn estimate_tokens(&self) -> usize {
        // Rough estimate: ~4 characters per token
        self.messages.iter().map(|m| m.content.len() / 4).sum()
    }

    /// Get agent performance metrics
    pub fn get_agent_metrics(&self) -> Vec<AgentMetrics> {
        self.agents
            .iter()
            .map(|agent| {
                let uptime = chrono::Utc::now()
                    .signed_duration_since(agent.created_at)
                    .num_seconds();
                let idle_time = chrono::Utc::now()
                    .signed_duration_since(agent.last_activity)
                    .num_seconds();

                AgentMetrics {
                    name: agent.name.clone(),
                    status: agent.status.clone(),
                    uptime_seconds: uptime,
                    idle_seconds: idle_time,
                    tool_count: agent.tools.len(),
                }
            })
            .collect()
    }

    /// Toggle auto-scroll setting
    pub fn toggle_auto_scroll(&mut self) {
        self.config.auto_scroll = !self.config.auto_scroll;
    }

    /// Toggle timestamp display
    pub fn toggle_timestamps(&mut self) {
        self.config.show_timestamps = !self.config.show_timestamps;
    }

    /// Toggle media preview
    pub fn toggle_media_preview(&mut self) {
        self.config.enable_media_preview = !self.config.enable_media_preview;
    }

    /// Get current mode as string
    pub fn get_mode_string(&self) -> &'static str {
        match self.mode {
            AppMode::Chat => "Chat",
            AppMode::AgentSwarm => "Agent Swarm",
            AppMode::MediaBrowser => "Media Browser",
            AppMode::Settings => "Settings",
            AppMode::DistributedAgents => "Distributed Agents",
            AppMode::AdvancedReasoning => "Advanced Reasoning",
            AppMode::Search => "Search",
        }
    }

    /// Get help text for current mode
    pub fn get_help_text(&self) -> Vec<String> {
        match self.mode {
            AppMode::Chat => vec![
                "Enter: Send message".to_string(),
                "Ctrl+C: Copy selected".to_string(),
                "Ctrl+E: Export conversation".to_string(),
                "Ctrl+L: Clear conversation".to_string(),
                "Ctrl+F: Search messages".to_string(),
                "Tab: Switch mode".to_string(),
                "Ctrl+Q: Quit".to_string(),
            ],
            AppMode::AgentSwarm => vec![
                "Enter: Start selected agent".to_string(),
                "Space: Pause/Resume".to_string(),
                "D: Delete selected agent".to_string(),
                "N: New agent".to_string(),
                "M: View metrics".to_string(),
                "Tab: Switch mode".to_string(),
            ],
            AppMode::MediaBrowser => vec![
                "Enter: Select/Deselect media".to_string(),
                "D: Delete selected".to_string(),
                "A: Add media file".to_string(),
                "P: Preview".to_string(),
                "C: Clear selection".to_string(),
                "Tab: Switch mode".to_string(),
            ],
            AppMode::Settings => vec![
                "1: Toggle auto-scroll".to_string(),
                "2: Toggle timestamps".to_string(),
                "3: Toggle media preview".to_string(),
                "↑/↓: Navigate settings".to_string(),
                "Enter: Change value".to_string(),
                "Tab: Switch mode".to_string(),
            ],
            AppMode::DistributedAgents => vec![
                "Enter: Deploy agent".to_string(),
                "S: View swarm status".to_string(),
                "C: Coordinate agents".to_string(),
                "H: Health check".to_string(),
                "Tab: Switch mode".to_string(),
            ],
            AppMode::AdvancedReasoning => vec![
                "Enter: Start reasoning".to_string(),
                "G: Set goal".to_string(),
                "P: Plan steps".to_string(),
                "E: Execute plan".to_string(),
                "V: Visualize reasoning".to_string(),
                "Tab: Switch mode".to_string(),
            ],
            AppMode::Search => vec![
                "Type: Enter search query".to_string(),
                "Enter: Execute search".to_string(),
                "↑/↓: Navigate results".to_string(),
                "Esc: Clear search / Return to Chat".to_string(),
                "Ctrl+C: Copy selected result".to_string(),
                "Tab: Switch mode".to_string(),
            ],
        }
    }

    // ===================== A2UI Event Processing =====================

    /// Process all pending A2UI events from the global channel
    pub fn process_a2ui_events(&mut self) {
        let events = match A2UI_CHANNEL.receive_all() {
            Ok(e) => e,
            Err(_) => return,
        };

        for event in events {
            self.handle_a2ui_event(event);
        }

        // Remove expired notifications
        self.cleanup_expired_notifications();
    }

    /// Handle a single A2UI event
    fn handle_a2ui_event(&mut self, event: A2UIEvent) {
        match event.event_type {
            A2UIEventType::Notify {
                message,
                level,
                duration_ms,
            } => {
                self.notifications.push(A2UINotification {
                    id: event.id,
                    message,
                    level,
                    timestamp: event.timestamp,
                    duration_ms,
                });
                // Keep only last 10 notifications
                while self.notifications.len() > 10 {
                    self.notifications.remove(0);
                }
            }

            A2UIEventType::Toast {
                message,
                level,
                duration_ms,
            } => {
                self.notifications.push(A2UINotification {
                    id: event.id,
                    message,
                    level,
                    timestamp: event.timestamp,
                    duration_ms: Some(duration_ms),
                });
            }

            A2UIEventType::Progress {
                id,
                label,
                current,
                total,
                message,
            } => {
                self.progress_indicators.insert(
                    id,
                    ProgressIndicator {
                        id,
                        label,
                        current,
                        total,
                        message,
                    },
                );
            }

            A2UIEventType::ProgressComplete { id } => {
                self.progress_indicators.remove(&id);
            }

            A2UIEventType::Status { text, section: _ } => {
                self.status_bar_text = Some(text);
            }

            A2UIEventType::Clear { target: _ } => {
                self.notifications.clear();
                self.progress_indicators.clear();
                self.status_bar_text = None;
            }

            A2UIEventType::Render {
                content,
                target: _,
                replace: _,
            } => {
                // For now, render content as a system message
                let text = match content {
                    crate::ai::a2ui::RenderContent::Text(t) => t,
                    crate::ai::a2ui::RenderContent::Markdown(m) => m,
                    crate::ai::a2ui::RenderContent::Json(j) => {
                        serde_json::to_string_pretty(&j).unwrap_or_default()
                    }
                    crate::ai::a2ui::RenderContent::Table { headers, rows } => {
                        let mut s = headers.join(" | ") + "\n";
                        s += &headers
                            .iter()
                            .map(|_| "---")
                            .collect::<Vec<_>>()
                            .join(" | ");
                        s += "\n";
                        for row in rows {
                            s += &row.join(" | ");
                            s += "\n";
                        }
                        s
                    }
                    crate::ai::a2ui::RenderContent::Code { language, content } => {
                        format!("```{}\n{}\n```", language, content)
                    }
                    crate::ai::a2ui::RenderContent::Image { alt, .. } => {
                        format!("[Image: {}]", alt.unwrap_or_default())
                    }
                    crate::ai::a2ui::RenderContent::Thinking {
                        steps,
                        final_answer,
                    } => {
                        let mut s = "🤔 Thinking:\n".to_string();
                        for (i, step) in steps.iter().enumerate() {
                            s += &format!("  {}. {}\n", i + 1, step);
                        }
                        if let Some(answer) = final_answer {
                            s += &format!("\n💡 Answer: {}", answer);
                        }
                        s
                    }
                };
                self.add_message(MessageRole::System, text);
            }

            A2UIEventType::Prompt {
                id,
                message,
                prompt_type,
            } => {
                self.pending_prompts.push((id, message, prompt_type));
            }

            A2UIEventType::AgentStarted { agent_id, task } => {
                // Update agent status if it exists
                for agent in &mut self.agents {
                    if agent.name == agent_id || agent.id.to_string() == agent_id {
                        agent.status = AgentStatus::Working;
                        agent.current_task = task.clone();
                        agent.last_activity = chrono::Utc::now();
                        break;
                    }
                }
            }

            A2UIEventType::AgentCompleted {
                agent_id,
                result,
                success,
            } => {
                for agent in &mut self.agents {
                    if agent.name == agent_id || agent.id.to_string() == agent_id {
                        agent.status = if success {
                            AgentStatus::Idle
                        } else {
                            AgentStatus::Error(result.clone().unwrap_or_default())
                        };
                        agent.current_task = None;
                        agent.last_activity = chrono::Utc::now();
                        break;
                    }
                }
            }

            A2UIEventType::AgentThinking {
                agent_id,
                thought,
                step,
            } => {
                // Add thinking step as a system message
                self.add_message(
                    MessageRole::System,
                    format!("🤔 {}: Step {} - {}", agent_id, step, thought),
                );
            }

            // Modal and other events - not yet implemented in TUI
            A2UIEventType::Modal { .. }
            | A2UIEventType::ModalClose { .. }
            | A2UIEventType::Highlight { .. }
            | A2UIEventType::Focus { .. }
            | A2UIEventType::ScrollTo { .. } => {
                // TODO: Implement modal and focus handling
            }
        }
    }

    /// Remove expired toast notifications
    fn cleanup_expired_notifications(&mut self) {
        let now = chrono::Utc::now();
        self.notifications.retain(|n| {
            if let Some(duration_ms) = n.duration_ms {
                let elapsed = (now - n.timestamp).num_milliseconds() as u64;
                elapsed < duration_ms
            } else {
                true // Keep notifications without duration
            }
        });
    }

    /// Get active notifications for display
    pub fn get_active_notifications(&self) -> &[A2UINotification] {
        &self.notifications
    }

    /// Get progress indicators for display
    pub fn get_progress_indicators(&self) -> Vec<&ProgressIndicator> {
        self.progress_indicators.values().collect()
    }

    /// Get status bar text
    pub fn get_status_bar_text(&self) -> Option<&str> {
        self.status_bar_text.as_deref()
    }

    /// Check if there are pending prompts
    pub fn has_pending_prompts(&self) -> bool {
        !self.pending_prompts.is_empty()
    }

    /// Get the next pending prompt
    pub fn pop_pending_prompt(&mut self) -> Option<(Uuid, String, crate::ai::a2ui::PromptType)> {
        if self.pending_prompts.is_empty() {
            None
        } else {
            Some(self.pending_prompts.remove(0))
        }
    }

    /// Submit a response to a prompt
    pub fn submit_prompt_response(
        &self,
        prompt_id: Uuid,
        response: crate::ai::a2ui::PromptResponse,
    ) {
        let _ = crate::ai::a2ui::submit_response(prompt_id, response);
    }
}

#[derive(Debug, Clone)]
pub struct ConversationStats {
    pub total_messages: usize,
    pub user_messages: usize,
    pub assistant_messages: usize,
    pub system_messages: usize,
    pub total_characters: usize,
    pub avg_message_length: usize,
    pub total_media_attachments: usize,
    pub active_agents: usize,
}

#[derive(Debug, Clone)]
pub struct AgentMetrics {
    pub name: String,
    pub status: AgentStatus,
    pub uptime_seconds: i64,
    pub idle_seconds: i64,
    pub tool_count: usize,
}