par_term/app/tmux_handler/gateway.rs
1//! tmux gateway session management and I/O routing.
2//!
3//! Covers:
4//! - Session lifecycle: initiate, attach, disconnect, status queries
5//! - Input routing: send_input_via_tmux, paste_via_tmux, prefix key handling
6//! - Pane operations: split_pane_via_tmux, close_pane_via_tmux
7//! - Clipboard + resize synchronization
8//!
9//! Profile auto-application on session connect lives in `gateway_profile`.
10
11use crate::app::window_state::WindowState;
12use crate::tmux::{SessionState, TmuxSession};
13
14impl WindowState {
15 // =========================================================================
16 // Gateway Mode Session Management
17 // =========================================================================
18
19 /// Initiate a new tmux session via gateway mode.
20 ///
21 /// This writes `tmux -CC new-session` to the active tab's PTY and enables
22 /// tmux control mode parsing. The session will be fully connected once we
23 /// receive the `%session-changed` notification.
24 ///
25 /// # Arguments
26 /// * `session_name` - Optional session name. If None, tmux will auto-generate one.
27 pub fn initiate_tmux_gateway(&mut self, session_name: Option<&str>) -> anyhow::Result<()> {
28 if !self.config.load().tmux.tmux_enabled {
29 anyhow::bail!("tmux integration is disabled");
30 }
31
32 if self.tmux_state.tmux_session.is_some() && self.is_tmux_connected() {
33 anyhow::bail!("Already connected to a tmux session");
34 }
35
36 crate::debug_info!(
37 "TMUX",
38 "Initiating gateway mode session: {:?}",
39 session_name.unwrap_or("(auto)")
40 );
41
42 // Generate the command
43 let cmd = match session_name {
44 Some(name) => TmuxSession::create_or_attach_command(name),
45 None => TmuxSession::create_new_command(None),
46 };
47
48 // Get the active tab ID and write the command to its PTY
49 let gateway_tab_id = self
50 .tab_manager
51 .active_tab_id()
52 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
53
54 let tab = self
55 .tab_manager
56 .active_tab_mut()
57 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
58
59 // Write the command to the PTY
60 // try_lock: intentional — initiate_tmux_gateway is user-initiated but called from
61 // the sync event loop context. If the terminal is locked by the async PTY reader
62 // the command cannot be sent. On miss: bails with an error so the caller can retry.
63 if let Ok(term) = tab.terminal.try_read() {
64 crate::debug_info!(
65 "TMUX",
66 "Writing gateway command to tab {}: {}",
67 gateway_tab_id,
68 cmd.trim()
69 );
70 term.write(cmd.as_bytes())?;
71 // Enable tmux control mode parsing AFTER writing the command
72 term.set_tmux_control_mode(true);
73 crate::debug_info!(
74 "TMUX",
75 "Enabled tmux control mode parsing on tab {}",
76 gateway_tab_id
77 );
78 } else {
79 anyhow::bail!("Could not acquire terminal lock");
80 }
81
82 // Mark this tab as the gateway
83 tab.tmux.tmux_gateway_active = true;
84
85 // Store the gateway tab ID so we know where to send commands
86 self.tmux_state.tmux_gateway_tab_id = Some(gateway_tab_id);
87 crate::debug_info!(
88 "TMUX",
89 "Gateway tab set to {}, state: Initiating",
90 gateway_tab_id
91 );
92
93 // Create session and set gateway state
94 let mut session = TmuxSession::new();
95 session.set_gateway_initiating();
96 self.tmux_state.tmux_session = Some(session);
97
98 // Show toast
99 self.show_toast("tmux: Connecting...");
100
101 Ok(())
102 }
103
104 /// Attach to an existing tmux session via gateway mode.
105 ///
106 /// This writes `tmux -CC attach -t session` to the active tab's PTY.
107 pub fn attach_tmux_gateway(&mut self, session_name: &str) -> anyhow::Result<()> {
108 if !self.config.load().tmux.tmux_enabled {
109 anyhow::bail!("tmux integration is disabled");
110 }
111
112 if self.tmux_state.tmux_session.is_some() && self.is_tmux_connected() {
113 anyhow::bail!("Already connected to a tmux session");
114 }
115
116 crate::debug_info!("TMUX", "Attaching to session via gateway: {}", session_name);
117
118 // Generate the attach command
119 let cmd = TmuxSession::create_attach_command(session_name);
120
121 // Get the active tab ID and write the command to its PTY
122 let gateway_tab_id = self
123 .tab_manager
124 .active_tab_id()
125 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
126
127 let tab = self
128 .tab_manager
129 .active_tab_mut()
130 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
131
132 // Write the command to the PTY
133 // try_lock: intentional — same rationale as initiate_tmux_gateway. On miss: bails
134 // so the user can retry the attach operation explicitly.
135 if let Ok(term) = tab.terminal.try_read() {
136 crate::debug_info!(
137 "TMUX",
138 "Writing attach command to tab {}: {}",
139 gateway_tab_id,
140 cmd.trim()
141 );
142 term.write(cmd.as_bytes())?;
143 term.set_tmux_control_mode(true);
144 crate::debug_info!(
145 "TMUX",
146 "Enabled tmux control mode parsing on tab {}",
147 gateway_tab_id
148 );
149 } else {
150 anyhow::bail!("Could not acquire terminal lock");
151 }
152
153 // Mark this tab as the gateway
154 tab.tmux.tmux_gateway_active = true;
155
156 // Store the gateway tab ID so we know where to send commands
157 self.tmux_state.tmux_gateway_tab_id = Some(gateway_tab_id);
158 crate::debug_info!(
159 "TMUX",
160 "Gateway tab set to {}, state: Initiating",
161 gateway_tab_id
162 );
163
164 // Create session and set gateway state
165 let mut session = TmuxSession::new();
166 session.set_gateway_initiating();
167 self.tmux_state.tmux_session = Some(session);
168
169 // Show toast
170 self.show_toast(format!("tmux: Attaching to '{}'...", session_name));
171
172 Ok(())
173 }
174
175 /// Disconnect from the current tmux session
176 pub fn disconnect_tmux_session(&mut self) {
177 // Restore gateway tab visibility before clearing state
178 self.show_gateway_tab();
179
180 // Clear the gateway tab ID
181 self.tmux_state.tmux_gateway_tab_id = None;
182
183 // First, disable tmux control mode on any gateway tabs
184 for tab in self.tab_manager.tabs_mut() {
185 if tab.tmux.tmux_gateway_active {
186 tab.tmux.tmux_gateway_active = false;
187 // try_lock: intentional — disconnect is called from the sync event loop.
188 // On miss: control mode stays on the terminal until the next frame; benign
189 // since the session is already being torn down and no further output arrives.
190 if let Ok(term) = tab.terminal.try_read() {
191 term.set_tmux_control_mode(false);
192 }
193 }
194 }
195
196 if let Some(mut session) = self.tmux_state.tmux_session.take() {
197 crate::debug_info!("TMUX", "Disconnecting from tmux session");
198 session.disconnect();
199 }
200
201 // Clear session name
202 self.tmux_state.tmux_session_name = None;
203
204 // Reset sync state
205 self.tmux_state.tmux_sync = crate::tmux::TmuxSync::new();
206
207 // Reset window title (now without tmux info)
208 self.update_window_title_with_tmux();
209 }
210
211 /// Check if tmux session is active
212 pub fn is_tmux_connected(&self) -> bool {
213 self.tmux_state
214 .tmux_session
215 .as_ref()
216 .is_some_and(|s| s.state() == SessionState::Connected)
217 }
218
219 /// Return true when a `tmux*` process is running under the active tab's
220 /// shell. Used by the input path to decide whether to encode Shift+Enter
221 /// as raw LF (iTerm2 convention) or as a CSI-u extended-keys sequence
222 /// that tmux's `extended-keys on` parser can relay to the inner app in
223 /// whatever keyboard protocol that app has negotiated (kitty/modifyOtherKeys).
224 pub fn shell_has_tmux_child(&self) -> bool {
225 use std::sync::atomic::Ordering;
226 let tab = match self.tab_manager.active_tab() {
227 Some(t) => t,
228 None => return false,
229 };
230 // Cache fallback: on `try_read` contention (frequent in release/LTO
231 // builds because the renderer holds the write lock briefly on every
232 // frame), fall back to the last-known result rather than reporting
233 // "no tmux". Returning `false` here was causing the Shift+Enter
234 // handler to send raw LF in shell context, which tmux mangles into
235 // Ctrl+J. See cached_has_tmux_child docs in src/tab/mod.rs.
236 match tab.terminal.try_read() {
237 Ok(term) => {
238 let has = term
239 .get_running_child_processes(&[])
240 .iter()
241 .any(|name| name.eq_ignore_ascii_case("tmux") || name.starts_with("tmux"));
242 tab.cached_has_tmux_child.store(has, Ordering::Relaxed);
243 has
244 }
245 Err(_) => tab.cached_has_tmux_child.load(Ordering::Relaxed),
246 }
247 }
248
249 /// Check if gateway mode is active (connected or connecting)
250 pub fn is_gateway_active(&self) -> bool {
251 self.tmux_state
252 .tmux_session
253 .as_ref()
254 .is_some_and(|s| s.is_gateway_active())
255 }
256
257 /// Update the tmux focused pane when a native pane is focused
258 ///
259 /// This should be called when the user clicks on a pane to ensure
260 /// input is routed to the correct tmux pane.
261 pub fn set_tmux_focused_pane_from_native(&mut self, native_pane_id: crate::pane::PaneId) {
262 let Some(tmux_pane_id) = self
263 .tmux_state
264 .native_pane_to_tmux_pane
265 .get(&native_pane_id)
266 .copied()
267 else {
268 return;
269 };
270 crate::debug_info!(
271 "TMUX",
272 "Setting focused pane: native {} -> tmux %{}",
273 native_pane_id,
274 tmux_pane_id
275 );
276 if let Some(session) = &mut self.tmux_state.tmux_session {
277 session.set_focused_pane(Some(tmux_pane_id));
278 } else if self.tmux_state.transport.is_some() {
279 // par-mux transport: remember the focused pane for input routing.
280 self.tmux_state.mux_focused_pane = Some(tmux_pane_id);
281 }
282 }
283
284 /// Focus the native pane backing a tmux/par-mux pane id — the target of
285 /// the agent-roster palette picker's `agent-roster-focus:<pane>` rows
286 /// (A2b task 3). Returns `false` when no native pane currently maps to
287 /// the id (session ended, layout mid-rebuild) or the owning tab is gone;
288 /// the caller logs and no-ops.
289 pub(crate) fn focus_agent_roster_pane(&mut self, tmux_pane_id: u64) -> bool {
290 let Some(&native_pane_id) = self.tmux_state.tmux_pane_to_native_pane.get(&tmux_pane_id)
291 else {
292 return false;
293 };
294 let owning_tab_index = self.tab_manager.tabs().iter().position(|tab| {
295 tab.pane_manager()
296 .is_some_and(|pm| pm.get_pane(native_pane_id).is_some())
297 });
298 let Some(tab_index) = owning_tab_index else {
299 return false;
300 };
301 self.switch_to_tab_index(tab_index);
302 if let Some(tab) = self.tab_manager.active_tab_mut()
303 && let Some(pm) = tab.pane_manager_mut()
304 {
305 pm.focus_pane(native_pane_id);
306 }
307 // Sync the tmux/mux side so input routes to the newly focused pane.
308 self.set_tmux_focused_pane_from_native(native_pane_id);
309 self.set_scroll_target(0);
310 self.focus_state.needs_redraw = true;
311 self.request_redraw();
312 true
313 }
314
315 // =========================================================================
316 // Gateway Mode Input Routing
317 // =========================================================================
318
319 /// Write a command to the gateway tab's terminal.
320 ///
321 /// The gateway tab is where the tmux control mode connection lives.
322 /// All tmux commands must be written to this tab, not the active tab.
323 pub(crate) fn write_to_gateway(&self, cmd: &str) -> bool {
324 let gateway_tab_id = match self.tmux_state.tmux_gateway_tab_id {
325 Some(id) => id,
326 None => {
327 crate::debug_trace!("TMUX", "No gateway tab ID set");
328 return false;
329 }
330 };
331
332 // try_lock: intentional — write_to_gateway is called from the sync event loop and
333 // from input handlers. Blocking would stall the GUI or create deadlock risk.
334 // On miss: the tmux command is silently dropped. For input this means a keypress
335 // is lost; for control commands (resize, split) the caller should retry as needed.
336 if let Some(tab) = self.tab_manager.get_tab(gateway_tab_id)
337 && tab.tmux.tmux_gateway_active
338 && let Ok(term) = tab.terminal.try_read()
339 {
340 match term.write(cmd.as_bytes()) {
341 Ok(()) => return true,
342 Err(e) => {
343 crate::debug_error!("TMUX", "PTY write failed (gateway command): {e}");
344 return false;
345 }
346 }
347 }
348
349 crate::debug_trace!("TMUX", "Failed to write to gateway tab");
350 false
351 }
352
353 /// Split the current pane via tmux control mode.
354 ///
355 /// Writes split-window command to the gateway PTY.
356 ///
357 /// # Arguments
358 /// * `vertical` - true for vertical split (side by side), false for horizontal (stacked)
359 ///
360 /// Returns true if the command was sent successfully.
361 pub fn split_pane_via_tmux(&self, vertical: bool) -> bool {
362 if !self.config.load().tmux.tmux_enabled || !self.is_tmux_connected() {
363 return false;
364 }
365
366 let session = match &self.tmux_state.tmux_session {
367 Some(s) => s,
368 None => return false,
369 };
370
371 // Get the focused pane ID
372 let pane_id = session.focused_pane();
373
374 // Format the split command
375 let cmd = if vertical {
376 match pane_id {
377 Some(id) => format!("split-window -h -t %{}\n", id),
378 None => "split-window -h\n".to_string(),
379 }
380 } else {
381 match pane_id {
382 Some(id) => format!("split-window -v -t %{}\n", id),
383 None => "split-window -v\n".to_string(),
384 }
385 };
386
387 // Write to gateway tab
388 if self.write_to_gateway(&cmd) {
389 crate::debug_info!(
390 "TMUX",
391 "Sent {} split command via gateway",
392 if vertical { "vertical" } else { "horizontal" }
393 );
394 return true;
395 }
396
397 false
398 }
399
400 /// Close the focused pane via tmux control mode.
401 ///
402 /// Writes kill-pane command to the gateway PTY.
403 ///
404 /// Returns true if the command was sent successfully.
405 pub fn close_pane_via_tmux(&self) -> bool {
406 if !self.config.load().tmux.tmux_enabled || !self.is_tmux_connected() {
407 return false;
408 }
409
410 let session = match &self.tmux_state.tmux_session {
411 Some(s) => s,
412 None => return false,
413 };
414
415 // Get the focused pane ID
416 let pane_id = match session.focused_pane() {
417 Some(id) => id,
418 None => {
419 crate::debug_info!("TMUX", "No focused pane to close");
420 return false;
421 }
422 };
423
424 let cmd = format!("kill-pane -t %{}\n", pane_id);
425
426 // Write to gateway tab
427 if self.write_to_gateway(&cmd) {
428 crate::debug_info!("TMUX", "Sent kill-pane command for pane %{}", pane_id);
429 return true;
430 }
431
432 false
433 }
434
435 /// Sync clipboard content to tmux paste buffer.
436 ///
437 /// Writes set-buffer command to the gateway PTY.
438 ///
439 /// Returns true if the command was sent successfully.
440 pub fn sync_clipboard_to_tmux(&self, content: &str) -> bool {
441 // Check if clipboard sync is enabled
442 if !self.config.load().tmux.tmux_clipboard_sync {
443 return false;
444 }
445
446 if !self.config.load().tmux.tmux_enabled || !self.is_tmux_connected() {
447 return false;
448 }
449
450 // Don't sync empty content
451 if content.is_empty() {
452 return false;
453 }
454
455 // Format the set-buffer command
456 let escaped = content.replace('\'', "'\\''");
457 let cmd = format!("set-buffer '{}'\n", escaped);
458
459 // Write to gateway tab
460 if self.write_to_gateway(&cmd) {
461 crate::debug_trace!(
462 "TMUX",
463 "Synced {} chars to tmux paste buffer",
464 content.len()
465 );
466 return true;
467 }
468
469 false
470 }
471
472 // =========================================================================
473 // Pane Resize Sync
474 // =========================================================================
475
476 /// Sync pane resize to tmux after a divider drag.
477 ///
478 /// When the user resizes panes by dragging a divider in par-term, this
479 /// sends the new pane sizes to tmux so external clients see the same layout.
480 ///
481 /// # Arguments
482 /// * `is_horizontal_divider` - true if dragging a horizontal divider (changes heights),
483 /// false if dragging a vertical divider (changes widths)
484 pub fn sync_pane_resize_to_tmux(&self, is_horizontal_divider: bool) {
485 // par-mux transport: the same absolute resize-pane form, sent
486 // through the daemon client. Without it a divider drag resized only
487 // the native panes — the daemon PTYs kept their old size and never
488 // sent SIGWINCH, so htop and friends never reflowed.
489 #[cfg(feature = "mux")]
490 let mux_transport = self.tmux_state.transport.as_ref();
491 #[cfg(not(feature = "mux"))]
492 let mux_transport: Option<&Box<dyn super::tmux_state::TmuxTransport>> = None;
493
494 // Only sync if tmux gateway is active (or a mux transport is)
495 if !self.is_gateway_active() && mux_transport.is_none() {
496 return;
497 }
498
499 // Get cell dimensions from renderer
500 let (cell_width, cell_height) = match &self.renderer {
501 Some(r) => (r.cell_width(), r.cell_height()),
502 None => return,
503 };
504
505 // Get pane sizes from active tab's pane manager
506 let pane_sizes: Vec<(crate::tmux::TmuxPaneId, usize, usize)> = if let Some(tab) =
507 self.tab_manager.active_tab()
508 && let Some(pm) = tab.pane_manager()
509 {
510 pm.all_panes()
511 .iter()
512 .filter_map(|pane| {
513 // Get the tmux pane ID for this native pane
514 let tmux_pane_id = self.tmux_state.native_pane_to_tmux_pane.get(&pane.id)?;
515 // Calculate size in columns/rows
516 let cols = (pane.bounds.width / cell_width).floor() as usize;
517 let rows = (pane.bounds.height / cell_height).floor() as usize;
518 Some((*tmux_pane_id, cols.max(1), rows.max(1)))
519 })
520 .collect()
521 } else {
522 return;
523 };
524
525 // Send resize commands for each pane, but only for the dimension that changed
526 // Horizontal divider: changes height (rows) - use -y
527 // Vertical divider: changes width (cols) - use -x
528 for (tmux_pane_id, cols, rows) in pane_sizes {
529 let cmd = if is_horizontal_divider {
530 format!("resize-pane -t %{} -y {}\n", tmux_pane_id, rows)
531 } else {
532 format!("resize-pane -t %{} -x {}\n", tmux_pane_id, cols)
533 };
534 let sent = match mux_transport {
535 Some(transport) => match transport.send_command(cmd.trim_end()) {
536 Ok(_) => true,
537 Err(e) => {
538 crate::debug_error!("MUX", "resize-pane failed: {e}");
539 false
540 }
541 },
542 None => self.write_to_gateway(&cmd),
543 };
544 if sent {
545 crate::debug_info!(
546 "TMUX",
547 "Synced pane %{} {} resize to {}",
548 tmux_pane_id,
549 if is_horizontal_divider {
550 "height"
551 } else {
552 "width"
553 },
554 if is_horizontal_divider { rows } else { cols }
555 );
556 }
557 }
558 }
559
560 // =========================================================================
561 // Gateway Tab Visibility
562 // =========================================================================
563
564 /// Hide the gateway tab from the tab bar once tmux windows are active.
565 ///
566 /// Called after the first tmux window tab is created so the control-mode
567 /// connection tab no longer clutters the tab bar. The tab still exists and
568 /// all PTY I/O continues to flow through it; it is simply excluded from the
569 /// visible tab list. The tab is restored when the session ends.
570 ///
571 /// No-op when `config.tmux_hide_gateway_tab` is false.
572 pub(crate) fn hide_gateway_tab(&mut self) {
573 if !self.config.load().tmux.tmux_hide_gateway_tab {
574 return;
575 }
576 if let Some(gateway_tab_id) = self.tmux_state.tmux_gateway_tab_id
577 && let Some(tab) = self.tab_manager.get_tab_mut(gateway_tab_id)
578 && !tab.is_hidden
579 {
580 tab.is_hidden = true;
581 crate::debug_info!(
582 "TMUX",
583 "Gateway tab {} hidden (tmux windows active)",
584 gateway_tab_id
585 );
586 }
587 }
588
589 /// Restore the gateway tab to the tab bar when no tmux windows are active.
590 pub(crate) fn show_gateway_tab(&mut self) {
591 if let Some(gateway_tab_id) = self.tmux_state.tmux_gateway_tab_id
592 && let Some(tab) = self.tab_manager.get_tab_mut(gateway_tab_id)
593 && tab.is_hidden
594 {
595 tab.is_hidden = false;
596 crate::debug_info!("TMUX", "Gateway tab {} restored to tab bar", gateway_tab_id);
597 }
598 }
599
600 // =========================================================================
601 // Prefix Key Handling
602 // =========================================================================
603}