par-term 0.49.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
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
//! Tab profile and title tracking methods.
//!
//! Provides methods for auto-updating tab titles from OSC sequences, tracking
//! hostname/CWD changes for automatic profile switching, and managing the
//! auto-profile lifecycle.

use crate::tab::Tab;
use crate::ui_constants::VISUAL_BELL_FLASH_DURATION_MS;

impl Tab {
    /// Check if the visual bell is currently active (within flash duration)
    pub fn is_bell_active(&self) -> bool {
        // Use active_bell() to route through the focused pane in split-pane mode.
        if let Some(flash_start) = self.active_bell().visual_flash {
            flash_start.elapsed().as_millis() < VISUAL_BELL_FLASH_DURATION_MS
        } else {
            false
        }
    }

    /// Update tab title from terminal OSC sequences or shell integration data.
    ///
    /// Priority when on a **remote** host (hostname detected via OSC 7):
    ///   1. Explicit OSC title (`\033]0;...\007`) if `remote_osc_priority` is true
    ///   2. `remote_format` — formatted from hostname/username/cwd
    ///
    /// Priority when **local**:
    ///   1. Explicit OSC title
    ///   2. Last CWD component (only in `TabTitleMode::Auto`)
    ///
    /// User-named tabs are never auto-updated.
    pub fn update_title(
        &mut self,
        title_mode: par_term_config::TabTitleMode,
        remote_format: par_term_config::RemoteTabTitleFormat,
        remote_osc_priority: bool,
    ) {
        // User-named tabs are static — never auto-update
        if self.user_named {
            return;
        }

        // Step 2 — Snapshot focused pane ID before the mutable borrow.
        // This avoids a Rust borrow-checker conflict: all_panes_mut() takes &mut pane_manager,
        // and we must re-borrow it immutably in Step 4 after the loop ends.
        let focused_id = self
            .pane_manager
            .as_ref()
            .and_then(|pm| pm.focused_pane_id());

        // Cache per-frame values that are constant across all panes (avoid syscall per pane).
        let local_hostname = hostname::get().ok().and_then(|h| h.into_string().ok());
        let home_dir = dirs::home_dir();

        // Step 3 — Iterate all panes and update each one's title from its own terminal.
        // try_read: intentional — called every frame; blocking would stall rendering.
        // On contention: skip that pane this frame, no data loss.
        if let Some(pm) = self.pane_manager.as_mut() {
            for pane in pm.all_panes_mut() {
                // A user-named pane is static, the same rule as a
                // user-named tab: OSC titles and CWD never overwrite it.
                if pane.user_named {
                    continue;
                }
                if let Ok(term) = pane.terminal.try_read() {
                    let osc_title = term.get_title();
                    let hostname = term.shell_integration_hostname();
                    let username = term.shell_integration_username();
                    let cwd = term.shell_integration_cwd();
                    drop(term);

                    let is_remote = if let Some(reported_host) = &hostname {
                        local_hostname
                            .as_ref()
                            .map(|local| !reported_host.eq_ignore_ascii_case(local))
                            .unwrap_or(false)
                    } else {
                        false
                    };

                    if is_remote {
                        if remote_osc_priority && !osc_title.is_empty() {
                            pane.title = osc_title;
                            pane.has_default_title = false;
                        } else {
                            pane.title =
                                format_remote_title(hostname, username, cwd, remote_format);
                            pane.has_default_title = false;
                        }
                    } else if !osc_title.is_empty() {
                        pane.title = osc_title;
                        pane.has_default_title = false;
                    } else if title_mode == par_term_config::TabTitleMode::Auto
                        && let Some(cwd) = cwd
                    {
                        let abbreviated = if let Some(ref home) = home_dir {
                            cwd.replace(&home.to_string_lossy().to_string(), "~")
                        } else {
                            cwd
                        };
                        if let Some(last) = abbreviated.rsplit('/').next() {
                            if !last.is_empty() {
                                pane.title = last.to_string();
                            } else {
                                pane.title = abbreviated;
                            }
                        } else {
                            pane.title = abbreviated;
                        }
                        pane.has_default_title = false;
                    }
                    // else: keep existing pane.title unchanged this frame
                }
            }
        }
        // mutable borrow of pane_manager ends here

        // Step 4 — Derive tab.title from the focused pane (immutable re-borrow is now safe).
        if let Some((focused_id, pm)) = focused_id.zip(self.pane_manager.as_ref())
            && let Some(pane) = pm.get_pane(focused_id)
        {
            self.title = pane.title.clone();
            self.has_default_title = pane.has_default_title;
        }
    }

