ftui-core 0.11.0

Terminal lifecycle, capabilities, and event parsing for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Unified terminal session teardown plan, escape sequences, and panic/signal hooks.
//!
//! Shared by the Crossterm backend (`terminal_session`, with the `crossterm`
//! feature) and the native Unix backend (`ftui-tty`).
//!
//! # Canonical Teardown Sequence Order
//! 1. `SYNC_END` (`\x1b[?2026l`) if requested
//! 2. Scroll region reset (`\x1b7\x1b[r\x1b8`) if requested
//! 3. Style / SGR reset (`\x1b[0m`) if requested
//! 4. Kitty keyboard pop (`\x1b[<u`) if requested
//! 5. Focus tracking disable (`\x1b[?1004l`) if requested
//! 6. Bracketed paste disable (`\x1b[?2004l`) if requested
//! 7. Mouse tracking disable (canonical SGR or mux-safe) if requested
//! 8. Show cursor (`\x1b[?25h`) if requested
//! 9. Leave alternate screen (`\x1b[?1049l`) if requested
//!
//! Note: Raw-mode restore is NOT part of the byte stream (it is an ioctl / termios
//! call) and is always performed last, after byte emission and stdout flush.

use std::io;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::terminal_capabilities::TerminalCapabilities;

/// Canonical escape sequence byte constants for terminal teardown and lifecycle.
pub mod seq {
    /// Save cursor position (DECSC).
    pub const DECSC: &[u8] = b"\x1b7";

    /// Restore cursor position (DECRC).
    pub const DECRC: &[u8] = b"\x1b8";

    /// Reset scroll region / margins to full screen (DECSTBM).
    pub const RESET_SCROLL_REGION: &[u8] = b"\x1b[r";

    /// Reset text style / SGR attributes to default (SGR 0).
    pub const RESET_STYLE: &[u8] = b"\x1b[0m";

    /// Alias for `RESET_STYLE` for compatibility.
    pub const SGR_RESET: &[u8] = RESET_STYLE;

    /// End synchronized output (DEC 2026).
    pub const SYNC_END: &[u8] = b"\x1b[?2026l";

    /// Kitty keyboard protocol push flags.
    pub const KITTY_KEYBOARD_ENABLE: &[u8] = b"\x1b[>15u";

    /// Kitty keyboard protocol pop flags.
    pub const KITTY_KEYBOARD_DISABLE: &[u8] = b"\x1b[<u";

    /// Disable focus event reporting.
    pub const FOCUS_DISABLE: &[u8] = b"\x1b[?1004l";

    /// Enable focus event reporting.
    pub const FOCUS_ENABLE: &[u8] = b"\x1b[?1004h";

    /// Disable bracketed paste mode.
    pub const BRACKETED_PASTE_DISABLE: &[u8] = b"\x1b[?2004l";

    /// Enable bracketed paste mode.
    pub const BRACKETED_PASTE_ENABLE: &[u8] = b"\x1b[?2004h";

    /// Canonical SGR mouse disable sequence.
    pub const MOUSE_DISABLE: &[u8] = b"\x1b[?1000;1002;1006l\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l";

    /// Conservative mouse disable sequence for mux sessions and panic paths.
    pub const MOUSE_DISABLE_MUX_SAFE: &[u8] =
        b"\x1b[?1016l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1001l\x1b[?1005l\x1b[?1015l";

