ccswarm 0.4.0

AI-powered multi-agent orchestration system with proactive intelligence, security monitoring, and session management
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
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
use anyhow::Result;
use chrono::{DateTime, Utc};
use tokio::time::{Duration, Instant};

use crate::agent::AgentStatus;
use crate::coordination::{CoordinationBus, StatusTracker, TaskQueue};
use crate::execution::{ExecutionEngine, TaskStatus};

/// Current UI tab
#[derive(Debug, Clone, PartialEq)]
pub enum Tab {
    Overview,
    Agents,
    Tasks,
    Logs,
    Delegation,
}

impl Tab {
    pub fn title(&self) -> &str {
        match self {
            Tab::Overview => "Overview",
            Tab::Agents => "Agents",
            Tab::Tasks => "Tasks",
            Tab::Logs => "Logs",
            Tab::Delegation => "Delegation",
        }
    }
}

/// Agent display information
#[derive(Debug, Clone)]
pub struct AgentInfo {
    pub id: String,
    pub name: String,
    pub specialization: String,
    pub provider_type: String,
    pub provider_icon: String,
    pub provider_color: String,
    pub status: AgentStatus,
    pub current_task: Option<String>,
    pub tasks_completed: u32,
    pub last_activity: DateTime<Utc>,
    pub workspace: String,
}

/// Task display information
#[derive(Debug, Clone)]
pub struct TaskInfo {
    pub id: String,
    pub description: String,
    pub priority: String,
    pub task_type: String,
    pub status: String,
    pub assigned_agent: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// Log entry
#[derive(Debug, Clone)]
pub struct LogEntry {
    pub timestamp: DateTime<Utc>,
    pub level: String,
    pub agent: Option<String>,
    pub message: String,
}

/// Delegation decision for display
#[derive(Debug, Clone)]
pub struct DelegationInfo {
    pub task_description: String,
    pub recommended_agent: String,
    pub confidence: f64,
    pub reasoning: String,
    pub created_at: DateTime<Utc>,
}

/// Delegation state for TUI
#[derive(Debug, Clone, PartialEq)]
pub enum DelegationMode {
    Analyze,
    Delegate,
    ViewStats,
}

/// Application state for TUI
pub struct App {
    /// Current active tab
    pub current_tab: Tab,

    /// Selection state for lists
    pub selected_agent: usize,
    pub selected_task: usize,
    pub selected_log: usize,
    pub selected_delegation: usize,

    /// Data
    pub agents: Vec<AgentInfo>,
    pub tasks: Vec<TaskInfo>,
    pub logs: Vec<LogEntry>,
    pub delegation_decisions: Vec<DelegationInfo>,

    /// System state
    pub system_status: String,
    pub total_agents: usize,
    pub active_agents: usize,
    pub pending_tasks: usize,
    pub completed_tasks: usize,

    /// Execution engine statistics
    pub tasks_executed: usize,
    pub tasks_failed: usize,
    pub success_rate: f64,
    pub orchestration_usage: f64,

    /// Session statistics (ai-session integration)
    pub total_sessions: usize,
    pub active_sessions: usize,
    pub multi_agent_enabled: bool,

    /// Input state
    pub input_mode: InputMode,
    pub input_buffer: String,

    /// Delegation state
    pub delegation_mode: DelegationMode,
    pub delegation_input: String,

    /// Coordination components
    pub coordination_bus: CoordinationBus,
    pub status_tracker: StatusTracker,
    pub task_queue: TaskQueue,

    /// Execution engine for real task data
    pub execution_engine: Option<ExecutionEngine>,

    /// Terminal size
    pub terminal_width: u16,
    pub terminal_height: u16,

    /// Last update time
    pub last_update: Instant,
    pub update_interval: Duration,

    /// Should quit flag
    pub should_quit: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum InputMode {
    Normal,
    AddingTask,
    CreatingAgent,
    Command,
    DelegationInput,
}

impl App {
    /// Create new app instance
    pub async fn new() -> Result<Self> {
        let coordination_bus = CoordinationBus::new().await?;
        let status_tracker = StatusTracker::new().await?;
        let task_queue = TaskQueue::new().await?;

        Ok(Self {
            current_tab: Tab::Overview,
            selected_agent: 0,
            selected_task: 0,
            selected_log: 0,
            selected_delegation: 0,
            agents: Vec::new(),
            tasks: Vec::new(),
            logs: Vec::new(),
            delegation_decisions: Vec::new(),
            system_status: "Starting...".to_string(),
            total_agents: 0,
            active_agents: 0,
            pending_tasks: 0,
            completed_tasks: 0,
            tasks_executed: 0,
            tasks_failed: 0,
            success_rate: 100.0,
            orchestration_usage: 0.0,
            total_sessions: 0,
            active_sessions: 0,
            multi_agent_enabled: true,
            input_mode: InputMode::Normal,
            input_buffer: String::new(),
            delegation_mode: DelegationMode::Analyze,
            delegation_input: String::new(),
            coordination_bus,
            status_tracker,
            task_queue,
            execution_engine: None, // Will be set by CLI runner
            terminal_width: 80,
            terminal_height: 24,
            last_update: Instant::now(),
            update_interval: Duration::from_millis(500), // More frequent updates for real-time feel
            should_quit: false,
        })
    }

    /// Navigate to next tab
    pub fn next_tab(&mut self) {
        self.current_tab = match self.current_tab {
            Tab::Overview => Tab::Agents,
            Tab::Agents => Tab::Tasks,
            Tab::Tasks => Tab::Logs,
            Tab::Logs => Tab::Delegation,
            Tab::Delegation => Tab::Overview,
        };
        self.reset_selection();
    }