    /// Set (or clear) a pane's user title (card 01a0d95dd318).
    ///
    /// A non-empty `name` marks the pane user-named — `update_title`'s
    /// per-pane loop then never overwrites it with an OSC title or CWD, the
    /// same guard a user-named tab gets. An empty or blank `name` reverts
    /// the pane to automatic titles. Returns whether the pane exists; the
    /// caller re-derives titles afterwards (an `update_title` pass).
    pub fn rename_pane(&mut self, pane_id: crate::pane::PaneId, name: &str) -> bool {
        let Some(pm) = self.pane_manager.as_mut() else {
            return false;
        };
        let Some(pane) = pm.get_pane_mut(pane_id) else {
            return false;
        };
        let name = name.trim();
        if name.is_empty() {
            // Blank name: revert to automatic titles (RenameTab's blank branch).
            pane.user_named = false;
            pane.has_default_title = true;
            pane.title = String::new();
        } else {
            pane.user_named = true;
            pane.has_default_title = false;
            pane.title = name.to_string();
        }
        true
    }

    /// The user title of this tab's sole pane, for persistence (card
    /// 01a0d95dd318). `None` unless the tab has exactly one pane and that
    /// pane is user-named — multi-pane layouts persist pane titles per-leaf
    /// in the pane tree instead.
    pub fn sole_pane_user_title(&self) -> Option<String> {
        let pm = self.pane_manager.as_ref()?;
        if pm.pane_count() != 1 {
            return None;
        }
        let panes = pm.all_panes();
        let pane = panes.first()?;
        pane.user_named.then(|| pane.title.clone())
    }

    /// Restore a persisted sole-pane user title (session/arrangement
    /// restore). Same field writes as [`Tab::rename_pane`] — a restored
    /// local pane has no daemon side, so nothing is pushed.
    pub fn restore_sole_pane_title(&mut self, title: &str) {
        let Some(pm) = self.pane_manager.as_mut() else {
            return;
        };
        if pm.pane_count() != 1 {
            return;
        }
        let Some(pane_id) = pm.focused_pane_id() else {
            return;
        };
        self.rename_pane(pane_id, title);
    }

    /// Set the tab's default title based on its position
    pub fn set_default_title(&mut self, tab_number: usize) {
        if self.has_default_title {
            let title = format!("Tab {}", tab_number);
            self.title = title.clone();
            // Also write pane.title for every pane that still has a default title so
            // update_title()'s Step 4 derivation from pane.title returns "Tab N" correctly
            // (a brand-new pane has pane.title == "" which would otherwise overwrite).
            if let Some(pm) = self.pane_manager.as_mut() {
                for pane in pm.all_panes_mut() {
                    if pane.has_default_title {
                        pane.title = title.clone();
                    }
                }
            }
        }
    }

    /// Explicitly set the tab title (for tmux window names, etc.)
    ///
    /// This overrides any default title and marks the tab as having a custom title.
    pub fn set_title(&mut self, title: &str) {
        self.title = title.to_string();
        self.has_default_title = false;
        // Sync focused pane so update_title() doesn't overwrite on the next frame.
        if let Some(pane) = self
            .pane_manager
            .as_mut()
            .and_then(|pm| pm.focused_pane_mut())
        {
            pane.title = title.to_string();
            pane.has_default_title = false;
        }
    }

    /// Check if the terminal in this tab is still running
    pub fn is_running(&self) -> bool {
        if let Ok(term) = self.terminal.try_read() {
            term.is_running()
        } else {
            true // Assume running if locked
        }
    }

    /// Get the current working directory of this tab's shell
    pub fn get_cwd(&self) -> Option<String> {
        if let Ok(term) = self.terminal.try_read() {
            term.shell_integration_cwd()
        } else {
            self.working_directory.clone()
        }
    }

