r3bl_tui 0.7.7

TUI library to build modern apps inspired by React, Elm, with Flexbox, CSS, editor component, emoji support, and more
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
// Copyright (c) 2025 R3BL LLC. Licensed under Apache License, Version 2.0.

use crate::{Controlled, ControlledChild, Controller, ControllerReader, OscBuffer,
            PtyCommandBuilder, PtyConfig, PtyReadOnlyOutputEvent, PtyReadOnlySession,
            READ_BUFFER_SIZE,
            pty_common_io::{create_pty_pair, spawn_command_in_pty}};
use miette::IntoDiagnostic;
use std::io::Read;

impl PtyCommandBuilder {
    /// Spawns a read-only PTY session; it spawns two Tokio tasks and one OS child
    /// process.
    ///
    /// ```text
    /// ┌──────────────────────────┐ ◄── output ◄── ┌───────────────────────────────┐
    /// │ Your Program             │     events     │ Spawned Task (1) in Read Only │
    /// │                          │                │            session            │
    /// │                          │                │               ↓               │
    /// │ a) Handle output events  │                │ ◄─── PTY creates pair ──────► │
    /// │    from                  │                │ ┊Controller┊     ┊Controlled┊ │
    /// │ b) Process completion of │                │     ↓                 ↓       │
    /// │ read only session        │                │ Spawn Tokio       Controlled  │
    /// │                          │                │ blocking task     spawns      │
    /// │                          │                │ (3) to read       child       │
    /// │                          │                │ from              process (2) │
    /// │                          │                │ Controller and                │
    /// │                          │                │ generate events               │
    /// │                          │                │ for your program              │
    /// └──────────────────────────┘                └───────────────────────────────┘
    /// ```
    ///
    /// # Why 3 Tasks?
    ///
    /// 1. **Background orchestration task [`tokio::spawn`]** -> Required because this
    ///    function needs to return immediately with a session handle, allowing the caller
    ///    to start processing events while the PTY command runs in the background.
    ///    Without this, the function would block until the entire PTY session completes.
    ///
    /// 2. **OS child process [`ControlledChild`]** -> The actual command being executed
    ///    in the PTY. This is not a Tokio task but a system process that runs your
    ///    command with terminal emulation (the child thinks it is in an interactive
    ///    terminal).
    ///
    /// 3. **Blocking reader task [`tokio::task::spawn_blocking`]** -> Required because
    ///    PTY file descriptors only provide synchronous [`std::io::Read`] APIs, not async
    ///    [`tokio::io::AsyncRead`]. Using regular [`tokio::spawn`] with blocking reads
    ///    would block the entire async runtime. [`spawn_blocking`] runs these synchronous
    ///    reads on a dedicated thread pool.
    ///
    /// # Returns
    ///
    /// A session with:
    /// - `output_event_receiver_half` combined stdout/stderr of child process -> events
    /// - `completion_handle` to await spawned child process completion
    ///
    /// # Example: Capturing OSC sequences from cargo build
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use r3bl_tui::{PtyCommandBuilder, PtyConfigOption, PtyReadOnlyOutputEvent, OscEvent};
    ///
    /// let mut session = PtyCommandBuilder::new("cargo")
    ///     .args(["build"])
    ///     .enable_osc_sequences()  // Enable OSC 9;4 progress sequences
    ///     .spawn_read_only(PtyConfigOption::Osc + PtyConfigOption::Output)?;
    ///
    /// let mut output = Vec::new();
    /// while let Some(event) = session.output_evt_ch_rx_half.recv().await {
    ///     match event {
    ///         PtyReadOnlyOutputEvent::Output(data) => output.extend_from_slice(&data),
    ///         PtyReadOnlyOutputEvent::Osc(OscEvent::ProgressUpdate(pct)) => {
    ///             println!("Build progress: {}%", pct);
    ///         }
    ///         PtyReadOnlyOutputEvent::Exit(status) if status.success() => {
    ///             println!("Build completed successfully");
    ///             break;
    ///         }
    ///         PtyReadOnlyOutputEvent::Exit(status) => {
    ///             eprintln!("Build failed with: {:?}", status);
    ///             break;
    ///         }
    ///         _ => {}
    ///     }
    /// }
    /// println!("Build output: {}", String::from_utf8_lossy(&output));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the PTY fails to spawn or initialize properly.
    ///
    /// [`ControlledChild`]: crate::ControlledChild
    /// [`spawn_blocking`]: tokio::task::spawn_blocking
    /// [`std::io::Read`]: std::io::Read
    /// [`tokio::io::AsyncRead`]: tokio::io::AsyncRead
    /// [`tokio::spawn`]: tokio::spawn
    /// [`tokio::task::spawn_blocking`]: tokio::task::spawn_blocking
    pub fn spawn_read_only(
        self,
        arg_config: impl Into<PtyConfig>,
    ) -> miette::Result<PtyReadOnlySession> {
        let pty_config = arg_config.into();

        // Create channel to bridge events from PTY controlled side -> your program.
        let (
            /* return this to your program */ output_evt_ch_tx_half,
            /* used by blocking reader task */ output_evt_ch_rx_half,
        ) = tokio::sync::mpsc::unbounded_channel();

        // [🛫 SPAWN 0] Spawn the main orchestration task. This is returned to your
        // program, which waits for this to complete.
        let session_completion_handle = tokio::spawn(async move {
            // Build the command, ensuring CWD is set.
            let command = self.build()?;

            // Create PTY pair: controller (master) for your program, controlled (slave)
            // for spawned process
            let (controller, controlled): (Controller, Controlled) =
                create_pty_pair(pty_config.get_pty_size())?;

            // [🛫 SPAWN 1] Spawn the command with PTY (makes is_terminal() return true).
            // The child process uses the controlled side as its stdin/stdout/stderr.
            let controlled_child: ControlledChild =
                spawn_command_in_pty(&controlled, command)?;

            // [🛫 SPAWN 2] Spawn the reader task to process output from the controller
            // side. NOTE: Critical resource management - see module docs for
            // PTY lifecycle details.
            let output_reader_task_handle = {
                let controller_reader = controller
                    .try_clone_reader()
                    .map_err(|e| miette::miette!("Failed to clone pty reader: {}", e))?;
                spawn_blocking_controller_output_reader_task(
                    controller_reader,
                    output_evt_ch_tx_half.clone(),
                    pty_config,
                )
            };

            // [🛬 WAIT 1] Wait for the command to complete.
            let child_proc_exit_code = spawn_child_process_waiter(
                controlled_child,
                output_evt_ch_tx_half.clone(),
            )
            .await
            .into_diagnostic()??;

            // See module docs for detailed PTY lifecycle management explanation.
            drop(controlled); // Close the controlled half. CRITICAL for EOF to be sent to reader.
            drop(controller); // Not critical, but good practice to release controller FD.

            // [🛬 WAIT 2] Wait for the reader task to complete.
            output_reader_task_handle.await.into_diagnostic()??;

            Ok(portable_pty::ExitStatus::with_exit_code(
                child_proc_exit_code,
            ))
        });

        Ok(PtyReadOnlySession {
            output_evt_ch_rx_half,
            // Pin the completion handle: JoinHandle is not Unpin but select! requires it
            // for efficient polling without moving.
            pinned_boxed_session_completion_handle: Box::pin(session_completion_handle),
        })
    }
}

