par-term 0.48.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! Tab lifecycle operations: create, close, navigate.
//!
//! Reopen (session undo) and tab-bar resize helpers live in `tab_reopen`.

use std::sync::Arc;

use super::super::window_state::WindowState;
use super::{ClosedTabInfo, HiddenMuxTab};
use crate::tmux::TmuxWindowId;
use par_term_config::TabId;

impl WindowState {
    /// Create a new tab, or open Open Profiles… (UX.md PR1, MD2) when
    /// `new_tab_shortcut_shows_profiles` is set and profiles exist.
    pub fn new_tab_or_show_profiles(&mut self) {
        if self.config.load().tabs.new_tab_shortcut_shows_profiles
            && !self.overlay_ui.profile_manager.is_empty()
        {
            self.open_profile_launcher();
            log::info!("Opened the profile launcher via the new-tab shortcut");
        } else {
            self.new_tab();
            log::info!("New tab created");
        }
    }

    /// The daemon window `tab_id` mirrors, when a mux transport is
    /// attached. `None` for local tabs and for every tab while no transport
    /// is installed (the tmux gateway keeps its own separate state).
    pub(crate) fn mux_window_for_tab(&self, tab_id: TabId) -> Option<TmuxWindowId> {
        self.tmux_state.transport.as_ref()?;
        self.tmux_state.tmux_sync.get_window(tab_id)
    }

    /// Whether closing the ACTIVE tab would end the attached par-mux
    /// session (UX.md M1): the tab mirrors a daemon window and no other
    /// tab maps to one, so the `kill-window` the close sends would empty
    /// the session and the daemon deletes it. The count is client-side:
    /// hidden mux tabs count (their windows survive through them), and a
    /// daemon window dropped by `max_tabs` overflow (UX.md M14) can only
    /// make this a false positive — an extra dialog, never a silent kill.
    pub(crate) fn closing_active_tab_ends_mux_session(&self) -> bool {
        let Some(tab_id) = self.tab_manager.active_tab_id() else {
            return false;
        };
        if self.mux_window_for_tab(tab_id).is_none() {
            return false;
        }
        !self
            .tab_manager
            .tabs()
            .iter()
            .any(|t| t.id != tab_id && self.mux_window_for_tab(t.id).is_some())
    }

