ftui-runtime 0.11.0

Elm-style runtime loop and subscriptions 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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
#![forbid(unsafe_code)]

//! Optional dedicated render/output thread (Mode B).
//!
//! When the `render-thread` feature is enabled, this module provides a
//! [`RenderThread`] that moves all terminal output onto a dedicated thread.
//! This solves the interleaving problem where background task logs and
//! tick-driven UI updates could collide, breaking inline mode invariants.
//!
//! The render thread enforces the **one-writer rule** by construction:
//! it is the only place bytes reach the terminal.
//!
//! # Coalescing Rules
//!
//! - **Render** messages are coalesced: if multiple buffers arrive before the
//!   thread processes them, only the latest buffer is presented.
//! - **Log** messages are never dropped, but are chunked to avoid starving
//!   the UI (at most `LOG_CHUNK_LIMIT` log messages per iteration).
//! - **Resize** and **SetMode** are applied immediately on the render thread.
//!
//! # Error Propagation
//!
//! IO errors from the render thread are sent back via a dedicated error
//! channel. The caller is responsible for polling [`RenderThread::check_error`]
//! to detect failures.

use std::io::{self, Write};
use std::sync::mpsc;
use std::thread::{self, JoinHandle};
use web_time::Instant;

use crate::terminal_writer::{ScreenMode, TerminalWriter};
use ftui_render::buffer::Buffer;
use ftui_render::sanitize::SanitizeMode;

/// Maximum number of log messages processed per render-loop iteration.
///
/// This prevents log spam from indefinitely starving UI presents.
const LOG_CHUNK_LIMIT: usize = 64;

/// Channel capacity for the outbound message queue.
const CHANNEL_CAPACITY: usize = 256;
/// Timeout for render-thread shutdown joins.
const RENDER_THREAD_JOIN_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(250);
/// Poll interval while waiting for render-thread shutdown.
const RENDER_THREAD_JOIN_POLL: std::time::Duration = std::time::Duration::from_millis(1);

/// Pending render state: buffer, cursor position, cursor visibility.
type PendingRender = (Buffer, Option<(u16, u16)>, bool);

/// Messages sent from the main thread to the render thread.
#[derive(Debug)]
pub enum OutMsg {
    /// Write a log chunk using an explicit terminal control policy.
    ///
    /// Use [`SanitizeMode::Strip`] for untrusted output. No newline is appended;
    /// invalid UTF-8 is replaced before the writer applies the selected policy.
    /// [`SanitizeMode::Raw`] permits terminal commands and requires trusted input.
    Log {
        bytes: Vec<u8>,
        mode: SanitizeMode,
    },
    Render {
        buffer: Buffer,
        cursor: Option<(u16, u16)>,
        cursor_visible: bool,
    },
    Resize {
        w: u16,
        h: u16,
    },
    SetMode(ScreenMode),
    Shutdown,
}

pub struct RenderThread {
    sender: Option<mpsc::SyncSender<OutMsg>>,
    handle: Option<JoinHandle<()>>,
    error_rx: mpsc::Receiver<io::Error>,
}

#[allow(clippy::result_large_err)]
impl RenderThread {
    pub fn start<W: Write + Send + 'static>(writer: TerminalWriter<W>) -> io::Result<Self> {
        let (tx, rx) = mpsc::sync_channel::<OutMsg>(CHANNEL_CAPACITY);
        let (err_tx, err_rx) = mpsc::sync_channel::<io::Error>(8);

        let handle = thread::Builder::new()
            .name("ftui-render".into())
            .spawn(move || {
                render_loop(writer, rx, err_tx);
            })?;