    /// Set a custom color for this tab
    pub fn set_custom_color(&mut self, color: [u8; 3]) {
        self.custom_color = Some(color);
    }

    /// Clear the custom color for this tab (reverts to default config colors)
    pub fn clear_custom_color(&mut self) {
        self.custom_color = None;
    }

    /// Check if this tab has a custom color set
    pub fn has_custom_color(&self) -> bool {
        self.custom_color.is_some()
    }

    /// Parse hostname from an OSC 7 file:// URL
    ///
    /// OSC 7 format: `file://hostname/path` or `file:///path` (localhost)
    /// Returns the hostname if present and not localhost, None otherwise.
    pub fn parse_hostname_from_osc7_url(url: &str) -> Option<String> {
        let path = url.strip_prefix("file://")?;

        if path.starts_with('/') {
            // file:///path - localhost implicit
            None
        } else {
            // file://hostname/path - extract hostname
            let hostname = path.split('/').next()?;
            if hostname.is_empty() || hostname == "localhost" {
                None
            } else {
                Some(hostname.to_string())
            }
        }
    }

    /// Check if hostname has changed and update tracking
    ///
    /// Returns Some(hostname) if a new remote hostname was detected,
    /// None if hostname hasn't changed or is local.
    ///
    /// This uses the hostname extracted from OSC 7 sequences by the terminal emulator.
    pub fn check_hostname_change(&mut self) -> Option<String> {
        let current_hostname = if let Ok(term) = self.terminal.try_read() {
            term.shell_integration_hostname()
        } else {
            return None;
        };

        // Check if hostname has changed
        if current_hostname != self.detected_hostname {
            let old_hostname = self.detected_hostname.take();
            self.detected_hostname = current_hostname.clone();

            crate::debug_info!(
                "PROFILE",
                "Hostname changed: {:?} -> {:?}",
                old_hostname,
                current_hostname
            );

            // Return the new hostname if it's a remote host (not None/localhost)
            current_hostname
        } else {
            None
        }
    }

    /// Check if CWD has changed and update tracking
    ///
    /// Returns Some(cwd) if the CWD has changed, None otherwise.
    /// Uses the CWD reported via OSC 7 by the terminal emulator.
    pub fn check_cwd_change(&mut self) -> Option<String> {
        let current_cwd = self.get_cwd();

        if current_cwd != self.detected_cwd {
            let old_cwd = self.detected_cwd.take();
            self.detected_cwd = current_cwd.clone();

            crate::debug_info!("PROFILE", "CWD changed: {:?} -> {:?}", old_cwd, current_cwd);

            current_cwd
        } else {
            None
        }
    }

    /// Clear auto-applied profile tracking
    ///
    /// Call this when manually switching profiles or when the hostname
    /// returns to local, or when disconnecting from tmux.
    pub fn clear_auto_profile(&mut self) {
        if let crate::tab::TitleChange::Set(original) = self.profile.revert_auto() {
            self.set_title(&original);
        }
    }
}

/// Format a tab title for a remote host based on the configured format.
///
/// Uses the remote username to abbreviate the home directory in `HostAndCwd` mode
/// (e.g. `/home/alice/projects` → `~/projects`) rather than the local `$HOME`,
/// which never matches remote paths.
fn format_remote_title(
    hostname: Option<String>,
    username: Option<String>,
    cwd: Option<String>,
    format: par_term_config::RemoteTabTitleFormat,
) -> String {
    use par_term_config::RemoteTabTitleFormat;
    let host = hostname.unwrap_or_default();
    match format {
        RemoteTabTitleFormat::UserAtHost => {
            if let Some(user) = username {
                format!("{}@{}", user, host)
            } else {
                host
            }
        }
        RemoteTabTitleFormat::Host => host,
        RemoteTabTitleFormat::HostAndCwd => {
            if let Some(cwd) = cwd {
                let abbrev = if let Some(ref user) = username {
                    let linux_home = format!("/home/{}", user);
                    let macos_home = format!("/Users/{}", user);
                    let abbrev_with = |home: &str| -> Option<String> {
                        if cwd == home {
                            Some("~".to_string())
                        } else if cwd.starts_with(&format!("{}/", home)) {
                            Some(format!("~{}", &cwd[home.len()..]))
                        } else {
                            None
                        }
                    };
                    if let Some(a) = abbrev_with(&linux_home) {
                        a
                    } else if let Some(a) = abbrev_with(&macos_home) {
                        a
                    } else {
                        cwd
                    }
                } else {
                    cwd
                };
                format!("{}:{}", host, abbrev)
            } else {
                host
            }
        }
    }
}

