tmux-tango 2.13.0

A CLI tool for managing tmux sessions - dance between your sessions!
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
//! Tmux integration and session management.
//!
//! This module provides types and functionality for interacting with tmux,
//! including session parsing, command execution, and caching for performance.

use std::process::{Command, Stdio};
use std::env;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::error::TmuxFzfError;
use crate::host::Host;

// Constants
const TMUX_ENV_VAR: &str = "TMUX";
const DEFAULT_WINDOWS: &str = "1";

/// Format passed to `tmux list-sessions -F`.
///
/// Tab-delimited because session names may contain almost anything except `:` and `.`.
const SESSION_FORMAT: &str = "#{session_name}\t#{session_windows}\t#{session_attached}\t\
                              #{session_last_attached}\t#{session_created}";

/// Represents a tmux session with its metadata.
///
/// This struct uses `Arc<str>` for efficient cloning and sharing of session data.
#[derive(Debug, Clone, PartialEq)]
pub struct TmuxSession {
    /// The session name
    pub name: Arc<str>,
    /// Number of windows in the session
    pub windows: Arc<str>,
    /// Whether at least one client is attached to this session
    pub attached: bool,
    /// Epoch seconds of the last attach; 0 if never attached
    pub last_attached: i64,
    /// Epoch seconds of session creation
    #[allow(dead_code)]
    pub created: i64,
}

/// Represents a tmux window within a session.
#[derive(Debug, Clone, PartialEq)]
pub struct TmuxWindow {
    /// The window index (0-based)
    pub index: u32,
    /// The window name
    pub name: Arc<str>,
    /// Number of panes in the window
    pub pane_count: u32,
    /// Whether this window is currently active
    pub is_active: bool,
}

impl TmuxWindow {
    /// Parse a tmux window from formatted output.
    ///
    /// Expected format: `index:name:pane_count:active_flag`
    /// where active_flag is "1" for active, "0" for inactive
    pub fn from_line(line: &str) -> Option<Self> {
        let parts: Vec<&str> = line.splitn(4, ':').collect();
        if parts.len() < 4 {
            return None;
        }

        let index = parts[0].parse().ok()?;
        let name: Arc<str> = parts[1].into();
        let pane_count = parts[2].parse().ok()?;
        let is_active = parts[3] == "1";

        Some(Self {
            index,
            name,
            pane_count,
            is_active,
        })
    }
}

/// Represents a tmux pane within a window.
#[derive(Debug, Clone, PartialEq)]
pub struct TmuxPane {
    /// The pane index (0-based)
    pub index: u32,
    /// The pane ID (e.g., "%0")
    pub pane_id: Arc<str>,
    /// The current command running in the pane
    pub command: Arc<str>,
    /// Whether this pane is currently active
    pub is_active: bool,
    /// The current working directory of the pane
    pub current_path: Arc<str>,
}

impl TmuxPane {
    /// Parse a tmux pane from formatted output.
    ///
    /// Expected format: `index:pane_id:command:active_flag:current_path`
    /// where active_flag is "1" for active, "0" for inactive
    pub fn from_line(line: &str) -> Option<Self> {
        let parts: Vec<&str> = line.splitn(5, ':').collect();
        if parts.len() < 5 {
            return None;
        }

        let index = parts[0].parse().ok()?;
        let pane_id: Arc<str> = parts[1].into();
        let command: Arc<str> = parts[2].into();
        let is_active = parts[3] == "1";
        let current_path: Arc<str> = parts[4].into();

        Some(Self {
            index,
            pane_id,
            command,
            is_active,
            current_path,
        })
    }
}

impl TmuxSession {
    /// Parse a tmux session from a line of `tmux list-sessions -F SESSION_FORMAT` output.
    ///
    /// Expected format: `name\twindows\tattached\tlast_attached\tcreated`
    ///
    /// `last_attached` is empty for sessions that have never been attached, and on tmux < 2.1
    /// where `#{session_last_attached}` does not exist at all — unknown format variables expand
    /// to an empty string, so the field count is unchanged and this still parses.
    pub fn from_line(line: &str) -> Option<Self> {
        let parts: Vec<&str> = line.splitn(5, '\t').collect();
        if parts.len() < 5 {
            return None;
        }

        let name: Arc<str> = parts[0].into();
        if name.is_empty() {
            return None;
        }

        let windows: Arc<str> = if parts[1].is_empty() {
            DEFAULT_WINDOWS.into()
        } else {
            parts[1].into()
        };

        // `session_attached` is a count of attached clients, not a boolean flag.
        let attached = parts[2].parse::<u32>().unwrap_or(0) > 0;

        Some(Self {
            name,
            windows,
            attached,
            last_attached: parts[3].parse().unwrap_or(0),
            created: parts[4].parse().unwrap_or(0),
        })
    }

    /// Check if this session is currently attached.
    pub fn is_attached(&self) -> bool {
        self.attached
    }
}

/// Order sessions most-recently-attached first.
///
/// Sessions that have never been attached report a `last_attached` of 0 and sink to the bottom.
/// Ties fall back to alphabetical order — which is also the whole story on tmux < 2.1, where
/// `#{session_last_attached}` expands to an empty field and every session reports 0.
pub fn sort_by_last_attached(sessions: &mut [TmuxSession]) {
    sessions.sort_by(|a, b| {
        b.last_attached
            .cmp(&a.last_attached)
            .then_with(|| a.name.cmp(&b.name))
    });
}

/// Prefix of the hidden grouped "viewer" sessions tango creates when attaching to a session
/// that already has a client, so each terminal gets its own current window instead of
/// mirroring the other.
pub const VIEWER_PREFIX: &str = "_tango-";