        Ok(Self {
            sender: Some(tx),
            handle: Some(handle),
            error_rx: err_rx,
        })
    }

    pub fn send(&self, msg: OutMsg) -> Result<(), mpsc::SendError<OutMsg>> {
        match &self.sender {
            Some(sender) => sender.send(msg),
            None => Err(mpsc::SendError(msg)),
        }
    }

    pub fn try_send(&self, msg: OutMsg) -> Result<(), mpsc::TrySendError<OutMsg>> {
        match &self.sender {
            Some(sender) => sender.try_send(msg),
            None => Err(mpsc::TrySendError::Disconnected(msg)),
        }
    }

    pub fn check_error(&self) -> Option<io::Error> {
        self.error_rx.try_recv().ok()
    }

    pub fn shutdown(mut self) {
        self.shutdown_inner();
    }

    fn shutdown_inner(&mut self) {
        request_shutdown_and_disconnect(&mut self.sender);
        if let Some(handle) = self.handle.take() {
            join_render_thread_bounded(handle);
        }
    }
}

impl Drop for RenderThread {
    fn drop(&mut self) {
        self.shutdown_inner();
    }
}

/// Best-effort shutdown for the bounded outbound queue.
///
/// If the queue has capacity we enqueue a `Shutdown` message so the render loop
/// can observe an orderly stop. If the queue is full or already disconnected,
/// we still drop the sender immediately so the receiver will exit once it drains
/// any queued work instead of deadlocking the caller on a blocking send.
fn request_shutdown_and_disconnect(sender: &mut Option<mpsc::SyncSender<OutMsg>>) {
    let Some(sender) = sender.take() else {
        return;
    };

    let _ = sender.try_send(OutMsg::Shutdown);
}

fn join_render_thread_bounded(handle: JoinHandle<()>) {
    let start = std::time::Instant::now();
    while !handle.is_finished() {
        if start.elapsed() >= RENDER_THREAD_JOIN_TIMEOUT {
            detach_render_thread_join(handle);
            return;
        }
        thread::sleep(RENDER_THREAD_JOIN_POLL);
    }
    let _ = handle.join();
}

fn detach_render_thread_join(handle: JoinHandle<()>) {
    let _ = thread::Builder::new()
        .name("ftui-render-detached-join".into())
        .spawn(move || {
            let _ = handle.join();
        });
}