#[cfg(test)]
mod format_remote_title_tests {
    use super::format_remote_title;
    use par_term_config::RemoteTabTitleFormat;

    #[test]
    fn user_at_host_with_both() {
        let result = format_remote_title(
            Some("server".into()),
            Some("alice".into()),
            None,
            RemoteTabTitleFormat::UserAtHost,
        );
        assert_eq!(result, "alice@server");
    }

    #[test]
    fn user_at_host_no_username_falls_back_to_host() {
        let result = format_remote_title(
            Some("server".into()),
            None,
            None,
            RemoteTabTitleFormat::UserAtHost,
        );
        assert_eq!(result, "server");
    }

    #[test]
    fn host_only() {
        let result = format_remote_title(
            Some("mybox".into()),
            Some("bob".into()),
            Some("/home/bob/projects".into()),
            RemoteTabTitleFormat::Host,
        );
        assert_eq!(result, "mybox");
    }

    #[test]
    fn host_and_cwd_abbreviates_linux_home() {
        let result = format_remote_title(
            Some("server".into()),
            Some("alice".into()),
            Some("/home/alice/projects/foo".into()),
            RemoteTabTitleFormat::HostAndCwd,
        );
        assert_eq!(result, "server:~/projects/foo");
    }

    #[test]
    fn host_and_cwd_abbreviates_macos_home() {
        let result = format_remote_title(
            Some("mac".into()),
            Some("alice".into()),
            Some("/Users/alice/dev".into()),
            RemoteTabTitleFormat::HostAndCwd,
        );
        assert_eq!(result, "mac:~/dev");
    }

    #[test]
    fn host_and_cwd_no_cwd_falls_back_to_host() {
        let result = format_remote_title(
            Some("server".into()),
            Some("alice".into()),
            None,
            RemoteTabTitleFormat::HostAndCwd,
        );
        assert_eq!(result, "server");
    }

    #[test]
    fn host_and_cwd_unknown_path_no_abbreviation() {
        let result = format_remote_title(
            Some("server".into()),
            Some("alice".into()),
            Some("/var/log".into()),
            RemoteTabTitleFormat::HostAndCwd,
        );
        assert_eq!(result, "server:/var/log");
    }

    #[test]
    fn host_and_cwd_does_not_abbreviate_partial_username_match() {
        let result = format_remote_title(
            Some("server".into()),
            Some("alice".into()),
            Some("/home/alice2/projects".into()),
            RemoteTabTitleFormat::HostAndCwd,
        );
        assert_eq!(result, "server:/home/alice2/projects");
    }

    #[test]
    fn host_and_cwd_exact_home_dir_shows_tilde() {
        let result = format_remote_title(
            Some("server".into()),
            Some("alice".into()),
            Some("/home/alice".into()),
            RemoteTabTitleFormat::HostAndCwd,
        );
        assert_eq!(result, "server:~");
    }
}

#[cfg(test)]
mod tests {
    use crate::tab::Tab;