    /// Create a new tab
    pub fn new_tab(&mut self) {
        // Check max tabs limit
        if self.config.load().tabs.max_tabs > 0
            && self.tab_manager.tab_count() >= self.config.load().tabs.max_tabs
        {
            log::warn!(
                "Cannot create new tab: max_tabs limit ({}) reached",
                self.config.load().tabs.max_tabs
            );
            return;
        }

        // While attached to a par-mux session, a new tab IS a daemon window
        // (the tmux -CC model): ask the daemon, and its %window-add
        // notification creates the display tab through the same path as
        // every other daemon window. No local shell tab is created — the
        // session outlives this client, so a local tab would be a window
        // the daemon cannot see or manage.
        let sent = self
            .tmux_state
            .transport
            .as_ref()
            .map(|t| t.send_command("new-window"));
        if let Some(result) = sent {
            match result {
                Ok(_) => {
                    log::info!("MUX: new-window sent; tab arrives via %window-add");
                }
                Err(e) => {
                    log::error!("MUX: new-window failed: {e}");
                    self.record_mux_error(format!("par-mux: new-window failed — {e}"));
                }
            }
            self.request_redraw();
            return;
        }

        // Remember tab count before creating new tab to detect tab bar visibility change
        let old_tab_count = self.tab_manager.tab_count();

        // Capture BEFORE creation — tab_manager switches active to the new tab inside new_tab()
        let prior_active_idx = self.tab_manager.active_tab_index();

        // Get current grid size from renderer to pass to new tab
        // This accounts for possible tab bar height changes
        let grid_size = self.renderer.as_ref().map(|r| r.grid_size());

        match self.tab_manager.new_tab(
            &self.config.load(),
            Arc::clone(&self.runtime),
            self.config.load().tabs.tab_inherit_cwd,
            grid_size,
        ) {
            Ok(tab_id) => {
                // Reposition new tab if configured
                if self.config.load().tabs.new_tab_position
                    == crate::config::NewTabPosition::AfterActive
                    && let Some(idx) = prior_active_idx
                {
                    self.tab_manager.move_tab_to_index(tab_id, idx + 1);
                }

                // Check if tab bar visibility changed (e.g., from 1 to 2 tabs with WhenMultiple mode)
                let new_tab_count = self.tab_manager.tab_count();
                let old_tab_bar_height = self
                    .tab_bar_ui
                    .get_height(old_tab_count, &self.config.load());
                let new_tab_bar_height = self
                    .tab_bar_ui
                    .get_height(new_tab_count, &self.config.load());
                let old_tab_bar_width = self
                    .tab_bar_ui
                    .get_width(old_tab_count, &self.config.load());
                let new_tab_bar_width = self
                    .tab_bar_ui
                    .get_width(new_tab_count, &self.config.load());

                // If tab bar dimensions changed, update content offsets and resize ALL existing tabs
                if ((new_tab_bar_height - old_tab_bar_height).abs() > 0.1
                    || (new_tab_bar_width - old_tab_bar_width).abs() > 0.1)
                    && let Some(renderer) = &mut self.renderer
                    && let Some((new_cols, new_rows)) = Self::apply_tab_bar_offsets_for_position(
                        self.config.load().tabs.tab_bar_position,
                        renderer,
                        new_tab_bar_height,
                        new_tab_bar_width,
                    )
                {
                    let cell_width = renderer.cell_width();
                    let cell_height = renderer.cell_height();
                    let width_px = (new_cols as f32 * cell_width) as usize;
                    let height_px = (new_rows as f32 * cell_height) as usize;

                    // Resize all EXISTING tabs (not including the new one yet)
                    for tab in self.tab_manager.tabs_mut() {
                        if tab.id != tab_id {
                            // try_lock: intentional — resize during new-tab creation in sync
                            // event loop. On miss: this tab keeps old dimensions; corrected
                            // on the next Resized event.
                            if let Ok(mut term) = tab.terminal.try_write() {
                                term.set_cell_dimensions(cell_width as u32, cell_height as u32);
                                if let Err(e) =
                                    term.resize_with_pixels(new_cols, new_rows, width_px, height_px)
                                {
                                    crate::debug_error!(
                                        "TERMINAL",
                                        "resize_with_pixels failed (new_tab): {e}"
                                    );
                                }
                            }
                            tab.active_cache_mut().cells = None;
                        }
                    }
                    log::info!(
                        "Tab bar appeared (position={:?}), resized existing tabs to {}x{}",
                        self.config.load().tabs.tab_bar_position,
                        new_cols,
                        new_rows
                    );
                }

                // Start refresh task for the new tab and resize to match window
                if let Some(window) = &self.window
                    && let Some(tab) = self.tab_manager.get_tab_mut(tab_id)
                {
                    tab.start_refresh_task(
                        Arc::clone(&self.runtime),
                        Arc::clone(window),
                        self.config.load().rendering.max_fps,
                        self.config.load().power.inactive_tab_fps,
                    );

                    // Resize terminal to match current renderer dimensions
                    // (which now has the correct content offset)
                    // try_lock: intentional — new-tab initialization in sync event loop.
                    // On miss: the new tab starts with default PTY dimensions; corrected
                    // on the next Resized event.
                    if let Some(renderer) = &self.renderer
                        && let Ok(mut term) = tab.terminal.try_write()
                    {
                        let (cols, rows) = renderer.grid_size();
                        let cell_width = renderer.cell_width();
                        let cell_height = renderer.cell_height();
                        let width_px = (cols as f32 * cell_width) as usize;
                        let height_px = (rows as f32 * cell_height) as usize;

                        // Set cell dimensions
                        term.set_cell_dimensions(cell_width as u32, cell_height as u32);

                        // Resize terminal to match window size
                        if let Err(e) = term.resize_with_pixels(cols, rows, width_px, height_px) {
                            crate::debug_error!(
                                "TERMINAL",
                                "resize_with_pixels failed (new_tab_init): {e}"
                            );
                        }
                        log::info!(
                            "Resized new tab {} terminal to {}x{} ({}x{} px)",
                            tab_id,
                            cols,
                            rows,
                            width_px,
                            height_px
                        );
                    }
                }

                // Play new tab alert sound if configured
                self.play_alert_sound(crate::config::AlertEvent::NewTab);

                self.focus_state.needs_redraw = true;
                self.request_redraw();
            }
            Err(e) => {
                log::error!("Failed to create new tab: {}", e);
            }
        }
    }

