workmux 0.1.174

An opinionated workflow tool that orchestrates git worktrees and tmux
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
//! Zellij multiplexer backend.
//!
//! Limitations:
//! - No percentage-based pane size control (can resize with +/- but not set exact %)
//! - No window insertion order (tabs always append)
//! - No visual status indicator (set_status is a no-op)

use anyhow::{Context, Result, anyhow};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tracing::{debug, warn};

use crate::cmd::Cmd;
use crate::config::SplitDirection;

use super::handshake::UnixPipeHandshake;
use super::types::{CreateWindowParams, LivePaneInfo};
use super::{Multiplexer, PaneHandshake};

/// Zellij multiplexer backend.
pub struct ZellijBackend {
    _private: (),
}

/// Info about a pane from `zellij action list-panes --json --tab --command`
#[derive(Debug, serde::Deserialize)]
struct PaneInfo {
    id: u32,
    is_plugin: bool,
    is_focused: bool,
    terminal_command: Option<String>,
    /// Running command (more reliable than terminal_command, available with --command flag)
    #[serde(default)]
    pane_command: Option<String>,
    /// Pane's current working directory (available with --command flag)
    #[serde(default)]
    pane_cwd: Option<String>,
    /// Stable tab ID (available with --tab flag)
    #[serde(default)]
    tab_id: Option<u32>,
    #[serde(default)]
    tab_name: String,
    #[serde(default)]
    title: String,
}

/// Info about a tab from `zellij action list-tabs --json`
#[derive(Debug, serde::Deserialize)]
struct TabInfo {
    tab_id: u32, // Stable tab ID (available in zellij 0.44.0+)
    #[allow(dead_code)]
    position: u32, // Tab position (can change when tabs are reordered)
    name: String,
    #[allow(dead_code)]
    active: bool,
}

impl TabInfo {
    /// Get stable tab ID
    fn tab_id(&self) -> u32 {
        self.tab_id
    }
}

/// Parse a numeric pane ID from a "terminal_X" string.
fn parse_pane_id(pane_id: &str) -> Option<u32> {
    pane_id
        .strip_prefix("terminal_")
        .and_then(|s| s.parse().ok())
}

/// Extract the base command name from a full command path/string.
///
/// Takes an optional command string (e.g., "/usr/bin/bash --login"),
/// extracts the first word, then returns only the basename.
fn extract_base_command(pane_command: Option<&str>, terminal_command: Option<&str>) -> String {
    pane_command
        .or(terminal_command)
        .and_then(|cmd| cmd.split_whitespace().next())
        .unwrap_or("")
        .split('/')
        .next_back()
        .unwrap_or("")
        .to_string()
}

/// Parse the focused tab name from `zellij action current-tab-info` output.
///
/// Output format: "name: Tab #1\nid: 0\nposition: 0\n..."
fn parse_tab_name_from_output(output: &str) -> Option<String> {
    output
        .lines()
        .find(|l| l.starts_with("name: "))
        .map(|l| l["name: ".len()..].to_string())
}

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

impl ZellijBackend {
    pub fn new() -> Self {
        Self { _private: () }
    }

    /// Check if inside a zellij session
    fn is_inside_session() -> bool {
        std::env::var("ZELLIJ").is_ok()
    }

    /// Get session name from environment
    fn session_name() -> Option<String> {
        std::env::var("ZELLIJ_SESSION_NAME").ok()
    }

    /// Get current pane ID from environment (format: terminal_1, plugin_2, etc.)
    fn pane_id_from_env() -> Option<String> {
        std::env::var("ZELLIJ_PANE_ID")
            .ok()
            .map(|id| format!("terminal_{}", id))
    }

    /// Get the name of the currently focused tab using `current-tab-info`.
    fn focused_tab_name() -> Option<String> {
        let output = Cmd::new("zellij")
            .args(&["action", "current-tab-info"])
            .run_and_capture_stdout()
            .ok()?;

        parse_tab_name_from_output(&output)
    }

    /// Query all panes using `zellij action list-panes --json --tab --command`
    ///
    /// The `--tab` flag includes `tab_id`, `tab_name`, `tab_position`.
    /// The `--command` flag includes `pane_command`, `pane_cwd`.
    fn list_panes() -> Result<Vec<PaneInfo>> {
        let output = Cmd::new("zellij")
            .args(&["action", "list-panes", "--json", "--tab", "--command"])
            .run_and_capture_stdout()
            .context("Failed to list panes")?;

        serde_json::from_str(&output).context("Failed to parse list-panes JSON output")
    }

    /// Query all tabs using `zellij action list-tabs --json`
    fn list_tabs() -> Result<Vec<TabInfo>> {
        let output = Cmd::new("zellij")
            .args(&["action", "list-tabs", "--json"])
            .run_and_capture_stdout()
            .context("Failed to list tabs")?;

        serde_json::from_str(&output).context("Failed to parse list-tabs JSON output")
    }