    /// Canonical SGR mouse enable sequence.
    pub const MOUSE_ENABLE: &[u8] = b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006;1000;1002h\x1b[?1006h\x1b[?1000h\x1b[?1002h";

    /// Canonical SGR-Pixels (`?1016h`) mouse enable sequence (appends `?1016h` after `?1006h`).
    pub const MOUSE_ENABLE_PIXEL: &[u8] = b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006;1000;1002h\x1b[?1006h\x1b[?1000h\x1b[?1002h\x1b[?1016h";

    /// Conservative mouse enable sequence for mux sessions.
    pub const MOUSE_ENABLE_MUX_SAFE: &[u8] =
        b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006h\x1b[?1000h\x1b[?1002h";

    /// Conservative SGR-Pixels (`?1016h`) mouse enable sequence for mux sessions.
    pub const MOUSE_ENABLE_PIXEL_MUX_SAFE: &[u8] =
        b"\x1b[?1001l\x1b[?1003l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?1006h\x1b[?1000h\x1b[?1002h\x1b[?1016h";

    /// Show cursor (DECTCEM).
    pub const CURSOR_SHOW: &[u8] = b"\x1b[?25h";

    /// Hide cursor (DECTCEM).
    pub const CURSOR_HIDE: &[u8] = b"\x1b[?25l";

    /// Leave alternate screen buffer (DECSET 1049).
    pub const ALT_SCREEN_LEAVE: &[u8] = b"\x1b[?1049l";

    /// Enter alternate screen buffer (DECSET 1049).
    pub const ALT_SCREEN_ENTER: &[u8] = b"\x1b[?1049h";
}

/// Process-wide serialization for terminal byte emission.
///
/// The signal/panic teardown paths (both backends' best-effort cleanup,
/// `TerminalSession::cleanup`, `ftui-tty`'s `TtyBackend` drop) and the render
/// path (ftui-runtime's `TerminalWriter`) all write escape sequences to the
/// same stdout. Without mutual exclusion, a frame flush in progress
/// interleaves with teardown bytes (`ESC[r`, `1049l`, ...) and the frame
/// remainder lands on the cooked screen (bd-kdn7n item 2, the one-writer
/// violation).
///
/// It lives here rather than in the Crossterm-gated `terminal_session`
/// because the native backend needs it as much: until
/// bd-g00-root-epic-ewths.33.4 a build without the `crossterm` feature got a
/// no-op stub, and `ftui-tty` never took the lock at all, so its signal
/// thread could write teardown bytes into the middle of a frame.
///
/// Reentrant on purpose: the panic hook runs ON the rendering thread while it
/// may already hold this lock mid-frame, so same-thread re-entry must not
/// deadlock; cross-thread callers (the signal thread) still block until the
/// in-flight emission batch completes. Emission batches are short (one
/// buffered frame or one teardown sequence), so a signal thread waiting on
/// this lock is bounded by a single flush.
static TERMINAL_OUTPUT_LOCK: Mutex<()> = Mutex::new(());

thread_local! {
    /// Per-thread nesting depth for [`TERMINAL_OUTPUT_LOCK`]. The outermost
    /// acquisition on a thread owns the mutex; nested acquisitions (teardown
    /// re-entering from the panic hook on the render thread) hold no OS lock.
    static TERMINAL_OUTPUT_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// Guard produced by [`terminal_output_lock`]; releases on drop.
#[derive(Debug)]
pub struct TerminalOutputGuard {
    /// Held only by the OUTERMOST acquisition on its thread; re-entries
    /// keep `None`.
    _inner: Option<std::sync::MutexGuard<'static, ()>>,
}

/// Acquire the process-wide terminal output lock (see
/// [`TERMINAL_OUTPUT_LOCK`]).
///
/// Emission sites hold this guard for the duration of one write batch:
/// teardown paths for their full restore sequence, `TerminalWriter` methods
/// per frame / log / control write. Reentrant per thread; cross-thread
/// callers block until the in-flight batch completes.
#[doc(hidden)]
#[must_use]
pub fn terminal_output_lock() -> TerminalOutputGuard {
    let is_outermost = TERMINAL_OUTPUT_DEPTH.with(|depth| {
        let current = depth.get();
        depth.set(current + 1);
        current == 0
    });
    // A panic while holding (e.g. a panicking write) poisons the mutex; the
    // teardown paths must still be able to acquire it, so poison is ignored.
    let inner = is_outermost.then(|| {
        TERMINAL_OUTPUT_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    });
    TerminalOutputGuard { _inner: inner }
}

impl Drop for TerminalOutputGuard {
    fn drop(&mut self) {
        // Release the OS lock before decrementing so a waiting thread can
        // proceed immediately once this thread's outermost batch ends.
        self._inner = None;
        TERMINAL_OUTPUT_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
    }
}

static KITTY_POP_LATCH: AtomicBool = AtomicBool::new(false);

/// Latch guarding stack-based Kitty keyboard pop emission.
///
/// Kitty keyboard mode is a *stack*: `CSI > flags u` pushes, `CSI < u` pops,
/// and popping more times than you pushed pops an enclosing terminal or
/// multiplexer's entry. The latch exists so the best-effort teardown paths -
/// the panic hook, the signal thread, `terminal_session::best_effort_cleanup_for_exit`
/// (with the `crossterm` feature) - emit at most one pop for the push they
/// are cleaning up after.
///
/// It tracks **one outstanding push, not one per process.** A session that
/// enables kitty keyboard pushes again and therefore owes another pop, so it
/// must call [`release`](Self::release) - see
/// `TerminalSession::enable_kitty_keyboard`. Without that, the latch stayed
/// claimed from the first cleanup onwards and every later session's push was
/// never popped, leaving the terminal in enhanced-key mode after exit: the
/// precise failure this module exists to prevent.
#[derive(Debug, Clone, Copy, Default)]
pub struct KittyPopLatch;

impl KittyPopLatch {
    /// Attempt to claim the pop for the outstanding push.
    ///
    /// Returns `true` if this caller claimed it, `false` if already claimed.
    #[inline]
    pub fn try_claim() -> bool {
        !KITTY_POP_LATCH.swap(true, Ordering::SeqCst)
    }

    /// Check if the latch has already been claimed.
    #[inline]
    pub fn is_claimed() -> bool {
        KITTY_POP_LATCH.load(Ordering::SeqCst)
    }

    /// Release the latch, because a new push now owes a new pop.
    ///
    /// Called when a session enables kitty keyboard mode. Tests also use it to
    /// start from a known state.
    #[inline]
    pub fn release() {
        KITTY_POP_LATCH.store(false, Ordering::SeqCst);
    }
}

/// Serialize the tests that read [`KITTY_POP_LATCH`], across modules.
///
/// nextest gives each test its own process, but `cargo test` does not, and the
/// latch is process-global - so without this these assertions are exact values
/// read from shared state.
#[cfg(test)]
pub(crate) fn kitty_latch_test_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: Mutex<()> = Mutex::new(());
    LOCK.lock().unwrap_or_else(|poison| poison.into_inner())
}

/// Declarative plan describing terminal restore escape sequences.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TeardownPlan {
    /// Emit synchronized output end sequence (`\x1b[?2026l`).
    pub emit_sync_end: bool,
    /// Reset scroll margins to full screen bracketed by DECSC/DECRC (`\x1b7\x1b[r\x1b8`).
    pub reset_scroll_region: bool,
    /// Reset text style/SGR attributes (`\x1b[0m`).
    pub reset_style: bool,
    /// Pop Kitty keyboard protocol stack (`\x1b[<u`).
    pub pop_kitty_keyboard: bool,
    /// Disable focus event reporting (`\x1b[?1004l`).
    pub disable_focus: bool,
    /// Disable bracketed paste mode (`\x1b[?2004l`).
    pub disable_paste: bool,
    /// Disable mouse tracking.
    pub disable_mouse: bool,
    /// Use mux-safe mouse disable sequence rather than full sequence.
    pub mouse_mux_safe: bool,
    /// Optional override for mouse disable byte sequence.
    pub mouse_disable_override: Option<&'static [u8]>,
    /// Show cursor (`\x1b[?25h`).
    pub show_cursor: bool,
    /// Leave alternate screen buffer (`\x1b[?1049l`).
    pub leave_alt_screen: bool,
}

impl TeardownPlan {
    /// Create a teardown plan from terminal capabilities and session options.
    ///
    /// Applies standard mux policies: kitty keyboard and focus events are
    /// disabled only if the capability is supported and not running inside a
    /// multiplexer (`!caps.in_any_mux()`).
    #[must_use]
    pub fn from_capabilities(
        caps: &TerminalCapabilities,
        alt_screen: bool,
        emit_sync_end: bool,
    ) -> Self {
        Self {
            emit_sync_end,
            reset_scroll_region: true,
            reset_style: true,
            pop_kitty_keyboard: caps.kitty_keyboard && !caps.in_any_mux(),
            disable_focus: caps.focus_events && !caps.in_any_mux(),
            disable_paste: caps.bracketed_paste,
            disable_mouse: caps.mouse_sgr,
            mouse_mux_safe: caps.in_any_mux(),
            mouse_disable_override: None,
            show_cursor: true,
            leave_alt_screen: alt_screen,
        }
    }

    /// Write all requested cleanup escape sequences in canonical order to `w`.
    pub fn write(&self, w: &mut impl io::Write) -> io::Result<()> {
        self.write_for_backend(w, "unknown")
    }

    /// Write all requested cleanup escape sequences in canonical order to `w`,
    /// logging structured start and end events if the `tracing` feature is enabled.
    pub fn write_for_backend(
        &self,
        w: &mut impl io::Write,
        _backend: &'static str,
    ) -> io::Result<()> {
        #[cfg(feature = "tracing")]
        tracing::info!(
            backend = _backend,
            plan = ?self,
            "teardown start"
        );

        if self.emit_sync_end {
            w.write_all(seq::SYNC_END)?;
        }
        if self.reset_scroll_region {
            w.write_all(seq::DECSC)?;
            w.write_all(seq::RESET_SCROLL_REGION)?;
            w.write_all(seq::DECRC)?;
        }
        if self.reset_style {
            w.write_all(seq::RESET_STYLE)?;
        }
        if self.pop_kitty_keyboard {
            w.write_all(seq::KITTY_KEYBOARD_DISABLE)?;
        }
        if self.disable_focus {
            w.write_all(seq::FOCUS_DISABLE)?;
        }
        if self.disable_paste {
            w.write_all(seq::BRACKETED_PASTE_DISABLE)?;
        }
        if self.disable_mouse {
            let mouse_seq = self
                .mouse_disable_override
                .unwrap_or(if self.mouse_mux_safe {
                    seq::MOUSE_DISABLE_MUX_SAFE
                } else {
                    seq::MOUSE_DISABLE
                });
            w.write_all(mouse_seq)?;
        }
        if self.show_cursor {
            w.write_all(seq::CURSOR_SHOW)?;
        }
        if self.leave_alt_screen {
            w.write_all(seq::ALT_SCREEN_LEAVE)?;
        }

        #[cfg(feature = "tracing")]
        tracing::info!(backend = _backend, "teardown end");

        Ok(())
    }
}

static INSTALLED_HOOKS: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());

thread_local! {
    static PANIC_CLEANUP_SUPPRESS_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// Deferred reports kept at most; later ones are only counted.
const MAX_DEFERRED_PANIC_REPORTS: usize = 16;

/// Reports of panics recovered while a terminal session was live, waiting for
/// the terminal to be restored (see [`install_chained_panic_hook`]).
struct DeferredPanicReports {
    reports: Vec<String>,
    dropped: usize,
}

static DEFERRED_PANIC_REPORTS: Mutex<DeferredPanicReports> = Mutex::new(DeferredPanicReports {
    reports: Vec::new(),
    dropped: 0,
});

fn defer_panic_report(info: &std::panic::PanicHookInfo<'_>) {
    let thread = std::thread::current();
    // The std hook's wording: `thread 'name' panicked at file:line:col:\nmsg`.
    let report = format!("thread '{}' {info}", thread.name().unwrap_or("<unnamed>"));
    let mut deferred = DEFERRED_PANIC_REPORTS
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if deferred.reports.len() < MAX_DEFERRED_PANIC_REPORTS {
        deferred.reports.push(report);
    } else {
        deferred.dropped = deferred.dropped.saturating_add(1);
    }
}

/// Write, and forget, the reports of panics recovered while a terminal
/// session was live.
///
/// Every teardown path calls this once the terminal is back in cooked mode,
/// with `stderr`; nothing is written when no report is waiting.
pub fn write_deferred_panic_reports(out: &mut impl io::Write) -> io::Result<()> {
    let (reports, dropped) = {
        let mut deferred = DEFERRED_PANIC_REPORTS
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        (
            std::mem::take(&mut deferred.reports),
            std::mem::take(&mut deferred.dropped),
        )
    };
    if reports.is_empty() && dropped == 0 {
        return Ok(());
    }
    for report in &reports {
        writeln!(
            out,
            "ftui: recovered from a panic while the terminal UI was running:\n{report}"
        )?;
    }
    if dropped > 0 {
        writeln!(out, "ftui: {dropped} more recovered panics were not kept")?;
    }
    out.flush()
}

/// Run a closure while suppressing best-effort terminal cleanup in panic hooks.
///
/// Use this around intentional `catch_unwind` boundaries. Terminal cleanup is
/// skipped for panics that are expected to be recovered, and while a terminal
/// session is live their reports wait for its teardown instead of being
/// written over the UI (see [`install_chained_panic_hook`]).
/// Suppression is per thread: a thread spawned inside `f` is not covered.
///
/// This lives here, not in the Crossterm-only `terminal_session`, because both
/// backends install cleanup hooks. It used to exist only with the `crossterm`
/// feature (a no-op stub otherwise), and `ftui-tty`'s hook never checked it.
///
/// In `panic = "abort"` builds, panics cannot be recovered by `catch_unwind`,
/// so suppression is disabled and this executes `f` directly.
pub fn with_panic_cleanup_suppressed<F, R>(f: F) -> R
where
    F: FnOnce() -> R,
{
    // The block below is compiled out here, so this is the tail expression.
    #[cfg(panic = "abort")]
    {
        f()
    }

    #[cfg(not(panic = "abort"))]
    {
        struct SuppressGuard;
        impl Drop for SuppressGuard {
            fn drop(&mut self) {
                PANIC_CLEANUP_SUPPRESS_DEPTH.with(|depth| {
                    depth.set(depth.get().saturating_sub(1));
                });
            }
        }

        PANIC_CLEANUP_SUPPRESS_DEPTH.with(|depth| {
            depth.set(depth.get().saturating_add(1));
        });
        let _guard = SuppressGuard;
        f()
    }
}

/// Whether the current thread is inside [`with_panic_cleanup_suppressed`].
#[must_use]
pub fn panic_cleanup_suppressed() -> bool {
    PANIC_CLEANUP_SUPPRESS_DEPTH.with(|depth| depth.get() > 0)
}

/// Install a panic hook with the given identifier that chains to the previously
/// installed hook.
///
/// Guaranteed to install at most once per `name`. When a panic occurs outside
/// [`with_panic_cleanup_suppressed`], `cleanup()` runs, then any deferred
/// reports are written to stderr, then the previously installed hook runs.
///
/// Inside [`with_panic_cleanup_suppressed`] (a panic the caller recovers from)
/// there is no cleanup, and while `session_live()` holds the previous hook is
/// not called either: the std default hook writes its report to stderr, which
/// is the terminal the UI is drawing on. The report is kept instead and
/// written by [`write_deferred_panic_reports`] once the teardown has restored
/// the terminal, or before the report of a panic that is not recovered.
pub fn install_chained_panic_hook(name: &'static str, cleanup: fn(), session_live: fn() -> bool) {
    let mut installed = match INSTALLED_HOOKS.lock() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };
    if installed.contains(&name) {
        return;
    }
    installed.push(name);
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        if panic_cleanup_suppressed() {
            // A recovered panic must not tear down a session that keeps
            // running (ftui-tty's hook did not check, so under the native
            // backend each panic a task or screen recovered from left raw
            // mode and the alternate screen mid-run), nor write over it
            // (bd-g00-root-epic-ewths.33.4).
            if session_live() {
                defer_panic_report(info);
                return;
            }
        } else {
            cleanup();
            let _ = write_deferred_panic_reports(&mut io::stderr());
        }
        previous(info);
    }));
}

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

    /// CONTRACT (bd-kdn7n item 2): the lock excludes OTHER threads — a
    /// signal thread running teardown must not complete acquisition while a
    /// frame batch is in flight, and must proceed once it completes. Lives
    /// here, not in the Crossterm-gated `terminal_session`, so builds without
    /// that feature run it too (bd-g00-root-epic-ewths.33.4).
    #[test]
    fn output_lock_excludes_other_threads() {
        let held = terminal_output_lock();
        let (tx, rx) = std::sync::mpsc::channel::<&'static str>();
        let worker = std::thread::spawn(move || {
            tx.send("started").expect("receiver alive");
            // Blocks until the main thread drops its guard.
            let _acquired = terminal_output_lock();
            tx.send("acquired").expect("receiver alive");
        });

        assert_eq!(rx.recv().expect("worker started"), "started");
        // The worker cannot have completed acquisition: it can only pass the
        // lock after this thread releases it, which has not happened yet.
        assert!(
            rx.try_recv().is_err(),
            "worker must still be blocked while the batch is held"
        );
        drop(held);
        assert_eq!(
            rx.recv().expect("worker acquired after release"),
            "acquired"
        );
        worker.join().expect("worker thread joins");
    }

    /// Same-thread re-entry holds no second OS lock: a nested guard on the
    /// owning thread returns at once (the panic hook re-enters mid-frame).
    #[test]
    fn output_lock_is_reentrant_on_the_owning_thread() {
        let _outer = terminal_output_lock();
        let inner = terminal_output_lock();
        assert!(inner._inner.is_none(), "a nested guard owns no mutex guard");
    }

    #[test]
    fn panic_cleanup_suppression_scope_restores_state() {
        assert!(
            !panic_cleanup_suppressed(),
            "suppression should start disabled"
        );
        with_panic_cleanup_suppressed(|| {
            if cfg!(panic = "abort") {
                assert!(
                    !panic_cleanup_suppressed(),
                    "abort profile must not suppress panic cleanup"
                );
                return;
            }
            assert!(panic_cleanup_suppressed(), "suppression should be enabled");
            with_panic_cleanup_suppressed(|| {
                assert!(
                    panic_cleanup_suppressed(),
                    "nested suppression should remain enabled"
                );
            });
            assert!(
                panic_cleanup_suppressed(),
                "outer suppression should still be enabled after nested scope"
            );
        });
        assert!(
            !panic_cleanup_suppressed(),
            "suppression should be disabled after scope exits"
        );
    }

    #[cfg(not(panic = "abort"))]
    #[test]
    fn chained_cleanup_hooks_skip_recovered_panics() {
        // Counted per thread, so panics in parallel tests cannot interfere.
        thread_local! {
            static CLEANUPS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
        }
        fn count_cleanup() {
            CLEANUPS.with(|n| n.set(n.get() + 1));
        }
        install_chained_panic_hook("test-chained-cleanup-gate", count_cleanup, || false);

        let recovered =
            with_panic_cleanup_suppressed(|| std::panic::catch_unwind(|| panic!("recovered")));
        assert!(recovered.is_err());
        assert_eq!(
            CLEANUPS.with(std::cell::Cell::get),
            0,
            "a recovered panic ran terminal cleanup"
        );

        let unrecovered = std::panic::catch_unwind(|| panic!("not suppressed"));
        assert!(unrecovered.is_err());
        assert_eq!(CLEANUPS.with(std::cell::Cell::get), 1);
    }

    /// While a session is live, a recovered panic's report is kept instead of
    /// going to the previous hook (the std one writes it over the UI), and
    /// the teardown writes it once (bd-g00-root-epic-ewths.33.4).
    #[cfg(not(panic = "abort"))]
    #[test]
    fn recovered_panic_report_waits_for_the_teardown_while_a_session_is_live() {
        use std::cell::Cell;
        // Per thread, so panics in parallel tests cannot interfere.
        thread_local! {
            static LIVE: Cell<bool> = const { Cell::new(false) };
            static PREVIOUS_HOOK_CALLS: Cell<u32> = const { Cell::new(0) };
        }
        let std_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            PREVIOUS_HOOK_CALLS.with(|n| n.set(n.get() + 1));
            std_hook(info);
        }));
        install_chained_panic_hook("test-deferred-report", || {}, || LIVE.with(Cell::get));

        LIVE.with(|live| live.set(true));
        let recovered = with_panic_cleanup_suppressed(|| {
            std::panic::catch_unwind(|| panic!("recovered mid-frame"))
        });
        assert!(recovered.is_err());
        assert_eq!(
            PREVIOUS_HOOK_CALLS.with(Cell::get),
            0,
            "the previous hook would write the report over the live UI"
        );

        let mut out = Vec::new();
        write_deferred_panic_reports(&mut out).expect("writes to a Vec");
        let text = String::from_utf8(out).expect("utf-8 report");
        assert!(text.contains("recovered mid-frame"), "{text}");
        assert!(
            text.contains("session_teardown.rs:"),
            "the report keeps the panic location: {text}"
        );
        let mut again = Vec::new();
        write_deferred_panic_reports(&mut again).expect("writes to a Vec");
        assert!(
            !String::from_utf8_lossy(&again).contains("recovered mid-frame"),
            "a report is written once"
        );

        // With no live session the previous hook reports it, as before.
        LIVE.with(|live| live.set(false));
        let recovered = with_panic_cleanup_suppressed(|| {
            std::panic::catch_unwind(|| panic!("recovered without a session"))
        });
        assert!(recovered.is_err());
        assert_eq!(PREVIOUS_HOOK_CALLS.with(Cell::get), 1);
    }

