macot 0.1.11

Multi Agent Control Tower - CLI for orchestrating Claude CLI instances
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
use anyhow::{bail, Context, Result};
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use std::process::{Output, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::process::Command;

use crate::config::Config;

fn check_tmux_output(output: Output, context: &str) -> Result<String> {
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "{}: tmux exited with {}: {}",
            context,
            output.status,
            stderr.trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn check_tmux_status(output: Output, context: &str) -> Result<()> {
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "{}: tmux exited with {}: {}",
            context,
            output.status,
            stderr.trim()
        );
    }
    Ok(())
}

fn parse_pane_paths(stdout: &str) -> HashMap<u32, String> {
    let mut paths = HashMap::new();
    for line in stdout.lines() {
        let mut parts = line.splitn(2, '\t');
        let Some(window_str) = parts.next() else {
            continue;
        };
        let Some(path) = parts.next() else {
            continue;
        };
        let Ok(window_id) = window_str.parse::<u32>() else {
            continue;
        };
        let path = path.trim();
        if !path.is_empty() {
            paths.insert(window_id, path.to_string());
        }
    }
    paths
}

static NEXT_BUFFER_ID: AtomicU64 = AtomicU64::new(1);

fn next_tmux_buffer_name(window_id: u32) -> String {
    let id = NEXT_BUFFER_ID.fetch_add(1, Ordering::Relaxed);
    format!("macot-{}-{}-{}", std::process::id(), window_id, id)
}

/// Trait for sending keys to and capturing output from tmux windows.
/// Extracted to allow mocking in tests.
#[async_trait::async_trait]
pub trait TmuxSender: Send + Sync {
    async fn send_keys(&self, window_id: u32, keys: &str) -> Result<()>;
    async fn capture_pane(&self, window_id: u32) -> Result<String>;

    fn pre_enter_delay(&self) -> std::time::Duration {
        std::time::Duration::ZERO
    }

    /// Send text content to a pane. For multiline text, implementations should
    /// use bracketed paste to prevent newlines from acting as Enter keypresses.
    /// Default falls back to send_keys (suitable for mocks and single-line text).
    async fn send_text(&self, window_id: u32, text: &str) -> Result<()> {
        self.send_keys(window_id, text).await
    }

    async fn send_keys_with_enter(&self, window_id: u32, keys: &str) -> Result<()> {
        self.send_keys(window_id, "C-l").await?;
        self.send_text(window_id, keys).await?;
        let delay = self.pre_enter_delay();
        if !delay.is_zero() {
            tokio::time::sleep(delay).await;
        }
        self.send_keys(window_id, "Enter").await?;
        Ok(())
    }

    async fn capture_pane_with_escapes(&self, window_id: u32) -> Result<String> {
        self.capture_pane(window_id).await
    }

    async fn capture_full_history(&self, window_id: u32) -> Result<String> {
        self.capture_pane_with_escapes(window_id).await
    }

    async fn resize_pane(&self, _window_id: u32, _width: u16, _height: u16) -> Result<()> {
        Ok(())
    }

    /// Get the current foreground command running in a tmux pane.
    /// Returns `None` by default (for mocks); real implementations should
    /// query tmux for `pane_current_command`.
    async fn get_pane_current_command(&self, _window_id: u32) -> Result<Option<String>> {
        Ok(None)
    }
}

#[async_trait::async_trait]
impl TmuxSender for TmuxManager {
    async fn send_keys(&self, window_id: u32, keys: &str) -> Result<()> {
        let output = Command::new("tmux")
            .args([
                "send-keys",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
                keys,
            ])
            .output()
            .await
            .context(format!("Failed to send keys to window {window_id}"))?;
        check_tmux_status(output, &format!("send-keys to window {window_id}"))
    }

    fn pre_enter_delay(&self) -> std::time::Duration {
        std::time::Duration::from_millis(300)
    }

    async fn send_text(&self, window_id: u32, text: &str) -> Result<()> {
        if !text.contains('\n') {
            return self.send_keys(window_id, text).await;
        }
        let target = format!("{}:{}", self.session_name, window_id);
        let buffer_name = next_tmux_buffer_name(window_id);
        let output = Command::new("tmux")
            .args(["set-buffer", "-b", &buffer_name, "--", text])
            .output()
            .await
            .context("Failed to set tmux buffer")?;
        check_tmux_status(output, "set-buffer")?;

        let output = Command::new("tmux")
            .args([
                "paste-buffer",
                "-d",
                "-p",
                "-b",
                &buffer_name,
                "-t",
                &target,
            ])
            .output()
            .await
            .context(format!("Failed to paste buffer to window {window_id}"))?;
        check_tmux_status(output, &format!("paste-buffer to window {window_id}"))
    }