    /// Close the current tab
    /// Returns true if the window should close (last tab was closed)
    pub fn close_current_tab(&mut self) -> bool {
        log::info!(
            "[CLOSE_TAB] close_current_tab called, confirm_close_running_jobs={}",
            self.config.load().shell.confirm_close_running_jobs
        );

        if self.confirm_current_tab_close() {
            return false; // Don't close yet, waiting for confirmation
        }

        log::info!(
            "[CLOSE_TAB] No running job detected or confirmation disabled, closing immediately"
        );

        self.close_current_tab_confirmed()
    }

    /// Close the current tab after the running-job dialog was confirmed (or
    /// found nothing to confirm). An attached tab still takes the last-tab
    /// gate: confirming a job's end is not choosing to end the session.
    /// Returns true if the window should close (last tab was closed).
    pub(crate) fn close_current_tab_confirmed(&mut self) -> bool {
        // UX.md M1: closing the LAST attached tab would end the whole
        // session — kill-window on the session's only window empties it
        // and the daemon deletes the session. Detach / End session /
        // Cancel is the user's call, not the close key's.
        if self.closing_active_tab_ends_mux_session() {
            self.show_mux_last_tab_dialog();
            return false; // the dialog decides
        }

        self.close_current_tab_immediately()
    }

    /// Open the last-attached-tab dialog (UX.md M1): Detach / End session
    /// / Cancel for the attached session.
    fn show_mux_last_tab_dialog(&mut self) {
        let session = self
            .tmux_state
            .tmux_session_name
            .clone()
            .unwrap_or_else(|| "session".to_string());
        self.overlay_ui.mux_last_tab_ui.show_for_session(&session);
        self.focus_state.needs_redraw = true;
        self.request_redraw();
    }

    /// Close the current tab immediately without confirmation
    /// Returns true if the window should close (last tab was closed)
    pub fn close_current_tab_immediately(&mut self) -> bool {
        self.close_current_tab_inner(true)
    }