    #[test]
    fn write_emits_canonical_order() {
        let mut expected = Vec::new();
        // 1. sync_end
        expected.extend_from_slice(seq::SYNC_END);
        // 2. scroll region reset: ESC 7, CSI r, ESC 8
        expected.extend_from_slice(seq::DECSC);
        expected.extend_from_slice(seq::RESET_SCROLL_REGION);
        expected.extend_from_slice(seq::DECRC);
        // 3. SGR reset
        expected.extend_from_slice(seq::RESET_STYLE);
        // 4. kitty pop
        expected.extend_from_slice(seq::KITTY_KEYBOARD_DISABLE);
        // 5. focus disable
        expected.extend_from_slice(seq::FOCUS_DISABLE);
        // 6. bracketed paste disable
        expected.extend_from_slice(seq::BRACKETED_PASTE_DISABLE);
        // 7. mouse disable
        expected.extend_from_slice(seq::MOUSE_DISABLE);
        // 8. cursor show
        expected.extend_from_slice(seq::CURSOR_SHOW);
        // 9. alt-screen leave
        expected.extend_from_slice(seq::ALT_SCREEN_LEAVE);

        let plan = TeardownPlan {
            emit_sync_end: true,
            reset_scroll_region: true,
            reset_style: true,
            pop_kitty_keyboard: true,
            disable_focus: true,
            disable_paste: true,
            disable_mouse: true,
            mouse_mux_safe: false,
            mouse_disable_override: None,
            show_cursor: true,
            leave_alt_screen: true,
        };

        let mut buf = Vec::new();
        plan.write(&mut buf).unwrap();
        assert_eq!(buf, expected);
    }

