cctakt 0.1.1

TUI orchestrator for multiple Claude Code agents using Git Worktree
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
//! Agent module - manages individual Claude Code sessions
//!
//! Supports two modes:
//! - Interactive (PTY): For orchestrator sessions with human interaction
//! - Non-interactive (stream-json): For worker sessions with deterministic completion

use anyhow::{Context, Result};
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use cctakt::stream_parser::{StreamEvent, StreamParser};
use cctakt::debug;

/// Agent execution mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentMode {
    /// Interactive mode using PTY (for orchestrator)
    Interactive,
    /// Non-interactive mode using stream-json (for workers)
    NonInteractive,
}

/// Status of an agent
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentStatus {
    Running,
    Ended,
}

/// Work state of an agent
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorkState {
    /// Agent is starting up
    Starting,
    /// Agent is actively working (receiving output)
    Working,
    /// Agent is idle (no output for a while, waiting for input)
    Idle,
    /// Agent has completed work (detected completion patterns)
    Completed,
}

/// Internal state for interactive (PTY) mode
struct InteractiveState {
    parser: Arc<Mutex<vt100::Parser>>,
    pty_writer: Option<Box<dyn Write + Send>>,
    pty_master: Option<Box<dyn MasterPty + Send>>,
    child: Option<Box<dyn portable_pty::Child + Send + Sync>>,
    last_activity: Arc<Mutex<Instant>>,
}

/// Internal state for non-interactive mode
struct NonInteractiveState {
    parser: Arc<Mutex<StreamParser>>,
    child: Option<Child>,
    output_buffer: Arc<Mutex<String>>,
}

/// Represents a single Claude Code session
pub struct Agent {
    #[allow(dead_code)]
    pub id: usize,
    pub name: String,
    #[allow(dead_code)]
    pub working_dir: PathBuf,
    pub status: AgentStatus,
    pub work_state: WorkState,
    pub task_sent: bool,
    pub mode: AgentMode,
    /// Branch name associated with this agent (for workers)
    pub branch: Option<String>,
    /// Error message if failed (non-interactive only)
    pub error: Option<String>,
    /// Result text if completed (non-interactive only)
    pub result: Option<String>,
    /// Total cost in USD (non-interactive only)
    pub cost_usd: Option<f64>,
    /// Total duration in milliseconds (non-interactive only)
    pub duration_ms: Option<u64>,
    /// Number of turns (non-interactive only)
    pub num_turns: Option<u32>,
    /// Interactive state (PTY)
    interactive: Option<InteractiveState>,
    /// Non-interactive state (stream-json)
    non_interactive: Option<NonInteractiveState>,
    /// Output reading thread handle
    _output_thread: Option<JoinHandle<()>>,
}