    async fn capture_pane(&self, window_id: u32) -> Result<String> {
        let output = Command::new("tmux")
            .args([
                "capture-pane",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
                "-p",
            ])
            .output()
            .await
            .context(format!("Failed to capture window {window_id}"))?;
        check_tmux_output(output, &format!("capture-pane {window_id}"))
    }

    async fn capture_pane_with_escapes(&self, window_id: u32) -> Result<String> {
        let output = Command::new("tmux")
            .args([
                "capture-pane",
                "-e",
                "-p",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
            ])
            .output()
            .await
            .context(format!("Failed to capture window {window_id} with escapes"))?;
        check_tmux_output(output, &format!("capture-pane-with-escapes {window_id}"))
    }

    async fn capture_full_history(&self, window_id: u32) -> Result<String> {
        let output = Command::new("tmux")
            .args([
                "capture-pane",
                "-e",
                "-J",
                "-p",
                "-S",
                "-",
                "-E",
                "-",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
            ])
            .output()
            .await
            .context(format!(
                "Failed to capture full history of window {window_id}"
            ))?;
        check_tmux_output(output, &format!("capture-full-history {window_id}"))
    }

    async fn resize_pane(&self, window_id: u32, width: u16, height: u16) -> Result<()> {
        // Use `resize-window`: `resize-pane` only adjusts pane boundaries
        // within a window and cannot grow a single-pane detached window.
        // Requires tmux >= 2.9 and `window-size manual` on the session.
        let output = Command::new("tmux")
            .args([
                "resize-window",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
                "-x",
                &width.to_string(),
                "-y",
                &height.to_string(),
            ])
            .output()
            .await
            .context(format!("Failed to resize window {window_id}"))?;
        check_tmux_status(output, &format!("resize-window {window_id}"))
    }

    async fn get_pane_current_command(&self, window_id: u32) -> Result<Option<String>> {
        let output = Command::new("tmux")
            .args([
                "display-message",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
                "-p",
                "#{pane_current_command}",
            ])
            .output()
            .await
            .context(format!(
                "Failed to get pane_current_command for window {window_id}"
            ))?;

        let stdout = check_tmux_output(
            output,
            &format!("get pane_current_command for window {window_id}"),
        )?;
        let cmd = stdout.trim().to_string();
        if cmd.is_empty() {
            Ok(None)
        } else {
            Ok(Some(cmd))
        }
    }
}

#[derive(Debug, Clone)]
pub struct SessionInfo {
    pub session_name: String,
    pub project_path: String,
    pub num_experts: u32,
    pub created_at: DateTime<Utc>,
}

#[derive(Clone)]
pub struct TmuxManager {
    session_name: String,
}

impl TmuxManager {
    pub fn new(session_name: String) -> Self {
        Self { session_name }
    }

    pub fn from_config(config: &Config) -> Self {
        Self::new(config.session_name())
    }

    #[allow(dead_code)]
    pub fn session_name(&self) -> &str {
        &self.session_name
    }

    pub async fn session_exists(&self) -> bool {
        Command::new("tmux")
            .args(["has-session", "-t", &self.session_name])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await
            .map(|s| s.success())
            .unwrap_or(false)
    }

    pub async fn create_session(&self, num_windows: u32, working_dir: &str) -> Result<()> {
        let output = Command::new("tmux")
            .args([
                "new-session",
                "-d",
                "-s",
                &self.session_name,
                "-c",
                working_dir,
            ])
            .output()
            .await
            .context("Failed to create tmux session")?;
        check_tmux_status(output, "new-session")?;

        let output = Command::new("tmux")
            .args([
                "set-option",
                "-t",
                &self.session_name,
                "history-limit",
                "10000",
            ])
            .output()
            .await
            .context("Failed to set history-limit")?;
        check_tmux_status(output, "set history-limit")?;

        // Without `window-size manual`, tmux auto-sizes detached windows to
        // `default-size` (80x24) because no client is attached. That would
        // make `resize_pane` below a silent no-op.
        let output = Command::new("tmux")
            .args([
                "set-option",
                "-t",
                &self.session_name,
                "window-size",
                "manual",
            ])
            .output()
            .await
            .context("Failed to set window-size")?;
        check_tmux_status(output, "set window-size")?;

        for i in 1..num_windows {
            let output = Command::new("tmux")
                .args(["new-window", "-t", &self.session_name, "-c", working_dir])
                .output()
                .await
                .context(format!("Failed to create window {i}"))?;
            check_tmux_status(output, &format!("new-window {i}"))?;
        }

        Ok(())
    }