    #[test]
    fn latch_claims_once() {
        let _serial = kitty_latch_test_lock();
        KittyPopLatch::release();
        assert!(!KittyPopLatch::is_claimed());
        assert!(KittyPopLatch::try_claim());
        assert!(KittyPopLatch::is_claimed());
        assert!(!KittyPopLatch::try_claim());
        assert!(!KittyPopLatch::try_claim());
        KittyPopLatch::release();
        assert!(!KittyPopLatch::is_claimed());
        assert!(KittyPopLatch::try_claim());
        KittyPopLatch::release();
    }

    #[test]
    fn a_released_latch_lets_a_second_teardown_pop_again() {
        let _serial = kitty_latch_test_lock();
        let caps = TerminalCapabilities::modern();
        let plan_for = || {
            let mut plan = TeardownPlan::from_capabilities(&caps, true, true);
            if !KittyPopLatch::try_claim() {
                plan.pop_kitty_keyboard = false;
            }
            plan.pop_kitty_keyboard
        };

        // One session's push, one pop, and no second pop for the same push.
        KittyPopLatch::release();
        assert!(plan_for(), "the outstanding push must be popped");
        assert!(!plan_for(), "and popped only once");

        // A new session pushes again, so the pop it owes must be emitted. The
        // release is explicit here because this test is about the latch's
        // semantics; that production actually performs it on enable is what
        // `enabling_kitty_keyboard_releases_the_pop_latch` covers.
        KittyPopLatch::release();
        assert!(plan_for(), "a fresh push owes a fresh pop");
        KittyPopLatch::release();
    }