/// Build the viewer session name for `source` owned by the tango process `pid`.
///
/// The pid sits in a fixed position (`_tango-<pid>-<source>`) so the name stays parseable
/// even when the source name itself contains `-`. Session names cannot contain `:` or `.`,
/// so no further escaping is needed.
pub fn viewer_session_name(source: &str, pid: u32) -> String {
    format!("{}{}-{}", VIEWER_PREFIX, pid, source)
}

/// Parse a viewer session name back into `(pid, source)`.
///
/// Returns `None` for anything that is not exactly `_tango-<digits>-<nonempty>`, which keeps
/// ordinary user sessions from ever being treated as viewers.
pub fn parse_viewer_name(name: &str) -> Option<(u32, &str)> {
    let rest = name.strip_prefix(VIEWER_PREFIX)?;
    let (pid_str, source) = rest.split_once('-')?;
    if source.is_empty() {
        return None;
    }
    let pid = pid_str.parse().ok()?;
    Some((pid, source))
}

/// Whether `list-sessions` failed only because no server is running, which is an empty
/// listing, not an error. tmux says "no server running" when the socket exists but nothing
/// listens (ECONNREFUSED), and "error connecting to <socket> (No such file or directory)"
/// when the socket was never created — the normal state of a freshly booted remote host.
/// Treating the latter as an error marks that host offline and `n` refuses to start the
/// first session there. Other `error connecting` causes (e.g. permission denied) stay errors.
fn means_no_server(stderr: &str) -> bool {
    stderr.contains("no sessions")
        || stderr.contains("no server running")
        || (stderr.contains("error connecting to") && stderr.contains("No such file or directory"))
}

/// Drop viewer sessions from a listing. An *attached* viewer marks its source session
/// attached, so the "(attached)" indicator stays truthful when the only client on a session
/// is riding a grouped view of it.
fn filter_viewer_sessions(sessions: Vec<TmuxSession>) -> Vec<TmuxSession> {
    let attached_sources: std::collections::HashSet<String> = sessions
        .iter()
        .filter(|s| s.attached)
        .filter_map(|s| parse_viewer_name(&s.name).map(|(_, source)| source.to_string()))
        .collect();

    sessions
        .into_iter()
        .filter(|s| parse_viewer_name(&s.name).is_none())
        .map(|mut s| {
            if attached_sources.contains(s.name.as_ref()) {
                s.attached = true;
            }
            s
        })
        .collect()
}

/// Whether a process with this pid is running. `ps -p` behaves identically on macOS and
/// Linux, so no extra dependency is needed. If `ps` itself cannot run we assume alive —
/// never sweep what we cannot verify.
fn process_alive(pid: u32) -> bool {
    Command::new("ps")
        .arg("-p")
        .arg(pid.to_string())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(true)
}

/// Client for interacting with tmux.
///
/// This client provides methods for listing, creating, attaching to, and managing
/// tmux sessions. It includes a cache for improved performance when listing sessions.
pub struct TmuxClient {
    host: Host,
    /// Path of the tmux binary on `host`. Plain `tmux` locally; on a remote host the poller
    /// substitutes the absolute path it resolved, because a non-interactive ssh shell often
    /// has a PATH without Homebrew or `~/.local/bin`.
    tmux_program: String,
    session_cache: Option<(Vec<TmuxSession>, Instant)>,
}

/// Argv for `tmux new-session`. `-P -F` makes tmux print the name it actually assigned, which
/// is the only reliable way to learn the name of an unnamed session. `start_dir` is passed
/// through `-c` when given.
fn new_session_args(session_name: Option<&str>, start_dir: Option<&Path>) -> Vec<String> {
    let mut args: Vec<String> = ["new-session", "-d", "-P", "-F", "#{session_name}"]
        .iter()
        .map(|s| s.to_string())
        .collect();

    if let Some(name) = session_name {
        args.push("-s".to_string());
        args.push(name.to_string());
    }

    if let Some(dir) = start_dir {
        args.push("-c".to_string());
        args.push(dir.to_string_lossy().into_owned());
    }

    args
}

impl TmuxClient {
    const CACHE_DURATION: Duration = Duration::from_millis(500);
    
    pub fn new() -> Self {
        Self::for_host(Host::Local)
    }

    /// A client whose every tmux call runs on `host`.
    pub fn for_host(host: Host) -> Self {
        Self {
            host,
            tmux_program: "tmux".to_string(),
            session_cache: None,
        }
    }

    /// Use an explicit tmux binary path (see `tmux_program`).
    pub fn with_program(mut self, path: &str) -> Self {
        self.tmux_program = path.to_string();
        self
    }

    #[allow(dead_code)] // Used through the library crate and its tests.
    pub fn host(&self) -> &Host {
        &self.host
    }

    /// The one place a tmux argv becomes a process: locally as-is, remotely via ssh.
    fn tmux(&self, args: &[&str]) -> Command {
        self.host.command(&self.tmux_program, args, false)
    }
    
    pub fn list_sessions(&mut self) -> Result<Vec<TmuxSession>, TmuxFzfError> {
        if let Some((ref cached_sessions, cached_time)) = self.session_cache {
            if cached_time.elapsed() < Self::CACHE_DURATION {
                return Ok(cached_sessions.clone());
            }
        }
        
        let output = self.tmux(&["list-sessions", "-F", SESSION_FORMAT])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux command: {}", e)))?;
        
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if means_no_server(&stderr) {
                return Err(TmuxFzfError::NoSessions);
            }
            return Err(TmuxFzfError::TmuxError(format!("tmux list-sessions failed: {}", stderr)));
        }
        