    pub async fn set_env(&self, key: &str, value: &str) -> Result<()> {
        let output = Command::new("tmux")
            .args(["setenv", "-t", &self.session_name, key, value])
            .output()
            .await
            .context(format!("Failed to set env {key}"))?;
        check_tmux_status(output, &format!("setenv {key}"))
    }

    pub async fn get_env(&self, key: &str) -> Result<Option<String>> {
        let output = Command::new("tmux")
            .args(["showenv", "-t", &self.session_name, key])
            .output()
            .await
            .context(format!("Failed to get env {key}"))?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if let Some(value) = stdout.strip_prefix(&format!("{key}=")) {
                return Ok(Some(value.trim().to_string()));
            }
        }

        Ok(None)
    }

    pub async fn kill_session(&self) -> Result<()> {
        let output = Command::new("tmux")
            .args(["kill-session", "-t", &self.session_name])
            .output()
            .await
            .context("Failed to kill tmux session")?;
        check_tmux_status(output, "kill-session")
    }

    pub async fn set_pane_title(&self, window_id: u32, title: &str) -> Result<()> {
        let output = Command::new("tmux")
            .args([
                "select-pane",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
                "-T",
                title,
            ])
            .output()
            .await
            .context(format!("Failed to set pane title for window {window_id}"))?;
        check_tmux_status(output, &format!("select-pane {window_id}"))
    }

    #[allow(dead_code)]
    pub async fn get_pane_current_path(&self, window_id: u32) -> Result<Option<String>> {
        let output = Command::new("tmux")
            .args([
                "display-message",
                "-t",
                &format!("{}:{}", self.session_name, window_id),
                "-p",
                "#{pane_current_path}",
            ])
            .output()
            .await
            .context(format!(
                "Failed to get pane_current_path for window {window_id}"
            ))?;

        if output.status.success() {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if path.is_empty() {
                Ok(None)
            } else {
                Ok(Some(path))
            }
        } else {
            Ok(None)
        }
    }

    /// Get current working directories for all panes in this session.
    /// Key is tmux window index.
    pub async fn get_all_pane_current_paths(&self) -> Result<HashMap<u32, String>> {
        let output = Command::new("tmux")
            .args([
                "list-panes",
                "-s",
                "-t",
                &self.session_name,
                "-F",
                "#{window_index}\t#{pane_current_path}",
            ])
            .output()
            .await
            .context("Failed to list pane_current_path for session")?;

        if !output.status.success() {
            return Ok(HashMap::new());
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        Ok(parse_pane_paths(&stdout))
    }

    pub async fn list_all_macot_sessions() -> Result<Vec<SessionInfo>> {
        let output = Command::new("tmux")
            .args(["list-sessions", "-F", "#{session_name}"])
            .output()
            .await?;

        if !output.status.success() {
            return Ok(Vec::new());
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut sessions = Vec::new();

        for line in stdout.lines() {
            if line.starts_with("macot-") {
                let manager = TmuxManager::new(line.to_string());

                let project_path = manager
                    .get_env("MACOT_PROJECT_PATH")
                    .await?
                    .unwrap_or_else(|| "unknown".to_string());

                let num_experts = manager
                    .get_env("MACOT_NUM_EXPERTS")
                    .await?
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(0);

                let created_at = manager
                    .get_env("MACOT_CREATED_AT")
                    .await?
                    .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                    .map(|dt| dt.with_timezone(&Utc))
                    .unwrap_or_else(Utc::now);

                sessions.push(SessionInfo {
                    session_name: line.to_string(),
                    project_path,
                    num_experts,
                    created_at,
                });
            }
        }

        Ok(sessions)
    }

    pub async fn init_session_metadata(&self, project_path: &str, num_experts: u32) -> Result<()> {
        self.set_env("MACOT_PROJECT_PATH", project_path).await?;
        self.set_env("MACOT_NUM_EXPERTS", &num_experts.to_string())
            .await?;
        self.set_env("MACOT_CREATED_AT", &Utc::now().to_rfc3339())
            .await?;
        Ok(())
    }

    /// Load session metadata from tmux environment variables.
    ///
    /// Fields like `project_path`, `num_experts`, and `created_at` are returned as `Option`
    /// so each caller can apply its own contextually-appropriate default.
    pub async fn load_session_metadata(&self) -> Result<SessionMetadata> {
        let project_path = self.get_env("MACOT_PROJECT_PATH").await?;

        let num_experts = self
            .get_env("MACOT_NUM_EXPERTS")
            .await?
            .and_then(|s| s.parse().ok());

        let created_at = self.get_env("MACOT_CREATED_AT").await?;

        let queue_path = self
            .get_env("MACOT_QUEUE_PATH")
            .await?
            .unwrap_or_else(|| "/tmp/macot".to_string());

        Ok(SessionMetadata {
            project_path,
            num_experts,
            created_at,
            queue_path,
        })
    }
}

/// Metadata stored as tmux environment variables for a running session.
///
/// `project_path`, `num_experts`, and `created_at` are `Option` because the tmux
/// env vars may not be set; each caller applies its own contextual default.
#[derive(Debug, Clone)]
pub struct SessionMetadata {
    pub project_path: Option<String>,
    pub num_experts: Option<u32>,
    pub created_at: Option<String>,
    pub queue_path: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::process::ExitStatusExt;
    use std::process::ExitStatus;

    fn make_output(code: i32, stdout: &str, stderr: &str) -> Output {
        Output {
            status: ExitStatus::from_raw(code << 8), // Unix: exit code is in bits 8-15
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        }
    }

    #[test]
    fn check_tmux_output_success_returns_stdout() {
        let output = make_output(0, "pane content\n", "");
        let result = check_tmux_output(output, "test-cmd");
        assert_eq!(
            result.unwrap(),
            "pane content\n",
            "check_tmux_output: success should return stdout"
        );
    }

    #[test]
    fn check_tmux_output_failure_returns_error_with_stderr() {
        let output = make_output(1, "", "no such pane");
        let result = check_tmux_output(output, "capture-pane");
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("capture-pane") && msg.contains("no such pane"),
            "check_tmux_output: error should contain context and stderr, got: {}",
            msg
        );
    }

    #[test]
    fn check_tmux_status_success_returns_ok() {
        let output = make_output(0, "", "");
        let result = check_tmux_status(output, "test-cmd");
        assert!(
            result.is_ok(),
            "check_tmux_status: success should return Ok"
        );
    }

    #[test]
    fn check_tmux_status_failure_returns_error() {
        let output = make_output(1, "", "session not found");
        let result = check_tmux_status(output, "send-keys");
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("send-keys") && msg.contains("session not found"),
            "check_tmux_status: error should contain context and stderr, got: {}",
            msg
        );
    }

    #[test]
    fn tmux_manager_new_sets_session_name() {
        let manager = TmuxManager::new("test-session".to_string());
        assert_eq!(manager.session_name(), "test-session");
    }

    #[test]
    fn tmux_manager_from_config_uses_config_session_name() {
        use std::path::PathBuf;

        let config = Config::default().with_project_path(PathBuf::from("/tmp/test"));
        let manager = TmuxManager::from_config(&config);

        assert!(manager.session_name().starts_with("macot-"));
    }

    #[tokio::test]
    async fn resize_pane_default_is_noop() {
        struct NoopSender;

        #[async_trait::async_trait]
        impl TmuxSender for NoopSender {
            async fn send_keys(&self, _window_id: u32, _keys: &str) -> Result<()> {
                Ok(())
            }
            async fn capture_pane(&self, _window_id: u32) -> Result<String> {
                Ok(String::new())
            }
        }

        let sender = NoopSender;
        let result = sender.resize_pane(0, 80, 24).await;
        assert!(
            result.is_ok(),
            "resize_pane: default trait impl should be a no-op that returns Ok"
        );
    }

    /// Mock TmuxSender that only implements the required methods (not `capture_pane_with_escapes`).
    /// Verifies the default trait implementation falls back to `capture_pane`.
    struct MockTmuxSender {
        capture_output: String,
    }

    #[async_trait::async_trait]
    impl TmuxSender for MockTmuxSender {
        async fn send_keys(&self, _window_id: u32, _keys: &str) -> Result<()> {
            Ok(())
        }

        async fn capture_pane(&self, _window_id: u32) -> Result<String> {
            Ok(self.capture_output.clone())
        }
    }

    #[tokio::test]
    async fn capture_full_history_default_falls_back_to_capture_pane_with_escapes() {
        let mock = MockTmuxSender {
            capture_output: "mock full history".to_string(),
        };

        let result = mock.capture_full_history(0).await.unwrap();
        assert_eq!(
            result, "mock full history",
            "capture_full_history: default impl should fall back to capture_pane_with_escapes → capture_pane"
        );
    }

    #[tokio::test]
    async fn capture_pane_with_escapes_default_falls_back() {
        let mock = MockTmuxSender {
            capture_output: "mock pane content".to_string(),
        };

        let result = mock.capture_pane_with_escapes(0).await.unwrap();
        assert_eq!(
            result, "mock pane content",
            "capture_pane_with_escapes: default impl should fall back to capture_pane"
        );
    }

    #[tokio::test]
    async fn send_text_default_falls_back_to_send_keys() {
        use std::sync::{Arc, Mutex};

        struct RecordingSender {
            sent: Arc<Mutex<Vec<String>>>,
        }

        #[async_trait::async_trait]
        impl TmuxSender for RecordingSender {
            async fn send_keys(&self, _window_id: u32, keys: &str) -> Result<()> {
                self.sent.lock().unwrap().push(keys.to_string());
                Ok(())
            }
            async fn capture_pane(&self, _window_id: u32) -> Result<String> {
                Ok(String::new())
            }
        }

        let sent = Arc::new(Mutex::new(Vec::new()));
        let sender = RecordingSender { sent: sent.clone() };

        sender.send_text(0, "multiline\ntext").await.unwrap();

        let recorded = sent.lock().unwrap();
        assert_eq!(
            recorded.as_slice(),
            &["multiline\ntext"],
            "send_text: default impl should fall back to send_keys"
        );
    }

    #[tokio::test]
    async fn send_keys_with_enter_routes_text_through_send_text() {
        use std::sync::{Arc, Mutex};

        struct TextTracker {
            keys: Arc<Mutex<Vec<String>>>,
        }

        #[async_trait::async_trait]
        impl TmuxSender for TextTracker {
            async fn send_keys(&self, _window_id: u32, keys: &str) -> Result<()> {
                self.keys.lock().unwrap().push(format!("keys:{}", keys));
                Ok(())
            }
            async fn send_text(&self, _window_id: u32, text: &str) -> Result<()> {
                self.keys.lock().unwrap().push(format!("text:{}", text));
                Ok(())
            }
            async fn capture_pane(&self, _window_id: u32) -> Result<String> {
                Ok(String::new())
            }
        }

        let keys = Arc::new(Mutex::new(Vec::new()));
        let tracker = TextTracker { keys: keys.clone() };

        tracker
            .send_keys_with_enter(0, "hello\nworld")
            .await
            .unwrap();

        let recorded = keys.lock().unwrap();
        assert_eq!(
            recorded[0], "keys:C-l",
            "send_keys_with_enter: should send C-l via send_keys"
        );
        assert_eq!(
            recorded[1], "text:hello\nworld",
            "send_keys_with_enter: should route text through send_text"
        );
        assert_eq!(
            recorded[2], "keys:Enter",
            "send_keys_with_enter: should send Enter via send_keys"
        );
    }

    #[test]
    fn next_tmux_buffer_name_is_unique() {
        let a = next_tmux_buffer_name(0);
        let b = next_tmux_buffer_name(0);
        assert_ne!(
            a, b,
            "next_tmux_buffer_name: successive calls should be unique"
        );
        assert!(
            a.starts_with("macot-"),
            "next_tmux_buffer_name: should use macot- prefix"
        );
    }

    #[test]
    fn parse_pane_paths_multiple_windows() {
        let stdout = "0\t/home/user/project\n1\t/home/user/docs\n2\t/tmp\n";
        let paths = parse_pane_paths(stdout);
        assert_eq!(
            paths.len(),
            3,
            "parse_pane_paths: should parse all window entries"
        );
        assert_eq!(paths[&0], "/home/user/project");
        assert_eq!(paths[&1], "/home/user/docs");
        assert_eq!(paths[&2], "/tmp");
    }

    #[test]
    fn parse_pane_paths_single_window() {
        let stdout = "0\t/home/user/project\n";
        let paths = parse_pane_paths(stdout);
        assert_eq!(
            paths.len(),
            1,
            "parse_pane_paths: should parse single entry"
        );
        assert_eq!(paths[&0], "/home/user/project");
    }

    #[test]
    fn parse_pane_paths_empty_input() {
        let paths = parse_pane_paths("");
        assert!(
            paths.is_empty(),
            "parse_pane_paths: empty input should return empty map"
        );
    }

    #[test]
    fn parse_pane_paths_skips_malformed_lines() {
        let stdout = "0\t/valid/path\nnot_a_number\t/skip\n\n1\t/another/path\n";
        let paths = parse_pane_paths(stdout);
        assert_eq!(
            paths.len(),
            2,
            "parse_pane_paths: should skip malformed lines"
        );
        assert_eq!(paths[&0], "/valid/path");
        assert_eq!(paths[&1], "/another/path");
    }

    #[test]
    fn check_tmux_status_with_nonzero_exit_returns_error() {
        let output = make_output(2, "", "unknown command");
        let result = check_tmux_status(output, "setenv");
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("setenv"),
            "check_tmux_status: error should contain context string, got: {}",
            msg
        );
    }

    #[test]
    fn check_tmux_status_with_empty_stderr_includes_context() {
        let output = make_output(127, "", "");
        let result = check_tmux_status(output, "kill-session");
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("kill-session"),
            "check_tmux_status: error with empty stderr should still include context, got: {}",
            msg
        );
    }

    #[tokio::test]
    async fn get_pane_current_command_default_returns_none() {
        struct NoopSender;

        #[async_trait::async_trait]
        impl TmuxSender for NoopSender {
            async fn send_keys(&self, _window_id: u32, _keys: &str) -> Result<()> {
                Ok(())
            }
            async fn capture_pane(&self, _window_id: u32) -> Result<String> {
                Ok(String::new())
            }
        }

        let sender = NoopSender;
        let result = sender.get_pane_current_command(0).await.unwrap();
        assert!(
            result.is_none(),
            "get_pane_current_command: default trait impl should return None"
        );
    }

    // --- Real-tmux integration tests (gated with #[ignore]) ---
    //
    // These spawn a real `tmux` process and verify that resize requests
    // actually change the window dimensions. Run with:
    //   cargo test -- --ignored
    //
    // They are ignored by default so CI environments without tmux can still
    // run the normal test suite.

    async fn tmux_available() -> bool {
        Command::new("tmux")
            .arg("-V")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await
            .map(|s| s.success())
            .unwrap_or(false)
    }

    async fn tmux_window_size(session: &str, window_id: u32) -> Option<(u16, u16)> {
        let output = Command::new("tmux")
            .args([
                "list-panes",
                "-t",
                &format!("{session}:{window_id}"),
                "-F",
                "#{window_width}x#{window_height}",
            ])
            .output()
            .await
            .ok()?;
        if !output.status.success() {
            return None;
        }
        let line = String::from_utf8_lossy(&output.stdout)
            .lines()
            .next()?
            .trim()
            .to_string();
        let (w, h) = line.split_once('x')?;
        Some((w.parse().ok()?, h.parse().ok()?))
    }

    /// Kills the tmux session on drop to prevent leaked sessions when
    /// assertions panic inside an integration test.
    struct SessionGuard {
        session_name: String,
    }

    impl Drop for SessionGuard {
        fn drop(&mut self) {
            let _ = std::process::Command::new("tmux")
                .args(["kill-session", "-t", &self.session_name])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
    }

    #[tokio::test]
    #[ignore]
    async fn resize_pane_actually_grows_window_with_real_tmux() {
        if !tmux_available().await {
            eprintln!("tmux not available, skipping");
            return;
        }

        let session_name = format!("macot-test-{}-resize", std::process::id());
        let _guard = SessionGuard {
            session_name: session_name.clone(),
        };
        let manager = TmuxManager::new(session_name.clone());

        manager
            .create_session(1, "/tmp")
            .await
            .expect("create_session should succeed");

        let initial = tmux_window_size(&session_name, 0).await;
        assert!(
            initial.is_some(),
            "tmux list-panes should return a size for the new session"
        );

        manager
            .resize_pane(0, 160, 40)
            .await
            .expect("resize_pane should succeed");

        let after = tmux_window_size(&session_name, 0).await;
        assert_eq!(
            after,
            Some((160, 40)),
            "resize_pane: window should report 160x40 after resize, got {:?}",
            after
        );
    }
}