/// Spawns a task to wait for child process completion and send exit event.
///
/// Flow: child process → this task → output event channel → your program
///
/// This task:
/// - Waits for the child process to complete in a blocking context using
///   [`tokio::task::spawn_blocking`] because [`portable_pty`] provides only synchronous
///   APIs, not async ones, like our code in this module
/// - Sends the exit status as a `PtyReadOnlyOutputEvent::Exit` event
/// - Returns the exit code for the orchestration task
///
/// This function encapsulates the child process waiting logic to keep the
/// main orchestration task cleaner and more focused.
///
/// Returns a `JoinHandle` that resolves to the child process exit code.
///
/// [`portable_pty`]: mod@portable_pty
/// [`tokio::task::spawn_blocking`]: tokio::task::spawn_blocking
#[must_use]
fn spawn_child_process_waiter(
    mut controlled_child: ControlledChild,
    output_evt_ch_tx_half: tokio::sync::mpsc::UnboundedSender<PtyReadOnlyOutputEvent>,
) -> tokio::task::JoinHandle<miette::Result<u32>> {
    tokio::task::spawn_blocking(move || -> miette::Result<u32> {
        let status = controlled_child.wait().into_diagnostic()?;
        let exit_code = status.exit_code();
        let _unused = output_evt_ch_tx_half.send(PtyReadOnlyOutputEvent::Exit(status));
        Ok(exit_code)
    })
}