    /// The last-pane close of a mux tab (D7, UX.md M4): the tab becomes
    /// HIDDEN — the same mechanism the tmux gateway tab uses — and the
    /// daemon window KEEPS RUNNING. The window↔tab mapping stays live, so
    /// daemon layout pushes keep landing and roster rows keep working;
    /// Cmd+Z (typed undo entry) and roster selection re-show the tab.
    /// A TAB close (the public method above) kills the daemon window
    /// instead.
    ///
    /// Returns true (close the window) only when no other tab could stay
    /// visible — the implicit-detach shape; the session survives daemon-side.
    ///
    /// A tab whose every daemon pane is HELD (exited, `%pane-exited`) is
    /// not hidden: a window of dead panes kept running is a leak nobody can
    /// see. It ends like a tab close — `kill-window` — unless it is the
    /// session's last window, where the close key must not end the session
    /// (an all-exited session is kept and restored as fresh shells), so
    /// the last-tab dialog (UX.md M1) decides instead.
    #[cfg_attr(not(feature = "mux"), allow(dead_code))]
    pub(crate) fn hide_active_mux_tab(&mut self) -> bool {
        let Some(tab_id) = self.tab_manager.active_tab_id() else {
            return true; // no tabs at all: the window closes
        };
        let Some(window_id) = self.mux_window_for_tab(tab_id) else {
            // Not a mapped mux tab (transport gone mid-close): the daemon
            // window is unreachable from this client either way.
            return self.close_current_tab_inner(false);
        };
        if self.tmux_state.all_tab_panes_held(tab_id) {
            if self.closing_active_tab_ends_mux_session() {
                self.show_mux_last_tab_dialog();
                return false; // the dialog decides
            }
            return self.close_current_tab_inner(true);
        }
        // The tab that stays visible and active: prefer an already-visible
        // sibling, else re-show a hidden one — a window with zero visible
        // tabs has no surface to render.
        let successor = self
            .tab_manager
            .tabs()
            .iter()
            .filter(|t| t.id != tab_id)
            .find(|t| !t.is_hidden)
            .or_else(|| {
                self.tab_manager
                    .tabs()
                    .iter()
                    .rev()
                    .find(|t| t.id != tab_id)
            })
            .map(|t| t.id);
        let Some(successor_id) = successor else {
            // Literally no other tab: closing the window is the detach
            // shape — the session survives daemon-side.
            return self.close_current_tab_inner(false);
        };

        if let Some(tab) = self.tab_manager.get_tab_mut(tab_id) {
            tab.is_hidden = true;
        }

        // Session-undo capture: a TYPED re-show entry — the tab is hidden,
        // not closed, so Cmd+Z re-shows it instead of restoring anything
        // (and consumes the entry rather than popping an older, unrelated
        // one — the M3 trap).
        if self.config.load().session_restore.session_undo_timeout_secs > 0 {
            let (title, has_default_title) = self
                .tab_manager
                .get_tab(tab_id)
                .map(|tab| (tab.title.clone(), tab.has_default_title))
                .unwrap_or_default();
            let info = ClosedTabInfo {
                cwd: None,
                title,
                has_default_title,
                index: self.tab_manager.active_tab_index().unwrap_or(0),
                closed_at: std::time::Instant::now(),
                pane_layout: None,
                custom_color: None,
                user_named: false,
                custom_icon: None,
                hidden_tab: None,
                ended_mux_window: None,
                hidden_mux_window: Some(HiddenMuxTab { tab_id, window_id }),
            };
            self.overlay_state.closed_tabs.push_front(info);
            while self.overlay_state.closed_tabs.len()
                > self.config.load().session_restore.session_undo_max_entries
            {
                self.overlay_state.closed_tabs.pop_back();
            }
        }

        if let Some(tab) = self.tab_manager.get_tab_mut(successor_id) {
            tab.is_hidden = false;
        }
        self.tab_manager.switch_to(successor_id);

        self.play_alert_sound(crate::config::AlertEvent::TabClose);
        self.post_reopen_toast(
            &format!("par-mux: tab hidden — window @{window_id} keeps running"),
            "Re-show",
        );
        self.focus_state.needs_redraw = true;
        self.request_redraw();
        false
    }