    /// Navigate to previous tab
    pub fn previous_tab(&mut self) {
        self.current_tab = match self.current_tab {
            Tab::Overview => Tab::Delegation,
            Tab::Agents => Tab::Overview,
            Tab::Tasks => Tab::Agents,
            Tab::Logs => Tab::Tasks,
            Tab::Delegation => Tab::Logs,
        };
        self.reset_selection();
    }

    /// Move selection up
    pub fn previous_item(&mut self) {
        match self.current_tab {
            Tab::Agents => {
                if self.selected_agent > 0 {
                    self.selected_agent -= 1;
                }
            }
            Tab::Tasks => {
                if self.selected_task > 0 {
                    self.selected_task -= 1;
                }
            }
            Tab::Logs => {
                if self.selected_log > 0 {
                    self.selected_log -= 1;
                }
            }
            Tab::Delegation => {
                if self.selected_delegation > 0 {
                    self.selected_delegation -= 1;
                }
            }
            _ => {}
        }
    }

    /// Move selection down
    pub fn next_item(&mut self) {
        match self.current_tab {
            Tab::Agents => {
                if self.selected_agent < self.agents.len().saturating_sub(1) {
                    self.selected_agent += 1;
                }
            }
            Tab::Tasks => {
                if self.selected_task < self.tasks.len().saturating_sub(1) {
                    self.selected_task += 1;
                }
            }
            Tab::Logs => {
                if self.selected_log < self.logs.len().saturating_sub(1) {
                    self.selected_log += 1;
                }
            }
            Tab::Delegation => {
                if self.selected_delegation < self.delegation_decisions.len().saturating_sub(1) {
                    self.selected_delegation += 1;
                }
            }
            _ => {}
        }
    }

    /// Reset selection for current tab
    fn reset_selection(&mut self) {
        match self.current_tab {
            Tab::Agents => self.selected_agent = 0,
            Tab::Tasks => self.selected_task = 0,
            Tab::Logs => self.selected_log = 0,
            Tab::Delegation => self.selected_delegation = 0,
            _ => {}
        }
    }