fn render_loop<W: Write + Send>(
    mut writer: TerminalWriter<W>,
    rx: mpsc::Receiver<OutMsg>,
    err_tx: mpsc::SyncSender<io::Error>,
) {
    let mut loop_count: u64 = 0;
    // Reuse buffer to avoid allocation churn in the hot loop
    let mut logs: Vec<(Vec<u8>, SanitizeMode)> = Vec::with_capacity(LOG_CHUNK_LIMIT * 4);
    let mut last_render_time = Instant::now();

    loop {
        loop_count += 1;
        let first = match rx.recv() {
            Ok(msg) => msg,
            Err(_) => {
                let _ = writer.flush();
                return;
            }
        };

        logs.clear();
        let mut latest_render: Option<PendingRender> = None;
        let mut shutdown = false;

        let mut io_failed = false;
        process_msg(
            first,
            &mut logs,
            &mut latest_render,
            &mut writer,
            &mut shutdown,
            &err_tx,
            &mut io_failed,
        );
        if io_failed {
            return;
        }

        if !shutdown {
            while let Ok(msg) = rx.try_recv() {
                process_msg(
                    msg,
                    &mut logs,
                    &mut latest_render,
                    &mut writer,
                    &mut shutdown,
                    &err_tx,
                    &mut io_failed,
                );
                if io_failed {
                    return;
                }
                if shutdown {
                    break;
                }
            }
        }

        // Processing Logic:
        // 1. If we have logs, write them in chunks.
        // 2. After each chunk, if we have a render, present it.
        //    This ensures the UI is updated periodically during heavy logging.
        // 3. If we have no logs but have a render, present it.

        if logs.is_empty() {
            if let Some((buffer, cursor, cursor_visible)) = &latest_render {
                if let Err(e) = writer.present_ui(buffer, *cursor, *cursor_visible) {
                    let _ = err_tx.try_send(e);
                    return;
                }
                last_render_time = Instant::now();
            }
        } else {
            let chunks_len = logs.chunks(LOG_CHUNK_LIMIT).len();
            for (i, chunk) in logs.chunks(LOG_CHUNK_LIMIT).enumerate() {
                let is_last_chunk = i == chunks_len - 1;

                // Write chunk
                for (log_bytes, mode) in chunk {
                    if let Err(e) =
                        writer.write_log_with_mode(&String::from_utf8_lossy(log_bytes), *mode)
                    {
                        let _ = err_tx.try_send(e);
                        return;
                    }
                }

                // Interleaved render (throttled)
                // Only render if sufficient time has passed (e.g. 33ms for ~30fps) to avoid
                // thrashing the terminal with Clear/Draw cycles when logs invalidate the UI state.
                // Always render on the last chunk to ensure final consistency.
                let now = Instant::now();
                let should_render = is_last_chunk
                    || now.saturating_duration_since(last_render_time).as_millis() >= 33;

                if should_render && let Some((buffer, cursor, cursor_visible)) = &latest_render {
                    if let Err(e) = writer.present_ui(buffer, *cursor, *cursor_visible) {
                        let _ = err_tx.try_send(e);
                        return;
                    }
                    last_render_time = now;
                }
            }
        }

        // The channel is drained. Overlay log lines batched by the writer
        // reach the terminal at a present; with no frame in this batch, flush
        // them now instead of holding them until the next message. Lines that
        // arrive together are still streamed together.
        if !shutdown
            && latest_render.is_none()
            && writer.has_pending_logs()
            && let Err(e) = writer.flush()
        {
            let _ = err_tx.try_send(e);
            return;
        }

        // Periodic grapheme pool GC
        if loop_count.is_multiple_of(1000) {
            writer.gc(latest_render.as_ref().map(|(buf, _, _)| buf));
        }

        if shutdown {
            let _ = writer.flush();
            return;
        }
    }
}

fn flush_queued_logs<W: Write>(
    logs: &mut Vec<(Vec<u8>, SanitizeMode)>,
    writer: &mut TerminalWriter<W>,
    err_tx: &mpsc::SyncSender<io::Error>,
) -> bool {
    for (log_bytes, mode) in logs.drain(..) {
        if let Err(e) = writer.write_log_with_mode(&String::from_utf8_lossy(&log_bytes), mode) {
            let _ = err_tx.try_send(e);
            return false;
        }
    }
    true
}

