vessel-pty 0.17.5

PTY-based runtime for orchestrating interactive terminal processes over Unix sockets
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
//! Viewer integration for vessel.
//!
//! Provides tmux-based viewing of agent output.

use std::collections::HashSet;
use std::process::Command;

/// Errors that can occur in the viewer.
#[derive(Debug, thiserror::Error)]
pub enum ViewError {
    #[error("tmux not found in PATH")]
    TmuxNotFound,

    #[error("tmux command failed: {0}")]
    TmuxFailed(String),

    #[error("unsupported multiplexer: {0}")]
    UnsupportedMux(String),

    #[error("unsupported view mode: {0} (use 'panes' or 'windows')")]
    UnsupportedMode(String),

    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
}

/// View layout mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ViewMode {
    /// All agents in split panes within one window (default).
    #[default]
    Panes,
    /// Each agent gets its own tmux window (tab-style navigation).
    Windows,
}

impl ViewMode {
    /// Parse mode from string.
    ///
    /// # Errors
    ///
    /// Returns [`ViewError::UnsupportedMode`] if `s` is not a recognized mode.
    pub fn parse(s: &str) -> Result<Self, ViewError> {
        match s.to_lowercase().as_str() {
            "panes" | "pane" => Ok(Self::Panes),
            "windows" | "window" | "tabs" | "tab" => Ok(Self::Windows),
            _ => Err(ViewError::UnsupportedMode(s.to_string())),
        }
    }
}

/// tmux session manager for vessel view.
pub struct TmuxView {
    session_name: String,
    /// Set of agent IDs with active panes/windows
    active_panes: HashSet<String>,
    /// Path to vessel binary (for spawning tail commands)
    vessel_path: String,
    /// Layout mode (panes vs windows)
    mode: ViewMode,
}

impl TmuxView {
    /// Create a new tmux view manager.
    #[must_use]
    pub fn new(vessel_path: String) -> Self {
        Self::with_mode(vessel_path, ViewMode::default())
    }

    /// Create a new tmux view manager with specified mode.
    #[must_use]
    pub fn with_mode(vessel_path: String, mode: ViewMode) -> Self {
        Self {
            session_name: "vessel".to_string(),
            active_panes: HashSet::new(),
            vessel_path,
            mode,
        }
    }

    /// Check if tmux is available.
    pub fn check_tmux() -> Result<(), ViewError> {
        let output = Command::new("which").arg("tmux").output()?;
        if output.status.success() {
            Ok(())
        } else {
            Err(ViewError::TmuxNotFound)
        }
    }

    /// Check if our session already exists.
    #[must_use]
    pub fn session_exists(&self) -> bool {
        Command::new("tmux")
            .args(["has-session", "-t", &self.session_name])
            .output()
            .is_ok_and(|o| o.status.success())
    }

    /// Ensure remain-on-exit is set on the agents window.
    /// Safe to call on existing sessions (idempotent).
    pub fn ensure_remain_on_exit(&self) {
        let status = Command::new("tmux")
            .args([
                "set-option",
                "-w",
                "-t",
                &format!("{}:agents", self.session_name),
                "remain-on-exit",
                "on",
            ])
            .status();

        if let Err(e) = status {
            eprintln!("Warning: failed to set remain-on-exit: {e}");
        }
    }

    /// Create a new tmux session (detached).
    /// Returns the window ID of the first window.
    pub fn create_session(&self) -> Result<(), ViewError> {
        let status = Command::new("tmux")
            .args([
                "new-session",
                "-d",
                "-s",
                &self.session_name,
                "-n",
                "agents",
            ])
            .status()?;

        if !status.success() {
            return Err(ViewError::TmuxFailed("failed to create session".into()));
        }

        // Set remain-on-exit at window level so panes don't disappear when their
        // process exits. This prevents the session from being destroyed when the
        // last pane's process exits, giving us time to respawn with the placeholder.
        self.ensure_remain_on_exit();

        // Enable pane border banners showing agent info
        let session_window = format!("{}:agents", self.session_name);
        let _ = Command::new("tmux")
            .args([
                "set-option",
                "-w",
                "-t",
                &session_window,
                "pane-border-status",
                "top",
            ])
            .status();

        // Format: "agent-id command [labels]"
        // Agent name in orange (#fab387), rest in default color
        // Uses @agent_id, @agent_command, @agent_labels pane options
        #[allow(clippy::literal_string_with_formatting_args)]
        let border_format = "#{?pane_active,#[reverse],}#[fg=#fab387] #{@agent_id} #[default]#{?#{@agent_command}, #{@agent_command},}#{?#{@agent_labels}, [#{@agent_labels}],} ";
        let _ = Command::new("tmux")
            .args([
                "set-option",
                "-w",
                "-t",
                &session_window,
                "pane-border-format",
                border_format,
            ])
            .status();

        Ok(())
    }