impl Agent {
    /// Create a new agent in interactive (PTY) mode
    pub fn spawn(id: usize, name: String, working_dir: PathBuf, rows: u16, cols: u16) -> Result<Self> {
        let parser = Arc::new(Mutex::new(vt100::Parser::new(rows, cols, 1000)));

        // Setup PTY
        let pty_system = native_pty_system();
        let pair = pty_system
            .openpty(PtySize {
                rows,
                cols,
                pixel_width: 0,
                pixel_height: 0,
            })
            .context("Failed to open pty")?;

        // Spawn Claude Code in the specified working directory (orchestrator mode)
        let mut cmd = CommandBuilder::new("claude");
        cmd.arg("--dangerously-skip-permissions");
        cmd.arg("--append-system-prompt");
        cmd.arg(
            "You are the ORCHESTRATOR. Your job is to coordinate work, NOT implement it yourself.\n\
            RULES:\n\
            1. DO NOT write implementation code - Workers do that\n\
            2. DO NOT edit source files (*.rs, *.ts, *.py, etc.)\n\
            3. Your ONLY job is to create plans in .cctakt/plan.json\n\
            4. Use Skill tool with skill=\"orchestrator\" to see plan format reference\n\
            When user requests a feature, write a plan.json with create_worker tasks."
        );
        cmd.cwd(&working_dir);

        let child = pair.slave.spawn_command(cmd).context("Failed to spawn claude")?;
        drop(pair.slave);

        // Setup PTY reader/writer
        let reader = pair.master.try_clone_reader().context("Failed to clone reader")?;
        let pty_writer = Some(pair.master.take_writer().context("Failed to take writer")?);
        let pty_master = Some(pair.master);

        // Activity tracking
        let last_activity = Arc::new(Mutex::new(Instant::now()));
        let last_activity_clone = Arc::clone(&last_activity);

        // Spawn output reading thread
        let parser_clone = Arc::clone(&parser);
        let output_thread = std::thread::spawn(move || {
            let mut reader = reader;
            let mut buf = [0u8; 4096];
            loop {
                match reader.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        if let Ok(mut ts) = last_activity_clone.lock() {
                            *ts = Instant::now();
                        }
                        let mut parser = parser_clone.lock().unwrap();
                        parser.process(&buf[..n]);
                    }
                    Err(_) => break,
                }
            }
        });

        Ok(Self {
            id,
            name,
            working_dir,
            status: AgentStatus::Running,
            work_state: WorkState::Starting,
            task_sent: false,
            mode: AgentMode::Interactive,
            branch: None,
            error: None,
            result: None,
            cost_usd: None,
            duration_ms: None,
            num_turns: None,
            interactive: Some(InteractiveState {
                parser,
                pty_writer,
                pty_master,
                child: Some(child),
                last_activity,
            }),
            non_interactive: None,
            _output_thread: Some(output_thread),
        })
    }

    /// Create a new agent in non-interactive mode
    pub fn spawn_non_interactive(
        id: usize,
        name: String,
        working_dir: PathBuf,
        task_description: &str,
        max_turns: Option<u32>,
        branch: Option<String>,
    ) -> Result<Self> {
        let parser = Arc::new(Mutex::new(StreamParser::new()));
        let output_buffer = Arc::new(Mutex::new(String::new()));

        // Build command
        let mut cmd = Command::new("claude");
        cmd.arg("-p")
            .arg(task_description)
            .arg("--output-format")
            .arg("stream-json")
            .arg("--verbose")
            .arg("--dangerously-skip-permissions");

        if let Some(turns) = max_turns {
            cmd.arg("--max-turns").arg(turns.to_string());
        }

        cmd.current_dir(&working_dir)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let mut child = cmd.spawn().context("Failed to spawn claude process")?;

        let stdout = child.stdout.take().context("Failed to capture stdout")?;
        let stderr = child.stderr.take().context("Failed to capture stderr")?;

        // Spawn output reading thread
        let parser_clone = Arc::clone(&parser);
        let output_buffer_clone = Arc::clone(&output_buffer);
        let worker_name = name.clone();
        let output_thread = std::thread::spawn(move || {
            let reader = BufReader::new(stdout);
            for line in reader.lines() {
                if let Ok(line) = line {
                    // Log raw stream-json output in debug builds
                    debug::log_worker(&worker_name, "stream", &line);

                    if let Ok(mut p) = parser_clone.lock() {
                        p.feed(&format!("{}\n", line));
                    }
                    if let Ok(mut buf) = output_buffer_clone.lock() {
                        buf.push_str(&line);
                        buf.push('\n');
                    }
                }
            }
            debug::log_worker(&worker_name, "EOF", "stdout closed");
        });

        // Spawn stderr reading thread
        std::thread::spawn(move || {
            let reader = BufReader::new(stderr);
            for line in reader.lines().map_while(Result::ok) {
                eprintln!("[agent stderr] {line}");
            }
        });

        Ok(Self {
            id,
            name,
            working_dir,
            status: AgentStatus::Running,
            work_state: WorkState::Working,
            task_sent: true,
            mode: AgentMode::NonInteractive,
            branch,
            error: None,
            result: None,
            cost_usd: None,
            duration_ms: None,
            num_turns: None,
            interactive: None,
            non_interactive: Some(NonInteractiveState {
                parser,
                child: Some(child),
                output_buffer,
            }),
            _output_thread: Some(output_thread),
        })
    }

    /// Send bytes to the agent (interactive mode only)
    pub fn send_bytes(&mut self, bytes: &[u8]) {
        if let Some(ref mut state) = self.interactive {
            if let Some(ref mut writer) = state.pty_writer {
                let _ = writer.write_all(bytes);
                let _ = writer.flush();
            }
        }
    }

    /// Resize the PTY (interactive mode only)
    pub fn resize(&mut self, cols: u16, rows: u16) {
        if let Some(ref mut state) = self.interactive {
            {
                let mut parser = state.parser.lock().unwrap();
                parser.set_size(rows, cols);
            }
            if let Some(ref master) = state.pty_master {
                let _ = master.resize(PtySize {
                    rows,
                    cols,
                    pixel_width: 0,
                    pixel_height: 0,
                });
            }
        }
    }

    /// Check if the process has ended
    pub fn check_status(&mut self) -> AgentStatus {
        if self.status == AgentStatus::Running {
            match self.mode {
                AgentMode::Interactive => {
                    if let Some(ref mut state) = self.interactive {
                        if let Some(ref mut child) = state.child {
                            if let Ok(Some(_)) = child.try_wait() {
                                self.status = AgentStatus::Ended;
                            }
                        }
                    }
                }
                AgentMode::NonInteractive => {
                    if let Some(ref mut state) = self.non_interactive {
                        if let Some(ref mut child) = state.child {
                            if let Ok(Some(exit_status)) = child.try_wait() {
                                self.status = AgentStatus::Ended;
                                if let Ok(p) = state.parser.lock() {
                                    if p.completed {
                                        self.work_state = WorkState::Completed;
                                        self.result = p.result.clone();
                                        self.error = p.error.clone();
                                    }
                                }
                                if !exit_status.success() && self.error.is_none() {
                                    self.error = Some(format!("Process exited with status: {exit_status}"));
                                }
                            }
                        }
                    }
                }
            }
        }
        self.status
    }

    /// Get time since last activity (interactive mode)
    pub fn idle_duration(&self) -> Duration {
        if let Some(ref state) = self.interactive {
            if let Ok(ts) = state.last_activity.lock() {
                return ts.elapsed();
            }
        }
        Duration::ZERO
    }

    /// Get the current screen content as text
    pub fn screen_text(&self) -> String {
        match self.mode {
            AgentMode::Interactive => {
                if let Some(ref state) = self.interactive {
                    if let Ok(parser) = state.parser.lock() {
                        let screen = parser.screen();
                        let mut text = String::new();
                        for row in 0..screen.size().0 {
                            let line = screen.contents_between(row, 0, row, screen.size().1);
                            text.push_str(&line);
                            text.push('\n');
                        }
                        return text;
                    }
                }
                String::new()
            }
            AgentMode::NonInteractive => {
                if let Some(ref state) = self.non_interactive {
                    if let Ok(buf) = state.output_buffer.lock() {
                        return buf.clone();
                    }
                }
                String::new()
            }
        }
    }

    /// Check work state and update based on activity
    /// Returns true if state changed to Completed
    pub fn update_work_state(&mut self, idle_threshold: Duration) -> bool {
        let old_state = self.work_state;

        match self.mode {
            AgentMode::Interactive => {
                if !self.task_sent {
                    return false;
                }

                let idle_time = self.idle_duration();
                let screen = self.screen_text();
                let is_at_prompt = self.detect_prompt_waiting(&screen);
                let has_committed = self.detect_commit_success(&screen);

                match self.work_state {
                    WorkState::Starting => {
                        self.work_state = WorkState::Working;
                    }
                    WorkState::Working | WorkState::Idle => {
                        if is_at_prompt && has_committed && idle_time >= idle_threshold {
                            self.work_state = WorkState::Completed;
                        } else if idle_time >= idle_threshold {
                            self.work_state = WorkState::Idle;
                        } else if idle_time < Duration::from_millis(500) {
                            self.work_state = WorkState::Working;
                        }
                    }
                    WorkState::Completed => {}
                }
            }
            AgentMode::NonInteractive => {
                if let Some(ref state) = self.non_interactive {
                    if let Ok(p) = state.parser.lock() {
                        // Always sync cost info (even before completion)
                        self.cost_usd = p.cost_usd;
                        self.duration_ms = p.duration_ms;
                        self.num_turns = p.num_turns;
                        if p.completed {
                            self.work_state = WorkState::Completed;
                            self.result = p.result.clone();
                            self.error = p.error.clone();
                        }
                    }
                }
            }
        }

        old_state != WorkState::Completed && self.work_state == WorkState::Completed
    }

    /// Detect if screen shows a prompt waiting for input (interactive mode)
    fn detect_prompt_waiting(&self, screen: &str) -> bool {
        let lines: Vec<&str> = screen
            .lines()
            .filter(|l| !l.trim().is_empty())
            .collect();

        if let Some(last_line) = lines.last() {
            let trimmed = last_line.trim();
            if trimmed.ends_with('>')
                || trimmed.ends_with('$')
                || trimmed.contains("")
                || trimmed.ends_with(':')
            {
                return true;
            }
        }
        false
    }

    /// Detect if there's been a successful commit (interactive mode)
    fn detect_commit_success(&self, screen: &str) -> bool {
        let lower = screen.to_lowercase();
        let patterns = [
            "successfully committed",
            "changes committed",
            "created commit",
            "commit created",
            "[main",
            "[master",
            "files changed",
            "insertions(+)",
            "deletions(-)",
        ];

        for pattern in patterns {
            if lower.contains(pattern) {
                return true;
            }
        }
        false
    }

    /// Get the vt100 parser (interactive mode only)
    pub fn get_parser(&self) -> Option<&Arc<Mutex<vt100::Parser>>> {
        self.interactive.as_ref().map(|s| &s.parser)
    }

    /// Get stream events (non-interactive mode only)
    #[allow(dead_code)]
    pub fn events(&self) -> Vec<StreamEvent> {
        if let Some(ref state) = self.non_interactive {
            if let Ok(p) = state.parser.lock() {
                return p.events.clone();
            }
        }
        Vec::new()
    }

    /// Check if completed successfully (non-interactive mode)
    #[allow(dead_code)]
    pub fn is_success(&self) -> bool {
        self.work_state == WorkState::Completed && self.error.is_none()
    }

    /// Check if completed with error (non-interactive mode)
    #[allow(dead_code)]
    pub fn is_error(&self) -> bool {
        self.work_state == WorkState::Completed && self.error.is_some()
    }
}