    #[test]
    fn from_capabilities_applies_mux_policy() {
        let mut caps = TerminalCapabilities::modern();
        caps.kitty_keyboard = true;
        caps.focus_events = true;
        caps.bracketed_paste = true;
        caps.mouse_sgr = true;

        // Normal modern terminal: kitty and focus enabled, standard mouse disable.
        let plan = TeardownPlan::from_capabilities(&caps, true, true);
        assert!(plan.pop_kitty_keyboard);
        assert!(plan.disable_focus);
        assert!(plan.disable_paste);
        assert!(plan.disable_mouse);
        assert!(!plan.mouse_mux_safe);
        assert!(plan.leave_alt_screen);
        assert!(plan.emit_sync_end);

        // Under tmux: kitty and focus inhibited, mux-safe mouse disable.
        let tmux_caps = TerminalCapabilities::tmux();
        let tmux_plan = TeardownPlan::from_capabilities(&tmux_caps, true, false);
        assert!(!tmux_plan.pop_kitty_keyboard);
        assert!(!tmux_plan.disable_focus);
        assert!(tmux_plan.mouse_mux_safe);
        assert!(!tmux_plan.emit_sync_end);
    }

    #[test]
    fn mux_suppresses_kitty_and_focus_in_plan() {
        from_capabilities_applies_mux_policy();
    }