        let stdout = String::from_utf8_lossy(&output.stdout);
        let sessions: Vec<TmuxSession> = stdout
            .lines()
            .filter_map(TmuxSession::from_line)
            .collect();

        // Hide tango's grouped viewer sessions before sorting/caching so neither the TUI
        // tree nor `tango list` ever shows them.
        let mut sessions = filter_viewer_sessions(sessions);

        // Sort before caching so cache hits and the `tango list` CLI path stay consistent.
        sort_by_last_attached(&mut sessions);

        self.session_cache = Some((sessions.clone(), Instant::now()));
        Ok(sessions)
    }

    /// Uncached `(name, attached_count)` listing that still includes the viewer sessions
    /// `list_sessions` hides. Used by the orphan sweep and the kill-time viewer scan.
    fn list_sessions_raw(&self) -> Result<Vec<(String, u32)>, TmuxFzfError> {
        let output = self.tmux(&["list-sessions", "-F", "#{session_name}\t#{session_attached}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux command: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!("tmux list-sessions failed: {}", stderr)));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        Ok(stdout
            .lines()
            .filter_map(|line| {
                let (name, attached) = line.split_once('\t')?;
                if name.is_empty() {
                    return None;
                }
                Some((name.to_string(), attached.parse().unwrap_or(0)))
            })
            .collect())
    }

    pub fn attach_session(&self, session_name: &str) -> Result<(), TmuxFzfError> {
        self.attach_target(session_name)
    }

    /// Attach to a specific window within a session.
    ///
    /// The target format is `session:window_index`
    pub fn attach_window(&self, session_name: &str, window_index: u32) -> Result<(), TmuxFzfError> {
        let target = format!("{}:{}", session_name, window_index);
        self.attach_target(&target)
    }

    /// Attach to a specific pane within a window.
    ///
    /// The target format is `session:window_index.pane_index`
    pub fn attach_pane(&self, session_name: &str, window_index: u32, pane_index: u32) -> Result<(), TmuxFzfError> {
        let target = format!("{}:{}.{}", session_name, window_index, pane_index);
        self.attach_target(&target)
    }

    /// Attach to a tmux target (session, window, or pane).
    /// Uses switch-client when inside tmux, attach-session otherwise.
    pub fn attach_target(&self, target: &str) -> Result<(), TmuxFzfError> {
        let (command, action) = if self.is_inside_tmux() {
            ("switch-client", "switch to")
        } else {
            ("attach-session", "attach to")
        };

        let status = self.tmux(&[command, "-t", target])
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux {}: {}", command, e)))?;

        if status.success() {
            Ok(())
        } else {
            let error_msg = match status.code() {
                Some(code) => {
                    format!("Failed to {} target '{}' (exit code: {})", action, target, code)
                },
                None => {
                    format!("tmux process was terminated while trying to {} target '{}'", action, target)
                }
            };

            Err(TmuxFzfError::TmuxError(error_msg))
        }
    }

    /// Live count of clients attached to `session_name`. Bypasses the session cache, which
    /// can be up to ~2.5 s stale (2 s TUI refresh + 500 ms cache) — too old to decide
    /// whether an attach needs a grouped viewer.
    pub fn session_attached_count(&self, session_name: &str) -> Result<u32, TmuxFzfError> {
        let output = self.tmux(&["display-message", "-t", session_name, "-p", "#{session_attached}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux display-message: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux display-message failed for session '{}': {}", session_name, stderr
            )));
        }

        String::from_utf8_lossy(&output.stdout)
            .trim()
            .parse()
            .map_err(|_| TmuxFzfError::TmuxError(format!(
                "Unparseable attached-client count for session '{}'", session_name
            )))
    }

    /// Create a detached session grouped with `source` (shared window set, independent
    /// current window per session). Returns the name tmux actually assigned.
    pub fn create_grouped_session(&mut self, source: &str, viewer_name: &str) -> Result<String, TmuxFzfError> {
        let output = self.tmux(&["new-session", "-d", "-t", source, "-s", viewer_name, "-P", "-F", "#{session_name}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux new-session: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "Failed to create grouped session for '{}': {}", source, stderr
            )));
        }

        let created = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if created.is_empty() {
            return Err(TmuxFzfError::TmuxError(
                "tmux did not report the name of the grouped session".to_string(),
            ));
        }
        self.session_cache = None;
        Ok(created)
    }

    /// Whether a session with exactly this name exists. Needed to observe viewer sessions,
    /// which `list_sessions` hides. The `=` target prefix disables tmux's prefix matching
    /// (tmux >= 2.1; on older servers this reports false, and nothing but tests rely on it).
    #[allow(dead_code)] // Used by integration tests through the library crate.
    pub fn session_exists(&self, session_name: &str) -> bool {
        self.tmux(&["has-session", "-t", &format!("={}", session_name)])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    /// Best-effort sweep of viewer sessions left behind by a crashed tango. A viewer is an
    /// orphan only when its owning pid is dead AND no client is attached — the liveness
    /// check keeps a sibling tango's just-created, not-yet-attached viewer alive.
    pub fn cleanup_orphaned_viewers(&mut self) {
        // Viewers belong to the tango process on their own host; `process_alive` only knows
        // local pids, so a remote sweep would kill every viewer of a live remote tango.
        if self.host.is_remote() {
            return;
        }
        let Ok(sessions) = self.list_sessions_raw() else {
            return;
        };
        for (name, attached) in sessions {
            let Some((pid, _)) = parse_viewer_name(&name) else {
                continue;
            };
            if attached == 0 && !process_alive(pid) {
                let _ = self.kill_one_session(&name);
            }
        }
    }

    pub fn kill_session(&mut self, session_name: &str) -> Result<(), TmuxFzfError> {
        // Killing a source session also kills its grouped viewers, so "kill" means kill even
        // while another terminal is viewing through a group — a surviving viewer would keep the
        // windows alive in a hidden session. Pure name matching, so it holds on a remote server
        // too (whose viewers a remote tango created). Viewers themselves skip the scan.
        if parse_viewer_name(session_name).is_none() {
            if let Ok(sessions) = self.list_sessions_raw() {
                for (name, _) in sessions {
                    let is_viewer_of_target = parse_viewer_name(&name)
                        .map(|(_, source)| source == session_name)
                        .unwrap_or(false);
                    if is_viewer_of_target {
                        let _ = self.kill_one_session(&name);
                    }
                }
            }
        }
        self.kill_one_session(session_name)
    }

    /// Kill exactly the named session, with no viewer scan.
    fn kill_one_session(&mut self, session_name: &str) -> Result<(), TmuxFzfError> {
        let status = self.tmux(&["kill-session", "-t", session_name])
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux kill-session: {}", e)))?;

        if status.success() {
            self.session_cache = None;
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to kill session '{}' (exit code: {})",
                session_name, status.code().unwrap_or(-1)
            )))
        }
    }

    pub fn kill_window(&mut self, session_name: &str, window_index: u32) -> Result<(), TmuxFzfError> {
        let target = format!("{}:{}", session_name, window_index);
        let status = self.tmux(&["kill-window", "-t", &target])
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux kill-window: {}", e)))?;

        if status.success() {
            self.session_cache = None;
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to kill window '{}' (exit code: {})",
                target, status.code().unwrap_or(-1)
            )))
        }
    }

    pub fn kill_pane(&mut self, session_name: &str, window_index: u32, pane_index: u32) -> Result<(), TmuxFzfError> {
        let target = format!("{}:{}.{}", session_name, window_index, pane_index);
        let status = self.tmux(&["kill-pane", "-t", &target])
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux kill-pane: {}", e)))?;

        if status.success() {
            self.session_cache = None;
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to kill pane '{}' (exit code: {})",
                target, status.code().unwrap_or(-1)
            )))
        }
    }

    pub fn rename_session(&mut self, old_name: &str, new_name: &str) -> Result<(), TmuxFzfError> {
        if new_name.is_empty() {
            return Err(TmuxFzfError::InvalidSessionName("Name cannot be empty".to_string()));
        }

        if new_name.contains(':') {
            return Err(TmuxFzfError::InvalidSessionName("Name cannot contain ':'".to_string()));
        }

        let status = self.tmux(&["rename-session", "-t", old_name, new_name])
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux rename-session: {}", e)))?;

        if status.success() {
            self.session_cache = None;
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to rename session '{}' to '{}' (exit code: {})",
                old_name, new_name, status.code().unwrap_or(-1)
            )))
        }
    }

    pub fn rename_window(&mut self, session_name: &str, window_index: u32, new_name: &str) -> Result<(), TmuxFzfError> {
        if new_name.is_empty() {
            return Err(TmuxFzfError::InvalidSessionName("Name cannot be empty".to_string()));
        }

        let target = format!("{}:{}", session_name, window_index);
        let status = self.tmux(&["rename-window", "-t", &target, new_name])
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux rename-window: {}", e)))?;

        if status.success() {
            self.session_cache = None;
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to rename window '{}' to '{}' (exit code: {})",
                target, new_name, status.code().unwrap_or(-1)
            )))
        }
    }
    
    pub fn new_session(&mut self, session_name: Option<&str>) -> Result<String, TmuxFzfError> {
        if let Some(name) = session_name {
            if name.is_empty() {
                return Err(TmuxFzfError::InvalidSessionName("Session name cannot be empty".to_string()));
            }
            if name.contains(':') {
                return Err(TmuxFzfError::InvalidSessionName("Session name cannot contain ':'".to_string()));
            }
        }

        // Our cwd only means something on this machine; on a remote host it would usually not
        // exist and tmux would refuse to start the session.
        let start_dir = if self.host.is_remote() { None } else { std::env::current_dir().ok() };
        let args = new_session_args(session_name, start_dir.as_deref());
        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
        let output = self.tmux(&arg_refs)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux new-session: {}", e)))?;

        if output.status.success() {
            let created_name = match session_name {
                Some(name) => name.to_string(),
                None => {
                    let printed = String::from_utf8_lossy(&output.stdout).trim().to_string();
                    if printed.is_empty() {
                        return Err(TmuxFzfError::TmuxError(
                            "tmux did not report the name of the new session".to_string(),
                        ));
                    }
                    printed
                }
            };
            self.session_cache = None;
            Ok(created_name)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to create session: {}", stderr
            )))
        }
    }
    
    /// Whether *this process* runs inside a tmux client of this host's server. Only ever true
    /// for the local host: `TMUX` in our environment says nothing about a remote server.
    pub fn is_inside_tmux(&self) -> bool {
        !self.host.is_remote() && env::var(TMUX_ENV_VAR).is_ok()
    }
    
    #[allow(dead_code)]
    pub fn has_sessions(&mut self) -> bool {
        self.list_sessions().is_ok()
    }

    pub fn clear_cache(&mut self) {
        self.session_cache = None;
    }

    /// Capture the contents of a pane.
    ///
    /// The target can be a pane ID (e.g., "%0") or a session:window.pane target.
    /// Returns the captured pane content as a string.
    pub fn capture_pane(&self, target: &str) -> Result<String, TmuxFzfError> {
        // `-e` keeps escape sequences (colors) for the preview.
        let output = self.tmux(&["capture-pane", "-p", "-e", "-t", target])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux capture-pane: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux capture-pane failed for '{}': {}", target, stderr
            )));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Capture pane contents as plain text (no ANSI escape sequences).
    /// Used for status detection where color information is unnecessary.
    pub fn capture_pane_plain(&self, target: &str) -> Result<String, TmuxFzfError> {
        let output = self.tmux(&["capture-pane", "-p", "-t", target])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux capture-pane: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux capture-pane failed for '{}': {}", target, stderr
            )));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Get the active pane ID for a session.
    ///
    /// Returns the pane ID (e.g., "%0") of the active pane in the session's active window.
    pub fn get_active_pane_target(&self, session_name: &str) -> Result<String, TmuxFzfError> {
        let output = self.tmux(&["display-message", "-t", session_name, "-p", "#{pane_id}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux display-message: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux display-message failed for session '{}': {}", session_name, stderr
            )));
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Get the active pane ID for a specific window.
    ///
    /// Returns the pane ID (e.g., "%0") of the active pane in the specified window.
    pub fn get_window_active_pane_target(&self, session_name: &str, window_index: u32) -> Result<String, TmuxFzfError> {
        let target = format!("{}:{}", session_name, window_index);
        let output = self.tmux(&["display-message", "-t", &target, "-p", "#{pane_id}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux display-message: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux display-message failed for window '{}': {}", target, stderr
            )));
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// List windows for a given session.
    ///
    /// Returns a vector of TmuxWindow structs for the specified session.
    pub fn list_windows(&self, session_name: &str) -> Result<Vec<TmuxWindow>, TmuxFzfError> {
        let output = self.tmux(&["list-windows", "-t", session_name, "-F", "#{window_index}:#{window_name}:#{window_panes}:#{window_active}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux list-windows: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux list-windows failed for session '{}': {}", session_name, stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let windows: Vec<TmuxWindow> = stdout
            .lines()
            .filter(|line| !line.is_empty())
            .filter_map(TmuxWindow::from_line)
            .collect();

        Ok(windows)
    }

    /// Every window of every session in one round trip, tagged with its session name.
    /// One call instead of one per session matters when each call is an ssh exchange.
    pub fn list_all_windows(&self) -> Result<Vec<(Arc<str>, TmuxWindow)>, TmuxFzfError> {
        let output = self.tmux(&[
            "list-windows",
            "-a",
            "-F",
            "#{session_name}\t#{window_index}:#{window_name}:#{window_panes}:#{window_active}",
        ])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux list-windows -a: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!("tmux list-windows -a failed: {}", stderr)));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        Ok(stdout.lines().filter_map(parse_all_windows_line).collect())
    }

    /// List panes for a given session and window.
    ///
    /// Returns a vector of TmuxPane structs for the specified window.
    pub fn list_panes(&self, session_name: &str, window_index: u32) -> Result<Vec<TmuxPane>, TmuxFzfError> {
        let target = format!("{}:{}", session_name, window_index);
        let output = self.tmux(&["list-panes", "-t", &target, "-F", "#{pane_index}:#{pane_id}:#{pane_current_command}:#{pane_active}:#{pane_current_path}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux list-panes: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux list-panes failed for '{}': {}", target, stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let panes: Vec<TmuxPane> = stdout
            .lines()
            .filter(|line| !line.is_empty())
            .filter_map(TmuxPane::from_line)
            .collect();

        Ok(panes)
    }

    /// Bulk query returning metadata for all panes across all sessions.
    /// Single tmux call — used for status monitoring without per-pane overhead.
    pub fn list_all_panes_info(&self) -> Result<Vec<PaneInfo>, TmuxFzfError> {
        let output = self.tmux(&["list-panes", "-a", "-F", "#{pane_id}\t#{session_name}\t#{window_index}\t#{pane_current_command}"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux list-panes -a: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TmuxFzfError::TmuxError(format!(
                "tmux list-panes -a failed: {}", stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let panes = stdout
            .lines()
            .filter(|line| !line.is_empty())
            .filter_map(PaneInfo::from_line)
            .collect();

        Ok(panes)
    }
}

/// Parse one `list-windows -a` line of the form `session\tindex:name:panes:active`.
fn parse_all_windows_line(line: &str) -> Option<(Arc<str>, TmuxWindow)> {
    let (session, rest) = line.split_once('\t')?;
    if session.is_empty() {
        return None;
    }
    Some((session.into(), TmuxWindow::from_line(rest)?))
}

/// Metadata for a pane from bulk query, used for status classification.
#[derive(Debug, Clone)]
pub struct PaneInfo {
    pub pane_id: String,
    pub session_name: String,
    pub window_index: u32,
    pub command: String,
}

impl PaneInfo {
    fn from_line(line: &str) -> Option<Self> {
        let parts: Vec<&str> = line.splitn(4, '\t').collect();
        if parts.len() < 4 {
            return None;
        }
        Some(Self {
            pane_id: parts[0].to_string(),
            session_name: parts[1].to_string(),
            window_index: parts[2].parse().ok()?,
            command: parts[3].to_string(),
        })
    }
}

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

    #[test]
    fn means_no_server_accepts_every_empty_server_message() {
        for stderr in [
            "no server running on /tmp/tmux-501/default\n",
            "error connecting to /tmp/tmux-1001/default (No such file or directory)\n",
            "no sessions\n",
        ] {
            assert!(means_no_server(stderr), "should read as an empty listing: {:?}", stderr);
        }
    }

    #[test]
    fn means_no_server_keeps_real_failures_as_errors() {
        for stderr in [
            "error connecting to /tmp/tmux-1001/default (Permission denied)\n",
            "ssh: connect to host box port 22: Connection refused\n",
            "sh: 1: /usr/bin/tmux: not found\n",
            "",
        ] {
            assert!(!means_no_server(stderr), "must stay an error: {:?}", stderr);
        }
    }

    #[test]
    fn new_session_args_named_with_start_dir() {
        let args = new_session_args(Some("dev"), Some(Path::new("/home/k/proj")));
        assert_eq!(
            args,
            vec!["new-session", "-d", "-P", "-F", "#{session_name}", "-s", "dev", "-c", "/home/k/proj"]
        );
    }

    #[test]
    fn new_session_args_unnamed_without_start_dir_omits_s_and_c() {
        let args = new_session_args(None, None);
        assert_eq!(args, vec!["new-session", "-d", "-P", "-F", "#{session_name}"]);
        assert!(!args.contains(&"-c".to_string()), "remote clients must not pass a local cwd");
    }

    #[test]
    fn new_session_args_always_asks_tmux_to_print_the_name() {
        for (name, dir) in [(None, None), (Some("x"), None), (None, Some(Path::new("/tmp")))] {
            let args = new_session_args(name, dir);
            let p = args.iter().position(|a| a == "-P").expect("-P present");
            assert_eq!(args[p + 1], "-F");
            assert_eq!(args[p + 2], "#{session_name}");
        }
    }

    #[test]
    fn test_tmux_window_from_line_valid() {
        let line = "0:main:2:1";
        let window = TmuxWindow::from_line(line).expect("Should parse valid window line");

        assert_eq!(window.index, 0);
        assert_eq!(window.name.as_ref(), "main");
        assert_eq!(window.pane_count, 2);
        assert!(window.is_active);
    }

    #[test]
    fn test_tmux_window_from_line_inactive() {
        let line = "1:editor:1:0";
        let window = TmuxWindow::from_line(line).expect("Should parse valid window line");

        assert_eq!(window.index, 1);
        assert_eq!(window.name.as_ref(), "editor");
        assert_eq!(window.pane_count, 1);
        assert!(!window.is_active);
    }

    #[test]
    fn test_tmux_window_from_line_special_name() {
        let line = "2:server-main:3:0";
        let window = TmuxWindow::from_line(line).expect("Should parse window with special name");

        assert_eq!(window.index, 2);
        assert_eq!(window.name.as_ref(), "server-main");
        assert_eq!(window.pane_count, 3);
        assert!(!window.is_active);
    }

    #[test]
    fn test_tmux_window_from_line_invalid_too_few_parts() {
        let line = "0:main:2";
        assert!(TmuxWindow::from_line(line).is_none(), "Should fail with too few parts");
    }

    #[test]
    fn test_tmux_window_from_line_invalid_index() {
        let line = "abc:main:2:1";
        assert!(TmuxWindow::from_line(line).is_none(), "Should fail with non-numeric index");
    }

    #[test]
    fn test_tmux_window_from_line_invalid_pane_count() {
        let line = "0:main:abc:1";
        assert!(TmuxWindow::from_line(line).is_none(), "Should fail with non-numeric pane count");
    }

    #[test]
    fn test_tmux_pane_from_line_valid() {
        let line = "0:%0:bash:1:/home/user/projects";
        let pane = TmuxPane::from_line(line).expect("Should parse valid pane line");

        assert_eq!(pane.index, 0);
        assert_eq!(pane.pane_id.as_ref(), "%0");
        assert_eq!(pane.command.as_ref(), "bash");
        assert!(pane.is_active);
        assert_eq!(pane.current_path.as_ref(), "/home/user/projects");
    }

    #[test]
    fn test_tmux_pane_from_line_inactive() {
        let line = "1:%1:nvim:0:/tmp";
        let pane = TmuxPane::from_line(line).expect("Should parse valid pane line");

        assert_eq!(pane.index, 1);
        assert_eq!(pane.pane_id.as_ref(), "%1");
        assert_eq!(pane.command.as_ref(), "nvim");
        assert!(!pane.is_active);
        assert_eq!(pane.current_path.as_ref(), "/tmp");
    }

    #[test]
    fn test_tmux_pane_from_line_with_special_command() {
        let line = "0:%0:node-server:1:/var/www/app";
        let pane = TmuxPane::from_line(line).expect("Should parse pane with special command");

        assert_eq!(pane.index, 0);
        assert_eq!(pane.pane_id.as_ref(), "%0");
        assert_eq!(pane.command.as_ref(), "node-server");
        assert!(pane.is_active);
        assert_eq!(pane.current_path.as_ref(), "/var/www/app");
    }

    #[test]
    fn test_tmux_pane_from_line_with_path_containing_colons() {
        // Paths with colons should still work since we use splitn(5, ':')
        let line = "0:%0:bash:1:/home/user/path:with:colons";
        let pane = TmuxPane::from_line(line).expect("Should parse pane with colons in path");

        assert_eq!(pane.index, 0);
        assert_eq!(pane.pane_id.as_ref(), "%0");
        assert_eq!(pane.command.as_ref(), "bash");
        assert!(pane.is_active);
        assert_eq!(pane.current_path.as_ref(), "/home/user/path:with:colons");
    }

    #[test]
    fn test_tmux_pane_from_line_invalid_too_few_parts() {
        let line = "0:%0:bash:1";
        assert!(TmuxPane::from_line(line).is_none(), "Should fail with too few parts (missing path)");
    }

    #[test]
    fn test_tmux_pane_from_line_invalid_index() {
        let line = "abc:%0:bash:1:/home";
        assert!(TmuxPane::from_line(line).is_none(), "Should fail with non-numeric index");
    }

    #[test]
    fn test_tmux_window_clone() {
        let window = TmuxWindow {
            index: 0,
            name: "test".into(),
            pane_count: 1,
            is_active: true,
        };
        let cloned = window.clone();
        assert_eq!(window, cloned);
    }

    #[test]
    fn test_tmux_pane_clone() {
        let pane = TmuxPane {
            index: 0,
            pane_id: "%0".into(),
            command: "bash".into(),
            is_active: true,
            current_path: "/home/user".into(),
        };
        let cloned = pane.clone();
        assert_eq!(pane, cloned);
    }

    #[test]
    fn test_for_host_remote_reports_remote() {
        assert!(TmuxClient::for_host(Host::remote("box")).host().is_remote());
        assert!(!TmuxClient::new().host().is_remote());
    }

    #[test]
    fn test_is_inside_tmux_is_never_true_for_remote_host() {
        // Whatever TMUX says about this process, it says nothing about a remote server.
        assert!(!TmuxClient::for_host(Host::remote("box")).is_inside_tmux());
    }

    #[test]
    fn test_with_program_overrides_binary_path() {
        let client = TmuxClient::for_host(Host::remote("box")).with_program("/opt/homebrew/bin/tmux");
        let cmd = client.tmux(&["list-sessions"]);
        let last = cmd.get_args().last().unwrap().to_string_lossy().into_owned();
        assert_eq!(last, "'/opt/homebrew/bin/tmux' 'list-sessions'");
    }

    #[test]
    fn test_parse_all_windows_line_valid() {
        let (session, window) = parse_all_windows_line("dev\t2:editor:3:1").unwrap();
        assert_eq!(session.as_ref(), "dev");
        assert_eq!(window.index, 2);
        assert_eq!(window.name.as_ref(), "editor");
        assert_eq!(window.pane_count, 3);
        assert!(window.is_active);
    }

    #[test]
    fn test_parse_all_windows_line_rejects_missing_tab_or_session() {
        assert!(parse_all_windows_line("dev 2:editor:3:1").is_none());
        assert!(parse_all_windows_line("\t2:editor:3:1").is_none());
        assert!(parse_all_windows_line("dev\tnot-a-window").is_none());
    }

    /// Build a `list-sessions -F SESSION_FORMAT` line for tests.
    fn session_line(name: &str, windows: &str, attached: &str, last: &str, created: &str) -> String {
        format!("{}\t{}\t{}\t{}\t{}", name, windows, attached, last, created)
    }

    #[test]
    fn test_tmux_session_from_line() {
        let line = session_line("dev", "3", "0", "1737972000", "1737968400");
        let session = TmuxSession::from_line(&line).expect("Should parse valid session line");

        assert_eq!(session.name.as_ref(), "dev");
        assert_eq!(session.windows.as_ref(), "3");
        assert!(!session.is_attached());
        assert_eq!(session.last_attached, 1737972000);
        assert_eq!(session.created, 1737968400);
    }

    #[test]
    fn test_tmux_session_attached() {
        let line = session_line("main", "2", "1", "1737972000", "1737968400");
        let session = TmuxSession::from_line(&line).expect("Should parse valid session line");

        assert_eq!(session.name.as_ref(), "main");
        assert!(session.is_attached());
    }

    #[test]
    fn test_tmux_session_attached_by_multiple_clients() {
        // `session_attached` is a client count, not a 0/1 flag.
        let line = session_line("shared", "1", "2", "1737972000", "1737968400");
        let session = TmuxSession::from_line(&line).expect("Should parse valid session line");

        assert!(session.is_attached(), "A count of 2 clients means attached");
    }

    #[test]
    fn test_tmux_session_single_window() {
        let line = session_line("single", "1", "0", "1737972000", "1737968400");
        let session = TmuxSession::from_line(&line).expect("Should parse valid session line");

        assert_eq!(session.name.as_ref(), "single");
        assert_eq!(session.windows.as_ref(), "1");
    }

    #[test]
    fn test_tmux_session_never_attached_reports_zero() {
        // tmux leaves `#{session_last_attached}` unset for a session created with `new -d` and
        // never attached; an unset format variable expands to an empty field.
        let line = session_line("scripted", "1", "0", "", "1737968400");
        let session = TmuxSession::from_line(&line).expect("Should parse valid session line");

        assert_eq!(session.last_attached, 0, "Empty last_attached should parse as 0");
        assert!(!session.is_attached());
    }

    #[test]
    fn test_tmux_session_from_line_rejects_short_line() {
        let line = "dev\t3\t0";
        assert!(
            TmuxSession::from_line(line).is_none(),
            "Should fail when fields are missing"
        );
    }

    #[test]
    fn test_tmux_session_from_line_rejects_empty_name() {
        let line = session_line("", "1", "0", "1737972000", "1737968400");
        assert!(
            TmuxSession::from_line(&line).is_none(),
            "Should fail on an empty session name"
        );
    }

    /// Build a session with only the fields the sort cares about.
    fn session_for_sort(name: &str, last_attached: i64) -> TmuxSession {
        TmuxSession {
            name: name.into(),
            windows: "1".into(),
            attached: false,
            last_attached,
            created: 0,
        }
    }

    fn names(sessions: &[TmuxSession]) -> Vec<&str> {
        sessions.iter().map(|s| s.name.as_ref()).collect()
    }

    #[test]
    fn test_sort_by_last_attached_most_recent_first() {
        let mut sessions = vec![
            session_for_sort("alpha", 100),
            session_for_sort("zulu", 300),
            session_for_sort("mike", 200),
        ];
        sort_by_last_attached(&mut sessions);

        assert_eq!(names(&sessions), vec!["zulu", "mike", "alpha"]);
    }

    #[test]
    fn test_sort_by_last_attached_never_attached_sinks_to_bottom() {
        let mut sessions = vec![
            session_for_sort("aaa-never", 0),
            session_for_sort("zzz-recent", 500),
            session_for_sort("bbb-never", 0),
            session_for_sort("mmm-old", 100),
        ];
        sort_by_last_attached(&mut sessions);

        assert_eq!(
            names(&sessions),
            vec!["zzz-recent", "mmm-old", "aaa-never", "bbb-never"],
            "Never-attached sessions belong at the bottom, alphabetical among themselves"
        );
    }

    #[test]
    fn test_sort_by_last_attached_ties_break_alphabetically() {
        let mut sessions = vec![
            session_for_sort("charlie", 100),
            session_for_sort("alpha", 100),
            session_for_sort("bravo", 100),
        ];
        sort_by_last_attached(&mut sessions);

        assert_eq!(names(&sessions), vec!["alpha", "bravo", "charlie"]);
    }

    #[test]
    fn test_sort_by_last_attached_degrades_to_alphabetical() {
        // On tmux < 2.1 `#{session_last_attached}` does not exist, so every session parses as 0
        // and the ordering must fall back to what tmux used to give us for free.
        let mut sessions = vec![
            session_for_sort("delta", 0),
            session_for_sort("alpha", 0),
            session_for_sort("charlie", 0),
            session_for_sort("bravo", 0),
        ];
        sort_by_last_attached(&mut sessions);

        assert_eq!(names(&sessions), vec!["alpha", "bravo", "charlie", "delta"]);
    }

    #[test]
    fn test_viewer_session_name_round_trip() {
        let name = viewer_session_name("dev", 4242);
        assert_eq!(name, "_tango-4242-dev");
        assert_eq!(
            parse_viewer_name(&name),
            Some((4242, "dev")),
            "Round trip should recover the pid and source exactly"
        );
    }

    #[test]
    fn test_parse_viewer_name_hyphenated_source() {
        // The pid is fixed-position, so hyphens (and digits) in the source must survive.
        let name = viewer_session_name("my-2nd-session", 7);
        assert_eq!(
            parse_viewer_name(&name),
            Some((7, "my-2nd-session")),
            "A source containing hyphens and digits must parse back unchanged"
        );
    }

    #[test]
    fn test_parse_viewer_name_rejections() {
        for bad in ["_tango-", "_tango-abc-x", "_tango-123", "_tango-123-", "dev", "tango-1-dev", "_tango"] {
            assert!(
                parse_viewer_name(bad).is_none(),
                "'{}' must not be treated as a viewer session name",
                bad
            );
        }
    }

    /// Build a session with only the fields the viewer filter cares about.
    fn session_with_attach(name: &str, attached: bool) -> TmuxSession {
        TmuxSession {
            name: name.into(),
            windows: "1".into(),
            attached,
            last_attached: 0,
            created: 0,
        }
    }

    #[test]
    fn test_filter_viewer_sessions_hides_viewers() {
        let filtered = filter_viewer_sessions(vec![
            session_with_attach("dev", true),
            session_with_attach("_tango-100-dev", false),
            session_with_attach("_tango-200-other", false),
        ]);

        assert_eq!(
            names(&filtered),
            vec!["dev"],
            "Viewer sessions must never appear in a listing, even without a matching source"
        );
    }

    #[test]
    fn test_filter_viewer_sessions_attached_viewer_marks_source() {
        let filtered = filter_viewer_sessions(vec![
            session_with_attach("dev", false),
            session_with_attach("_tango-100-dev", true),
        ]);

        assert_eq!(names(&filtered), vec!["dev"]);
        assert!(
            filtered[0].attached,
            "A source whose only client rides a viewer must still show as attached"
        );
    }

    #[test]
    fn test_filter_viewer_sessions_leaves_plain_sessions_untouched() {
        let filtered = filter_viewer_sessions(vec![
            session_with_attach("alpha", false),
            session_with_attach("bravo", true),
        ]);

        assert_eq!(names(&filtered), vec!["alpha", "bravo"]);
        assert!(!filtered[0].attached, "No viewer present, so flags must be unchanged");
        assert!(filtered[1].attached, "No viewer present, so flags must be unchanged");
    }

    #[test]
    fn test_tmux_client_new() {
        let client = TmuxClient::new();
        assert!(client.session_cache.is_none(), "New client should have no cache");
    }

    #[test]
    fn test_tmux_client_clear_cache() {
        let mut client = TmuxClient::new();
        client.clear_cache();
        assert!(client.session_cache.is_none(), "Cache should be cleared");
    }

    #[test]
    fn test_capture_pane_invalid_target_returns_error() {
        let client = TmuxClient::new();
        let result = client.capture_pane("nonexistent-session-12345:0.0");
        // capture_pane with explicit invalid target returns error
        assert!(result.is_err(), "capture_pane with invalid target should return error");
    }

    #[test]
    fn test_get_active_pane_target_returns_result() {
        // display-message may succeed even with invalid session depending on tmux state,
        // so we only verify the method returns a Result without panicking
        let client = TmuxClient::new();
        let _result = client.get_active_pane_target("test-session");
        // Method should not panic regardless of tmux state
    }

    #[test]
    fn test_get_window_active_pane_target_returns_result() {
        // display-message may succeed even with invalid session depending on tmux state,
        // so we only verify the method returns a Result without panicking
        let client = TmuxClient::new();
        let _result = client.get_window_active_pane_target("test-session", 0);
        // Method should not panic regardless of tmux state
    }
}