/// Manages multiple agents
pub struct AgentManager {
    agents: Vec<Agent>,
    active_index: usize,
    next_id: usize,
}

impl AgentManager {
    /// Create a new empty AgentManager
    pub fn new() -> Self {
        Self {
            agents: Vec::new(),
            active_index: 0,
            next_id: 1,
        }
    }

    /// Add a new agent in interactive (PTY) mode
    pub fn add(&mut self, name: String, working_dir: PathBuf, rows: u16, cols: u16) -> Result<usize> {
        let id = self.next_id;
        let agent = Agent::spawn(id, name, working_dir, rows, cols)?;
        self.agents.push(agent);
        self.next_id += 1;
        self.active_index = self.agents.len() - 1;
        Ok(id)
    }

    /// Add a new agent in non-interactive mode
    pub fn add_non_interactive(
        &mut self,
        name: String,
        working_dir: PathBuf,
        task_description: &str,
        max_turns: Option<u32>,
        branch: Option<String>,
    ) -> Result<usize> {
        let id = self.next_id;
        let agent = Agent::spawn_non_interactive(id, name, working_dir, task_description, max_turns, branch)?;
        self.agents.push(agent);
        self.next_id += 1;
        self.active_index = self.agents.len() - 1;
        Ok(id)
    }

    /// Get the active agent
    pub fn active(&self) -> Option<&Agent> {
        self.agents.get(self.active_index)
    }