#[allow(clippy::too_many_arguments)]
fn process_msg<W: Write>(
    msg: OutMsg,
    logs: &mut Vec<(Vec<u8>, SanitizeMode)>,
    latest_render: &mut Option<PendingRender>,
    writer: &mut TerminalWriter<W>,
    shutdown: &mut bool,
    err_tx: &mpsc::SyncSender<io::Error>,
    io_failed: &mut bool,
) {
    match msg {
        OutMsg::Log { bytes, mode } => {
            logs.push((bytes, mode));
        }
        OutMsg::Render {
            buffer,
            cursor,
            cursor_visible,
        } => {
            *latest_render = Some((buffer, cursor, cursor_visible));
        }
        OutMsg::Resize { w, h } => {
            if !flush_queued_logs(logs, writer, err_tx) {
                *io_failed = true;
                return;
            }
            if latest_render
                .as_ref()
                .is_some_and(|(buf, _, _)| buf.width() != w || buf.height() != h)
            {
                *latest_render = None;
            }
            writer.set_size(w, h);
        }
        OutMsg::SetMode(mode) => {
            if !flush_queued_logs(logs, writer, err_tx) {
                *io_failed = true;
                return;
            }
            if writer.screen_mode() != mode {
                *latest_render = None;
            }
            writer.set_screen_mode(mode);
            tracing::info!(
                target: crate::telemetry_schema::TARGET_RUNTIME,
                ?mode,
                "render thread updated screen mode"
            );
        }
        OutMsg::Shutdown => {
            *shutdown = true;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ftui_core::terminal_capabilities::TerminalCapabilities;
    use ftui_render::cell::Cell;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Condvar, Mutex, mpsc};
    use std::time::Duration;

    #[derive(Clone)]
    struct TestWriter {
        inner: Arc<Mutex<Vec<u8>>>,
    }

    impl TestWriter {
        fn new() -> Self {
            Self {
                inner: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn output(&self) -> Vec<u8> {
            self.inner
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .clone()
        }
    }

    impl Write for TestWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.inner
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .write(buf)
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    fn test_writer() -> (TerminalWriter<TestWriter>, TestWriter) {
        let tw = TestWriter::new();
        let writer = TerminalWriter::new(
            tw.clone(),
            ScreenMode::Inline { ui_height: 5 },
            crate::terminal_writer::UiAnchor::Bottom,
            TerminalCapabilities::basic(),
        );
        (writer, tw)
    }

    #[test]
    fn start_and_shutdown() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();
        rt.shutdown();
    }

    #[test]
    fn send_log_is_written() {
        let (writer, tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();

        rt.send(OutMsg::Log {
            bytes: b"hello world\n".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();
        std::thread::sleep(Duration::from_millis(50));
        rt.shutdown();

        let raw = tw.output();
        let output = String::from_utf8_lossy(&raw);
        assert!(output.contains("hello world"));
    }

    #[test]
    fn mixed_log_modes_preserve_fifo_and_filter_controls() {
        let (writer, tw) = test_writer();
        let mut rt = RenderThread::start(writer).unwrap();
        let raw_payload = "RAW:\x1b[34mblue\x1b]0;raw-title\x07\x1b[1J\x1b[?2026h:done\x1b[0m";
        for (text, mode) in [
            (
                "STRIP:\x1b[31mred\x1b[0m\x1b]0;strip-title\x07\x1b[2J\x1b[?1049h:done",
                SanitizeMode::Strip,
            ),
            (
                "SGR:\x1b[32mgreen\x1b]0;sgr-title\x07\x1b[3J\x1b[?2004h:done",
                SanitizeMode::SgrOnly,
            ),
            ("PLAIN:after", SanitizeMode::Strip),
            (raw_payload, SanitizeMode::Raw),
        ] {
            rt.send(OutMsg::Log {
                bytes: text.as_bytes().to_vec(),
                mode,
            })
            .unwrap();
        }
        rt.send(OutMsg::Shutdown).unwrap();
        rt.handle.take().unwrap().join().unwrap();
        assert!(rt.check_error().is_none());

        let output = String::from_utf8(tw.output()).unwrap();
        let positions = ["STRIP:", "SGR:", "PLAIN:", "RAW:"].map(|marker| {
            assert_eq!(output.matches(marker).count(), 1, "marker {marker:?}");
            output.find(marker).unwrap()
        });
        assert!(positions.windows(2).all(|pair| pair[0] < pair[1]));
        assert!(output.contains("STRIP:red:done"));
        for forbidden in ["\x1b[31m", "strip-title", "\x1b[2J", "\x1b[?1049h"] {
            assert!(!output.contains(forbidden), "strip leaked {forbidden:?}");
        }
        // G48 transport framing: messages without a newline continue one open
        // line (no per-message ESC 7 / ESC 8).
        assert!(output.contains("SGR:\x1b[32mgreen:done\x1b[0mPLAIN:after"));
        for forbidden in ["sgr-title", "\x1b[3J", "\x1b[?2004h"] {
            assert!(!output.contains(forbidden), "SGR leaked {forbidden:?}");
        }
        assert!(output.contains("PLAIN:after"));
        assert!(output.contains(raw_payload), "raw requires explicit opt-in");
    }

    #[test]
    fn raw_log_chunks_preserve_line_endings_without_appending_and_decode_lossily() {
        let (writer, tw) = test_writer();
        let mut rt = RenderThread::start(writer).unwrap();
        rt.send(OutMsg::Log {
            bytes: b"RAWCHUNK:one\r\ntwo\nbad:\xff:end".to_vec(),
            mode: SanitizeMode::Raw,
        })
        .unwrap();
        rt.send(OutMsg::Shutdown).unwrap();
        rt.handle.take().unwrap().join().unwrap();
        assert!(rt.check_error().is_none());

        let output = String::from_utf8(tw.output()).unwrap();
        // G48 transport framing: complete lines end with CR LF, and the
        // trailing text stays open (no line break after it, no ESC 8).
        assert!(output.contains("RAWCHUNK:one\r\ntwo\r\n"), "{output:?}");
        let open = output.find("bad:\u{fffd}:end").expect("open text");
        assert!(!output[open..].contains(['\r', '\n']), "{output:?}");
        assert!(!output.contains("\r\r\n"));
    }

    #[test]
    fn log_only_batch_reaches_the_terminal_without_a_render() {
        // G48: a log with no frame after it must not wait for a later
        // Render, Resize, SetMode or Shutdown message.
        let (writer, tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();
        rt.send(OutMsg::Log {
            bytes: b"held-line\n".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();
        let deadline = Instant::now() + Duration::from_secs(5) * ftui_core::cx::test_time_scale();
        while !String::from_utf8_lossy(&tw.output()).contains("held-line") {
            assert!(
                Instant::now() < deadline,
                "a log-only batch was held back with no frame to present"
            );
            std::thread::sleep(Duration::from_millis(5));
        }
        rt.shutdown();
        let output = String::from_utf8_lossy(&tw.output()).into_owned();
        assert_eq!(output.matches("held-line").count(), 1);
    }

    #[test]
    fn interleaved_logs_and_renders() {
        let (mut writer, tw) = test_writer();
        writer.set_size(10, 10);
        let rt = RenderThread::start(writer).unwrap();

        // Send enough logs to force chunking (> 64)
        // plus a render in between
        let mut logs = Vec::new();
        for i in 0..100 {
            logs.push(OutMsg::Log {
                bytes: format!("log-{i}\n").into_bytes(),
                mode: SanitizeMode::Strip,
            });
        }

        let mut buf = Buffer::new(10, 5);
        buf.set_raw(0, 0, Cell::from_char('X'));

        // Send logs, then render
        // Note: channel is FIFO. render loop drains ALL.
        // It will see 100 logs + 1 render (if we send render last).
        // Since we want to test interleaving logic, we rely on the loop's
        // behavior of processing the batch.

        for msg in logs {
            rt.send(msg).unwrap();
        }
        rt.send(OutMsg::Render {
            buffer: buf,
            cursor: None,
            cursor_visible: true,
        })
        .unwrap();

        std::thread::sleep(Duration::from_millis(200));
        rt.shutdown();

        let raw = tw.output();
        let output = String::from_utf8_lossy(&raw);

        // Verify logs are present
        assert!(output.contains("log-0"));
        assert!(output.contains("log-99"));

        // Verify render occurred (X is present)
        // With corrected logic, X should appear after first chunk(64),
        // and potentially again after last chunk (100-64=36).
        assert!(output.contains('X'));
    }

    #[test]
    fn constants_have_expected_values() {
        assert_eq!(LOG_CHUNK_LIMIT, 64);
        assert_eq!(CHANNEL_CAPACITY, 256);
    }

    #[test]
    fn check_error_none_when_clean() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();
        assert!(rt.check_error().is_none());
        rt.shutdown();
    }

    #[test]
    fn try_send_succeeds() {
        let (writer, tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();

        assert!(
            rt.try_send(OutMsg::Log {
                bytes: b"try-send-test\n".to_vec(),
                mode: SanitizeMode::Strip,
            })
            .is_ok()
        );
        std::thread::sleep(Duration::from_millis(50));
        rt.shutdown();

        let bytes = tw.output();
        let output = String::from_utf8_lossy(&bytes);
        assert!(output.contains("try-send-test"));
    }

    #[test]
    fn drop_triggers_shutdown() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();
        // Drop without explicit shutdown should not hang
        drop(rt);
    }

    #[test]
    fn render_coalescing_uses_latest() {
        let (mut writer, tw) = test_writer();
        writer.set_size(10, 5);
        let rt = RenderThread::start(writer).unwrap();

        // Send two renders in quick succession: first with 'A', second with 'Z'
        let mut buf_a = Buffer::new(10, 5);
        buf_a.set_raw(0, 0, Cell::from_char('A'));
        let mut buf_z = Buffer::new(10, 5);
        buf_z.set_raw(0, 0, Cell::from_char('Z'));

        rt.send(OutMsg::Render {
            buffer: buf_a,
            cursor: None,
            cursor_visible: true,
        })
        .unwrap();
        rt.send(OutMsg::Render {
            buffer: buf_z,
            cursor: None,
            cursor_visible: true,
        })
        .unwrap();

        std::thread::sleep(Duration::from_millis(100));
        rt.shutdown();

        let bytes = tw.output();
        let output = String::from_utf8_lossy(&bytes);
        // The latest render (Z) must appear
        assert!(output.contains('Z'));
    }

    #[test]
    fn resize_message_processed() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();
        // Resize should not cause errors
        rt.send(OutMsg::Resize { w: 120, h: 40 }).unwrap();
        std::thread::sleep(Duration::from_millis(50));
        assert!(rt.check_error().is_none());
        rt.shutdown();
    }

    #[test]
    fn set_mode_message_processed() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();
        rt.send(OutMsg::SetMode(ScreenMode::AltScreen)).unwrap();
        std::thread::sleep(Duration::from_millis(50));
        assert!(rt.check_error().is_none());
        rt.shutdown();
    }

    #[test]
    fn multiple_logs_all_written() {
        let (writer, tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();

        for i in 0..10 {
            rt.send(OutMsg::Log {
                bytes: format!("msg-{i}\n").into_bytes(),
                mode: SanitizeMode::Strip,
            })
            .unwrap();
        }
        std::thread::sleep(Duration::from_millis(100));
        rt.shutdown();

        let bytes = tw.output();
        let output = String::from_utf8_lossy(&bytes);
        for i in 0..10 {
            assert!(output.contains(&format!("msg-{i}")), "missing msg-{i}");
        }
    }

    #[test]
    fn outmsg_debug_format() {
        let log = OutMsg::Log {
            bytes: b"hi".to_vec(),
            mode: SanitizeMode::Strip,
        };
        let dbg = format!("{log:?}");
        assert!(dbg.contains("Log"));

        let render = OutMsg::Render {
            buffer: Buffer::new(1, 1),
            cursor: Some((0, 0)),
            cursor_visible: false,
        };
        let dbg = format!("{render:?}");
        assert!(dbg.contains("Render"));

        let resize = OutMsg::Resize { w: 80, h: 24 };
        let dbg = format!("{resize:?}");
        assert!(dbg.contains("Resize"));

        let shutdown = OutMsg::Shutdown;
        let dbg = format!("{shutdown:?}");
        assert!(dbg.contains("Shutdown"));
    }

    #[test]
    fn send_after_shutdown_returns_err() {
        let (writer, _tw) = test_writer();
        let mut rt = RenderThread::start(writer).unwrap();
        request_shutdown_and_disconnect(&mut rt.sender);
        // Wait for render thread to exit
        std::thread::sleep(Duration::from_millis(100));
        // Now sending should fail (disconnected)
        let result = rt.send(OutMsg::Log {
            bytes: b"late\n".to_vec(),
            mode: SanitizeMode::Strip,
        });
        assert!(result.is_err());
    }

    #[test]
    fn set_mode_debug_format() {
        let msg = OutMsg::SetMode(ScreenMode::AltScreen);
        let dbg = format!("{msg:?}");
        assert!(dbg.contains("SetMode"));
    }

    #[test]
    fn render_with_cursor_position() {
        let (mut writer, tw) = test_writer();
        writer.set_size(10, 5);
        let rt = RenderThread::start(writer).unwrap();

        let buf = Buffer::new(10, 5);
        rt.send(OutMsg::Render {
            buffer: buf,
            cursor: Some((3, 2)),
            cursor_visible: true,
        })
        .unwrap();

        std::thread::sleep(Duration::from_millis(50));
        assert!(rt.check_error().is_none());
        rt.shutdown();

        let bytes = tw.output();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn render_with_hidden_cursor() {
        let (mut writer, _tw) = test_writer();
        writer.set_size(10, 5);
        let rt = RenderThread::start(writer).unwrap();

        let buf = Buffer::new(10, 5);
        rt.send(OutMsg::Render {
            buffer: buf,
            cursor: None,
            cursor_visible: false,
        })
        .unwrap();

        std::thread::sleep(Duration::from_millis(50));
        assert!(rt.check_error().is_none());
        rt.shutdown();
    }

    #[test]
    fn rapid_resize_messages() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();

        for size in [(80, 24), (120, 40), (40, 10), (200, 60)] {
            rt.send(OutMsg::Resize {
                w: size.0,
                h: size.1,
            })
            .unwrap();
        }

        std::thread::sleep(Duration::from_millis(50));
        assert!(rt.check_error().is_none());
        rt.shutdown();
    }

    #[test]
    fn sequential_log_send_no_panic() {
        let (writer, _tw) = test_writer();
        let rt = RenderThread::start(writer).unwrap();

        // Rapidly send different message types in sequence
        rt.send(OutMsg::Log {
            bytes: b"line-1\n".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();
        rt.send(OutMsg::Resize { w: 20, h: 10 }).unwrap();
        rt.send(OutMsg::Log {
            bytes: b"line-2\n".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();
        rt.send(OutMsg::SetMode(ScreenMode::AltScreen)).unwrap();
        rt.send(OutMsg::Log {
            bytes: b"line-3\n".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();

        std::thread::sleep(Duration::from_millis(100));
        assert!(rt.check_error().is_none());
        rt.shutdown();
    }

    #[test]
    fn shutdown_helper_enqueues_shutdown_when_channel_has_capacity() {
        let (tx, rx) = mpsc::sync_channel::<OutMsg>(1);
        let mut sender = Some(tx);

        request_shutdown_and_disconnect(&mut sender);

        assert!(sender.is_none());
        assert!(matches!(rx.recv().unwrap(), OutMsg::Shutdown));
        assert!(
            rx.recv().is_err(),
            "sender should be disconnected after shutdown"
        );
    }

    #[test]
    fn shutdown_helper_disconnects_without_blocking_when_channel_is_full() {
        let (tx, rx) = mpsc::sync_channel::<OutMsg>(1);
        tx.send(OutMsg::Log {
            bytes: b"queued".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();
        let mut sender = Some(tx);

        request_shutdown_and_disconnect(&mut sender);

        assert!(sender.is_none());
        assert!(matches!(
            rx.recv().unwrap(),
            OutMsg::Log { bytes, mode: SanitizeMode::Strip } if bytes == b"queued".to_vec()
        ));
        assert!(
            rx.recv().is_err(),
            "full-channel shutdown fallback should disconnect once queued work drains"
        );
    }

    #[derive(Clone)]
    struct BlockingWriter {
        entered_tx: Arc<Mutex<Option<mpsc::Sender<()>>>>,
        released: Arc<(Mutex<bool>, Condvar)>,
        sent_entered: Arc<AtomicBool>,
    }

    impl Write for BlockingWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if !self.sent_entered.swap(true, Ordering::SeqCst)
                && let Some(tx) = self
                    .entered_tx
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .take()
            {
                let _ = tx.send(());
            }

            let (released_lock, released_ready) = &*self.released;
            let mut released = released_lock
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            while !*released {
                released = released_ready
                    .wait(released)
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
            }
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn shutdown_does_not_block_when_writer_is_stuck() {
        let (entered_tx, entered_rx) = mpsc::channel();
        let released = Arc::new((Mutex::new(false), Condvar::new()));
        let writer = BlockingWriter {
            entered_tx: Arc::new(Mutex::new(Some(entered_tx))),
            released: Arc::clone(&released),
            sent_entered: Arc::new(AtomicBool::new(false)),
        };
        let writer = TerminalWriter::new(
            writer,
            ScreenMode::Inline { ui_height: 5 },
            crate::terminal_writer::UiAnchor::Bottom,
            TerminalCapabilities::basic(),
        );
        let rt = RenderThread::start(writer).unwrap();
        rt.send(OutMsg::Log {
            bytes: b"blocked\n".to_vec(),
            mode: SanitizeMode::Strip,
        })
        .unwrap();

        assert!(
            entered_rx.recv_timeout(Duration::from_secs(1)).is_ok(),
            "render thread should enter the blocking writer"
        );

        // shutdown() gives up on the stuck writer after
        // RENDER_THREAD_JOIN_TIMEOUT (250 ms); without that it would block
        // until the writer is released below, i.e. forever. The 5 s bound is
        // a hang guard with room for a loaded runner (G04.2).
        let started = std::time::Instant::now();
        rt.shutdown();
        let elapsed = started.elapsed();
        assert!(
            elapsed < Duration::from_secs(5) * ftui_core::cx::test_time_scale(),
            "render-thread shutdown should not block on a stuck writer: {elapsed:?}"
        );

        let (released_lock, released_ready) = &*released;
        let mut released = released_lock
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *released = true;
        released_ready.notify_all();
    }

    #[test]
    fn set_mode_updates_writer_and_invalidates_stale_render_on_resize() {
        let (mut writer, _tw) = test_writer();
        writer.set_size(20, 10);
        let mut logs = Vec::new();
        let mut latest_render = None;
        let mut shutdown = false;
        let mut io_failed = false;
        let (err_tx, _err_rx) = mpsc::sync_channel(4);

        let mut old_buf = Buffer::new(20, 10);
        old_buf.set(0, 0, Cell::from_char('A'));
        process_msg(
            OutMsg::Render {
                buffer: old_buf,
                cursor: None,
                cursor_visible: false,
            },
            &mut logs,
            &mut latest_render,
            &mut writer,
            &mut shutdown,
            &err_tx,
            &mut io_failed,
        );
        assert!(latest_render.is_some());

        // Resize to 40x15 must drop the stale 20x10 pending render and update writer dimensions.
        process_msg(
            OutMsg::Resize { w: 40, h: 15 },
            &mut logs,
            &mut latest_render,
            &mut writer,
            &mut shutdown,
            &err_tx,
            &mut io_failed,
        );
        assert!(latest_render.is_none());
        assert_eq!((writer.width(), writer.height()), (40, 15));

        // SetMode(AltScreen) must update writer.screen_mode() and invalidate any inline pending render.
        let mut new_buf = Buffer::new(40, 15);
        new_buf.set(0, 0, Cell::from_char('B'));
        process_msg(
            OutMsg::Render {
                buffer: new_buf,
                cursor: None,
                cursor_visible: false,
            },
            &mut logs,
            &mut latest_render,
            &mut writer,
            &mut shutdown,
            &err_tx,
            &mut io_failed,
        );
        process_msg(
            OutMsg::SetMode(ScreenMode::AltScreen),
            &mut logs,
            &mut latest_render,
            &mut writer,
            &mut shutdown,
            &err_tx,
            &mut io_failed,
        );
        assert_eq!(writer.screen_mode(), ScreenMode::AltScreen);
        assert!(latest_render.is_none());
        assert!(!io_failed);
    }
}