/// Spawn a blocking reader task that processes output from the PTY controller half.
///
/// This function spawns a blocking task that continuously reads data from the PTY
/// controller half and processes it according to the provided configuration options.
///
/// # Why `spawn_blocking`?
///
/// PTY operations are inherently **synchronous** and require `spawn_blocking` for proper
/// async integration:
///
/// ## Synchronous PTY APIs
/// - The `portable_pty` crate and underlying PTY file descriptors only provide
///   synchronous I/O
/// - `controller_reader` implements `std::io::Read` (blocking), not
///   `tokio::io::AsyncRead`
/// - PTY file descriptors are Unix concepts that operate at the kernel level with
///   blocking semantics
///
/// ## No `AsyncRead` Implementation
/// - There is no `AsyncRead` implementation available for PTY file descriptors
/// - `portable_pty::MasterPty::take_reader()` returns `Box<dyn Read + Send>`
///   (synchronous)
/// - PTY operations don't map cleanly to async file I/O patterns
///
/// ## Tokio Integration
/// - Using regular `tokio::spawn()` with blocking `Read::read()` would block the entire
///   async runtime
/// - `spawn_blocking()` runs the blocking operation on a dedicated thread pool
/// - This allows other async tasks to continue running while PTY I/O happens on separate
///   threads
///
/// ## Alternative Approaches (and why they don't work)
/// - **Polling/Non-blocking**: PTY file descriptors don't reliably support non-blocking
///   mode across platforms
/// - **Native async PTY library**: Doesn't exist with required cross-platform support
/// - **File descriptor conversion**: `tokio::fs::File::from_std()` doesn't work with PTY
///   FDs
///
/// # Arguments
///
/// * `controller_reader` - A boxed reader that implements [`Read`] + [`Send`], typically
///   the read end of a PTY master file descriptor
/// * `output_event_sender_half` - An unbounded sender for [`PtyReadOnlyOutputEvent`]s to
///   communicate with other parts of the application
/// * `config` - Configuration settings that determine which events to capture
///
/// # Returns
///
/// A [`tokio::task::JoinHandle`]`<`[`miette::Result`]`<()>>` for the spawned blocking
/// task. The task will complete when the PTY is closed (EOF) or an error occurs during
/// reading. CRITICAL - If the PTY is not closed and this join handle is awaited, it will
/// deadlock.
///
/// [`Read`]: std::io::Read
/// [`Send`]: std::marker::Send
/// [`miette::Result`]: miette::Result
/// [`tokio::task::JoinHandle`]: tokio::task::JoinHandle
#[must_use]
pub fn spawn_blocking_controller_output_reader_task(
    mut controller_reader: ControllerReader,
    output_event_ch_tx_half: tokio::sync::mpsc::UnboundedSender<PtyReadOnlyOutputEvent>,
    arg_config: impl Into<PtyConfig>,
) -> tokio::task::JoinHandle<miette::Result<()>> {
    let pty_config: PtyConfig = arg_config.into();

    // Async <-> Sync bridge using `spawn_blocking`.
    tokio::task::spawn_blocking(move || -> miette::Result<()> {
        let mut read_buffer = [0u8; READ_BUFFER_SIZE];
        let mut osc_buffer = if pty_config.is_osc_capture_enabled() {
            Some(OscBuffer::new())
        } else {
            None
        };

        loop {
            // This is a synchronous blocking read operation.
            match controller_reader.read(&mut read_buffer) {
                Ok(0) | Err(_) => break, // EOF or error - PTY closed.
                Ok(n) => {
                    let data = &read_buffer[..n];

                    // Send raw output if configured.
                    if pty_config.is_output_capture_enabled() {
                        let _unused = output_event_ch_tx_half
                            .send(PtyReadOnlyOutputEvent::Output(data.to_vec()));
                    }

                    // Process OSC sequences if configured.
                    if let Some(ref mut osc_buf) = osc_buffer {
                        for event in osc_buf.append_and_extract(data, n) {
                            let _unused = output_event_ch_tx_half
                                .send(PtyReadOnlyOutputEvent::Osc(event));
                        }
                    }
                }
            }
        }

        // Reader drops here automatically when the closure ends.
        drop(controller_reader);

        Ok(())
    })
}