    /// The shared close body. `kill_mux_window` decides a mux tab's
    /// daemon-window fate: `true` for tab closes (kill-window — the
    /// tmux -CC semantic, no stale mappings), `false` for the last-pane
    /// close's recorded keep-the-window decision.
    fn close_current_tab_inner(&mut self, kill_mux_window: bool) -> bool {
        if let Some(tab_id) = self.tab_manager.active_tab_id() {
            // If the tab being closed is the tmux gateway, send detach-client first so
            // that tmux can cleanly detach rather than treating the disconnect as a crash
            // (which may destroy the session if destroy-unattached is enabled).
            let is_tmux_gateway = self.config.load().tmux.tmux_enabled
                && self.tmux_state.tmux_gateway_tab_id == Some(tab_id)
                && self.is_gateway_active();
            if is_tmux_gateway {
                self.write_to_gateway("detach-client\n");
                self.disconnect_tmux_session();
            }

            // A mux tab mirrors a daemon window: closing it kills that
            // window daemon-side, and the %window-close notification runs
            // the tab teardown (close_tab_fast + unmap) — the same path as
            // a shell exiting in the daemon pane. Killing (rather than
            // detaching one window) matches tmux semantics and leaves no
            // stale mappings behind; the SESSION survives via detach.
            if kill_mux_window && let Some(window_id) = self.mux_window_for_tab(tab_id) {
                let killed = self
                    .tmux_state
                    .transport
                    .as_ref()
                    .map(|t| t.send_command(&format!("kill-window -t @{window_id}")));
                if matches!(&killed, Some(Ok(_))) {
                    log::info!("MUX: kill-window @{} sent for tab {tab_id}", window_id);
                    // Session-undo capture is a TYPED entry, not a
                    // restorable one: a killed daemon window cannot be
                    // rebuilt from local metadata, but the entry must
                    // still sit on the undo stack so the next Cmd+Z
                    // consumes it and says so instead of silently
                    // restoring an older, unrelated tab (UX.md M3).
                    if self.config.load().session_restore.session_undo_timeout_secs > 0 {
                        let (title, has_default_title) = self
                            .tab_manager
                            .get_tab(tab_id)
                            .map(|tab| (tab.title.clone(), tab.has_default_title))
                            .unwrap_or_default();
                        let info = ClosedTabInfo {
                            cwd: None,
                            title,
                            has_default_title,
                            index: self.tab_manager.active_tab_index().unwrap_or(0),
                            closed_at: std::time::Instant::now(),
                            pane_layout: None,
                            custom_color: None,
                            user_named: false,
                            custom_icon: None,
                            hidden_tab: None,
                            ended_mux_window: Some(window_id),
                            hidden_mux_window: None,
                        };
                        self.overlay_state.closed_tabs.push_front(info);
                    }
                    return false; // the tab closes when %window-close lands
                }
                if let Some(Err(e)) = &killed {
                    log::error!("MUX: kill-window @{window_id} failed: {e}");
                    self.record_mux_error(format!("par-mux: kill-window failed — {e}"));
                    // Fall through to the local close: the daemon
                    // window is unreachable from this client either way.
                }
            }

            // Track whether this is a tmux display tab (non-gateway tab that shows tmux window
            // content) so we can restore the hidden gateway tab after it is closed.
            let is_tmux_display_tab = self.config.load().tmux.tmux_enabled
                && self.tmux_state.tmux_gateway_tab_id.is_some()
                && self.tmux_state.tmux_gateway_tab_id != Some(tab_id)
                && self.is_gateway_active();

            // Remember tab count before closing to detect tab bar visibility change
            let old_tab_count = self.tab_manager.tab_count();
            let old_tab_bar_height = self
                .tab_bar_ui
                .get_height(old_tab_count, &self.config.load());
            let old_tab_bar_width = self
                .tab_bar_ui
                .get_width(old_tab_count, &self.config.load());

            let is_last_tab = self.tab_manager.tab_count() <= 1;
            let preserve_shell = self
                .config
                .load()
                .session_restore
                .session_undo_preserve_shell
                && self.config.load().session_restore.session_undo_timeout_secs > 0;

            // Capture closed tab metadata for session undo (before destroying the tab)
            let is_last = if preserve_shell {
                // Preserve mode: extract the live Tab and store it in ClosedTabInfo
                if let Some(tab) = self.tab_manager.get_tab(tab_id) {
                    let cwd = tab.get_cwd();
                    let title = tab.title.clone();
                    let has_default_title = tab.has_default_title;
                    let custom_color = tab.custom_color;
                    let user_named = tab.user_named;
                    let custom_icon = tab.custom_icon.clone();
                    let index = self.tab_manager.active_tab_index().unwrap_or(0);

                    if let Some((mut hidden_tab, is_empty)) = self.tab_manager.remove_tab(tab_id) {
                        // Stop refresh task to prevent invisible redraws
                        hidden_tab.stop_refresh_task();

                        let info = ClosedTabInfo {
                            cwd,
                            title,
                            has_default_title,
                            index,
                            closed_at: std::time::Instant::now(),
                            pane_layout: None, // Preserved inside the hidden Tab itself
                            custom_color,
                            user_named,
                            custom_icon,
                            hidden_tab: Some(hidden_tab),
                            ended_mux_window: None,
                            hidden_mux_window: None,
                        };
                        self.overlay_state.closed_tabs.push_front(info);
                        while self.overlay_state.closed_tabs.len()
                            > self.config.load().session_restore.session_undo_max_entries
                        {
                            self.overlay_state.closed_tabs.pop_back();
                        }
                        is_empty
                    } else {
                        // Fallback: tab disappeared between get and remove
                        self.tab_manager.close_tab(tab_id)
                    }
                } else {
                    self.tab_manager.close_tab(tab_id)
                }
            } else {
                // Standard mode: capture metadata, then close (drops the Tab)
                if self.config.load().session_restore.session_undo_timeout_secs > 0
                    && let Some(tab) = self.tab_manager.get_tab(tab_id)
                {
                    let info = ClosedTabInfo {
                        cwd: tab.get_cwd(),
                        title: tab.title.clone(),
                        has_default_title: tab.has_default_title,
                        index: self.tab_manager.active_tab_index().unwrap_or(0),
                        closed_at: std::time::Instant::now(),
                        pane_layout: tab
                            .pane_manager
                            .as_ref()
                            .and_then(|pm| pm.root())
                            .map(crate::session::capture::capture_pane_node),
                        custom_color: tab.custom_color,
                        user_named: tab.user_named,
                        custom_icon: tab.custom_icon.clone(),
                        hidden_tab: None,
                        ended_mux_window: None,
                        hidden_mux_window: None,
                    };
                    self.overlay_state.closed_tabs.push_front(info);
                    while self.overlay_state.closed_tabs.len()
                        > self.config.load().session_restore.session_undo_max_entries
                    {
                        self.overlay_state.closed_tabs.pop_back();
                    }
                }

                self.tab_manager.close_tab(tab_id)
            };

            // After closing a tmux display tab, check if the hidden gateway tab needs to
            // be restored.  This happens when the user manually closes all display tabs
            // while still connected — the gateway tab was hidden but is the only one left.
            if is_tmux_display_tab && self.is_gateway_active() {
                let gateway_tab_id = self.tmux_state.tmux_gateway_tab_id;
                let has_other_visible = self
                    .tab_manager
                    .tabs()
                    .iter()
                    .any(|t| !t.is_hidden && Some(t.id) != gateway_tab_id);
                if !has_other_visible {
                    self.show_gateway_tab();
                    // Switch focus to the gateway tab so the user can interact with it
                    if let Some(gtid) = gateway_tab_id {
                        self.tab_manager.switch_to(gtid);
                    }
                }
            }

            // Play tab close alert sound if configured
            self.play_alert_sound(crate::config::AlertEvent::TabClose);

            // Undo toast (only if not the last tab — window is closing)
            if !is_last_tab {
                let timeout = self.config.load().session_restore.session_undo_timeout_secs;
                if timeout > 0 {
                    self.post_reopen_toast(&format!("Tab closed — undo within {timeout}s"), "Undo");
                }
            }

            // Check if tab bar visibility changed (e.g., from 2 to 1 tabs with WhenMultiple mode)
            if !is_last {
                let new_tab_count = self.tab_manager.tab_count();
                let new_tab_bar_height = self
                    .tab_bar_ui
                    .get_height(new_tab_count, &self.config.load());
                let new_tab_bar_width = self
                    .tab_bar_ui
                    .get_width(new_tab_count, &self.config.load());

                if ((new_tab_bar_height - old_tab_bar_height).abs() > 0.1
                    || (new_tab_bar_width - old_tab_bar_width).abs() > 0.1)
                    && let Some(renderer) = &mut self.renderer
                    && let Some((new_cols, new_rows)) = Self::apply_tab_bar_offsets_for_position(
                        self.config.load().tabs.tab_bar_position,
                        renderer,
                        new_tab_bar_height,
                        new_tab_bar_width,
                    )
                {
                    let cell_width = renderer.cell_width();
                    let cell_height = renderer.cell_height();
                    let width_px = (new_cols as f32 * cell_width) as usize;
                    let height_px = (new_rows as f32 * cell_height) as usize;

                    // Resize all remaining tabs
                    for tab in self.tab_manager.tabs_mut() {
                        // try_lock: intentional — tab close resize in sync event loop.
                        // On miss: tab keeps old dimensions; fixed on the next Resized event.
                        if let Ok(mut term) = tab.terminal.try_write() {
                            term.set_cell_dimensions(cell_width as u32, cell_height as u32);
                            if let Err(e) =
                                term.resize_with_pixels(new_cols, new_rows, width_px, height_px)
                            {
                                crate::debug_error!(
                                    "TERMINAL",
                                    "resize_with_pixels failed (close_tab): {e}"
                                );
                            }
                        }
                        tab.active_cache_mut().cells = None;
                    }
                    log::info!(
                        "Tab bar visibility changed (position={:?}), resized remaining tabs to {}x{}",
                        self.config.load().tabs.tab_bar_position,
                        new_cols,
                        new_rows
                    );
                }
            }

            self.focus_state.needs_redraw = true;
            self.request_redraw();
            is_last
        } else {
            true // No tabs, window should close
        }
    }