    #[test]
    fn chained_hook_runs_previous() {
        static HOOK_A_RAN: AtomicBool = AtomicBool::new(false);
        static HOOK_B_RAN: AtomicBool = AtomicBool::new(false);

        fn hook_a() {
            HOOK_A_RAN.store(true, Ordering::SeqCst);
        }
        fn hook_b() {
            HOOK_B_RAN.store(true, Ordering::SeqCst);
        }

        install_chained_panic_hook("test-hook-a", hook_a, || false);
        install_chained_panic_hook("test-hook-b", hook_b, || false);

        // Suppress default stderr output from panic hook during test.
        let prev_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));

        let _ = std::panic::catch_unwind(|| {
            // Restore chained hook inside catch_unwind
        });

        // Re-install and trigger
        std::panic::set_hook(prev_hook);
        let _ = std::panic::catch_unwind(|| {
            panic!("test panic for chained hook");
        });

        assert!(HOOK_A_RAN.load(Ordering::SeqCst));
        assert!(HOOK_B_RAN.load(Ordering::SeqCst));
    }

    #[test]
    fn hook_runs_under_unwind() {
        static UNWIND_HOOK_RAN: AtomicBool = AtomicBool::new(false);
        static TEST_SESSION_ACTIVE: AtomicBool = AtomicBool::new(false);

        fn session_hook() {
            if TEST_SESSION_ACTIVE.load(Ordering::SeqCst) {
                UNWIND_HOOK_RAN.store(true, Ordering::SeqCst);
            }
        }

        install_chained_panic_hook("test-unwind-hook", session_hook, || false);

        TEST_SESSION_ACTIVE.store(true, Ordering::SeqCst);
        let handle = std::thread::spawn(|| {
            let _ = std::panic::catch_unwind(|| {
                panic!("trigger hook under unwind");
            });
        });
        let _ = handle.join();
        TEST_SESSION_ACTIVE.store(false, Ordering::SeqCst);

        assert!(
            UNWIND_HOOK_RAN.load(Ordering::SeqCst),
            "hook must run under panic=unwind when session is active"
        );
    }
}