#[cfg(test)]
mod tests {
    use crate::{OscEvent, PtyCommandBuilder, PtyConfigOption, PtyReadOnlyOutputEvent,
                PtyReadOnlySession,
                pty_read_only::spawn_blocking_controller_output_reader_task};
    use miette::IntoDiagnostic;
    use tokio::{sync::mpsc::unbounded_channel,
                time::{Duration, timeout}};

    /// Helper function to collect events with a timeout
    async fn collect_events_with_timeout(
        mut session: PtyReadOnlySession,
        max_duration: Duration,
    ) -> miette::Result<(Vec<PtyReadOnlyOutputEvent>, portable_pty::ExitStatus)> {
        let mut events = Vec::new();

        let result = timeout(max_duration, async move {
            loop {
                tokio::select! {
                    result = &mut session.pinned_boxed_session_completion_handle => {
                        // Process completed.
                        let status = result.into_diagnostic()??;

                        // Drain any remaining events.
                        while let Ok(event) = session.output_evt_ch_rx_half.try_recv() {
                            events.push(event);
                        }

                        return Ok::<_, miette::Error>((events, status));
                    }
                    Some(event) = session.output_evt_ch_rx_half.recv() => {
                        events.push(event);
                    }
                }
            }
        })
        .await;

        match result {
            Ok(Ok(data)) => Ok(data),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(miette::miette!("Test timed out")),
        }
    }