    /// Get the active agent mutably
    pub fn active_mut(&mut self) -> Option<&mut Agent> {
        self.agents.get_mut(self.active_index)
    }

    /// Get an agent by index
    pub fn get(&self, index: usize) -> Option<&Agent> {
        self.agents.get(index)
    }

    /// Get an agent by index mutably
    pub fn get_mut(&mut self, index: usize) -> Option<&mut Agent> {
        self.agents.get_mut(index)
    }

    /// Get the number of agents
    pub fn len(&self) -> usize {
        self.agents.len()
    }

    /// Switch to a specific agent by index
    pub fn switch_to(&mut self, index: usize) {
        if index < self.agents.len() {
            self.active_index = index;
        }
    }

    /// Switch to the next agent
    pub fn next(&mut self) {
        if !self.agents.is_empty() {
            self.active_index = (self.active_index + 1) % self.agents.len();
        }
    }

    /// Switch to the previous agent
    pub fn prev(&mut self) {
        if !self.agents.is_empty() {
            self.active_index = if self.active_index == 0 {
                self.agents.len() - 1
            } else {
                self.active_index - 1
            };
        }
    }

    /// Close an agent by index
    pub fn close(&mut self, index: usize) {
        if index < self.agents.len() {
            self.agents.remove(index);
            if self.agents.is_empty() {
                self.active_index = 0;
            } else if self.active_index >= self.agents.len() {
                self.active_index = self.agents.len() - 1;
            } else if index < self.active_index {
                self.active_index -= 1;
            }
        }
    }