    /// Set metadata on a pane (command, labels) for display in the border banner.
    pub fn set_pane_metadata(&self, agent_id: &str, command: &str, labels: &[String]) {
        // Find the pane by @agent_id and set additional options
        #[allow(clippy::literal_string_with_formatting_args)]
        let format_str = "#{pane_id}:#{@agent_id}";
        let session_window = format!("{}:agents", self.session_name);

        let output = match self.mode {
            ViewMode::Panes => Command::new("tmux")
                .args(["list-panes", "-t", &session_window, "-F", format_str])
                .output(),
            ViewMode::Windows => Command::new("tmux")
                .args([
                    "list-panes",
                    "-s",
                    "-t",
                    &self.session_name,
                    "-F",
                    format_str,
                ])
                .output(),
        };
        if let Ok(output) = output
            && output.status.success()
        {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                if let Some((pane_id, pane_agent)) = line.split_once(':')
                    && pane_agent == agent_id
                {
                    let _ = Command::new("tmux")
                        .args(["set-option", "-p", "-t", pane_id, "@agent_command", command])
                        .status();
                    if !labels.is_empty() {
                        let label_str = labels.join(",");
                        let _ = Command::new("tmux")
                            .args([
                                "set-option",
                                "-p",
                                "-t",
                                pane_id,
                                "@agent_labels",
                                &label_str,
                            ])
                            .status();
                    }
                    break;
                }
            }
        }
    }

    /// Create a pane/window for an agent.
    /// In panes mode: splits the window.
    /// In windows mode: creates a new tmux window.
    pub fn add_pane(&mut self, agent_id: &str) -> Result<(), ViewError> {
        if self.active_panes.contains(agent_id) {
            // Already have a pane/window for this agent
            return Ok(());
        }

        // Use attach --readonly instead of tail for proper TUI display.
        // attach --readonly:
        // 1. Sends initial screen render (full screen with colors/positioning)
        // 2. Streams live PTY output in raw mode
        // 3. Properly handles cursor positioning and scroll regions
        //
        // Pane runs attach --readonly, which exits when the agent exits.
        // Dead pane cleanup is handled by the view event loop (AgentExited),
        // not by the tmux pane-died hook, to avoid races during mass exit.
        // The pane-died hook only respawns the last pane as placeholder.
        let tail_cmd = format!("{} attach --readonly '{}'", self.vessel_path, agent_id);

        match self.mode {
            ViewMode::Panes => self.add_pane_split(agent_id, &tail_cmd)?,
            ViewMode::Windows => self.add_window(agent_id, &tail_cmd)?,
        }

        self.active_panes.insert(agent_id.to_string());
        Ok(())
    }

    /// Add agent as a pane (split mode).
    fn add_pane_split(&self, agent_id: &str, tail_cmd: &str) -> Result<(), ViewError> {
        if self.active_panes.is_empty() {
            // First pane - respawn it with our command (replaces the shell)
            let status = Command::new("tmux")
                .args([
                    "respawn-pane",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "-k", // kill existing process
                    tail_cmd,
                ])
                .status()?;

            if !status.success() {
                return Err(ViewError::TmuxFailed("failed to respawn first pane".into()));
            }

            // Rename the pane (set pane title)
            let _ = Command::new("tmux")
                .args([
                    "select-pane",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "-T",
                    agent_id,
                ])
                .status();
            // Also set @agent_id pane option for auto-resize (immune to title overwrites)
            let _ = Command::new("tmux")
                .args([
                    "set-option",
                    "-p",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "@agent_id",
                    agent_id,
                ])
                .status();
        } else {
            // Split window and run tail command
            let status = Command::new("tmux")
                .args([
                    "split-window",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "-h", // horizontal split
                    tail_cmd,
                ])
                .status()?;

            if !status.success() {
                return Err(ViewError::TmuxFailed("failed to split window".into()));
            }

            // Set pane title
            let _ = Command::new("tmux")
                .args([
                    "select-pane",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "-T",
                    agent_id,
                ])
                .status();
            // Also set @agent_id pane option for auto-resize (immune to title overwrites)
            let _ = Command::new("tmux")
                .args([
                    "set-option",
                    "-p",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "@agent_id",
                    agent_id,
                ])
                .status();

            // Re-tile the layout
            self.retile()?;
        }
        Ok(())
    }

    /// Add agent as a new window (windows/tabs mode).
    fn add_window(&self, agent_id: &str, tail_cmd: &str) -> Result<(), ViewError> {
        if self.active_panes.is_empty() {
            // First window - respawn the initial window
            let status = Command::new("tmux")
                .args([
                    "respawn-window",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "-k",
                    tail_cmd,
                ])
                .status()?;

            if !status.success() {
                return Err(ViewError::TmuxFailed(
                    "failed to respawn first window".into(),
                ));
            }

            // Rename the window
            let _ = Command::new("tmux")
                .args([
                    "rename-window",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    agent_id,
                ])
                .status();
            // Set @agent_id pane option for auto-resize
            let _ = Command::new("tmux")
                .args([
                    "set-option",
                    "-p",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "@agent_id",
                    agent_id,
                ])
                .status();
        } else {
            // Create a new window
            let status = Command::new("tmux")
                .args([
                    "new-window",
                    "-t",
                    &self.session_name,
                    "-n",
                    agent_id,
                    tail_cmd,
                ])
                .status()?;

            if !status.success() {
                return Err(ViewError::TmuxFailed("failed to create window".into()));
            }
            // Set @agent_id pane option for auto-resize
            let _ = Command::new("tmux")
                .args([
                    "set-option",
                    "-p",
                    "-t",
                    &format!("{}:{}", self.session_name, agent_id),
                    "@agent_id",
                    agent_id,
                ])
                .status();
        }
        Ok(())
    }

    /// Remove a pane/window for an agent.
    pub fn remove_pane(&mut self, agent_id: &str) -> Result<(), ViewError> {
        if !self.active_panes.contains(agent_id) {
            return Ok(());
        }

        match self.mode {
            ViewMode::Panes => self.remove_pane_split(agent_id)?,
            ViewMode::Windows => self.remove_window(agent_id),
        }

        self.active_panes.remove(agent_id);
        Ok(())
    }

    /// Remove a pane in split mode.
    fn remove_pane_split(&self, agent_id: &str) -> Result<(), ViewError> {
        // Find and kill the pane with this agent ID
        // Use @agent_id pane option which is immune to title overwrites by TUI programs
        #[allow(clippy::literal_string_with_formatting_args)]
        let format_str = "#{pane_id}:#{@agent_id}";

        let output = Command::new("tmux")
            .args([
                "list-panes",
                "-t",
                &format!("{}:agents", self.session_name),
                "-F",
                format_str,
            ])
            .output()?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                if let Some((pane_id, pane_agent_id)) = line.split_once(':')
                    && pane_agent_id == agent_id
                {
                    // Kill this pane
                    let _ = Command::new("tmux")
                        .args(["kill-pane", "-t", pane_id])
                        .status();
                    break;
                }
            }
        }

        // Re-tile if we still have panes
        if self.active_panes.len() > 1 {
            self.retile()?;
        }

        Ok(())
    }

    /// Remove a window in windows mode.
    fn remove_window(&self, agent_id: &str) {
        // In windows mode, window name is the agent ID
        let _ = Command::new("tmux")
            .args([
                "kill-window",
                "-t",
                &format!("{}:{}", self.session_name, agent_id),
            ])
            .status();
    }

    /// Re-tile all panes in the window.
    pub fn retile(&self) -> Result<(), ViewError> {
        let status = Command::new("tmux")
            .args([
                "select-layout",
                "-t",
                &format!("{}:agents", self.session_name),
                "tiled",
            ])
            .status()?;

        if status.success() {
            Ok(())
        } else {
            Err(ViewError::TmuxFailed("failed to retile".into()))
        }
    }

    /// Attach to the tmux session (blocking).
    pub fn attach(&self) -> Result<(), ViewError> {
        let status = Command::new("tmux")
            .args(["attach-session", "-t", &self.session_name])
            .status()?;

        if status.success() {
            Ok(())
        } else {
            Err(ViewError::TmuxFailed("failed to attach".into()))
        }
    }

    /// Kill the entire session.
    pub fn kill_session(&self) -> Result<(), ViewError> {
        let _ = Command::new("tmux")
            .args(["kill-session", "-t", &self.session_name])
            .status();
        Ok(())
    }

    /// Show a "waiting for agents" placeholder in the session.
    /// Used when no agents are running to keep the session alive.
    pub fn show_waiting_placeholder(&self) -> Result<(), ViewError> {
        // Create a simple script that displays the waiting message
        // Using a bash loop so it stays alive and can be killed when agents spawn
        let placeholder_cmd = r"printf '\033[2J\033[H\033[90m'; printf '
    ╭─────────────────────────────────────╮
    │                                     │
    │      Waiting for agents...          │
    │                                     │
    │   Run: vessel spawn -- <command>     │
    │                                     │
    ╰─────────────────────────────────────╯
'; sleep 3600"; // 1-hour timeout to avoid running forever if abandoned

        match self.mode {
            ViewMode::Panes => {
                // Respawn the main pane with placeholder
                let status = Command::new("tmux")
                    .args([
                        "respawn-pane",
                        "-t",
                        &format!("{}:agents", self.session_name),
                        "-k",
                        "bash",
                        "-c",
                        placeholder_cmd,
                    ])
                    .status()?;

                if !status.success() {
                    return Err(ViewError::TmuxFailed("failed to show placeholder".into()));
                }

                // Clear agent metadata so stale info doesn't show in border
                let session_window = format!("{}:agents", self.session_name);
                let _ = Command::new("tmux")
                    .args(["set-option", "-p", "-t", &session_window, "@agent_id", ""])
                    .status();
                let _ = Command::new("tmux")
                    .args([
                        "set-option",
                        "-p",
                        "-t",
                        &session_window,
                        "@agent_command",
                        "",
                    ])
                    .status();
                let _ = Command::new("tmux")
                    .args([
                        "set-option",
                        "-p",
                        "-t",
                        &session_window,
                        "@agent_labels",
                        "",
                    ])
                    .status();

                // Set pane title
                let _ = Command::new("tmux")
                    .args(["select-pane", "-t", &session_window, "-T", "waiting"])
                    .status();
            }
            ViewMode::Windows => {
                let session_window = format!("{}:agents", self.session_name);

                // Respawn the agents window with placeholder
                let status = Command::new("tmux")
                    .args([
                        "respawn-window",
                        "-t",
                        &session_window,
                        "-k",
                        "bash",
                        "-c",
                        placeholder_cmd,
                    ])
                    .status()?;

                if !status.success() {
                    return Err(ViewError::TmuxFailed("failed to show placeholder".into()));
                }

                // Clear agent metadata so stale info doesn't show in border
                let _ = Command::new("tmux")
                    .args(["set-option", "-p", "-t", &session_window, "@agent_id", ""])
                    .status();
                let _ = Command::new("tmux")
                    .args([
                        "set-option",
                        "-p",
                        "-t",
                        &session_window,
                        "@agent_command",
                        "",
                    ])
                    .status();
                let _ = Command::new("tmux")
                    .args([
                        "set-option",
                        "-p",
                        "-t",
                        &session_window,
                        "@agent_labels",
                        "",
                    ])
                    .status();

                // Rename window
                let _ = Command::new("tmux")
                    .args(["rename-window", "-t", &session_window, "waiting"])
                    .status();
            }
        }

        Ok(())
    }

    /// Get the number of active panes.
    #[must_use]
    pub fn pane_count(&self) -> usize {
        self.active_panes.len()
    }

    /// Check if we have any active panes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.active_panes.is_empty()
    }

    /// Mark a pane as existing (for initializing from known state).
    /// This doesn't create a pane, just tracks that one exists.
    pub fn mark_pane_exists(&mut self, agent_id: &str) {
        self.active_panes.insert(agent_id.to_string());
    }

    /// Clear all pane tracking (used when replacing last pane with placeholder).
    pub fn clear_pane_tracking(&mut self) {
        self.active_panes.clear();
    }

    /// Discover panes that already exist in the tmux session.
    /// Reads @`agent_id` from each pane and populates `active_panes`.
    /// Returns the set of agent IDs found.
    pub fn discover_existing_panes(&mut self) -> Result<HashSet<String>, ViewError> {
        #[allow(clippy::literal_string_with_formatting_args)]
        let format_str = "#{@agent_id}";

        let output = match self.mode {
            ViewMode::Panes => Command::new("tmux")
                .args([
                    "list-panes",
                    "-t",
                    &format!("{}:agents", self.session_name),
                    "-F",
                    format_str,
                ])
                .output()?,
            ViewMode::Windows => Command::new("tmux")
                .args([
                    "list-panes",
                    "-s",
                    "-t",
                    &self.session_name,
                    "-F",
                    format_str,
                ])
                .output()?,
        };

        let mut found = HashSet::new();
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                let agent_id = line.trim();
                if !agent_id.is_empty() {
                    found.insert(agent_id.to_string());
                    self.active_panes.insert(agent_id.to_string());
                }
            }
        }

        Ok(found)
    }

    /// Find panes with dead processes that need respawning.
    /// Returns a list of (`pane_id`, `agent_id`) pairs where the pane process has exited.
    /// Uses tmux's `pane_dead` format variable to detect dead panes.
    pub fn find_dead_panes(&self) -> Result<Vec<(String, String)>, ViewError> {
        #[allow(clippy::literal_string_with_formatting_args)]
        let format_str = "#{pane_id}:#{@agent_id}:#{pane_dead}";

        let session_window = format!("{}:agents", self.session_name);
        let output = match self.mode {
            ViewMode::Panes => Command::new("tmux")
                .args(["list-panes", "-t", &session_window, "-F", format_str])
                .output()?,
            ViewMode::Windows => Command::new("tmux")
                .args([
                    "list-panes",
                    "-s",
                    "-t",
                    &self.session_name,
                    "-F",
                    format_str,
                ])
                .output()?,
        };

        let mut dead = Vec::new();
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                let parts: Vec<&str> = line.splitn(3, ':').collect();
                if parts.len() >= 3 {
                    let pane_id = parts[0];
                    let agent_id = parts[1];
                    let is_dead = parts[2] == "1";
                    if is_dead && !agent_id.is_empty() {
                        dead.push((pane_id.to_string(), agent_id.to_string()));
                    }
                }
            }
        }

        Ok(dead)
    }

    /// Respawn a dead pane with a fresh attach command.
    pub fn respawn_pane(&self, pane_id: &str, agent_id: &str) -> Result<(), ViewError> {
        let attach_cmd = format!("{} attach --readonly '{}'", self.vessel_path, agent_id);

        let status = Command::new("tmux")
            .args(["respawn-pane", "-k", "-t", pane_id, &attach_cmd])
            .status()?;

        if !status.success() {
            return Err(ViewError::TmuxFailed(format!(
                "failed to respawn pane {pane_id} for agent {agent_id}"
            )));
        }

        Ok(())
    }

    /// Get the sizes of all panes/windows, keyed by agent ID.
    /// Uses @`agent_id` pane option which is immune to programs overwriting titles.
    /// Returns a map of `agent_id` -> (rows, cols).
    pub fn get_pane_sizes(
        &self,
    ) -> Result<std::collections::HashMap<String, (u16, u16)>, ViewError> {
        let mut sizes = std::collections::HashMap::new();

        // Use @agent_id pane option - immune to title overwrites by programs
        #[allow(clippy::literal_string_with_formatting_args)]
        let format_str = "#{@agent_id}:#{pane_height}:#{pane_width}";

        let session_window = format!("{}:agents", self.session_name);
        let output = match self.mode {
            ViewMode::Panes => Command::new("tmux")
                .args(["list-panes", "-t", &session_window, "-F", format_str])
                .output()?,
            ViewMode::Windows => Command::new("tmux")
                .args([
                    "list-panes",
                    "-s",
                    "-t",
                    &self.session_name,
                    "-F",
                    format_str,
                ])
                .output()?,
        };

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                let parts: Vec<&str> = line.split(':').collect();
                if parts.len() >= 3 {
                    let agent_id = parts[0];
                    // Skip if @agent_id is empty (pane not managed by us)
                    if agent_id.is_empty() {
                        continue;
                    }
                    if let (Ok(rows), Ok(cols)) = (parts[1].parse::<u16>(), parts[2].parse::<u16>())
                        && self.active_panes.contains(agent_id)
                    {
                        sizes.insert(agent_id.to_string(), (rows, cols));
                    }
                }
            }
        }

        Ok(sizes)
    }

    /// Set up a tmux hook to call vessel resize when panes are resized.
    /// The hook runs a script that resizes all agents to match their pane sizes.
    pub fn setup_resize_hook(&self) -> Result<(), ViewError> {
        // Create a resize command that will be called on pane resize
        // This iterates through panes and calls vessel resize for each
        let resize_cmd = format!(r"run-shell '{} resize-all-panes'", self.vessel_path);

        // Note: tmux hooks are tricky. For now, we'll use a simpler approach
        // and just resize on attach and when panes are added.
        // A proper hook would be:
        // tmux set-hook -t vessel after-resize-pane "run-shell '...'"

        // For now, this is a no-op placeholder. The resize-all-panes command
        // doesn't exist yet, and implementing proper hooks requires more work.
        let _ = resize_cmd;

        Ok(())
    }

    /// Get the vessel path (for external use in resize commands).
    #[must_use]
    pub fn vessel_path(&self) -> &str {
        &self.vessel_path
    }
}