    #[tokio::test]
    async fn test_simple_echo_command() -> miette::Result<()> {
        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        let session = PtyCommandBuilder::new("echo")
            .args(["Hello, PTY!"])
            .cwd(temp_dir)
            .spawn_read_only(PtyConfigOption::Output)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        assert!(status.success());

        // Should have output and exit events.
        let output_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Output(data) => {
                    Some(String::from_utf8_lossy(data).to_string())
                }
                _ => None,
            })
            .collect();

        assert!(!output_events.is_empty());
        let combined_output = output_events.join("");
        assert!(combined_output.contains("Hello, PTY!"));

        Ok(())
    }

    #[tokio::test]
    async fn test_osc_sequence_with_printf() -> miette::Result<()> {
        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Use bash's builtin printf to emit a known OSC sequence.
        // Note: macOS /usr/bin/printf doesn't support \x escapes, so we use bash -c
        // with \033 octal escapes which work on both Linux and macOS.
        let session = PtyCommandBuilder::new("bash")
            .args(["-c", r"printf '\033]9;4;1;50\033\\'"])
            .cwd(temp_dir)
            .spawn_read_only(PtyConfigOption::Osc)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        assert!(status.success());

        // Should have received the OSC event.
        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc.clone()),
                _ => None,
            })
            .collect();

        assert_eq!(osc_events, vec![OscEvent::ProgressUpdate(50)]);

        Ok(())
    }

    #[tokio::test]
    async fn test_multiple_osc_sequences() -> miette::Result<()> {
        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Emit multiple OSC sequences using bash's builtin printf.
        // Note: macOS /usr/bin/printf doesn't support \x escapes.
        let session = PtyCommandBuilder::new("bash")
            .args([
                "-c",
                r"printf '\033]9;4;1;25\033\\\033]9;4;1;50\033\\\033]9;4;0;0\033\\'",
            ])
            .cwd(temp_dir)
            .spawn_read_only(PtyConfigOption::Osc)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        assert!(status.success());

        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc.clone()),
                _ => None,
            })
            .collect();

        assert_eq!(
            osc_events,
            vec![
                OscEvent::ProgressUpdate(25),
                OscEvent::ProgressUpdate(50),
                OscEvent::ProgressCleared,
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_osc_with_mixed_output() -> miette::Result<()> {
        // Mix regular output with OSC sequences.
        // This test requires bash/sh with working printf escape sequences
        if cfg!(target_os = "windows") {
            return Ok(()); // Skip on Windows
        }

        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Try using bash first, then sh.
        let config = PtyConfigOption::Osc + PtyConfigOption::Output;
        let session = PtyCommandBuilder::new("bash")
            .args([
                "-c",
                r"echo 'Starting...'; printf '\033]9;4;1;50\033\\'; echo 'Done!'",
            ])
            .cwd(temp_dir)
            .spawn_read_only(config)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        assert!(status.success());

        // Check we got output events (OSC might not work on all systems)
        let has_output = events
            .iter()
            .any(|e| matches!(e, PtyReadOnlyOutputEvent::Output(_)));
        assert!(has_output);

        // Check if we got OSC events (may not work on all printf implementations)
        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc.clone()),
                _ => None,
            })
            .collect();

        // If OSC sequences were parsed, verify they're correct.
        if !osc_events.is_empty() {
            assert_eq!(osc_events, vec![OscEvent::ProgressUpdate(50)]);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_split_osc_sequence_simulation() -> miette::Result<()> {
        // This test simulates a split sequence using shell commands.
        // Note: This is platform-specific and may not work on all systems
        if cfg!(target_os = "windows") {
            return Ok(()); // Skip on Windows
        }

        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Try using bash with better escape sequence handling.
        let session = PtyCommandBuilder::new("bash")
            .args(["-c", r"printf '\033]9;4;1;'; sleep 0.01; printf '75\033\\'"])
            .cwd(temp_dir)
            .spawn_read_only(PtyConfigOption::Osc)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        // Command should succeed.
        assert!(status.success());

        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc.clone()),
                _ => None,
            })
            .collect();

        // This test may not produce OSC events on all systems due to printf limitations.
        // We just verify the command ran successfully.
        if !osc_events.is_empty() {
            // If we did get OSC events, they should be correct.
            assert_eq!(osc_events, vec![OscEvent::ProgressUpdate(75)]);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_all_osc_event_types() -> miette::Result<()> {
        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Test all four OSC event types using bash's builtin printf with octal escapes.
        // Note: macOS /usr/bin/printf doesn't support \x escapes.
        let sequences = [
            (r"printf '\033]9;4;0;0\033\\'", OscEvent::ProgressCleared),
            (
                r"printf '\033]9;4;1;42\033\\'",
                OscEvent::ProgressUpdate(42),
            ),
            (r"printf '\033]9;4;2;0\033\\'", OscEvent::BuildError),
            (
                r"printf '\033]9;4;3;0\033\\'",
                OscEvent::IndeterminateProgress,
            ),
        ];

        for (bash_cmd, expected) in sequences {
            let session = PtyCommandBuilder::new("bash")
                .args(["-c", bash_cmd])
                .cwd(temp_dir.clone())
                .spawn_read_only(PtyConfigOption::Osc)?;

            let (events, status) =
                collect_events_with_timeout(session, Duration::from_secs(5)).await?;

            assert!(status.success());

            let osc_events: Vec<_> = events
                .iter()
                .filter_map(|e| match e {
                    PtyReadOnlyOutputEvent::Osc(osc) => Some(osc.clone()),
                    _ => None,
                })
                .collect();

            assert_eq!(osc_events, vec![expected]);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_command_failure() -> miette::Result<()> {
        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Test that we properly handle command failures.
        let session = PtyCommandBuilder::new("false")
            .cwd(temp_dir)
            .spawn_read_only(PtyConfigOption::NoCaptureOutput)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        // Command should fail.
        assert!(!status.success());

        // Should have an exit event.
        let has_exit = events
            .iter()
            .any(|e| matches!(e, PtyReadOnlyOutputEvent::Exit(_)));
        assert!(has_exit);

        Ok(())
    }

    #[tokio::test]
    async fn test_no_capture_option() -> miette::Result<()> {
        // Create a temporary directory for the test.
        let temp_dir = std::env::temp_dir();

        // Test that NoCaptureOutput doesn't capture anything.
        let session = PtyCommandBuilder::new("echo")
            .args(["test"])
            .cwd(temp_dir)
            .spawn_read_only(PtyConfigOption::NoCaptureOutput)?;

        let (events, status) =
            collect_events_with_timeout(session, Duration::from_secs(5)).await?;

        assert!(status.success());

        // Should only have exit event, no output.
        let output_events: Vec<_> = events
            .iter()
            .filter(|e| matches!(e, PtyReadOnlyOutputEvent::Output(_)))
            .collect();

        assert!(output_events.is_empty());

        Ok(())
    }

    #[tokio::test]
    async fn test_create_reader_task_no_capture() {
        let (event_sender, mut event_receiver) = unbounded_channel();

        // Create a mock reader that sends some data then EOF.
        let mock_data = b"test data";
        let reader = Box::new(std::io::Cursor::new(mock_data.to_vec()));

        let handle = spawn_blocking_controller_output_reader_task(
            reader,
            event_sender,
            PtyConfigOption::NoCaptureOutput,
        );

        // Reader should complete successfully.
        let result = tokio::time::timeout(Duration::from_millis(100), handle).await;
        assert!(result.is_ok());

        // No events should be sent since capture is disabled.
        assert!(event_receiver.try_recv().is_err());
    }

    #[tokio::test]
    async fn test_create_reader_task_with_output_capture() {
        let (event_sender, mut event_receiver) = unbounded_channel();

        let mock_data = b"test data";
        let reader = Box::new(std::io::Cursor::new(mock_data.to_vec()));

        let handle = spawn_blocking_controller_output_reader_task(
            reader,
            event_sender,
            PtyConfigOption::Output,
        );

        // Wait for task to complete.
        let result = tokio::time::timeout(Duration::from_millis(100), handle).await;
        assert!(result.is_ok());

        // Should receive output event.
        if let Ok(event) = event_receiver.try_recv() {
            match event {
                PtyReadOnlyOutputEvent::Output(data) => assert_eq!(data, mock_data),
                _ => panic!("Expected Output event"),
            }
        }
    }

    #[tokio::test]
    async fn test_create_reader_task_with_osc_capture() {
        let (event_sender, mut event_receiver) = unbounded_channel();

        // OSC sequence for Cargo progress update (50%) - using actual escape bytes
        let mock_data = b"\x1b]9;4;1;50\x1b\\";
        let reader = Box::new(std::io::Cursor::new(mock_data.to_vec()));

        // This test now uses the new OSC-only test as the comprehensive one.
        // This version keeps the old behavior for backward compatibility.
        let handle = spawn_blocking_controller_output_reader_task(
            reader,
            event_sender,
            PtyConfigOption::Osc,
        );

        // Wait for task to complete.
        let result = tokio::time::timeout(Duration::from_millis(100), handle).await;
        assert!(result.is_ok());

        // Collect all events - PtyConfigOption::Osc.into() enables both capture_osc and
        // capture_output
        let mut events = Vec::new();
        while let Ok(event) = event_receiver.try_recv() {
            events.push(event);
        }

        assert!(
            !events.is_empty(),
            "Should have received at least one event"
        );

        // Check that we received an OSC event (may also receive raw output due to
        // default. behavior)
        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc),
                _ => None,
            })
            .collect();

        assert!(
            !osc_events.is_empty(),
            "Should have received at least one OSC event"
        );

        // Verify we got the correct OSC event.
        let has_correct_event = osc_events
            .iter()
            .any(|osc| matches!(osc, crate::OscEvent::ProgressUpdate(50)));

        assert!(
            has_correct_event,
            "Expected OSC progress update event with 50%"
        );
    }

    #[tokio::test]
    async fn test_create_reader_task_with_osc_only_capture() {
        let (event_sender, mut event_receiver) = unbounded_channel();

        // OSC sequence for Cargo progress update (75%)
        let mock_data = b"\x1b]9;4;1;75\x1b\\";
        let reader = Box::new(std::io::Cursor::new(mock_data.to_vec()));

        // Create config with OSC capture only (disable output capture)
        let config = PtyConfigOption::Osc
            + PtyConfigOption::NoCaptureOutput
            + PtyConfigOption::Osc;

        let handle =
            spawn_blocking_controller_output_reader_task(reader, event_sender, config);

        // Wait for task to complete.
        let result = tokio::time::timeout(Duration::from_millis(100), handle).await;
        assert!(result.is_ok());

        // Collect all events - should only get OSC events, no raw output.
        let mut events = Vec::new();
        while let Ok(event) = event_receiver.try_recv() {
            events.push(event);
        }

        assert!(
            !events.is_empty(),
            "Should have received at least one event"
        );

        // Should have OSC events but no output events.
        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc),
                _ => None,
            })
            .collect();

        let output_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Output(_) => Some(()),
                _ => None,
            })
            .collect();

        assert!(!osc_events.is_empty(), "Should have received OSC events");
        assert!(
            output_events.is_empty(),
            "Should NOT have received output events (OSC-only capture)"
        );

        // Verify we got the correct OSC event.
        let has_correct_event = osc_events
            .iter()
            .any(|osc| matches!(osc, crate::OscEvent::ProgressUpdate(75)));

        assert!(
            has_correct_event,
            "Expected OSC progress update event with 75%"
        );
    }

    #[tokio::test]
    async fn test_create_reader_task_with_both_osc_and_output_capture() {
        let (event_sender, mut event_receiver) = unbounded_channel();

        // OSC sequence for Cargo progress update (25%)
        let mock_data = b"\x1b]9;4;1;25\x1b\\";
        let reader = Box::new(std::io::Cursor::new(mock_data.to_vec()));

        // Create config with both output and OSC capture enabled.
        let config = PtyConfigOption::Osc + PtyConfigOption::Output;

        let handle =
            spawn_blocking_controller_output_reader_task(reader, event_sender, config);

        // Wait for task to complete.
        let result = tokio::time::timeout(Duration::from_millis(100), handle).await;
        assert!(result.is_ok());

        // Collect all events - should get both raw output AND OSC events.
        let mut events = Vec::new();
        while let Ok(event) = event_receiver.try_recv() {
            events.push(event);
        }

        assert!(
            !events.is_empty(),
            "Should have received at least one event"
        );

        // Should have both OSC events AND output events.
        let osc_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Osc(osc) => Some(osc),
                _ => None,
            })
            .collect();

        let output_events: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                PtyReadOnlyOutputEvent::Output(_) => Some(()),
                _ => None,
            })
            .collect();

        assert!(!osc_events.is_empty(), "Should have received OSC events");
        assert!(
            !output_events.is_empty(),
            "Should have received output events (both capture enabled)"
        );

        // Verify we got the correct OSC event.
        let has_correct_event = osc_events
            .iter()
            .any(|osc| matches!(osc, crate::OscEvent::ProgressUpdate(25)));

        assert!(
            has_correct_event,
            "Expected OSC progress update event with 25%"
        );
    }
}