    /// Activate selected item (start agent if available)
    pub async fn activate_selected(&mut self) -> Result<()> {
        match self.current_tab {
            Tab::Agents => {
                if let Some(agent) = self.agents.get(self.selected_agent).cloned() {
                    match agent.status {
                        AgentStatus::Available => {
                            // Start the agent
                            self.start_agent(&agent.id).await?;
                        }
                        AgentStatus::Working => {
                            // Show agent details
                            self.show_agent_details(&agent.id).await?;
                        }
                        _ => {
                            // Show agent details for other statuses
                            self.show_agent_details(&agent.id).await?;
                        }
                    }
                }
            }
            Tab::Tasks => {
                if let Some(task) = self.tasks.get(self.selected_task) {
                    let task_id = task.id.clone();
                    self.show_task_details(&task_id).await?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Start an available agent
    pub async fn start_agent(&mut self, agent_id: &str) -> Result<()> {
        let mut agent_info = None;

        // Find the agent and collect info
        if let Some(agent) = self.agents.iter_mut().find(|a| a.id == agent_id) {
            // Change status to Working
            agent.status = AgentStatus::Working;
            agent.last_activity = Utc::now();

            // Collect info for logging
            agent_info = Some((agent.name.clone(), agent.specialization.clone()));

            // Update system stats
            self.active_agents += 1;
        }

        // Log after borrowing ends
        if let Some((name, specialization)) = agent_info {
            self.add_log(
                "System",
                &format!("🚀 Starting agent: {} ({})", name, specialization),
            )
            .await;

            // If this is a Master agent, provide special logging
            if specialization.contains("Master") {
                self.add_log("Master", "🎯 Master Claude Code orchestrator activated")
                    .await;
                self.add_log("Master", "📋 Ready to coordinate multi-agent tasks")
                    .await;
            }
        }

        Ok(())
    }

    /// Start agent by ID or name
    pub async fn start_agent_by_id(&mut self, identifier: &str) -> Result<()> {
        // Find agent by ID or name
        let agent_to_start = self
            .agents
            .iter()
            .find(|a| a.id == identifier || a.name == identifier)
            .map(|a| a.id.clone());

        if let Some(agent_id) = agent_to_start {
            self.start_agent(&agent_id).await?;
        } else {
            self.add_log("System", &format!("Agent not found: {}", identifier))
                .await;
        }
        Ok(())
    }

    /// Create new session (agent)
    pub async fn create_new_session(&mut self) -> Result<()> {
        self.input_mode = InputMode::CreatingAgent;
        self.input_buffer.clear();
        self.add_log("System", "Enter agent type (frontend/backend/devops/qa):")
            .await;
        Ok(())
    }

    /// Delete current session
    pub async fn delete_current_session(&mut self) -> Result<()> {
        if let Some(agent) = self.agents.get(self.selected_agent) {
            self.add_log("System", &format!("Deleting agent: {}", agent.name))
                .await;
            // TODO: Implement actual agent deletion
        }
        Ok(())
    }

    /// Show system status
    pub async fn show_status(&mut self) -> Result<()> {
        self.current_tab = Tab::Overview;
        self.refresh_data().await?;
        Ok(())
    }

    /// Add task prompt
    pub async fn add_task_prompt(&mut self) -> Result<()> {
        self.input_mode = InputMode::AddingTask;
        self.input_buffer.clear();
        self.add_log("System", "Enter task description:").await;
        Ok(())
    }

    /// Open command prompt
    pub async fn open_command_prompt(&mut self) -> Result<()> {
        self.input_mode = InputMode::Command;
        self.input_buffer.clear();
        self.add_log("System", "Enter command (help for available commands):")
            .await;
        Ok(())
    }

    /// Refresh all data
    pub async fn refresh_data(&mut self) -> Result<()> {
        self.load_agents().await?;
        self.load_tasks().await?;
        self.update_system_stats().await?;
        self.last_update = Instant::now();
        Ok(())
    }

    /// Set execution engine for real task data
    pub fn set_execution_engine(&mut self, engine: ExecutionEngine) {
        self.execution_engine = Some(engine);
    }

    /// Cancel current action
    pub fn cancel_current_action(&mut self) {
        self.input_mode = InputMode::Normal;
        self.input_buffer.clear();
    }

    /// Update terminal size
    pub fn update_size(&mut self, width: u16, height: u16) {
        self.terminal_width = width;
        self.terminal_height = height;
    }

    /// Periodic update
    pub async fn update(&mut self) -> Result<()> {
        if self.last_update.elapsed() >= self.update_interval {
            self.refresh_data().await?;
        }
        Ok(())
    }

    /// Load agents from coordination system
    async fn load_agents(&mut self) -> Result<()> {
        let statuses = self.status_tracker.get_all_statuses().await?;

        self.agents.clear();

        // Always add Master Claude Code agent
        let master_agent = AgentInfo {
            id: "master-claude-code".to_string(),
            name: "master".to_string(),
            specialization: "Master Claude Code".to_string(),
            provider_type: "claude_code".to_string(),
            provider_icon: "👑".to_string(),
            provider_color: "gold".to_string(),
            status: AgentStatus::Available,
            current_task: None,
            tasks_completed: 0,
            last_activity: Utc::now(),
            workspace: "/workspace".to_string(),
        };
        self.agents.push(master_agent);

        // Add other default agents
        let default_agents = vec![
            ("qa-agent", "qa", "QA Specialist"),
            ("devops-agent", "devops", "DevOps Specialist"),
            ("test-agent", "test", "Test Specialist"),
            ("error-agent", "error", "Error Handler"),
            ("backend-agent", "backend", "Backend Specialist"),
            ("frontend-agent", "frontend", "Frontend Specialist"),
        ];

        for (id, name, spec) in default_agents {
            let agent = AgentInfo {
                id: id.to_string(),
                name: name.to_string(),
                specialization: spec.to_string(),
                provider_type: "claude_code".to_string(),
                provider_icon: "🤖".to_string(),
                provider_color: "blue".to_string(),
                status: AgentStatus::Available,
                current_task: None,
                tasks_completed: 0,
                last_activity: Utc::now(),
                workspace: "Unknown".to_string(),
            };
            self.agents.push(agent);
        }

        // Load dynamic agents from coordination system
        for status in statuses.iter() {
            if let (Some(agent_id), Some(status_val)) = (
                status.get("agent_id").and_then(|v| v.as_str()),
                status.get("status").and_then(|v| v.as_str()),
            ) {
                // Skip if already exists in default agents
                if self.agents.iter().any(|a| a.id == agent_id) {
                    continue;
                }

                let agent_info = AgentInfo {
                    id: agent_id.to_string(),
                    name: agent_id.split('-').next().unwrap_or("Unknown").to_string(),
                    specialization: status
                        .get("specialization")
                        .and_then(|v| v.as_str())
                        .unwrap_or("Unknown")
                        .to_string(),
                    provider_type: "claude_code".to_string(),
                    provider_icon: "🤖".to_string(),
                    provider_color: "blue".to_string(),
                    status: parse_agent_status(status_val),
                    current_task: status
                        .get("current_task")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string()),
                    tasks_completed: status
                        .get("tasks_completed")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(0) as u32,
                    last_activity: status
                        .get("timestamp")
                        .and_then(|v| v.as_str())
                        .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
                        .map(|dt| dt.with_timezone(&Utc))
                        .unwrap_or_else(Utc::now),
                    workspace: status
                        .get("workspace")
                        .and_then(|v| v.as_str())
                        .unwrap_or("Unknown")
                        .to_string(),
                };
                self.agents.push(agent_info);
            }
        }

        // Ensure selection is valid
        if self.selected_agent >= self.agents.len() {
            self.selected_agent = 0;
        }

        Ok(())
    }

    /// Load tasks from task queue or execution engine
    async fn load_tasks(&mut self) -> Result<()> {
        self.tasks.clear();

        // If execution engine is available, use it for real-time task data
        if let Some(ref execution_engine) = self.execution_engine {
            let executor = execution_engine.get_executor();
            let task_queue = executor.get_task_queue();
            let all_tasks = task_queue.list_tasks(None, None).await;

            for queued_task in all_tasks {
                let status_str = match &queued_task.status {
                    TaskStatus::Pending => "⏳ Pending",
                    TaskStatus::Assigned { .. } => "📋 Assigned",
                    TaskStatus::InProgress { .. } => "🏃 In Progress",
                    TaskStatus::Completed { .. } => "✅ Completed",
                    TaskStatus::Failed { .. } => "❌ Failed",
                    TaskStatus::Cancelled { .. } => "🚫 Cancelled",
                };

                let task_info = TaskInfo {
                    id: queued_task.task.id.clone(),
                    description: queued_task.task.description.clone(),
                    priority: format!("{:?}", queued_task.task.priority),
                    task_type: format!("{}", queued_task.task.task_type), // Use Display trait
                    status: status_str.to_string(),
                    assigned_agent: queued_task.assigned_agent,
                    created_at: queued_task.created_at,
                };
                self.tasks.push(task_info);
            }
        } else {
            // Fall back to original task queue
            let pending_tasks = self.task_queue.get_pending_tasks().await?;

            for task in pending_tasks {
                let task_info = TaskInfo {
                    id: task.id.clone(),
                    description: task.description.clone(),
                    priority: format!("{:?}", task.priority),
                    task_type: format!("{}", task.task_type),
                    status: "Pending".to_string(),
                    assigned_agent: None,
                    created_at: Utc::now(), // TODO: Get actual creation time
                };
                self.tasks.push(task_info);
            }
        }

        // Ensure selection is valid
        if self.selected_task >= self.tasks.len() {
            self.selected_task = 0;
        }

        Ok(())
    }

    /// Update system statistics
    async fn update_system_stats(&mut self) -> Result<()> {
        self.total_agents = self.agents.len();
        self.active_agents = self
            .agents
            .iter()
            .filter(|a| matches!(a.status, AgentStatus::Available | AgentStatus::Working))
            .count();

        // Update task counts from execution engine if available
        if let Some(ref execution_engine) = self.execution_engine {
            let executor = execution_engine.get_executor();
            let queue_stats = executor.get_task_queue().get_stats().await;
            let execution_stats = executor.get_stats().await;

            self.pending_tasks = queue_stats.pending_count + queue_stats.active_count;
            self.completed_tasks = execution_stats.tasks_succeeded;
            self.tasks_executed = execution_stats.tasks_executed;
            self.tasks_failed = execution_stats.tasks_failed;
            self.orchestration_usage = execution_stats.orchestration_usage;

            // Calculate success rate
            self.success_rate = if execution_stats.tasks_executed > 0 {
                (execution_stats.tasks_succeeded as f64 / execution_stats.tasks_executed as f64)
                    * 100.0
            } else {
                100.0
            };

            self.system_status = if self.active_agents > 0 {
                format!("Running ({:.1}% success)", self.success_rate)
            } else {
                "Stopped".to_string()
            };
        } else {
            // Fall back to original calculation
            self.pending_tasks = self.tasks.len();
            self.completed_tasks =
                self.agents.iter().map(|a| a.tasks_completed).sum::<u32>() as usize;

            self.system_status = if self.active_agents > 0 {
                "Running".to_string()
            } else {
                "Stopped".to_string()
            };
        }

        Ok(())
    }

    /// Show agent details
    async fn show_agent_details(&mut self, agent_id: &str) -> Result<()> {
        self.add_log(
            "System",
            &format!("Showing details for agent: {}", agent_id),
        )
        .await;
        Ok(())
    }

    /// Show task details
    async fn show_task_details(&mut self, task_id: &str) -> Result<()> {
        self.add_log("System", &format!("Showing details for task: {}", task_id))
            .await;
        Ok(())
    }

    /// Add log entry
    async fn add_log(&mut self, source: &str, message: &str) {
        let log_entry = LogEntry {
            timestamp: Utc::now(),
            level: "INFO".to_string(),
            agent: if source == "System" {
                None
            } else {
                Some(source.to_string())
            },
            message: message.to_string(),
        };
        self.logs.push(log_entry);

        // Keep only last 1000 log entries
        if self.logs.len() > 1000 {
            self.logs.remove(0);
        }

        // Auto-scroll to bottom
        self.selected_log = self.logs.len().saturating_sub(1);
    }

    /// Handle character input
    pub fn handle_char_input(&mut self, c: char) {
        if self.input_mode != InputMode::Normal {
            self.input_buffer.push(c);
        }
    }

    /// Handle backspace input
    pub fn handle_backspace(&mut self) {
        if self.input_mode != InputMode::Normal && !self.input_buffer.is_empty() {
            self.input_buffer.pop();
        }
    }

    /// Process input and execute command/action
    pub async fn process_input(&mut self) -> Result<()> {
        let input = self.input_buffer.trim().to_string();

        match self.input_mode {
            InputMode::AddingTask => {
                if !input.is_empty() {
                    self.execute_add_task(&input).await?;
                }
            }
            InputMode::CreatingAgent => {
                if !input.is_empty() {
                    self.execute_create_agent(&input).await?;
                }
            }
            InputMode::Command => {
                if !input.is_empty() {
                    self.execute_command(&input).await?;
                }
            }
            InputMode::DelegationInput => {
                if !input.is_empty() {
                    self.execute_delegation_action(&input).await?;
                }
            }
            _ => {}
        }

        self.input_mode = InputMode::Normal;
        self.input_buffer.clear();
        Ok(())
    }

    /// Execute add task command
    async fn execute_add_task(&mut self, description: &str) -> Result<()> {
        // Parse priority and type from description if included
        let (desc, priority, task_type) = self.parse_task_description(description);

        let task =
            crate::agent::Task::new(uuid::Uuid::new_v4().to_string(), desc, priority, task_type);

        self.task_queue.add_task(&task).await?;
        self.add_log("System", &format!("Task added: {}", task.description))
            .await;
        self.refresh_data().await?;
        Ok(())
    }

    /// Execute create agent command
    async fn execute_create_agent(&mut self, agent_type: &str) -> Result<()> {
        let agent_type = agent_type.to_lowercase();
        match agent_type.as_str() {
            "frontend" | "backend" | "devops" | "qa" => {
                self.add_log("System", &format!("Creating {} agent...", agent_type))
                    .await;
                // TODO: Implement actual agent creation
                self.add_log(
                    "System",
                    &format!("{} agent created successfully", agent_type),
                )
                .await;
            }
            _ => {
                self.add_log(
                    "System",
                    "Invalid agent type. Use: frontend, backend, devops, qa",
                )
                .await;
            }
        }
        Ok(())
    }

    /// Execute command
    async fn execute_command(&mut self, command: &str) -> Result<()> {
        let parts: Vec<&str> = command.split_whitespace().collect();
        if parts.is_empty() {
            return Ok(());
        }

        let cmd = parts[0].to_lowercase();
        let args = &parts[1..];

        match cmd.as_str() {
            "help" => self.show_help().await,
            "status" => self.show_detailed_status().await?,
            "agents" => self.list_agents_command().await?,
            "tasks" => self.list_tasks_command().await?,
            "task" => {
                if !args.is_empty() {
                    let full_desc = args.join(" ");
                    self.execute_add_task(&full_desc).await?;
                } else {
                    self.add_log("System", "Usage: task <description>").await;
                }
            }
            "agent" => {
                if let Some(agent_type) = args.first() {
                    self.execute_create_agent(agent_type).await?;
                } else {
                    self.add_log("System", "Usage: agent <type>").await;
                }
            }
            "start_agent" | "activate" => {
                if let Some(agent_id) = args.first() {
                    self.start_agent_by_id(agent_id).await?;
                } else {
                    self.add_log("System", "Usage: start_agent <agent_id|agent_name>")
                        .await;
                }
            }
            "start" => self.start_orchestrator().await?,
            "stop" => self.stop_orchestrator().await?,
            "refresh" => {
                self.refresh_data().await?;
                self.add_log("System", "Data refreshed").await;
            }
            "clear" => {
                self.logs.clear();
                self.add_log("System", "Logs cleared").await;
            }
            "worktree" => {
                if args.is_empty() {
                    self.list_worktrees().await?;
                } else {
                    match args[0] {
                        "list" => self.list_worktrees().await?,
                        "prune" => self.prune_worktrees().await?,
                        _ => self.add_log("System", "Usage: worktree [list|prune]").await,
                    }
                }
            }
            _ => {
                self.add_log(
                    "System",
                    &format!(
                        "Unknown command: {}. Type 'help' for available commands.",
                        cmd
                    ),
                )
                .await;
            }
        }

        Ok(())
    }

    /// Show available commands
    async fn show_help(&mut self) {
        let help_text = vec![
            "Available commands:",
            "  help                    - Show this help",
            "  status                  - Show system status",
            "  agents                  - List all agents",
            "  tasks                   - List all tasks",
            "  task <description>      - Add new task",
            "  agent <type>            - Create new agent (frontend/backend/devops/qa)",
            "  start_agent <id|name>   - Start/activate an agent (e.g., 'start_agent master')",
            "  activate <id|name>      - Alias for start_agent",
            "  start                   - Start orchestrator",
            "  stop                    - Stop orchestrator",
            "  refresh                 - Refresh all data",
            "  clear                   - Clear logs",
            "  worktree [list|prune] - Manage worktrees",
        ];

        for line in help_text {
            self.add_log("System", line).await;
        }
    }

    /// Parse task description for priority and type
    fn parse_task_description(
        &self,
        description: &str,
    ) -> (String, crate::agent::Priority, crate::agent::TaskType) {
        use crate::agent::{Priority, TaskType};

        let mut desc = description.to_string();
        let mut priority = Priority::Medium;
        let mut task_type = TaskType::Development;

        // Extract priority
        if desc.contains("[high]") || desc.contains("[urgent]") {
            priority = Priority::High;
            desc = desc.replace("[high]", "").replace("[urgent]", "");
        } else if desc.contains("[low]") {
            priority = Priority::Low;
            desc = desc.replace("[low]", "");
        } else if desc.contains("[critical]") {
            priority = Priority::Critical;
            desc = desc.replace("[critical]", "");
        }

        // Extract task type
        if desc.contains("[test]") || desc.contains("[testing]") {
            task_type = TaskType::Testing;
            desc = desc.replace("[test]", "").replace("[testing]", "");
        } else if desc.contains("[docs]") || desc.contains("[documentation]") {
            task_type = TaskType::Documentation;
            desc = desc.replace("[docs]", "").replace("[documentation]", "");
        } else if desc.contains("[infra]") || desc.contains("[infrastructure]") {
            task_type = TaskType::Infrastructure;
            desc = desc.replace("[infra]", "").replace("[infrastructure]", "");
        } else if desc.contains("[bug]") || desc.contains("[bugfix]") {
            task_type = TaskType::Bugfix;
            desc = desc.replace("[bug]", "").replace("[bugfix]", "");
        } else if desc.contains("[feature]") {
            task_type = TaskType::Feature;
            desc = desc.replace("[feature]", "");
        }

        (desc.trim().to_string(), priority, task_type)
    }

    /// Show detailed status
    async fn show_detailed_status(&mut self) -> Result<()> {
        self.add_log("System", "=== Detailed System Status ===")
            .await;
        self.add_log("System", &format!("System Status: {}", self.system_status))
            .await;
        self.add_log("System", &format!("Total Agents: {}", self.total_agents))
            .await;
        self.add_log("System", &format!("Active Agents: {}", self.active_agents))
            .await;
        self.add_log("System", &format!("Pending Tasks: {}", self.pending_tasks))
            .await;
        self.add_log(
            "System",
            &format!("Completed Tasks: {}", self.completed_tasks),
        )
        .await;

        // Show Master Claude Code status specifically
        if let Some(master) = self
            .agents
            .iter()
            .find(|a| a.specialization.contains("Master"))
        {
            self.add_log(
                "System",
                &format!("👑 Master Claude Code: {:?}", master.status),
            )
            .await;
        }
        Ok(())
    }

    /// List agents command
    async fn list_agents_command(&mut self) -> Result<()> {
        if self.agents.is_empty() {
            self.add_log("System", "No agents found").await;
        } else {
            self.add_log("System", "Active agents:").await;
            let agent_info: Vec<String> = self
                .agents
                .iter()
                .map(|agent| {
                    format!(
                        "  {} ({}) - {:?}",
                        agent.name, agent.specialization, agent.status
                    )
                })
                .collect();

            for info in agent_info {
                self.add_log("System", &info).await;
            }
        }
        Ok(())
    }

    /// List tasks command
    async fn list_tasks_command(&mut self) -> Result<()> {
        if self.tasks.is_empty() {
            self.add_log("System", "No pending tasks").await;
        } else {
            self.add_log("System", "Pending tasks:").await;
            let task_info: Vec<String> = self
                .tasks
                .iter()
                .map(|task| {
                    format!(
                        "  {} - {} ({})",
                        task.description, task.priority, task.task_type
                    )
                })
                .collect();

            for info in task_info {
                self.add_log("System", &info).await;
            }
        }
        Ok(())
    }

    /// Start orchestrator
    async fn start_orchestrator(&mut self) -> Result<()> {
        self.add_log("System", "Starting orchestrator...").await;
        // TODO: Implement actual orchestrator start
        self.system_status = "Running".to_string();
        self.add_log("System", "Orchestrator started successfully")
            .await;
        Ok(())
    }

    /// Stop orchestrator
    async fn stop_orchestrator(&mut self) -> Result<()> {
        self.add_log("System", "Stopping orchestrator...").await;
        // TODO: Implement actual orchestrator stop
        self.system_status = "Stopped".to_string();
        self.add_log("System", "Orchestrator stopped").await;
        Ok(())
    }

    /// List worktrees
    async fn list_worktrees(&mut self) -> Result<()> {
        self.add_log("System", "Git worktrees:").await;
        // TODO: Implement actual worktree listing
        self.add_log("System", "  No worktrees found").await;
        Ok(())
    }

    /// Prune worktrees
    async fn prune_worktrees(&mut self) -> Result<()> {
        self.add_log("System", "Pruning stale worktrees...").await;
        // TODO: Implement actual worktree pruning
        self.add_log("System", "Worktree pruning completed").await;
        Ok(())
    }

    /// Switch delegation mode
    pub fn switch_delegation_mode(&mut self) {
        self.delegation_mode = match self.delegation_mode {
            DelegationMode::Analyze => DelegationMode::Delegate,
            DelegationMode::Delegate => DelegationMode::ViewStats,
            DelegationMode::ViewStats => DelegationMode::Analyze,
        };
    }

    /// Start delegation input mode
    pub async fn start_delegation_input(&mut self) -> Result<()> {
        self.input_mode = InputMode::DelegationInput;
        self.delegation_input.clear();

        match self.delegation_mode {
            DelegationMode::Analyze => {
                self.add_log("Master", "Enter task description to analyze:")
                    .await;
            }
            DelegationMode::Delegate => {
                self.add_log("Master", "Enter task description to delegate:")
                    .await;
            }
            _ => {}
        }
        Ok(())
    }

    /// Execute delegation action
    async fn execute_delegation_action(&mut self, input: &str) -> Result<()> {
        match self.delegation_mode {
            DelegationMode::Analyze => {
                self.analyze_task_for_delegation(input).await?;
            }
            DelegationMode::Delegate => {
                self.delegate_task_to_agent(input).await?;
            }
            _ => {}
        }
        Ok(())
    }

    /// Analyze task for delegation
    async fn analyze_task_for_delegation(&mut self, task_description: &str) -> Result<()> {
        self.add_log(
            "Master",
            &format!("🔍 Analyzing task: '{}'", task_description),
        )
        .await;

        // Use basic rule-based analysis for demo
        let (recommended_agent, confidence, reasoning) =
            self.analyze_task_content(task_description);

        let delegation_info = DelegationInfo {
            task_description: task_description.to_string(),
            recommended_agent: recommended_agent.clone(),
            confidence,
            reasoning: reasoning.clone(),
            created_at: chrono::Utc::now(),
        };

        self.delegation_decisions.push(delegation_info);

        self.add_log(
            "Master",
            &format!(
                "✅ Analysis complete: {} agent recommended ({:.1}% confidence)",
                recommended_agent,
                confidence * 100.0
            ),
        )
        .await;
        self.add_log("Master", &format!("📝 Reasoning: {}", reasoning))
            .await;

        Ok(())
    }

    /// Delegate task to specific agent
    async fn delegate_task_to_agent(&mut self, input: &str) -> Result<()> {
        // Parse input as "agent_type task_description"
        let parts: Vec<&str> = input.splitn(2, ' ').collect();
        if parts.len() < 2 {
            self.add_log("Master", "Usage: <agent_type> <task_description>")
                .await;
            return Ok(());
        }

        let agent_type = parts[0];
        let task_description = parts[1];

        // Validate agent type
        let valid_agents = ["frontend", "backend", "devops", "qa"];
        if !valid_agents.contains(&agent_type) {
            self.add_log(
                "Master",
                &format!(
                    "Invalid agent type: {}. Valid agents: {}",
                    agent_type,
                    valid_agents.join(", ")
                ),
            )
            .await;
            return Ok(());
        }

        self.add_log(
            "Master",
            &format!(
                "🎯 Delegating task to {} agent: '{}'",
                agent_type, task_description
            ),
        )
        .await;

        // Create and add task to queue
        let task = crate::agent::Task::new(
            uuid::Uuid::new_v4().to_string(),
            task_description.to_string(),
            crate::agent::Priority::Medium,
            crate::agent::TaskType::Development,
        );

        self.task_queue.add_task(&task).await?;

        // Add delegation decision for tracking
        let delegation_info = DelegationInfo {
            task_description: task_description.to_string(),
            recommended_agent: agent_type.to_string(),
            confidence: 1.0, // Manual delegation is 100% confident
            reasoning: "Manual delegation by Master".to_string(),
            created_at: chrono::Utc::now(),
        };

        self.delegation_decisions.push(delegation_info);

        self.add_log(
            "Master",
            &format!("✅ Task delegated to {} agent successfully", agent_type),
        )
        .await;
        self.refresh_data().await?;

        Ok(())
    }

    /// Analyze task content and recommend agent
    fn analyze_task_content(&self, task_description: &str) -> (String, f64, String) {
        let desc_lower = task_description.to_lowercase();

        // Frontend keywords
        if desc_lower.contains("ui")
            || desc_lower.contains("html")
            || desc_lower.contains("css")
            || desc_lower.contains("javascript")
            || desc_lower.contains("component")
            || desc_lower.contains("react")
            || desc_lower.contains("vue")
            || desc_lower.contains("frontend")
        {
            return (
                "Frontend".to_string(),
                0.9,
                "Contains UI/frontend keywords".to_string(),
            );
        }

        // Backend keywords
        if desc_lower.contains("api")
            || desc_lower.contains("server")
            || desc_lower.contains("database")
            || desc_lower.contains("backend")
            || desc_lower.contains("endpoint")
            || desc_lower.contains("node")
            || desc_lower.contains("express")
            || desc_lower.contains("rest")
        {
            return (
                "Backend".to_string(),
                0.9,
                "Contains API/backend keywords".to_string(),
            );
        }

        // Testing keywords
        if desc_lower.contains("test")
            || desc_lower.contains("testing")
            || desc_lower.contains("qa")
            || desc_lower.contains("quality")
            || desc_lower.contains("validation")
            || desc_lower.contains("unit")
        {
            return (
                "QA".to_string(),
                0.9,
                "Contains testing/QA keywords".to_string(),
            );
        }

        // Infrastructure keywords
        if desc_lower.contains("deploy")
            || desc_lower.contains("ci/cd")
            || desc_lower.contains("docker")
            || desc_lower.contains("infrastructure")
            || desc_lower.contains("pipeline")
            || desc_lower.contains("build")
            || desc_lower.contains("devops")
        {
            return (
                "DevOps".to_string(),
                0.9,
                "Contains infrastructure/DevOps keywords".to_string(),
            );
        }

        // Default to backend for general development
        (
            "Backend".to_string(),
            0.6,
            "General development task, defaulting to backend".to_string(),
        )
    }

    /// Get delegation statistics
    pub fn get_delegation_stats(&self) -> String {
        if self.delegation_decisions.is_empty() {
            return "No delegation decisions yet".to_string();
        }

        let total = self.delegation_decisions.len();
        let mut agent_counts = std::collections::HashMap::new();
        let mut total_confidence = 0.0;

        for decision in &self.delegation_decisions {
            *agent_counts
                .entry(decision.recommended_agent.clone())
                .or_insert(0) += 1;
            total_confidence += decision.confidence;
        }

        let avg_confidence = total_confidence / total as f64;

        let mut stats = "📊 Delegation Statistics:\n".to_string();
        stats.push_str(&format!("Total delegations: {}\n", total));
        stats.push_str(&format!(
            "Average confidence: {:.1}%\n",
            avg_confidence * 100.0
        ));
        stats.push_str("Agent distribution:\n");

        for (agent, count) in agent_counts {
            let percentage = (count as f64 / total as f64) * 100.0;
            stats.push_str(&format!("  {}: {} ({:.1}%)\n", agent, count, percentage));
        }

        stats
    }

    /// Handle delegation tab interactions
    pub async fn handle_delegation_enter(&mut self) -> Result<()> {
        match self.delegation_mode {
            DelegationMode::Analyze | DelegationMode::Delegate => {
                self.start_delegation_input().await?;
            }
            DelegationMode::ViewStats => {
                // Show delegation statistics
                let stats = self.get_delegation_stats();
                for line in stats.lines() {
                    self.add_log("Master", line).await;
                }
            }
        }
        Ok(())
    }

    /// Handle keyboard input
    pub fn handle_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
        use crossterm::event::{KeyCode, KeyModifiers};

        match self.input_mode {
            InputMode::Normal => {
                match key.code {
                    KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        self.should_quit = true;
                    }
                    KeyCode::Tab => self.next_tab(),
                    KeyCode::BackTab => self.previous_tab(),
                    KeyCode::Up | KeyCode::Char('k') => self.previous_item(),
                    KeyCode::Down | KeyCode::Char('j') => self.next_item(),
                    KeyCode::Enter => {
                        // Handle enter based on current tab
                        tokio::spawn({
                            let mut app_clone = self.clone_for_async();
                            async move {
                                let _ = app_clone.activate_selected().await;
                            }
                        });
                    }
                    KeyCode::Char('n') => {
                        tokio::spawn({
                            let mut app_clone = self.clone_for_async();
                            async move {
                                let _ = app_clone.create_new_session().await;
                            }
                        });
                    }
                    KeyCode::Char('t') => {
                        tokio::spawn({
                            let mut app_clone = self.clone_for_async();
                            async move {
                                let _ = app_clone.add_task_prompt().await;
                            }
                        });
                    }
                    KeyCode::Char(':') => {
                        self.input_mode = InputMode::Command;
                        self.input_buffer.clear();
                    }
                    _ => {}
                }
            }
            InputMode::AddingTask
            | InputMode::CreatingAgent
            | InputMode::Command
            | InputMode::DelegationInput => {
                match key.code {
                    KeyCode::Esc => {
                        self.input_mode = InputMode::Normal;
                        self.input_buffer.clear();
                    }
                    KeyCode::Enter => {
                        let input = self.input_buffer.clone();
                        let mode = self.input_mode.clone();
                        self.input_mode = InputMode::Normal;
                        self.input_buffer.clear();

                        // Process the input based on mode
                        tokio::spawn({
                            let mut app_clone = self.clone_for_async();
                            async move {
                                match mode {
                                    InputMode::AddingTask => {
                                        let _ = app_clone.add_task(&input).await;
                                    }
                                    InputMode::CreatingAgent => {
                                        let _ = app_clone.create_agent(&input).await;
                                    }
                                    InputMode::Command => {
                                        let _ = app_clone.execute_command(&input).await;
                                    }
                                    InputMode::DelegationInput => {
                                        let _ = app_clone.handle_delegation_input(&input).await;
                                    }
                                    _ => {}
                                }
                            }
                        });
                    }
                    KeyCode::Char(c) => {
                        self.input_buffer.push(c);
                    }
                    KeyCode::Backspace => {
                        self.input_buffer.pop();
                    }
                    _ => {}
                }
            }
        }

        Ok(())
    }

    /// Handle mouse events
    pub fn handle_mouse(&mut self, mouse: crossterm::event::MouseEvent) -> Result<()> {
        use crossterm::event::{MouseButton, MouseEventKind};

        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                // Handle tab clicks based on mouse position
                if mouse.row == 0 {
                    // Tab bar is at row 0
                    let tab_width = self.terminal_width / 5; // 5 tabs
                    let tab_index = mouse.column / tab_width;

                    self.current_tab = match tab_index {
                        0 => Tab::Overview,
                        1 => Tab::Agents,
                        2 => Tab::Tasks,
                        3 => Tab::Logs,
                        4 => Tab::Delegation,
                        _ => self.current_tab.clone(),
                    };
                    self.reset_selection();
                }
            }
            MouseEventKind::ScrollDown => {
                self.next_item();
            }
            MouseEventKind::ScrollUp => {
                self.previous_item();
            }
            _ => {}
        }