    /// Switch to next tab
    pub fn next_tab(&mut self) {
        self.copy_mode.exit();
        self.tab_manager.next_tab();
        self.clear_and_invalidate();
        self.after_user_tab_switch();
    }

    /// Switch to previous tab
    pub fn prev_tab(&mut self) {
        self.copy_mode.exit();
        self.tab_manager.prev_tab();
        self.clear_and_invalidate();
        self.after_user_tab_switch();
    }

    /// Switch to tab by index (1-based)
    pub fn switch_to_tab_index(&mut self, index: usize) {
        self.copy_mode.exit();
        self.tab_manager.switch_to_index(index);
        self.clear_and_invalidate();
        self.after_user_tab_switch();
    }

    /// Move current tab left
    pub fn move_tab_left(&mut self) {
        self.tab_manager.move_active_tab_left();
        if let Some(id) = self.tab_manager.active_tab_id() {
            self.sync_mux_tab_order(id);
        }
        self.focus_state.needs_redraw = true;
        self.request_redraw();
    }

    /// Move current tab right
    pub fn move_tab_right(&mut self) {
        self.tab_manager.move_active_tab_right();
        if let Some(id) = self.tab_manager.active_tab_id() {
            self.sync_mux_tab_order(id);
        }
        self.focus_state.needs_redraw = true;
        self.request_redraw();
    }

    /// UX.md U11: a reordered par-mux tab moves its daemon window to the
    /// same position in the session's window list (`move-window`), so the
    /// order survives reattach and other clients see it. The position is
    /// the tab's index among this window's par-mux tabs, in tab order.
    pub(crate) fn sync_mux_tab_order(&mut self, tab_id: TabId) {
        let Some(window) = self.mux_window_for_tab(tab_id) else {
            return;
        };
        let position = self
            .tab_manager
            .tabs()
            .iter()
            .filter(|t| self.mux_window_for_tab(t.id).is_some())
            .position(|t| t.id == tab_id);
        #[cfg(feature = "mux")]
        if let Some(position) = position {
            self.send_mux_pane_command(
                &format!("move-window -s @{window} -t {position}"),
                "tab reorder",
            );
        }
        #[cfg(not(feature = "mux"))]
        let _ = (window, position);
    }
}