    /// Get focused pane ID from list-panes output
    ///
    /// Returns the focused pane in the currently active tab.
    fn focused_pane_id() -> Result<u32> {
        let panes = Self::list_panes()?;
        let focused_tab = Self::focused_tab_name();

        // Filter by focused tab if we know which tab is focused
        if let Some(tab_name) = focused_tab {
            panes
                .iter()
                .find(|p| p.is_focused && !p.is_plugin && p.tab_name == tab_name)
                .map(|p| p.id)
                .ok_or_else(|| anyhow!("No focused terminal pane found in tab '{}'", tab_name))
        } else {
            // Fallback: just find any focused terminal pane
            panes
                .iter()
                .find(|p| p.is_focused && !p.is_plugin)
                .map(|p| p.id)
                .ok_or_else(|| anyhow!("No focused terminal pane found"))
        }
    }

    /// Get tab ID by tab name (for future use)
    #[allow(dead_code)]
    fn get_tab_id_by_name(name: &str) -> Result<Option<u32>> {
        let tabs = Self::list_tabs()?;
        Ok(tabs
            .into_iter()
            .find(|t| t.name == name)
            .map(|t| t.tab_id()))
    }
}

impl Multiplexer for ZellijBackend {
    fn name(&self) -> &'static str {
        "zellij"
    }

    fn supports_preview(&self) -> bool {
        false // Preview requires expensive process spawning
    }

    fn requires_focus_for_input(&self) -> bool {
        true // Zellij's write-chars with --pane-id works, but tab must be active
    }

    fn should_exit_on_jump(&self) -> bool {
        false // Dashboard runs in a persistent tab; keep it alive when switching to agent tabs
    }

    // === Server/Session ===

    fn is_running(&self) -> Result<bool> {
        if Self::is_inside_session() {
            return Ok(true);
        }
        // Try a simple command to check if zellij is accessible
        Cmd::new("zellij")
            .args(&["action", "dump-screen", "/dev/null"])
            .run_as_check()
    }

    fn current_pane_id(&self) -> Option<String> {
        // Fast path: Try environment variable first
        Self::pane_id_from_env()
    }

    fn active_pane_id(&self) -> Option<String> {
        // Reliable path: Query focused pane ID
        Self::focused_pane_id()
            .ok()
            .map(|id| format!("terminal_{}", id))
    }

    fn get_client_active_pane_path(&self) -> Result<PathBuf> {
        // Zellij doesn't expose this via CLI
        // Fall back to current directory
        std::env::current_dir().context("Failed to get current directory")
    }

    fn instance_id(&self) -> String {
        Self::session_name().unwrap_or_else(|| "default".to_string())
    }

    // === Session Management (not supported in Zellij) ===

    fn create_session(&self, _params: super::types::CreateSessionParams) -> Result<String> {
        Err(anyhow!(
            "Session mode (--session) is not supported in Zellij. Use window mode instead."
        ))
    }

    fn switch_to_session(&self, _prefix: &str, _name: &str) -> Result<()> {
        Err(anyhow!(
            "Session mode is not supported in Zellij. Use window mode instead."
        ))
    }

    fn session_exists(&self, _full_name: &str) -> Result<bool> {
        Ok(false)
    }

    fn kill_session(&self, _full_name: &str) -> Result<()> {
        Ok(())
    }

    fn schedule_session_close(&self, _full_name: &str, _delay: Duration) -> Result<()> {
        Err(anyhow!(
            "Session mode is not supported in Zellij. Use window mode instead."
        ))
    }

    fn get_all_session_names(&self) -> Result<HashSet<String>> {
        Ok(HashSet::new())
    }

    fn wait_until_session_closed(&self, _full_session_name: &str) -> Result<()> {
        Err(anyhow!(
            "Session mode is not supported in Zellij. Use window mode instead."
        ))
    }

    fn run_deferred_script(&self, script: &str) -> Result<()> {
        let bg_script = format!("nohup sh -c '{}' >/dev/null 2>&1 &", script);
        Cmd::new("sh").args(&["-c", &bg_script]).run()?;
        Ok(())
    }

    fn shell_select_window_cmd(&self, full_name: &str) -> Result<String> {
        let tabs = Self::list_tabs()?;
        let tab = tabs
            .iter()
            .find(|t| t.name == full_name)
            .ok_or_else(|| anyhow!("Window '{}' not found", full_name))?;
        Ok(format!(
            "zellij action go-to-tab-by-id {} >/dev/null 2>&1",
            tab.tab_id()
        ))
    }

    fn shell_kill_window_cmd(&self, full_name: &str) -> Result<String> {
        let tabs = Self::list_tabs()?;
        let tab = tabs
            .iter()
            .find(|t| t.name == full_name)
            .ok_or_else(|| anyhow!("Window '{}' not found", full_name))?;
        Ok(format!(
            "zellij action close-tab-by-id {} >/dev/null 2>&1",
            tab.tab_id()
        ))
    }

    fn shell_switch_session_cmd(&self, _full_name: &str) -> Result<String> {
        Err(anyhow!(
            "Session mode is not supported in Zellij. Use window mode instead."
        ))
    }

    fn shell_kill_session_cmd(&self, _full_name: &str) -> Result<String> {
        Err(anyhow!(
            "Session mode is not supported in Zellij. Use window mode instead."
        ))
    }

    // === Window/Tab Management ===

    /// Create a new tab in Zellij.
    /// Returns: Pane ID of the initial pane (e.g., "terminal_5")
    fn create_window(&self, params: CreateWindowParams) -> Result<String> {
        let full_name = format!("{}{}", params.prefix, params.name);
        let cwd_str = params
            .cwd
            .to_str()
            .ok_or_else(|| anyhow!("Path contains non-UTF8 characters"))?;

        if params.after_window.is_some() {
            debug!("Zellij does not support window insertion order - ignoring after_window");
        }

        // new-tab returns tab_id on stdout and auto-focuses the new tab
        let tab_id_str = Cmd::new("zellij")
            .args(&["action", "new-tab", "--name", &full_name, "--cwd", cwd_str])
            .run_and_capture_stdout()
            .with_context(|| format!("Failed to create zellij tab '{}'", full_name))?;

        let tab_id: u32 = tab_id_str
            .trim()
            .parse()
            .with_context(|| format!("Invalid tab ID from new-tab: '{}'", tab_id_str.trim()))?;

        // Find the initial pane in the new tab by tab_id
        let panes = Self::list_panes()?;
        let pane = panes
            .iter()
            .find(|p| !p.is_plugin && p.tab_id == Some(tab_id))
            .ok_or_else(|| anyhow!("No terminal pane found in new tab {}", tab_id))?;

        Ok(format!("terminal_{}", pane.id))
    }

    fn kill_window(&self, full_name: &str) -> Result<()> {
        // Try to find the tab by name and close it by ID (zellij PR #4695)
        let tabs = Self::list_tabs()?;
        if let Some(tab) = tabs.iter().find(|t| t.name == full_name) {
            let tab_id = tab.tab_id().to_string();
            Cmd::new("zellij")
                .args(&["action", "close-tab-by-id", &tab_id])
                .run()
                .context("Failed to close zellij tab by ID")?;
        } else {
            // Fallback to old method if tab not found
            warn!("Tab '{}' not found, using fallback close method", full_name);
            Cmd::new("zellij")
                .args(&["action", "go-to-tab-name", full_name])
                .run()
                .context("Failed to switch to tab for closing")?;

            Cmd::new("zellij")
                .args(&["action", "close-tab"])
                .run()
                .context("Failed to close zellij tab")?;
        }
        Ok(())
    }

    fn schedule_window_close(&self, full_name: &str, delay: Duration) -> Result<()> {
        // Try to find the tab ID for more reliable closing (zellij PR #4695)
        let tabs = Self::list_tabs()?;
        let tab_id = tabs
            .iter()
            .find(|t| t.name == full_name)
            .map(|t| t.tab_id().to_string());

        let delay_secs = delay.as_secs();

        let cmd = if let Some(id) = tab_id {
            // Use ID-based close (no need to focus the tab first)
            format!(
                "sleep {} && zellij action close-tab-by-id {}",
                delay_secs, id
            )
        } else {
            // Fallback to name-based close
            format!(
                "sleep {} && zellij action go-to-tab-name '{}' && zellij action close-tab",
                delay_secs,
                full_name.replace('\'', "'\\''")
            )
        };

        std::process::Command::new("sh")
            .args(["-c", &cmd])
            .spawn()
            .context("Failed to spawn delayed close")?;

        Ok(())
    }

    fn select_window(&self, prefix: &str, name: &str) -> Result<()> {
        let full_name = format!("{}{}", prefix, name);

        // Try to find the tab by name and switch by ID (zellij PR #4695)
        let tabs = Self::list_tabs()?;
        if let Some(tab) = tabs.iter().find(|t| t.name == full_name) {
            let tab_id = tab.tab_id().to_string();
            Cmd::new("zellij")
                .args(&["action", "go-to-tab-by-id", &tab_id])
                .run()
                .context("Failed to select zellij tab by ID")?;
        } else {
            // Fallback to old method
            warn!(
                "Tab '{}' not found, using fallback select method",
                full_name
            );
            Cmd::new("zellij")
                .args(&["action", "go-to-tab-name", &full_name])
                .run()
                .context("Failed to select zellij tab")?;
        }
        Ok(())
    }

    fn window_exists(&self, prefix: &str, name: &str) -> Result<bool> {
        let full_name = format!("{}{}", prefix, name);
        self.window_exists_by_full_name(&full_name)
    }

    fn window_exists_by_full_name(&self, full_name: &str) -> Result<bool> {
        if !Self::is_inside_session() {
            return Ok(false);
        }

        let tabs = Self::list_tabs()?;
        Ok(tabs.iter().any(|t| t.name == full_name))
    }

    fn current_window_name(&self) -> Result<Option<String>> {
        Ok(Self::focused_tab_name())
    }

    fn get_all_window_names(&self) -> Result<HashSet<String>> {
        if !Self::is_inside_session() {
            return Ok(HashSet::new());
        }

        // Use list_tabs() for richer metadata and better efficiency
        let tabs = Self::list_tabs()?;
        Ok(tabs.into_iter().map(|t| t.name).collect())
    }

    fn filter_active_windows(&self, windows: &[String]) -> Result<Vec<String>> {
        let active = self.get_all_window_names()?;
        Ok(windows
            .iter()
            .filter(|w| active.contains(*w))
            .cloned()
            .collect())
    }

    fn find_last_window_with_prefix(&self, _prefix: &str) -> Result<Option<String>> {
        // Zellij doesn't support window ordering
        Ok(None)
    }

    fn find_last_window_with_base_handle(
        &self,
        _prefix: &str,
        _base_handle: &str,
    ) -> Result<Option<String>> {
        Ok(None)
    }

    fn wait_until_windows_closed(&self, full_window_names: &[String]) -> Result<()> {
        use std::thread;

        loop {
            let active = self.get_all_window_names()?;
            if full_window_names.iter().all(|w| !active.contains(w)) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(100));
        }
    }

    // === Pane Management ===

    fn select_pane(&self, pane_id: &str) -> Result<()> {
        // Zellij doesn't have a focus-pane-by-id action, so we need to navigate
        // using focus-next-pane or focus-previous-pane

        // Extract numeric ID from pane_id
        let target_id: u32 =
            parse_pane_id(pane_id).ok_or_else(|| anyhow!("Invalid pane_id: {}", pane_id))?;

        // Get focused tab name to filter panes
        let focused_tab =
            Self::focused_tab_name().ok_or_else(|| anyhow!("Could not determine focused tab"))?;

        // Get all panes in the current tab
        let all_panes = Self::list_panes()?;
        let tab_panes: Vec<_> = all_panes
            .iter()
            .filter(|p| !p.is_plugin && p.tab_name == focused_tab)
            .collect();

        // Find current and target indices
        let current_idx = tab_panes
            .iter()
            .position(|p| p.is_focused)
            .ok_or_else(|| anyhow!("No focused pane found in current tab"))?;

        let target_idx = tab_panes
            .iter()
            .position(|p| p.id == target_id)
            .ok_or_else(|| anyhow!("Target pane {} not found in current tab", pane_id))?;

        if current_idx == target_idx {
            // Already focused
            return Ok(());
        }

        // Navigate to target pane
        if target_idx < current_idx {
            // Navigate backwards
            let steps = current_idx - target_idx;
            debug!(
                current_idx,
                target_idx, steps, "Navigating backwards to focused pane"
            );
            for _ in 0..steps {
                Cmd::new("zellij")
                    .args(&["action", "focus-previous-pane"])
                    .run()
                    .context("Failed to navigate to previous pane")?;
            }
        } else {
            // Navigate forwards
            let steps = target_idx - current_idx;
            debug!(
                current_idx,
                target_idx, steps, "Navigating forwards to focused pane"
            );
            for _ in 0..steps {
                Cmd::new("zellij")
                    .args(&["action", "focus-next-pane"])
                    .run()
                    .context("Failed to navigate to next pane")?;
            }
        }

        Ok(())
    }

    fn switch_to_pane(&self, pane_id: &str, window_hint: Option<&str>) -> Result<()> {
        // Zellij can't switch to arbitrary panes by ID, so switch to the containing tab.
        let tab_name = window_hint.ok_or_else(|| {
            anyhow!(
                "Zellij switch_to_pane requires window_hint (tab name) for pane '{}'",
                pane_id
            )
        })?;

        debug!(pane_id, tab_name, "switch_to_pane: switching to tab");

        // Try to switch by tab ID for more reliability
        let tabs = Self::list_tabs()?;
        if let Some(tab) = tabs.iter().find(|t| t.name == tab_name) {
            let tab_id = tab.tab_id().to_string();
            Cmd::new("zellij")
                .args(&["action", "go-to-tab-by-id", &tab_id])
                .run()
                .with_context(|| format!("Failed to switch to tab '{}' by ID", tab_name))?;
        } else {
            // Fallback to name-based switch
            Cmd::new("zellij")
                .args(&["action", "go-to-tab-name", tab_name])
                .run()
                .with_context(|| format!("Failed to switch to tab '{}'", tab_name))?;
        }

        Ok(())
    }

    fn kill_pane(&self, pane_id: &str) -> Result<()> {
        let numeric_id =
            parse_pane_id(pane_id).ok_or_else(|| anyhow!("Invalid pane_id format: {}", pane_id))?;
        let panes = Self::list_panes().context("Failed to list panes in kill_pane")?;
        let tab_id = panes
            .iter()
            .find(|p| p.id == numeric_id && !p.is_plugin)
            .and_then(|p| p.tab_id)
            .ok_or_else(|| anyhow!("Pane {} not found or tab_id unavailable", pane_id))?;
        Cmd::new("zellij")
            .args(&["action", "close-tab-by-id", &tab_id.to_string()])
            .run()?;
        Ok(())
    }

    fn respawn_pane(&self, pane_id: &str, cwd: &Path, cmd: Option<&str>) -> Result<String> {
        debug!(pane_id, "respawn_pane: starting");

        // Verify the pane exists - if list-panes returns it, it's ready for --pane-id targeting
        let panes = Self::list_panes().context("Failed to list panes in respawn_pane")?;
        let numeric_id: u32 =
            parse_pane_id(pane_id).ok_or_else(|| anyhow!("Invalid pane_id format: {}", pane_id))?;

        if !panes.iter().any(|p| p.id == numeric_id && !p.is_plugin) {
            return Err(anyhow!(
                "Pane {} not found. Available panes: {:?}",
                pane_id,
                panes
                    .iter()
                    .map(|p| format!("terminal_{}", p.id))
                    .collect::<Vec<_>>()
            ));
        }

        // Zellij doesn't have respawn-pane; send cd + command to the target pane
        let cwd_str = cwd
            .to_str()
            .ok_or_else(|| anyhow!("Path contains non-UTF8 characters"))?;

        // Combine cd + command into a single write-chars call to reduce subprocess spawns
        let combined = if let Some(command) = cmd {
            debug!(
                pane_id,
                command = &command[..command.len().min(100)],
                "respawn_pane: sending cd + command"
            );
            format!("cd '{}' && {}", cwd_str.replace('\'', "'\\''"), command)
        } else {
            debug!(pane_id, "respawn_pane: sending cd command");
            format!("cd '{}'", cwd_str.replace('\'', "'\\''"))
        };

        Cmd::new("zellij")
            .args(&["action", "write-chars", "--pane-id", pane_id, &combined])
            .run()?;
        Cmd::new("zellij")
            .args(&["action", "write", "--pane-id", pane_id, "13"])
            .run()?;

        debug!(pane_id, "respawn_pane: completed");
        Ok(pane_id.to_string())
    }

    fn capture_pane(&self, _pane_id: &str, _lines: u16) -> Option<String> {
        // Zellij limitation: dump-screen always captures the focused pane,
        // not the pane specified by pane_id. When the dashboard is focused,
        // it captures itself, creating a recursive loop. We detect this and
        // return None to prevent the recursion.

        // Use PID + thread ID + timestamp for thread-safe temp file naming
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let thread_id = std::thread::current().id();
        let temp_path = std::env::temp_dir().join(format!(
            "zellij_capture_{}_{:?}_{}",
            std::process::id(),
            thread_id,
            timestamp
        ));
        let temp_str = temp_path.to_string_lossy();

        if Cmd::new("zellij")
            .args(&["action", "dump-screen", &temp_str])
            .run()
            .is_ok()
        {
            if let Ok(content) = std::fs::read_to_string(&temp_path) {
                let _ = std::fs::remove_file(&temp_path);
                return Some(content);
            }
            let _ = std::fs::remove_file(&temp_path);
        }

        None
    }

    // === Text I/O ===

    fn send_keys(&self, pane_id: &str, command: &str) -> Result<()> {
        // Use --pane-id for reliable pane targeting (zellij PR #4691)
        Cmd::new("zellij")
            .args(&["action", "write-chars", "--pane-id", pane_id, command])
            .run()
            .context("Failed to send keys")?;

        // Send Enter (ASCII 13)
        Cmd::new("zellij")
            .args(&["action", "write", "--pane-id", pane_id, "13"])
            .run()
            .context("Failed to send Enter")?;
        Ok(())
    }

    fn send_keys_to_agent(&self, pane_id: &str, command: &str, agent: Option<&str>) -> Result<()> {
        use super::agent;

        let profile = agent::resolve_profile(agent);

        if profile.needs_bang_delay() && command.starts_with('!') {
            // Send ! first, wait, then rest of command
            Cmd::new("zellij")
                .args(&["action", "write-chars", "--pane-id", pane_id, "!"])
                .run()?;

            std::thread::sleep(std::time::Duration::from_millis(50));

            Cmd::new("zellij")
                .args(&["action", "write-chars", "--pane-id", pane_id, &command[1..]])
                .run()?;

            Cmd::new("zellij")
                .args(&["action", "write", "--pane-id", pane_id, "13"])
                .run()?;

            Ok(())
        } else {
            self.send_keys(pane_id, command)
        }
    }

    fn send_key(&self, pane_id: &str, key: &str) -> Result<()> {
        // Map common key names to ASCII codes
        let code = match key {
            "Enter" => "13",
            "Escape" => "27",
            "Tab" => "9",
            _ => {
                // For single chars, use write-chars with pane targeting
                Cmd::new("zellij")
                    .args(&["action", "write-chars", "--pane-id", pane_id, key])
                    .run()
                    .context("Failed to send key")?;
                return Ok(());
            }
        };

        Cmd::new("zellij")
            .args(&["action", "write", "--pane-id", pane_id, code])
            .run()
            .context("Failed to send key")?;
        Ok(())
    }

    fn paste_multiline(&self, pane_id: &str, content: &str) -> Result<()> {
        // Send line by line with pane targeting
        for line in content.lines() {
            Cmd::new("zellij")
                .args(&["action", "write-chars", "--pane-id", pane_id, line])
                .run()?;
            Cmd::new("zellij")
                .args(&["action", "write", "--pane-id", pane_id, "13"])
                .run()?;
        }
        Ok(())
    }

    fn clear_pane(&self, pane_id: &str) -> Result<()> {
        // Clear the pane to hide handshake setup commands
        // Try with --pane-id first, fall back to focused pane if not supported
        let result = Cmd::new("zellij")
            .args(&["action", "clear", "--pane-id", pane_id])
            .run();

        if result.is_err() {
            // Fallback for older zellij versions without --pane-id support for clear
            Cmd::new("zellij")
                .args(&["action", "clear"])
                .run()
                .context("Failed to clear pane")?;
        }
        Ok(())
    }

    // === Shell ===

    fn get_default_shell(&self) -> Result<String> {
        std::env::var("SHELL").or_else(|_| Ok("/bin/sh".to_string()))
    }

    fn create_handshake(&self) -> Result<Box<dyn PaneHandshake>> {
        // Reuse the same Unix pipe handshake as WezTerm
        Ok(Box::new(UnixPipeHandshake::new()?))
    }

    // === Status ===

    fn set_status(&self, _pane_id: &str, _icon: &str, _auto_clear_on_focus: bool) -> Result<()> {
        // No-op: can't target specific panes, and rename-pane would hijack
        // the user's focused pane. Status is tracked in StateStore by tab name.
        Ok(())
    }

    fn clear_status(&self, _pane_id: &str) -> Result<()> {
        // No-op: status is managed by StateStore
        Ok(())
    }

    fn ensure_status_format(&self, _pane_id: &str) -> Result<()> {
        // No-op for zellij
        Ok(())
    }

    // === Pane Setup ===

    // Use default implementation from trait - no need for Zellij-specific workarounds
    // now that pane targeting is reliable with --pane-id (zellij PR #4691)

    /// Split a pane in Zellij.
    ///
    /// **Zellij CLI Limitations:**
    /// - `target_pane_id` is ignored - Zellij's `new-pane` command doesn't support
    ///   targeting specific panes for splitting (always splits the focused pane).
    /// - `size`/`percentage` are ignored - all splits are 50/50.
    ///
    /// **Returns:** The pane ID from `new-pane` stdout (e.g., "terminal_5").
    fn split_pane(
        &self,
        target_pane_id: &str,
        direction: &SplitDirection,
        cwd: &Path,
        _size: Option<u16>,
        _percentage: Option<u8>,
        command: Option<&str>,
    ) -> Result<String> {
        debug!(
            "split_pane: target_pane_id '{}' (note: new-pane splits focused pane only)",
            target_pane_id
        );

        let dir_arg = match direction {
            SplitDirection::Horizontal => "right", // panes side-by-side (left/right)
            SplitDirection::Vertical => "down",    // panes stacked (top/bottom)
        };

        let cwd_str = cwd
            .to_str()
            .ok_or_else(|| anyhow!("Path contains non-UTF8 characters"))?;

        let mut cmd = Cmd::new("zellij").args(&[
            "action",
            "new-pane",
            "--direction",
            dir_arg,
            "--cwd",
            cwd_str,
        ]);

        // Pass command inline via -- syntax (runs as `sh -c 'script'`)
        if let Some(script) = command {
            cmd = cmd.args(&["--", "sh", "-c", script]);
        }

        // new-pane returns pane ID on stdout (e.g., "terminal_5")
        let pane_id = cmd
            .run_and_capture_stdout()
            .context("Failed to split pane")?;

        Ok(pane_id.trim().to_string())
    }

    // === State Reconciliation ===

    fn get_live_pane_info(&self, pane_id: &str) -> Result<Option<LivePaneInfo>> {
        let panes = Self::list_panes()?;

        // Extract numeric ID from "terminal_X"
        let numeric_id: u32 =
            parse_pane_id(pane_id).ok_or_else(|| anyhow!("Invalid pane_id: {}", pane_id))?;

        // Find pane by ID
        let pane = match panes.iter().find(|p| p.id == numeric_id && !p.is_plugin) {
            Some(p) => p,
            None => return Ok(None), // Pane doesn't exist
        };

        let current_command = extract_base_command(
            pane.pane_command.as_deref(),
            pane.terminal_command.as_deref(),
        );
        let current_command = if current_command.is_empty() {
            None
        } else {
            Some(current_command)
        };

        // Use actual pane_cwd instead of process cwd
        let working_dir = pane
            .pane_cwd
            .as_deref()
            .map(PathBuf::from)
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

        Ok(Some(LivePaneInfo {
            pid: None, // Zellij doesn't expose PID
            current_command,
            working_dir,
            title: Some(pane.title.clone()).filter(|t| !t.is_empty()),
            session: Self::session_name(),
            window: Some(pane.tab_name.clone()).filter(|t| !t.is_empty()),
        }))
    }

    fn validate_agent_alive(&self, state: &crate::state::AgentState) -> Result<bool> {
        // Check if pane exists
        let pane_info = self.get_live_pane_info(&state.pane_key.pane_id)?;
        let pane_info = match pane_info {
            Some(info) => info,
            None => return Ok(false), // Pane doesn't exist
        };

        // Secondary validation: Check if command matches stored command
        // This detects if the agent process was killed and replaced with something else
        if let Some(ref live_command) = pane_info.current_command
            && !state.command.is_empty()
            && !live_command.is_empty()
        {
            // Extract base command name for comparison
            let expected_base = state
                .command
                .split('/')
                .next_back()
                .unwrap_or(&state.command);
            let actual_base = live_command.split('/').next_back().unwrap_or(live_command);

            if expected_base != actual_base {
                debug!(
                    "Agent validation: command mismatch - expected '{}', got '{}'",
                    expected_base, actual_base
                );
                return Ok(false); // Different command running
            }
        }

        Ok(true) // Agent is valid
    }

    fn get_all_live_pane_info(&self) -> Result<std::collections::HashMap<String, LivePaneInfo>> {
        use std::collections::HashMap;

        let mut result = HashMap::new();

        // Use list-panes to get all panes (not just focused ones)
        let panes = Self::list_panes()?;

        for pane in panes {
            // Skip plugin panes, only include terminal panes
            if pane.is_plugin {
                continue;
            }

            let pane_id = format!("terminal_{}", pane.id);

            let current_command = extract_base_command(
                pane.pane_command.as_deref(),
                pane.terminal_command.as_deref(),
            );
            let current_command = if current_command.is_empty() {
                None
            } else {
                Some(current_command)
            };

            // Use actual pane_cwd instead of process cwd
            let working_dir = pane
                .pane_cwd
                .as_deref()
                .map(PathBuf::from)
                .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

            result.insert(
                pane_id,
                LivePaneInfo {
                    pid: None, // Zellij doesn't expose PID
                    current_command,
                    working_dir,
                    title: Some(pane.title.clone()).filter(|t| !t.is_empty()),
                    session: Self::session_name(),
                    window: Some(pane.tab_name.clone()).filter(|t| !t.is_empty()),
                },
            );
        }

        Ok(result)
    }
}

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

    // === parse_pane_id ===

    #[test]
    fn parse_pane_id_valid() {
        assert_eq!(parse_pane_id("terminal_0"), Some(0));
        assert_eq!(parse_pane_id("terminal_1"), Some(1));
        assert_eq!(parse_pane_id("terminal_42"), Some(42));
        assert_eq!(parse_pane_id("terminal_999"), Some(999));
    }

    #[test]
    fn parse_pane_id_invalid_prefix() {
        assert_eq!(parse_pane_id("plugin_1"), None);
        assert_eq!(parse_pane_id("pane_1"), None);
        assert_eq!(parse_pane_id("1"), None);
        assert_eq!(parse_pane_id(""), None);
    }

    #[test]
    fn parse_pane_id_non_numeric() {
        assert_eq!(parse_pane_id("terminal_abc"), None);
        assert_eq!(parse_pane_id("terminal_"), None);
        assert_eq!(parse_pane_id("terminal_1.5"), None);
        assert_eq!(parse_pane_id("terminal_-1"), None);
    }

    // === extract_base_command ===

    #[test]
    fn extract_base_command_full_path() {
        assert_eq!(extract_base_command(Some("/usr/bin/bash"), None), "bash");
    }

    #[test]
    fn extract_base_command_with_args() {
        assert_eq!(
            extract_base_command(Some("/usr/bin/bash --login -i"), None),
            "bash"
        );
    }

    #[test]
    fn extract_base_command_bare_name() {
        assert_eq!(extract_base_command(Some("zsh"), None), "zsh");
    }

    #[test]
    fn extract_base_command_prefers_pane_command() {
        assert_eq!(extract_base_command(Some("fish"), Some("bash")), "fish");
    }

    #[test]
    fn extract_base_command_falls_back_to_terminal_command() {
        assert_eq!(extract_base_command(None, Some("/bin/zsh")), "zsh");
    }

    #[test]
    fn extract_base_command_both_none() {
        assert_eq!(extract_base_command(None, None), "");
    }

    #[test]
    fn extract_base_command_empty_strings() {
        assert_eq!(extract_base_command(Some(""), None), "");
    }

    // === parse_tab_name_from_output ===

    #[test]
    fn parse_tab_name_standard() {
        let output = "name: Tab #1\nid: 0\nposition: 0\n";
        assert_eq!(
            parse_tab_name_from_output(output),
            Some("Tab #1".to_string())
        );
    }

    #[test]
    fn parse_tab_name_custom_name() {
        let output = "name: my-worktree\nid: 3\nposition: 2\n";
        assert_eq!(
            parse_tab_name_from_output(output),
            Some("my-worktree".to_string())
        );
    }

    #[test]
    fn parse_tab_name_with_spaces() {
        let output = "name: My Project Tab\nid: 1\nposition: 0\n";
        assert_eq!(
            parse_tab_name_from_output(output),
            Some("My Project Tab".to_string())
        );
    }

    #[test]
    fn parse_tab_name_empty_output() {
        assert_eq!(parse_tab_name_from_output(""), None);
    }

    #[test]
    fn parse_tab_name_no_name_field() {
        let output = "id: 0\nposition: 0\n";
        assert_eq!(parse_tab_name_from_output(output), None);
    }

    #[test]
    fn parse_tab_name_name_field_in_middle() {
        let output = "id: 5\nname: middle-tab\nposition: 3\nactive: true\n";
        assert_eq!(
            parse_tab_name_from_output(output),
            Some("middle-tab".to_string())
        );
    }

    // === PaneInfo deserialization ===

    #[test]
    fn pane_info_deserialize_full() {
        let json = r#"{
            "id": 5,
            "is_plugin": false,
            "is_focused": true,
            "terminal_command": "/bin/bash",
            "pane_command": "/usr/bin/fish",
            "pane_cwd": "/home/user/project",
            "tab_id": 2,
            "tab_name": "my-tab",
            "title": "fish"
        }"#;

        let pane: PaneInfo = serde_json::from_str(json).unwrap();
        assert_eq!(pane.id, 5);
        assert!(!pane.is_plugin);
        assert!(pane.is_focused);
        assert_eq!(pane.terminal_command.as_deref(), Some("/bin/bash"));
        assert_eq!(pane.pane_command.as_deref(), Some("/usr/bin/fish"));
        assert_eq!(pane.pane_cwd.as_deref(), Some("/home/user/project"));
        assert_eq!(pane.tab_id, Some(2));
        assert_eq!(pane.tab_name, "my-tab");
        assert_eq!(pane.title, "fish");
    }

    #[test]
    fn pane_info_deserialize_minimal() {
        // Only required fields; optional fields use serde defaults
        let json = r#"{
            "id": 0,
            "is_plugin": true,
            "is_focused": false,
            "terminal_command": null
        }"#;

        let pane: PaneInfo = serde_json::from_str(json).unwrap();
        assert_eq!(pane.id, 0);
        assert!(pane.is_plugin);
        assert!(!pane.is_focused);
        assert!(pane.terminal_command.is_none());
        assert!(pane.pane_command.is_none());
        assert!(pane.pane_cwd.is_none());
        assert!(pane.tab_id.is_none());
        assert_eq!(pane.tab_name, "");
        assert_eq!(pane.title, "");
    }

    #[test]
    fn pane_info_deserialize_list() {
        let json = r#"[
            {"id": 1, "is_plugin": false, "is_focused": true, "terminal_command": "bash", "tab_name": "tab1"},
            {"id": 2, "is_plugin": true, "is_focused": false, "terminal_command": null, "tab_name": "tab1"}
        ]"#;

        let panes: Vec<PaneInfo> = serde_json::from_str(json).unwrap();
        assert_eq!(panes.len(), 2);
        assert_eq!(panes[0].id, 1);
        assert!(!panes[0].is_plugin);
        assert_eq!(panes[1].id, 2);
        assert!(panes[1].is_plugin);
    }

    // === TabInfo deserialization ===

    #[test]
    fn tab_info_deserialize() {
        let json = r#"{
            "tab_id": 3,
            "position": 1,
            "name": "workmux-feature",
            "active": true
        }"#;

        let tab: TabInfo = serde_json::from_str(json).unwrap();
        assert_eq!(tab.tab_id(), 3);
        assert_eq!(tab.position, 1);
        assert_eq!(tab.name, "workmux-feature");
        assert!(tab.active);
    }

    #[test]
    fn tab_info_deserialize_list() {
        let json = r#"[
            {"tab_id": 0, "position": 0, "name": "Tab #1", "active": true},
            {"tab_id": 1, "position": 1, "name": "my-feature", "active": false}
        ]"#;

        let tabs: Vec<TabInfo> = serde_json::from_str(json).unwrap();
        assert_eq!(tabs.len(), 2);
        assert_eq!(tabs[0].tab_id(), 0);
        assert_eq!(tabs[0].name, "Tab #1");
        assert!(tabs[0].active);
        assert_eq!(tabs[1].tab_id(), 1);
        assert_eq!(tabs[1].name, "my-feature");
        assert!(!tabs[1].active);
    }
}