        Ok(())
    }

    /// Handle terminal resize
    pub fn handle_resize(&mut self, width: u16, height: u16) -> Result<()> {
        self.terminal_width = width;
        self.terminal_height = height;
        Ok(())
    }

    /// Add a task from input
    pub async fn add_task(&mut self, description: &str) -> Result<()> {
        let task = TaskInfo {
            id: format!("task-{}", uuid::Uuid::new_v4()),
            description: description.to_string(),
            priority: "Medium".to_string(),
            task_type: "Development".to_string(),
            status: "Pending".to_string(),
            assigned_agent: None,
            created_at: Utc::now(),
        };

        self.tasks.push(task);
        self.pending_tasks += 1;
        self.add_log("System", &format!("Task added: {}", description))
            .await;

        Ok(())
    }

    /// Create a new agent from input
    pub async fn create_agent(&mut self, agent_type: &str) -> Result<()> {
        let agent = AgentInfo {
            id: format!("agent-{}", uuid::Uuid::new_v4()),
            name: format!("{}-specialist", agent_type),
            specialization: agent_type.to_string(),
            provider_type: "Claude Code".to_string(),
            provider_icon: "🤖".to_string(),
            provider_color: "#4CAF50".to_string(),
            status: AgentStatus::Available,
            current_task: None,
            tasks_completed: 0,
            last_activity: Utc::now(),
            workspace: format!("./workspace/{}", agent_type),
        };

        self.agents.push(agent);
        self.total_agents += 1;
        self.add_log(
            "System",
            &format!("Agent created: {}-specialist", agent_type),
        )
        .await;

        Ok(())
    }