    /// Get all agents
    pub fn list(&self) -> &[Agent] {
        &self.agents
    }

    /// Get the current active index
    pub fn active_index(&self) -> usize {
        self.active_index
    }

    /// Check if there are any agents
    pub fn is_empty(&self) -> bool {
        self.agents.is_empty()
    }

    /// Check status of all agents
    pub fn check_all_status(&mut self) {
        for agent in &mut self.agents {
            agent.check_status();
        }
    }

    /// Resize all agents' PTYs
    pub fn resize_all(&mut self, cols: u16, rows: u16) {
        for agent in &mut self.agents {
            agent.resize(cols, rows);
        }
    }

    /// Get the first Interactive (orchestrator) agent
    pub fn get_interactive(&self) -> Option<&Agent> {
        self.agents.iter().find(|a| a.mode == AgentMode::Interactive)
    }

    /// Get the Interactive (orchestrator) agent (mutable)
    pub fn get_interactive_mut(&mut self) -> Option<&mut Agent> {
        self.agents.iter_mut().find(|a| a.mode == AgentMode::Interactive)
    }

    /// Get all NonInteractive (worker) agents
    #[allow(dead_code)]
    pub fn get_non_interactive_agents(&self) -> Vec<&Agent> {
        self.agents.iter().filter(|a| a.mode == AgentMode::NonInteractive).collect()
    }

    /// Check if there are any non-interactive agents
    pub fn has_non_interactive(&self) -> bool {
        self.agents.iter().any(|a| a.mode == AgentMode::NonInteractive)
    }

    /// Get mutable references to all non-interactive agents
    pub fn get_all_non_interactive_mut(&mut self) -> impl Iterator<Item = &mut Agent> {
        self.agents.iter_mut().filter(|a| a.mode == AgentMode::NonInteractive)
    }

    /// Get the active NonInteractive agent (based on active_index among workers)
    pub fn get_active_non_interactive(&self) -> Option<&Agent> {
        let workers: Vec<_> = self.agents.iter()
            .enumerate()
            .filter(|(_, a)| a.mode == AgentMode::NonInteractive)
            .collect();

        if workers.is_empty() {
            return None;
        }

        // Find if active_index points to a worker
        if let Some(agent) = self.agents.get(self.active_index) {
            if agent.mode == AgentMode::NonInteractive {
                return Some(agent);
            }
        }

        // Default to first worker
        workers.first().map(|(_, a)| *a)
    }