    #[test]
    fn test_parse_hostname_from_osc7_url_localhost() {
        // file:///path - localhost implicit, should return None
        assert_eq!(Tab::parse_hostname_from_osc7_url("file:///home/user"), None);
        assert_eq!(Tab::parse_hostname_from_osc7_url("file:///"), None);
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("file:///var/log/syslog"),
            None
        );
    }

    #[test]
    fn test_parse_hostname_from_osc7_url_remote() {
        // file://hostname/path - should extract hostname
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("file://server.example.com/home/user"),
            Some("server.example.com".to_string())
        );
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("file://myhost/tmp"),
            Some("myhost".to_string())
        );
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("file://192.168.1.100/var/log"),
            Some("192.168.1.100".to_string())
        );
    }

    #[test]
    fn test_parse_hostname_from_osc7_url_localhost_explicit() {
        // file://localhost/path - localhost should return None
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("file://localhost/home/user"),
            None
        );
    }

    #[test]
    fn test_parse_hostname_from_osc7_url_invalid() {
        // Invalid URLs should return None
        assert_eq!(Tab::parse_hostname_from_osc7_url(""), None);
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("http://example.com"),
            None
        );
        assert_eq!(Tab::parse_hostname_from_osc7_url("/home/user"), None);
        assert_eq!(Tab::parse_hostname_from_osc7_url("file://"), None);
    }

    #[test]
    fn test_parse_hostname_from_osc7_url_edge_cases() {
        // Empty hostname after file://
        assert_eq!(Tab::parse_hostname_from_osc7_url("file:///"), None);

        // Hostname with no path (unusual but valid)
        assert_eq!(
            Tab::parse_hostname_from_osc7_url("file://host"),
            Some("host".to_string())
        );
    }
}

#[cfg(test)]
mod pane_rename_tests {
    use crate::tab::Tab;

    /// Card 01a0d95dd318 criterion 2: a user-named pane keeps its name
    /// when the program changes its OSC title (the same skip that keeps a
    /// user-named tab static; the CWD fallback is skipped by the same
    /// guard).
    #[test]
    fn user_named_pane_keeps_its_title_against_osc() {
        let mut tab = Tab::new_stub(1, 1);
        // Feed an OSC 0 title into the stub pane's terminal — the
        // auto-title loop must pick it up while the pane is not
        // user-named.
        {
            let pm = tab.pane_manager.as_mut().expect("pane manager");
            let pane = pm.focused_pane_mut().expect("focused pane");
            if let Ok(term) = pane.terminal.try_read() {
                term.process_data(b"\x1b]0;vim terminal\x07");
            }
        }
        tab.update_title(
            par_term_config::TabTitleMode::Auto,
            par_term_config::RemoteTabTitleFormat::default(),
            false,
        );
        {
            let pm = tab.pane_manager.as_ref().expect("pane manager");
            let pane = pm.focused_pane().expect("focused pane");
            assert_eq!(
                pane.title, "vim terminal",
                "the OSC title applies while the pane is not user-named"
            );
        }

        // User-name it: the same OSC title must not reclaim the pane.
        {
            let pm = tab.pane_manager.as_mut().expect("pane manager");
            let pane = pm.focused_pane_mut().expect("focused pane");
            pane.user_named = true;
            pane.title = "my pane".to_string();
        }
        tab.update_title(
            par_term_config::TabTitleMode::Auto,
            par_term_config::RemoteTabTitleFormat::default(),
            false,
        );
        let pm = tab.pane_manager.as_ref().expect("pane manager");
        let pane = pm.focused_pane().expect("focused pane");
        assert_eq!(pane.title, "my pane", "a user-named pane is static");
        assert!(pane.user_named);
    }

    /// Card 01a0d95dd318 criterion 1: setting a name marks the pane
    /// user-named; a blank name reverts it to automatic titles.
    #[test]
    fn rename_pane_sets_and_clears_the_user_name() {
        let mut tab = Tab::new_stub(1, 1);
        let pane_id = tab
            .pane_manager
            .as_ref()
            .expect("pane manager")
            .focused_pane_id()
            .expect("focused pane");

        assert!(tab.rename_pane(pane_id, "build box"));
        {
            let pane = tab
                .pane_manager
                .as_ref()
                .expect("pane manager")
                .focused_pane()
                .expect("focused pane");
            assert_eq!(pane.title, "build box");
            assert!(pane.user_named);
            assert!(!pane.has_default_title);
        }

        // Blank (whitespace-only) input reverts to automatic titles.
        assert!(tab.rename_pane(pane_id, "   "));
        let pane = tab
            .pane_manager
            .as_ref()
            .expect("pane manager")
            .focused_pane()
            .expect("focused pane");
        assert!(pane.title.is_empty(), "the old name must be dropped now");
        assert!(!pane.user_named);
        assert!(pane.has_default_title);
    }