    /// Handle delegation input
    pub async fn handle_delegation_input(&mut self, input: &str) -> Result<()> {
        match self.delegation_mode {
            DelegationMode::Analyze => {
                self.add_log("Delegation", &format!("Analyzing: {}", input))
                    .await;

                // Create a delegation decision
                let decision = DelegationInfo {
                    task_description: input.to_string(),
                    recommended_agent: "frontend-specialist".to_string(),
                    confidence: 0.85,
                    reasoning: "Task requires frontend expertise".to_string(),
                    created_at: Utc::now(),
                };

                self.delegation_decisions.push(decision);
            }
            DelegationMode::Delegate => {
                self.add_log("Delegation", &format!("Delegating: {}", input))
                    .await;
                // Actually delegate the task
                if let Some(task) = self.tasks.iter_mut().find(|t| t.status == "Pending") {
                    task.assigned_agent = Some("frontend-specialist".to_string());
                    task.status = "Assigned".to_string();
                }
            }
            DelegationMode::ViewStats => {
                self.add_log("Delegation", "Viewing delegation statistics")
                    .await;
            }
        }

        Ok(())
    }

    /// Clone for async operations (simplified clone without Arc fields)
    fn clone_for_async(&self) -> Self {
        // This is a simplified clone for async operations
        // In a real implementation, you'd want to share state properly
        Self {
            current_tab: self.current_tab.clone(),
            selected_agent: self.selected_agent,
            selected_task: self.selected_task,
            selected_log: self.selected_log,
            selected_delegation: self.selected_delegation,
            agents: self.agents.clone(),
            tasks: self.tasks.clone(),
            logs: self.logs.clone(),
            delegation_decisions: self.delegation_decisions.clone(),
            system_status: self.system_status.clone(),
            total_agents: self.total_agents,
            active_agents: self.active_agents,
            pending_tasks: self.pending_tasks,
            completed_tasks: self.completed_tasks,
            tasks_executed: self.tasks_executed,
            tasks_failed: self.tasks_failed,
            success_rate: self.success_rate,
            orchestration_usage: self.orchestration_usage,
            total_sessions: self.total_sessions,
            active_sessions: self.active_sessions,
            multi_agent_enabled: self.multi_agent_enabled,
            input_mode: self.input_mode.clone(),
            input_buffer: self.input_buffer.clone(),
            delegation_mode: self.delegation_mode.clone(),
            delegation_input: self.delegation_input.clone(),
            coordination_bus: self.coordination_bus.clone(),
            status_tracker: self.status_tracker.clone(),
            task_queue: self.task_queue.clone(),
            execution_engine: self.execution_engine.clone(),
            terminal_width: self.terminal_width,
            terminal_height: self.terminal_height,
            last_update: self.last_update,
            update_interval: self.update_interval,
            should_quit: self.should_quit,
        }
    }
}

/// Parse agent status from string
fn parse_agent_status(status: &str) -> AgentStatus {
    match status {
        "Initializing" => AgentStatus::Initializing,
        "Available" => AgentStatus::Available,
        "Working" => AgentStatus::Working,
        "WaitingForReview" => AgentStatus::WaitingForReview,
        "ShuttingDown" => AgentStatus::ShuttingDown,
        _ => AgentStatus::Error(format!("Unknown status: {}", status)),
    }
}