    /// Get the active NonInteractive agent (mutable)
    pub fn get_active_non_interactive_mut(&mut self) -> Option<&mut Agent> {
        let worker_indices: Vec<_> = self.agents.iter()
            .enumerate()
            .filter(|(_, a)| a.mode == AgentMode::NonInteractive)
            .map(|(idx, _)| idx)
            .collect();

        if worker_indices.is_empty() {
            return None;
        }

        // Find if active_index points to a worker
        if worker_indices.contains(&self.active_index) {
            return self.agents.get_mut(self.active_index);
        }

        // Default to first worker
        let first_idx = worker_indices[0];
        self.agents.get_mut(first_idx)
    }

    /// Get the index of the active NonInteractive agent within workers list
    #[allow(dead_code)]
    pub fn active_worker_index(&self) -> Option<usize> {
        let workers: Vec<_> = self.agents.iter()
            .enumerate()
            .filter(|(_, a)| a.mode == AgentMode::NonInteractive)
            .collect();

        if workers.is_empty() {
            return None;
        }

        // Check if active_index points to a worker
        workers.iter()
            .position(|(idx, _)| *idx == self.active_index)
            .or(Some(0))
    }

    /// Switch to a worker by its index within the workers list
    #[allow(dead_code)]
    pub fn switch_to_worker(&mut self, worker_index: usize) {
        let workers: Vec<_> = self.agents.iter()
            .enumerate()
            .filter(|(_, a)| a.mode == AgentMode::NonInteractive)
            .map(|(idx, _)| idx)
            .collect();

        if let Some(&global_idx) = workers.get(worker_index) {
            self.active_index = global_idx;
        }
    }

    /// Switch to the next worker (cycle through workers)
    pub fn switch_to_next_worker(&mut self) {
        let workers: Vec<_> = self.agents.iter()
            .enumerate()
            .filter(|(_, a)| a.mode == AgentMode::NonInteractive)
            .map(|(idx, _)| idx)
            .collect();

        if workers.is_empty() {
            return;
        }

        // Find current position in workers list
        let current_pos = workers.iter()
            .position(|&idx| idx == self.active_index)
            .unwrap_or(0);

        // Move to next worker (wrap around)
        let next_pos = (current_pos + 1) % workers.len();
        self.active_index = workers[next_pos];
    }

    /// Switch to the previous worker (cycle through workers)
    pub fn switch_to_prev_worker(&mut self) {
        let workers: Vec<_> = self.agents.iter()
            .enumerate()
            .filter(|(_, a)| a.mode == AgentMode::NonInteractive)
            .map(|(idx, _)| idx)
            .collect();

        if workers.is_empty() {
            return;
        }

        // Find current position in workers list
        let current_pos = workers.iter()
            .position(|&idx| idx == self.active_index)
            .unwrap_or(0);

        // Move to previous worker (wrap around)
        let prev_pos = if current_pos == 0 {
            workers.len() - 1
        } else {
            current_pos - 1
        };
        self.active_index = workers[prev_pos];
    }

    /// Restart the interactive (orchestrator) agent
    /// Stops the existing orchestrator and spawns a new one
    pub fn restart_interactive(&mut self, rows: u16, cols: u16) -> Result<()> {
        // Find and remove existing interactive agent
        if let Some(idx) = self.agents.iter().position(|a| a.mode == AgentMode::Interactive) {
            self.agents.remove(idx);
            // Adjust active_index if needed
            if self.active_index >= self.agents.len() && !self.agents.is_empty() {
                self.active_index = self.agents.len() - 1;
            } else if idx < self.active_index && self.active_index > 0 {
                self.active_index -= 1;
            }
        }

        // Get working directory
        let working_dir = std::env::current_dir()
            .context("Failed to get current directory for orchestrator restart")?;

        // Spawn new orchestrator
        let agent = Agent::spawn(
            self.next_id,
            "Orchestrator".to_string(),
            working_dir,
            rows,
            cols,
        )?;
        self.next_id += 1;

        // Insert at the beginning (orchestrator is always first)
        self.agents.insert(0, agent);
        self.active_index = 0;

        Ok(())
    }
}