    /// The name is trimmed before it lands, and an unknown pane id (a pane
    /// closed while the rename popup was open) is reported, not silently
    /// ignored.
    #[test]
    fn rename_pane_trims_and_reports_unknown_panes() {
        let mut tab = Tab::new_stub(1, 1);
        let pane_id = tab
            .pane_manager
            .as_ref()
            .expect("pane manager")
            .focused_pane_id()
            .expect("focused pane");

        assert!(tab.rename_pane(pane_id, "  spaced  "));
        let pane = tab
            .pane_manager
            .as_ref()
            .expect("pane manager")
            .focused_pane()
            .expect("focused pane");
        assert_eq!(pane.title, "spaced", "surrounding whitespace is trimmed");

        assert!(
            !tab.rename_pane(u64::MAX, "nope"),
            "an unmapped pane id must report failure"
        );
    }

    /// Card 01a0d95dd318 criterion 4, local half: the sole pane's user
    /// title round-trips through the persistence helpers (what
    /// TabSnapshot.pane_user_title carries), and an automatic-titled pane
    /// captures as None.
    #[test]
    fn sole_pane_user_title_round_trips_through_the_helpers() {
        let mut tab = Tab::new_stub(1, 1);
        assert_eq!(
            tab.sole_pane_user_title(),
            None,
            "an automatic-titled pane captures as None"
        );

        tab.rename_pane(
            tab.pane_manager
                .as_ref()
                .expect("pane manager")
                .focused_pane_id()
                .expect("focused pane"),
            "build box",
        );
        assert_eq!(tab.sole_pane_user_title(), Some("build box".to_string()));

        // Restore into a fresh tab: the pane comes back user-named.
        let mut restored = Tab::new_stub(1, 1);
        restored.restore_sole_pane_title("build box");
        let pane = restored
            .pane_manager
            .as_ref()
            .expect("pane manager")
            .focused_pane()
            .expect("focused pane");
        assert_eq!(pane.title, "build box");
        assert!(pane.user_named);
    }
}
#[cfg(test)]
mod default_title_tests {
    use crate::tab::Tab;

    /// set_default_title() must write pane.title for default-titled panes
    /// so that update_title()'s Step 4 derivation doesn't produce an empty string.
    #[test]
    fn set_default_title_syncs_pane_title() {
        let mut tab = Tab::new_stub(1, 1);
        // Fresh pane: has default title, pane.title starts as ""
        {
            let pm = tab.pane_manager.as_ref().unwrap();
            let pane = pm.focused_pane().unwrap();
            assert!(pane.has_default_title);
            assert_eq!(pane.title, "");
        }
        tab.set_default_title(3);
        assert_eq!(tab.title, "Tab 3");
        // Pane must also be updated so derivation survives the next frame
        let pm = tab.pane_manager.as_ref().unwrap();
        let pane = pm.focused_pane().unwrap();
        assert_eq!(pane.title, "Tab 3");
        assert!(pane.has_default_title);
    }

    /// set_default_title() must NOT overwrite panes that already have a real title.
    #[test]
    fn set_default_title_skips_non_default_panes() {
        let mut tab = Tab::new_stub(1, 1);
        // Simulate pane having received a real title
        {
            let pm = tab.pane_manager.as_mut().unwrap();
            let pane = pm.focused_pane_mut().unwrap();
            pane.title = "vim".to_string();
            pane.has_default_title = false;
        }
        // tab.has_default_title stays true (simulates multi-pane where focused has real title
        // but tab-level tracking is slightly stale)
        tab.has_default_title = true;
        tab.set_default_title(2);
        // Pane with a real title must be untouched
        let pm = tab.pane_manager.as_ref().unwrap();
        let pane = pm.focused_pane().unwrap();
        assert_eq!(pane.title, "vim");
        assert!(!pane.has_default_title);
    }

    #[test]
    fn set_title_syncs_focused_pane() {
        let mut tab = Tab::new_stub(1, 1);
        tab.set_title("my-session");
        assert_eq!(tab.title, "my-session");
        assert!(!tab.has_default_title);
        let pm = tab.pane_manager.as_ref().unwrap();
        let pane = pm.focused_pane().unwrap();
        assert_eq!(pane.title, "my-session");
        assert!(!pane.has_default_title);
    }
}