impl Default for AgentManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ==================== AgentMode tests ====================

    #[test]
    fn test_agent_mode_values() {
        assert_eq!(AgentMode::Interactive, AgentMode::Interactive);
        assert_eq!(AgentMode::NonInteractive, AgentMode::NonInteractive);
        assert_ne!(AgentMode::Interactive, AgentMode::NonInteractive);
    }

    // ==================== AgentStatus tests ====================

    #[test]
    fn test_agent_status_running() {
        let status = AgentStatus::Running;
        assert_eq!(status, AgentStatus::Running);
    }

    #[test]
    fn test_agent_status_ended() {
        let status = AgentStatus::Ended;
        assert_eq!(status, AgentStatus::Ended);
    }

    #[test]
    fn test_agent_status_copy() {
        let status = AgentStatus::Running;
        let copied = status;
        assert_eq!(status, copied);
    }

    #[test]
    fn test_agent_status_clone() {
        let status = AgentStatus::Ended;
        let cloned = status;
        assert_eq!(status, cloned);
    }

    #[test]
    fn test_agent_status_debug() {
        let status = AgentStatus::Running;
        let debug_str = format!("{status:?}");
        assert!(debug_str.contains("Running"));
    }

    // ==================== WorkState tests ====================

    #[test]
    fn test_work_state_values() {
        assert_eq!(WorkState::Starting, WorkState::Starting);
        assert_eq!(WorkState::Working, WorkState::Working);
        assert_eq!(WorkState::Idle, WorkState::Idle);
        assert_eq!(WorkState::Completed, WorkState::Completed);
    }

    #[test]
    fn test_work_state_inequality() {
        assert_ne!(WorkState::Starting, WorkState::Working);
        assert_ne!(WorkState::Working, WorkState::Completed);
    }

    // ==================== AgentManager tests ====================

    #[test]
    fn test_agent_manager_new() {
        let manager = AgentManager::new();
        assert!(manager.is_empty());
        assert_eq!(manager.active_index(), 0);
    }

    #[test]
    fn test_agent_manager_default() {
        let manager = AgentManager::default();
        assert!(manager.is_empty());
    }

    #[test]
    fn test_agent_manager_list_empty() {
        let manager = AgentManager::new();
        assert!(manager.list().is_empty());
    }

    #[test]
    fn test_agent_manager_active_empty() {
        let manager = AgentManager::new();
        assert!(manager.active().is_none());
    }

    #[test]
    fn test_agent_manager_active_mut_empty() {
        let mut manager = AgentManager::new();
        assert!(manager.active_mut().is_none());
    }

    #[test]
    fn test_agent_manager_get_empty() {
        let manager = AgentManager::new();
        assert!(manager.get(0).is_none());
        assert!(manager.get(100).is_none());
    }

    #[test]
    fn test_agent_manager_get_mut_empty() {
        let mut manager = AgentManager::new();
        assert!(manager.get_mut(0).is_none());
        assert!(manager.get_mut(100).is_none());
    }

    #[test]
    fn test_agent_manager_switch_to_empty() {
        let mut manager = AgentManager::new();
        manager.switch_to(0);
        assert_eq!(manager.active_index(), 0);
        manager.switch_to(100);
        assert_eq!(manager.active_index(), 0);
    }

    #[test]
    fn test_agent_manager_next_empty() {
        let mut manager = AgentManager::new();
        manager.next();
        assert_eq!(manager.active_index(), 0);
    }

    #[test]
    fn test_agent_manager_prev_empty() {
        let mut manager = AgentManager::new();
        manager.prev();
        assert_eq!(manager.active_index(), 0);
    }

    #[test]
    fn test_agent_manager_close_empty() {
        let mut manager = AgentManager::new();
        manager.close(0);
        assert!(manager.is_empty());
    }

    #[test]
    fn test_agent_manager_close_invalid_index() {
        let mut manager = AgentManager::new();
        manager.close(100);
        assert!(manager.is_empty());
    }

    #[test]
    fn test_agent_manager_check_all_status_empty() {
        let mut manager = AgentManager::new();
        manager.check_all_status();
        assert!(manager.is_empty());
    }

    #[test]
    fn test_agent_manager_resize_all_empty() {
        let mut manager = AgentManager::new();
        manager.resize_all(80, 24);
        assert!(manager.is_empty());
    }
}