Skip to main content

ftui_runtime/
process_subscription.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Process subscription for spawning and monitoring external processes.
3//!
4//! [`ProcessSubscription`] wraps [`std::process::Command`] as a first-class
5//! runtime [`Subscription`]. It spawns a child process, captures stdout
6//! line-by-line, and sends messages to the model. When the subscription is
7//! stopped (via [`StopSignal`]), termination of the immediate child is requested
8//! and its cleanup outcome is checked.
9//!
10//! # Migration rationale
11//!
12//! Web Worker APIs and child-process patterns in source frameworks translate
13//! to process-based subscriptions in the terminal context. This provides a
14//! clean target for the migration code emitter.
15//!
16//! # Example
17//!
18//! ```ignore
19//! use ftui_runtime::process_subscription::{ProcessSubscription, ProcessEvent};
20//! use std::time::Duration;
21//!
22//! #[derive(Debug)]
23//! enum Msg {
24//!     ProcessOutput(ProcessEvent),
25//!     // ...
26//! }
27//!
28//! fn subscriptions() -> Vec<Box<dyn Subscription<Msg>>> {
29//!     vec![Box::new(
30//!         ProcessSubscription::new("tail", Msg::ProcessOutput)
31//!             .arg("-f")
32//!             .arg("/var/log/syslog")
33//!             .timeout(Duration::from_secs(60))
34//!     )]
35//! }
36//! ```
37
38#![forbid(unsafe_code)]
39
40use crate::subscription::{StopSignal, StopTrigger, SubId, Subscription, SubscriptionSender};
41use std::collections::hash_map::DefaultHasher;
42use std::hash::{Hash, Hasher};
43use std::io::{self, BufRead, Read, Write};
44use std::process::{Command, Stdio};
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::sync::{Arc, Mutex, mpsc};
47use web_time::{Duration, Instant};
48
49/// Events emitted by a [`ProcessSubscription`].
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum ProcessEvent {
52    /// A UTF-8 stdout line, without LF or CRLF, up to [`MAX_PROCESS_LINE_BYTES`].
53    Stdout(String),
54    /// A UTF-8 stderr line, without LF or CRLF, up to [`MAX_PROCESS_LINE_BYTES`].
55    Stderr(String),
56    /// Cumulative valid UTF-8 prefix of the pending stdout line.
57    ///
58    /// Emitted only with [`ProcessSubscription::partial_output`]. Replace the
59    /// previous preview; do not append it or count it as a completed line.
60    /// The original controls are retained for whole-prefix sanitization.
61    StdoutPartial(String),
62    /// Cumulative pending stderr prefix, with the same contract as
63    /// [`Self::StdoutPartial`].
64    StderrPartial(String),
65    /// The process exited with a status code.
66    Exited(i32),
67    /// The process was terminated by a Unix signal.
68    Signaled(i32),
69    /// Termination was requested and the immediate child was reaped.
70    ///
71    /// On Unix its observed status must be SIGKILL. Pending input/output may
72    /// be incomplete. Failed or unconfirmed cleanup produces [`Self::Error`].
73    Killed,
74    /// Spawning, monitoring, or process pipe I/O failed.
75    Error(String),
76}
77
78/// Result of the most recent interrupt request for one process run.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub enum ProcessInterruptStatus {
81    /// No interrupt has been requested.
82    Idle,
83    /// One interrupt is waiting for the supervisor.
84    Pending,
85    /// The operating system accepted SIGINT; the child may ignore it.
86    Sent,
87    /// Signal delivery failed; no successful delivery is claimed.
88    Failed(String),
89    /// The run closed before the pending request was delivered.
90    Canceled,
91}
92
93/// A snapshot of one process run, independent of model queue capacity.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct ProcessControlStatus {
96    /// Immediate child PID while control is open. Never use it to send signals.
97    pub pid: Option<u32>,
98    /// The supervisor accepts no further requests for this run.
99    pub closed: bool,
100    /// No child was spawned, or its owner confirmed that it was reaped.
101    ///
102    /// This does not prove output drain completion. Wait for this run's terminal
103    /// [`ProcessEvent`] as well before replacing its subscription. A retained
104    /// background reaper can set this after an unconfirmed-cleanup error.
105    pub can_restart: bool,
106    /// Outcome of the most recent interrupt request.
107    pub interrupt: ProcessInterruptStatus,
108}
109
110/// Why an interrupt could not be admitted. No child I/O occurs during admission.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum ProcessControlError {
113    /// The supervisor has not spawned this run yet.
114    NotRunning,
115    /// This run no longer accepts requests.
116    Closed,
117    /// One request is already waiting; there is no unbounded request queue.
118    AlreadyPending,
119    /// SIGINT delivery is not supported on this platform.
120    Unsupported,
121}
122
123#[derive(Debug)]
124struct ProcessControlState {
125    claimed: bool,
126    status: ProcessControlStatus,
127    /// Latest requested PTY size as (columns, rows); sizes coalesce, not queue.
128    resize: Option<(u16, u16)>,
129}
130
131/// Cloneable interrupt control for exactly one [`ProcessSubscription`] run.
132///
133/// Keep the handle in the model, rebuilding subscriptions with clones. Tag
134/// process messages with [`generation`](Self::generation) to reject delayed
135/// messages after a restart. Use a fresh handle for each new run. Dropping a
136/// descriptor or a handle clone does not close an active run.
137///
138/// Requests never wait for child I/O or model/stdin queue capacity. The owning
139/// supervisor sends SIGINT to the immediate child on Unix, without a shell or
140/// process-group signal. Linux requires a retained pidfd; if unavailable,
141/// delivery fails instead of falling back to a potentially reused PID. Other
142/// Unix platforms require the supervisor to remain the child's sole reaper.
143/// A [`ProcessSubscription::pty`] run is the exception: SIGINT goes to the
144/// child's whole process group, as Ctrl-C does in a terminal, and
145/// [`request_resize`](Self::request_resize) resizes its PTY.
146#[derive(Clone, Debug)]
147pub struct ProcessControl {
148    id: u64,
149    state: Arc<Mutex<ProcessControlState>>,
150}
151
152impl Default for ProcessControl {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158impl ProcessControl {
159    /// Create control for a future process run.
160    #[must_use]
161    pub fn new() -> Self {
162        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
163        Self {
164            id: NEXT_ID
165                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
166                .expect("process control identity space exhausted"),
167            state: Arc::new(Mutex::new(ProcessControlState {
168                claimed: false,
169                status: ProcessControlStatus {
170                    pid: None,
171                    closed: false,
172                    can_restart: true,
173                    interrupt: ProcessInterruptStatus::Idle,
174                },
175                resize: None,
176            })),
177        }
178    }
179
180    /// Stable identity shared by clones; fresh handles have distinct identities.
181    #[must_use]
182    pub const fn generation(&self) -> u64 {
183        self.id
184    }
185
186    /// Read one consistent snapshot. A closed handle need not mean output drained.
187    #[must_use]
188    pub fn status(&self) -> ProcessControlStatus {
189        self.state
190            .lock()
191            .unwrap_or_else(|error| error.into_inner())
192            .status
193            .clone()
194    }
195
196    /// Admit one interrupt for the supervisor to deliver.
197    ///
198    /// Admission is not delivery. Read [`status`](Self::status) for the outcome;
199    /// even `Sent` does not imply that a child handler ran or the child exited.
200    pub fn request_interrupt(&self) -> Result<(), ProcessControlError> {
201        if !cfg!(unix) {
202            return Err(ProcessControlError::Unsupported);
203        }
204        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
205        let status = &mut state.status;
206        if status.closed {
207            return Err(ProcessControlError::Closed);
208        }
209        if status.pid.is_none() {
210            return Err(ProcessControlError::NotRunning);
211        }
212        if status.interrupt == ProcessInterruptStatus::Pending {
213            return Err(ProcessControlError::AlreadyPending);
214        }
215        status.interrupt = ProcessInterruptStatus::Pending;
216        Ok(())
217    }
218
219    /// Ask the supervisor to resize this run's PTY to `cols` x `rows` cells.
220    ///
221    /// The latest request replaces a pending one. A request made before the
222    /// child spawns sets its initial size. Otherwise the supervisor applies it
223    /// within one 50 ms poll, then sends SIGWINCH to the child's process group.
224    /// Zero dimensions become one. Runs without [`ProcessSubscription::pty`]
225    /// ignore resizes, and admission does not report whether one was applied.
226    pub fn request_resize(&self, cols: u16, rows: u16) -> Result<(), ProcessControlError> {
227        if !cfg!(unix) {
228            return Err(ProcessControlError::Unsupported);
229        }
230        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
231        if state.status.closed {
232            return Err(ProcessControlError::Closed);
233        }
234        state.resize = Some((cols.max(1), rows.max(1)));
235        Ok(())
236    }
237
238    /// The `(cols, rows)` a [`request_resize`](Self::request_resize) has yet
239    /// to apply, if any: before spawn, the size the PTY will start at.
240    #[must_use]
241    pub fn pending_resize(&self) -> Option<(u16, u16)> {
242        self.state
243            .lock()
244            .unwrap_or_else(|error| error.into_inner())
245            .resize
246    }
247
248    #[cfg(unix)]
249    fn take_resize(&self) -> Option<(u16, u16)> {
250        self.state
251            .lock()
252            .unwrap_or_else(|error| error.into_inner())
253            .resize
254            .take()
255    }
256
257    fn claim(&self) -> Option<ProcessControlRun> {
258        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
259        if state.claimed {
260            return None;
261        }
262        state.claimed = true;
263        Some(ProcessControlRun(self.clone()))
264    }
265
266    fn started(&self, pid: u32) {
267        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
268        state.status.pid = Some(pid);
269        state.status.can_restart = false;
270    }
271
272    fn close(&self) {
273        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
274        state.status.pid = None;
275        state.status.closed = true;
276        if state.status.interrupt == ProcessInterruptStatus::Pending {
277            state.status.interrupt = ProcessInterruptStatus::Canceled;
278        }
279    }
280
281    fn confirm_reaped(&self) {
282        self.state
283            .lock()
284            .unwrap_or_else(|error| error.into_inner())
285            .status
286            .can_restart = true;
287    }
288
289    fn dispatch_interrupt(&self, child: &std::process::Child, group: Option<&ProcessGroup>) {
290        let status = self.status();
291        if status.closed || status.interrupt != ProcessInterruptStatus::Pending {
292            return;
293        }
294        // Only the supervisor calls this, before reaping. No state lock spans
295        // the OS call, and no message queue is needed to publish its result.
296        let result = match group {
297            Some(group) => group.interrupt(),
298            None => interrupt_child(child),
299        };
300        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
301        state.status.interrupt = match result {
302            Ok(()) => ProcessInterruptStatus::Sent,
303            Err(error) => ProcessInterruptStatus::Failed(error.to_string()),
304        };
305    }
306}
307
308struct ProcessControlRun(ProcessControl);
309
310impl Drop for ProcessControlRun {
311    fn drop(&mut self) {
312        self.0.close();
313    }
314}
315
316#[cfg(unix)]
317fn interrupt_child(child: &std::process::Child) -> io::Result<()> {
318    #[cfg(target_os = "linux")]
319    std::os::linux::process::ChildExt::pidfd(child).map_err(|error| {
320        io::Error::new(
321            io::ErrorKind::Unsupported,
322            format!("retained pidfd unavailable; interrupt not sent: {error}"),
323        )
324    })?;
325    std::os::unix::process::ChildExt::send_signal(child, rustix::process::Signal::INT.as_raw())
326}
327
328#[cfg(not(unix))]
329fn interrupt_child(_child: &std::process::Child) -> io::Result<()> {
330    Err(io::Error::new(
331        io::ErrorKind::Unsupported,
332        "SIGINT is unsupported",
333    ))
334}
335
336/// The session and process group of a [`ProcessSubscription::pty`] child,
337/// owned by its run.
338///
339/// The child starts a new session, so its PID is also its process group ID.
340/// Group signals are sent only while that leader is unreaped: an unreaped
341/// child keeps its PID reserved, and with it the group ID, so a signal can
342/// never reach a group that reused the ID. The group is swept with SIGKILL
343/// before the leader is reaped, so nothing that stayed in it outlives the run.
344/// A descendant that leaves the group (`setsid`, `setpgid`) is not tracked.
345#[cfg(unix)]
346struct ProcessGroup {
347    leader: rustix::process::Pid,
348    swept: bool,
349}
350
351#[cfg(unix)]
352impl ProcessGroup {
353    fn new(child: &std::process::Child) -> Self {
354        Self {
355            leader: rustix::process::Pid::from_child(child),
356            swept: false,
357        }
358    }
359
360    fn signal(&self, signal: rustix::process::Signal) -> io::Result<()> {
361        if self.swept {
362            return Err(io::Error::other("process group was already swept"));
363        }
364        rustix::process::kill_process_group(self.leader, signal).map_err(io::Error::from)
365    }
366
367    fn interrupt(&self) -> io::Result<()> {
368        self.signal(rustix::process::Signal::INT)
369    }
370
371    const fn is_swept(&self) -> bool {
372        self.swept
373    }
374
375    /// Send SIGKILL to every process still in the group, once.
376    fn kill(&mut self) -> io::Result<()> {
377        let result = self.signal(rustix::process::Signal::KILL);
378        self.swept = true;
379        result
380    }
381
382    /// Whether the leader has exited, leaving it unreaped.
383    fn leader_exited(&self) -> io::Result<bool> {
384        use rustix::process::{WaitId, WaitIdOptions, waitid};
385        let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
386        Ok(waitid(WaitId::Pid(self.leader), options)?.is_some())
387    }
388}
389
390/// Never constructed: PTY runs are refused before spawning off Unix.
391#[cfg(not(unix))]
392enum ProcessGroup {}
393
394#[cfg(not(unix))]
395impl ProcessGroup {
396    fn interrupt(&self) -> io::Result<()> {
397        match *self {}
398    }
399
400    const fn is_swept(&self) -> bool {
401        match *self {}
402    }
403
404    fn kill(&mut self) -> io::Result<()> {
405        match *self {}
406    }
407}
408
409/// Maximum queued input lines, excluding the one currently being written.
410pub const PROCESS_INPUT_CAPACITY: usize = 16;
411
412/// A rejected input line. The original text is returned without modification.
413#[derive(Debug, PartialEq, Eq)]
414pub enum ProcessInputError {
415    /// The bounded queue has no room; retry after the child reads input.
416    Full(String),
417    /// Input was closed, or its process run ended.
418    Closed(String),
419    /// The line exceeds [`MAX_PROCESS_LINE_BYTES`] UTF-8 bytes.
420    TooLong(String),
421}
422
423#[derive(Debug)]
424struct ProcessInputState {
425    sender: Option<mpsc::SyncSender<Box<str>>>,
426    receiver: Option<mpsc::Receiver<Box<str>>>,
427}
428
429/// Bounded, cloneable input for one [`ProcessSubscription`] run.
430///
431/// Keep this handle in the model and pass a clone to [`ProcessSubscription::stdin`]
432/// each time `subscriptions()` is rebuilt. Clones share one queue and identity.
433/// A fresh handle is required to start another process run. Dropping a clone
434/// does not close input; call [`close`](Self::close) to request EOF.
435///
436/// Sending never waits for pipe I/O or queue capacity. At most
437/// [`PROCESS_INPUT_CAPACITY`] lines are queued, plus one being written, each
438/// limited to [`MAX_PROCESS_LINE_BYTES`] bytes. Acceptance means queued, not
439/// acknowledged by the child; stop, exit, or I/O failure can discard pending
440/// input. A worker writes accepted lines in FIFO order with an appended LF.
441#[derive(Clone, Debug)]
442pub struct ProcessInput {
443    id: u64,
444    state: Arc<Mutex<ProcessInputState>>,
445}
446
447impl Default for ProcessInput {
448    fn default() -> Self {
449        Self::new()
450    }
451}
452
453impl ProcessInput {
454    /// Create input for a single future process run. Lines may be queued now.
455    #[must_use]
456    pub fn new() -> Self {
457        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
458        let (sender, receiver) = mpsc::sync_channel(PROCESS_INPUT_CAPACITY);
459        Self {
460            id: NEXT_ID
461                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
462                .expect("process input identity space exhausted"),
463            state: Arc::new(Mutex::new(ProcessInputState {
464                sender: Some(sender),
465                receiver: Some(receiver),
466            })),
467        }
468    }
469
470    /// Queue UTF-8 text followed by LF, preserving any embedded newlines.
471    ///
472    /// Returns the unchanged text on rejection. Oversized input is checked
473    /// before queue state. The short state lock never covers child I/O.
474    pub fn try_send_line(&self, line: String) -> Result<(), ProcessInputError> {
475        if line.len() > MAX_PROCESS_LINE_BYTES {
476            return Err(ProcessInputError::TooLong(line));
477        }
478        let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
479        let Some(sender) = &state.sender else {
480            return Err(ProcessInputError::Closed(line));
481        };
482        // Do not retain excess capacity supplied by the caller in the queue.
483        match sender.try_send(line.into_boxed_str()) {
484            Ok(()) => Ok(()),
485            Err(mpsc::TrySendError::Full(line)) => Err(ProcessInputError::Full(line.into())),
486            Err(mpsc::TrySendError::Disconnected(line)) => {
487                Err(ProcessInputError::Closed(line.into()))
488            }
489        }
490    }
491
492    /// Reject future sends, drain accepted lines, then close the child's stdin.
493    ///
494    /// This is idempotent across clones. Drain still depends on the child
495    /// reading; stop/timeout can cancel it. Closing before spawn gives EOF
496    /// after any lines already queued.
497    pub fn close(&self) {
498        self.state
499            .lock()
500            .unwrap_or_else(|error| error.into_inner())
501            .sender
502            .take();
503    }
504
505    fn claim(&self) -> Option<(ProcessInputRun, mpsc::Receiver<Box<str>>)> {
506        let receiver = self
507            .state
508            .lock()
509            .unwrap_or_else(|error| error.into_inner())
510            .receiver
511            .take()?;
512        Some((ProcessInputRun(self.clone()), receiver))
513    }
514}
515
516struct ProcessInputRun(ProcessInput);
517
518impl Drop for ProcessInputRun {
519    fn drop(&mut self) {
520        self.0.close();
521    }
522}
523
524/// A parent-owned pipe or PTY endpoint. Unix makes it nonblocking and polls it.
525#[cfg(unix)]
526trait ProcessEndpoint: std::os::fd::AsFd + Send + 'static {}
527#[cfg(unix)]
528impl<T: std::os::fd::AsFd + Send + 'static> ProcessEndpoint for T {}
529#[cfg(not(unix))]
530trait ProcessEndpoint: Send + 'static {}
531#[cfg(not(unix))]
532impl<T: Send + 'static> ProcessEndpoint for T {}
533
534/// Maximum bytes written to a canonical PTY before flushing with `VEOF` so
535/// the kernel's 4095-byte canonical buffer advances `canon_head` and applies
536/// normal flow control instead of discarding bytes.
537const PTY_CANONICAL_CHUNK_BYTES: usize = 2048;
538
539/// Write queued lines, then `end_of_input` once input is closed.
540///
541/// A pipe signals EOF by closing, so its `end_of_input` is empty. A PTY has no
542/// write side to close: EOF is the VEOF byte (Ctrl-D) at the start of a line,
543/// and intermediate `VEOF` flushes on a non-empty canonical buffer deliver
544/// lines longer than the 4095-byte kernel canonical line limit without newline.
545fn write_process_input<W: Write + ProcessEndpoint>(
546    stdin: W,
547    receiver: mpsc::Receiver<Box<str>>,
548    stop: StopSignal,
549    end_of_input: &[u8],
550) -> io::Result<()> {
551    #[cfg(unix)]
552    let mut stdin = process_pipe(stdin, stop.clone())?;
553    #[cfg(not(unix))]
554    let mut stdin = stdin;
555    loop {
556        match receiver.recv_timeout(PROCESS_READER_JOIN_POLL) {
557            Ok(line) => {
558                if stop.is_stopped() {
559                    return Err(io::Error::other("queued stdin was canceled before writing"));
560                }
561                if end_of_input.is_empty() {
562                    stdin.write_all(line.as_bytes())?;
563                    stdin.write_all(b"\n")?;
564                } else {
565                    for segment in line.as_bytes().split(|&byte| byte == b'\n') {
566                        let mut rest = segment;
567                        while rest.len() > PTY_CANONICAL_CHUNK_BYTES {
568                            let (chunk, tail) = rest.split_at(PTY_CANONICAL_CHUNK_BYTES);
569                            stdin.write_all(chunk)?;
570                            stdin.write_all(end_of_input)?;
571                            rest = tail;
572                        }
573                        stdin.write_all(rest)?;
574                        stdin.write_all(b"\n")?;
575                    }
576                }
577            }
578            Err(mpsc::RecvTimeoutError::Timeout) if stop.is_stopped() => break,
579            Err(mpsc::RecvTimeoutError::Timeout) => {}
580            Err(mpsc::RecvTimeoutError::Disconnected) => {
581                match stdin.write_all(end_of_input) {
582                    // A stopping run closes input before it stops this worker,
583                    // and a child whose side is gone cannot read EOF anyway.
584                    Err(error) if stop.is_stopped() || is_hangup(&error) => {}
585                    result => result?,
586                }
587                break;
588            }
589        }
590    }
591    Ok(())
592}
593
594/// A write found no reader: a closed pipe, or a PTY whose slave side is
595/// closed on systems that report EIO for it (Linux buffers the write instead).
596fn is_hangup(error: &io::Error) -> bool {
597    #[cfg(unix)]
598    if error.raw_os_error() == Some(rustix::io::Errno::IO.raw_os_error()) {
599        return true;
600    }
601    error.kind() == io::ErrorKind::BrokenPipe
602}
603
604/// The parent's read endpoint of a PTY.
605///
606/// Once no slave descriptor remains open, Linux reports EIO where a pipe
607/// reports end-of-file. Both mean the output is complete.
608#[cfg(unix)]
609struct PtyOutput(std::fs::File);
610
611#[cfg(unix)]
612impl Read for PtyOutput {
613    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
614        match self.0.read(buffer) {
615            Err(error) if error.raw_os_error() == Some(rustix::io::Errno::IO.raw_os_error()) => {
616                Ok(0)
617            }
618            result => result,
619        }
620    }
621}
622
623#[cfg(unix)]
624impl std::os::fd::AsFd for PtyOutput {
625    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
626        self.0.as_fd()
627    }
628}
629
630/// Parent-side endpoints of one run's PTY, made before the child spawns.
631#[cfg(unix)]
632struct PtyEndpoints {
633    /// Kept by the supervisor to resize the PTY.
634    master: std::os::fd::OwnedFd,
635    output: PtyOutput,
636    input: Option<std::fs::File>,
637}
638
639/// Open a PTY of `(cols, rows)` and attach its slave to `cmd`.
640///
641/// stdout and stderr share the slave, which is also stdin when `stdin` is set;
642/// otherwise stdin stays as configured. Echo is off because the host shows its
643/// own input, and LF stays LF so captured lines do not gain a CR. The child
644/// starts a new session without a controlling terminal: it cannot open the
645/// host terminal through `/dev/tty`, and its PID becomes its process group ID.
646#[cfg(unix)]
647fn prepare_pty(
648    cmd: &mut Command,
649    (cols, rows): (u16, u16),
650    stdin: bool,
651) -> io::Result<PtyEndpoints> {
652    use rustix::fs::{Mode, OFlags};
653    use rustix::pty::OpenptFlags;
654    use rustix::termios::{InputModes, LocalModes, OptionalActions, OutputModes};
655
656    #[cfg(any(
657        target_os = "linux",
658        target_os = "android",
659        target_os = "freebsd",
660        target_os = "netbsd"
661    ))]
662    let master =
663        rustix::pty::openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY | OpenptFlags::CLOEXEC)?;
664    #[cfg(not(any(
665        target_os = "linux",
666        target_os = "android",
667        target_os = "freebsd",
668        target_os = "netbsd"
669    )))]
670    let master = {
671        let master = rustix::pty::openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY)?;
672        rustix::io::fcntl_setfd(&master, rustix::io::FdFlags::CLOEXEC)?;
673        master
674    };
675    rustix::pty::grantpt(&master)?;
676    rustix::pty::unlockpt(&master)?;
677    let name = rustix::pty::ptsname(&master, Vec::new())?;
678    let slave = rustix::fs::open(
679        name.as_c_str(),
680        OFlags::RDWR | OFlags::NOCTTY | OFlags::CLOEXEC,
681        Mode::empty(),
682    )?;
683    let mut termios = rustix::termios::tcgetattr(&slave)?;
684    termios
685        .local_modes
686        .remove(LocalModes::ECHO | LocalModes::ECHONL | LocalModes::IEXTEN);
687    termios.input_modes.remove(InputModes::IXON);
688    termios.output_modes.remove(OutputModes::ONLCR);
689    rustix::termios::tcsetattr(&slave, OptionalActions::Now, &termios)?;
690    resize_pty(&master, cols, rows)?;
691
692    let output = PtyOutput(std::fs::File::from(master.try_clone()?));
693    let input = if stdin {
694        cmd.stdin(Stdio::from(slave.try_clone()?));
695        Some(std::fs::File::from(master.try_clone()?))
696    } else {
697        None
698    };
699    cmd.stdout(Stdio::from(slave.try_clone()?))
700        .stderr(Stdio::from(slave));
701    std::os::unix::process::CommandExt::setsid(cmd, true);
702    Ok(PtyEndpoints {
703        master,
704        output,
705        input,
706    })
707}
708
709#[cfg(unix)]
710fn resize_pty(master: impl std::os::fd::AsFd, cols: u16, rows: u16) -> io::Result<()> {
711    let size = rustix::termios::Winsize {
712        ws_row: rows,
713        ws_col: cols,
714        ws_xpixel: 0,
715        ws_ypixel: 0,
716    };
717    rustix::termios::tcsetwinsize(master, size).map_err(io::Error::from)
718}
719
720/// A new PTY's size: the host terminal's, from stdout then stdin, else 80x24.
721#[cfg(unix)]
722fn host_terminal_size() -> (u16, u16) {
723    [
724        rustix::termios::tcgetwinsize(io::stdout()),
725        rustix::termios::tcgetwinsize(io::stdin()),
726    ]
727    .into_iter()
728    .flatten()
729    .find(|size| size.ws_col > 0 && size.ws_row > 0)
730    .map_or((80, 24), |size| (size.ws_col, size.ws_row))
731}
732
733// Only the parent-owned endpoint becomes nonblocking. The child's opposite
734// endpoint remains blocking, including copies inherited by its descendants.
735#[cfg(unix)]
736fn process_pipe<P: std::os::fd::AsFd>(pipe: P, stop: StopSignal) -> io::Result<ProcessPipe<P>> {
737    rustix::io::ioctl_fionbio(&pipe, true)?;
738    Ok(ProcessPipe { pipe, stop })
739}
740
741#[cfg(unix)]
742struct ProcessPipe<P> {
743    pipe: P,
744    stop: StopSignal,
745}
746
747#[cfg(unix)]
748impl<P: std::os::fd::AsFd> ProcessPipe<P> {
749    fn wait_ready(&self, interest: rustix::event::PollFlags) -> io::Result<()> {
750        let mut fds = [rustix::event::PollFd::new(&self.pipe, interest)];
751        // Readiness wakes immediately for data/space/EOF. The finite timeout
752        // bounds cancellation latency even when a descendant holds the pipe.
753        let timeout = rustix::event::Timespec {
754            tv_sec: 0,
755            tv_nsec: 50_000_000,
756        };
757        match rustix::event::poll(&mut fds, Some(&timeout)) {
758            Ok(_) | Err(rustix::io::Errno::INTR) => Ok(()),
759            Err(error) => Err(error.into()),
760        }
761    }
762}
763
764#[cfg(unix)]
765impl<P: Read + std::os::fd::AsFd> Read for ProcessPipe<P> {
766    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
767        loop {
768            if self.stop.is_stopped() {
769                // read_process_line checks stop before retrying Interrupted.
770                return Err(io::Error::from(io::ErrorKind::Interrupted));
771            }
772            match self.pipe.read(buffer) {
773                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
774                    self.wait_ready(rustix::event::PollFlags::IN)?;
775                }
776                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
777                result => return result,
778            }
779        }
780    }
781}
782
783#[cfg(unix)]
784impl<P: Write + std::os::fd::AsFd> Write for ProcessPipe<P> {
785    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
786        loop {
787            if self.stop.is_stopped() {
788                // write_all retries Interrupted; cancellation must terminate
789                // that loop rather than spinning on a permanently stopped run.
790                return Err(io::Error::other("stdin write canceled before completion"));
791            }
792            match self.pipe.write(buffer) {
793                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
794                    self.wait_ready(rustix::event::PollFlags::OUT)?;
795                }
796                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
797                result => return result,
798            }
799        }
800    }
801
802    fn flush(&mut self) -> io::Result<()> {
803        self.pipe.flush()
804    }
805}
806
807/// A subscription that spawns and monitors an external process.
808///
809/// Captures stdout/stderr line-by-line and sends [`ProcessEvent`] messages.
810/// Termination is requested when the subscription's [`StopSignal`] fires or
811/// when the optional timeout expires. [`ProcessEvent::Killed`] requires a
812/// successful kill request and confirmed reaping (with SIGKILL status on Unix).
813/// Failed or unconfirmed cleanup produces [`ProcessEvent::Error`].
814///
815/// Normal exit waits for stdout/stderr forwarding to finish, including bounded
816/// channel backpressure. The timeout remains active during that drain. If the
817/// drain is canceled after the child exits, an error describes the exit and
818/// incomplete output. Cancellation can reject an unsent line, preview, or final
819/// status when the model queue is full; final-status delivery is not guaranteed.
820/// Each UTF-8 line is limited to [`MAX_PROCESS_LINE_BYTES`] payload bytes.
821/// LF and its immediately preceding CR are excluded from the limit. An
822/// unterminated final line is delivered at EOF (preserving any trailing CR).
823/// Opt-in [`partial_output`](Self::partial_output) also previews growing valid
824/// prefixes before the next read blocks. It does not change completed lines.
825/// Oversized lines, invalid UTF-8, and read failures stop forwarding, request
826/// termination of the immediate child, and produce one error instead of a
827/// normal exit. That error reports incomplete output and the cleanup outcome.
828/// Monitoring and input failures use the same cleanup path. After an accepted
829/// kill request, foreground reaping is limited to 500 ms; a rejected request
830/// never leads to a blocking foreground wait. If ownership remains safe, an
831/// unconfirmed child is handed to a background reaper. If that thread cannot
832/// start, the error says so; a later wait failure is logged and leaves restart
833/// disabled. Late reaping does not turn the earlier error into success. Linux
834/// retains a pidfd when available; after a wait error, targets without a
835/// retained process handle refuse further waits and signals for that PID.
836/// On Unix, parent pipe endpoints use nonblocking I/O and readiness waits;
837/// cancellation stops the workers even if descendants retain their endpoints.
838/// Other targets still use blocking pipes and bounded joins, so an inherited
839/// endpoint can keep a detached worker alive after cancellation.
840/// Input is closed by default; [`stdin`](Self::stdin) enables a bounded input
841/// worker. Over pipes, descendants are neither terminated nor reaped on any
842/// target. [`pty`](Self::pty) runs the child on a pseudo-terminal in its own
843/// session, and ends its whole process group with the run.
844/// Cancellation is not an atomic write boundary: a prefix may already have
845/// reached the child, and an I/O syscall can race with the stop request.
846/// Optional [`control`](Self::control) admits interrupts independently of those
847/// queues. Its generation belongs to one run. Restart only after that run's
848/// terminal event and confirmed child cleanup, using a fresh control handle.
849pub struct ProcessSubscription<M: Send + 'static> {
850    program: String,
851    args: Vec<String>,
852    env: Vec<(String, String)>,
853    timeout: Option<Duration>,
854    input: Option<ProcessInput>,
855    control: Option<ProcessControl>,
856    partial_output: bool,
857    pty: bool,
858    id: SubId,
859    explicit_id: bool,
860    make_msg: std::sync::Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>,
861}
862
863const PROCESS_READER_JOIN_TIMEOUT: Duration = Duration::from_millis(250);
864const PROCESS_READER_JOIN_POLL: Duration = Duration::from_millis(5);
865const PROCESS_REAP_TIMEOUT: Duration = Duration::from_millis(500);
866
867/// Maximum UTF-8 payload bytes in a process stdout/stderr line (64 KiB).
868///
869/// The LF or CRLF delimiter is excluded. Each reader's assembly buffer holds
870/// at most this many bytes plus one possible CR delimiter, alongside an 8 KiB
871/// input buffer and one in-flight line or preview of at most this many bytes.
872/// This does not bound allocations in the message conversion callback or model.
873pub const MAX_PROCESS_LINE_BYTES: usize = 64 * 1024;
874
875#[derive(Debug)]
876enum ProcessReadError {
877    LineTooLong,
878    InvalidUtf8(std::str::Utf8Error),
879    Io(io::Error),
880}
881
882impl std::fmt::Display for ProcessReadError {
883    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
884        match self {
885            Self::LineTooLong => write!(f, "line exceeds {MAX_PROCESS_LINE_BYTES} payload bytes"),
886            Self::InvalidUtf8(error) => write!(f, "invalid UTF-8: {error}"),
887            Self::Io(error) => write!(f, "read failed: {error}"),
888        }
889    }
890}
891
892#[cfg(test)]
893fn read_process_line<R: BufRead>(
894    reader: &mut R,
895    line: &mut Vec<u8>,
896    stop: &StopSignal,
897    preview: Option<&mut dyn FnMut(&str) -> bool>,
898) -> Result<Option<String>, ProcessReadError> {
899    read_process_line_mode(reader, line, stop, false, preview)
900}
901
902fn read_process_line_mode<R: BufRead>(
903    reader: &mut R,
904    line: &mut Vec<u8>,
905    stop: &StopSignal,
906    cr_rewinds: bool,
907    mut preview: Option<&mut dyn FnMut(&str) -> bool>,
908) -> Result<Option<String>, ProcessReadError> {
909    line.clear();
910    let mut previewed_bytes = 0;
911    loop {
912        if stop.is_stopped() {
913            return Ok(None);
914        }
915        let available = match reader.fill_buf() {
916            Ok(available) => available,
917            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
918            Err(error) => return Err(ProcessReadError::Io(error)),
919        };
920        if available.is_empty() {
921            if line.is_empty() {
922                return Ok(None);
923            }
924            break;
925        }
926        if cr_rewinds && line.last() == Some(&b'\r') {
927            match available[0] {
928                b'\r' => {
929                    let crs = available.iter().take_while(|&&byte| byte == b'\r').count();
930                    reader.consume(crs);
931                    continue;
932                }
933                b'\n' => {
934                    reader.consume(1);
935                    line.pop();
936                    break;
937                }
938                _ => {
939                    std::str::from_utf8(line).map_err(ProcessReadError::InvalidUtf8)?;
940                    line.clear();
941                    previewed_bytes = 0;
942                }
943            }
944        }
945        if cr_rewinds {
946            let stop_pos = available
947                .iter()
948                .position(|&byte| byte == b'\n' || byte == b'\r');
949            let count = stop_pos.unwrap_or(available.len());
950            let payload = &available[..count];
951            let total = line.len().saturating_add(count);
952            if total > MAX_PROCESS_LINE_BYTES {
953                return Err(ProcessReadError::LineTooLong);
954            }
955            line.extend_from_slice(payload);
956            match available.get(count) {
957                Some(&b'\n') => {
958                    reader.consume(count + 1);
959                    break;
960                }
961                Some(&b'\r') => {
962                    let crs = available[count..]
963                        .iter()
964                        .take_while(|&&byte| byte == b'\r')
965                        .count();
966                    line.push(b'\r');
967                    reader.consume(count + crs);
968                }
969                _ => {
970                    reader.consume(count);
971                }
972            }
973        } else {
974            let end = available.iter().position(|byte| *byte == b'\n');
975            let count = end.unwrap_or(available.len());
976            let payload = &available[..count];
977            let total = line.len().saturating_add(count);
978            // Retain one extra CR only while it could still be part of CRLF.
979            // Check before appending so allocation never follows untrusted length.
980            if total > MAX_PROCESS_LINE_BYTES
981                && (total != MAX_PROCESS_LINE_BYTES + 1
982                    || payload.last().or_else(|| line.last()) != Some(&b'\r'))
983            {
984                return Err(ProcessReadError::LineTooLong);
985            }
986            line.extend_from_slice(payload);
987            reader.consume(count + usize::from(end.is_some()));
988            if end.is_some() {
989                if line.last() == Some(&b'\r') {
990                    line.pop();
991                }
992                break;
993            }
994        }
995        if let Some(preview) = preview.as_mut() {
996            let prefix = match std::str::from_utf8(line) {
997                Ok(text) => text,
998                Err(error) if error.error_len().is_none() => {
999                    // Preserve an incomplete scalar for the next physical read.
1000                    std::str::from_utf8(&line[..error.valid_up_to()])
1001                        .map_err(ProcessReadError::InvalidUtf8)?
1002                }
1003                Err(error) => return Err(ProcessReadError::InvalidUtf8(error)),
1004            };
1005            // A final CR might be the first half of CRLF. Keep it in assembly
1006            // but do not expose it until another payload byte or EOF resolves it.
1007            let prefix = if line.last() == Some(&b'\r') {
1008                prefix.strip_suffix('\r').unwrap_or(prefix)
1009            } else {
1010                prefix
1011            };
1012            if prefix.len() > previewed_bytes {
1013                if !preview(prefix) {
1014                    return Ok(None);
1015                }
1016                previewed_bytes = prefix.len();
1017            }
1018        }
1019    }
1020    if line.len() > MAX_PROCESS_LINE_BYTES {
1021        return Err(ProcessReadError::LineTooLong);
1022    }
1023    let text = std::str::from_utf8(line).map_err(ProcessReadError::InvalidUtf8)?;
1024    // Copy only the payload; the reusable maximum-sized assembly buffer stays
1025    // with the reader instead of inflating every short queued message.
1026    Ok(Some(text.to_owned()))
1027}
1028
1029fn forward_lines<R: Read, M: Send + 'static>(
1030    reader: R,
1031    sender: SubscriptionSender<M>,
1032    stop: StopSignal,
1033    partial_output: bool,
1034    cr_rewinds: bool,
1035    make_msg: impl Fn(String) -> M,
1036    make_partial: impl Fn(String) -> M,
1037) -> Result<(), ProcessReadError> {
1038    let mut reader = io::BufReader::with_capacity(8 * 1024, reader);
1039    let mut line = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
1040    let mut preview = |prefix: &str| {
1041        if stop.is_stopped() {
1042            return false;
1043        }
1044        let message = make_partial(prefix.to_owned());
1045        !stop.is_stopped() && sender.send(message).is_ok()
1046    };
1047    while let Some(line) = read_process_line_mode(
1048        &mut reader,
1049        &mut line,
1050        &stop,
1051        cr_rewinds,
1052        partial_output.then_some(&mut preview as &mut dyn FnMut(&str) -> bool),
1053    )? {
1054        if stop.is_stopped() {
1055            break;
1056        }
1057        let message = make_msg(line);
1058        if stop.is_stopped() || sender.send(message).is_err() {
1059            break;
1060        }
1061    }
1062    Ok(())
1063}
1064
1065/// What every output reader of one run shares.
1066struct LineReaders<M: Send + 'static> {
1067    sender: SubscriptionSender<M>,
1068    stop: StopSignal,
1069    partial_output: bool,
1070    cr_rewinds: bool,
1071    make_msg: std::sync::Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>,
1072}
1073
1074impl<M: Send + 'static> LineReaders<M> {
1075    /// Forward `reader`'s lines and previews from a new thread.
1076    fn spawn<R: Read + ProcessEndpoint>(
1077        &self,
1078        reader: R,
1079        line_event: fn(String) -> ProcessEvent,
1080        partial_event: fn(String) -> ProcessEvent,
1081    ) -> std::thread::JoinHandle<Result<(), ProcessReadError>> {
1082        let sender = self.sender.clone();
1083        let stop = self.stop.clone();
1084        let partial_output = self.partial_output;
1085        let cr_rewinds = self.cr_rewinds;
1086        let make_msg = std::sync::Arc::clone(&self.make_msg);
1087        std::thread::spawn(move || {
1088            #[cfg(unix)]
1089            let reader = process_pipe(reader, stop.clone()).map_err(ProcessReadError::Io)?;
1090            forward_lines(
1091                reader,
1092                sender,
1093                stop,
1094                partial_output,
1095                cr_rewinds,
1096                |line| (make_msg.as_ref())(line_event(line)),
1097                |prefix| (make_msg.as_ref())(partial_event(prefix)),
1098            )
1099        })
1100    }
1101}
1102
1103fn take_reader_error<E: std::fmt::Display>(
1104    handle: &mut Option<std::thread::JoinHandle<Result<(), E>>>,
1105    stream: &str,
1106) -> Option<String> {
1107    if !handle
1108        .as_ref()
1109        .is_some_and(std::thread::JoinHandle::is_finished)
1110    {
1111        return None;
1112    }
1113    match handle.take()?.join() {
1114        Ok(Ok(())) => None,
1115        Ok(Err(error)) => Some(format!("{stream} {error}")),
1116        Err(_) => Some(format!("{stream} worker panicked")),
1117    }
1118}
1119
1120#[derive(Debug)]
1121struct ChildCleanup {
1122    status: Option<std::process::ExitStatus>,
1123    kill_sent: bool,
1124    detail: String,
1125}
1126
1127impl ChildCleanup {
1128    fn reaped(status: std::process::ExitStatus, kill_sent: bool, prior_error: &str) -> Self {
1129        Self {
1130            status: Some(status),
1131            kill_sent,
1132            detail: format!(
1133                "{prior_error}child reaped: {:?}",
1134                process_exit_event(status)
1135            ),
1136        }
1137    }
1138
1139    fn unconfirmed(detail: String) -> Self {
1140        Self {
1141            status: None,
1142            kill_sent: false,
1143            detail: format!("{detail}; child may still be running or unreaped"),
1144        }
1145    }
1146}
1147
1148fn reap_child_until(
1149    child: &mut std::process::Child,
1150    deadline: Instant,
1151    wait_error: &mut Option<String>,
1152) -> io::Result<Option<std::process::ExitStatus>> {
1153    loop {
1154        match try_wait_child(child, wait_error) {
1155            Ok(Some(status)) => return Ok(Some(status)),
1156            Ok(None) => {}
1157            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
1158            Err(error) => return Err(error),
1159        }
1160        let remaining = deadline.saturating_duration_since(Instant::now());
1161        if remaining.is_zero() {
1162            return Ok(None);
1163        }
1164        // A stopped cancellation token would return immediately and spin.
1165        std::thread::sleep(PROCESS_READER_JOIN_POLL.min(remaining));
1166    }
1167}
1168
1169fn has_retained_process_handle(child: &std::process::Child) -> bool {
1170    #[cfg(target_os = "linux")]
1171    {
1172        std::os::linux::process::ChildExt::pidfd(child).is_ok()
1173    }
1174    #[cfg(not(target_os = "linux"))]
1175    {
1176        let _ = child;
1177        // Windows retains a process handle; other Unix targets only retain a
1178        // PID, which must not be signaled after ownership becomes uncertain.
1179        cfg!(windows)
1180    }
1181}
1182
1183fn try_wait_child(
1184    child: &mut std::process::Child,
1185    wait_error: &mut Option<String>,
1186) -> io::Result<Option<std::process::ExitStatus>> {
1187    if let Some(error) = wait_error.as_ref()
1188        && !has_retained_process_handle(child)
1189    {
1190        // Ownership uncertainty is sticky. A later numeric-PID wait could
1191        // observe a different child that reused this PID, even without a kill.
1192        return Err(io::Error::other(error.clone()));
1193    }
1194    let result = child.try_wait();
1195    if let Err(error) = &result {
1196        wait_error.get_or_insert_with(|| error.to_string());
1197    }
1198    result
1199}
1200
1201/// [`try_wait_child`] for a run that may own its child's process group.
1202///
1203/// An exited leader of an unswept group is reaped only after the group is
1204/// swept, while its unreaped PID still reserves the group ID.
1205fn try_wait_leader(
1206    child: &mut std::process::Child,
1207    wait_error: &mut Option<String>,
1208    group: Option<&mut ProcessGroup>,
1209) -> io::Result<Option<std::process::ExitStatus>> {
1210    #[cfg(unix)]
1211    if let Some(group) = group
1212        && !group.is_swept()
1213    {
1214        match group.leader_exited() {
1215            Ok(false) => return Ok(None),
1216            Ok(true) => {
1217                if let Err(error) = group.kill()
1218                    && error.raw_os_error() != Some(rustix::io::Errno::SRCH.raw_os_error())
1219                {
1220                    tracing::warn!(%error, "process group sweep after leader exit failed");
1221                }
1222            }
1223            Err(error) => {
1224                wait_error.get_or_insert_with(|| error.to_string());
1225                return Err(error);
1226            }
1227        }
1228    }
1229    #[cfg(not(unix))]
1230    if let Some(group) = group {
1231        match *group {}
1232    }
1233    try_wait_child(child, wait_error)
1234}
1235
1236fn cleanup_child(
1237    child: &mut std::process::Child,
1238    wait_error: &mut Option<String>,
1239    mut group: Option<&mut ProcessGroup>,
1240) -> ChildCleanup {
1241    let prior_error = match try_wait_leader(child, wait_error, group.as_deref_mut()) {
1242        Ok(Some(status)) => return ChildCleanup::reaped(status, false, ""),
1243        Ok(None) => String::new(),
1244        Err(error) => {
1245            let context = format!("child wait failed: {error}; ");
1246            if !has_retained_process_handle(child) {
1247                return ChildCleanup::unconfirmed(format!(
1248                    "{context}kill and further waits not attempted without a retained process handle"
1249                ));
1250            }
1251            context
1252        }
1253    };
1254    // An owned group is killed whole; the leader is one of its members.
1255    let kill = match group {
1256        Some(group) if !group.is_swept() => group.kill(),
1257        _ => child.kill(),
1258    };
1259    if let Err(error) = kill {
1260        let context = format!("{prior_error}child kill failed: {error}; ");
1261        // An exit can race with kill. Observe it once; never block waiting for
1262        // a still-running child after the termination request was rejected.
1263        return match try_wait_child(child, wait_error) {
1264            Ok(Some(status)) => ChildCleanup::reaped(status, false, &context),
1265            Ok(None) => ChildCleanup::unconfirmed(format!("{context}child has not exited")),
1266            Err(error) => ChildCleanup::unconfirmed(format!("{context}reaping failed: {error}")),
1267        };
1268    }
1269    // This budget is independent of an already-expired subscription timeout.
1270    match reap_child_until(child, Instant::now() + PROCESS_REAP_TIMEOUT, wait_error) {
1271        Ok(Some(status)) => ChildCleanup::reaped(status, true, &prior_error),
1272        Ok(None) => ChildCleanup::unconfirmed(format!(
1273            "{prior_error}child kill accepted but reaping exceeded {} ms",
1274            PROCESS_REAP_TIMEOUT.as_millis()
1275        )),
1276        Err(error) => ChildCleanup::unconfirmed(format!(
1277            "{prior_error}child kill accepted but reaping failed: {error}"
1278        )),
1279    }
1280}
1281
1282fn cleanup_failure_event(error: &str, cleanup: &ChildCleanup) -> ProcessEvent {
1283    ProcessEvent::Error(format!(
1284        "{error}; {}; stdout/stderr output is incomplete",
1285        cleanup.detail
1286    ))
1287}
1288
1289fn output_failure_event(
1290    error: &str,
1291    child: &mut std::process::Child,
1292    wait_error: &mut Option<String>,
1293    group: Option<&mut ProcessGroup>,
1294) -> ProcessEvent {
1295    cleanup_failure_event(error, &cleanup_child(child, wait_error, group))
1296}
1297
1298fn stopped_process_event(
1299    reason: &str,
1300    child: &mut std::process::Child,
1301    wait_error: &mut Option<String>,
1302    group: Option<&mut ProcessGroup>,
1303) -> ProcessEvent {
1304    let cleanup = cleanup_child(child, wait_error, group);
1305    let terminated = cleanup.status.is_some_and(|status| {
1306        #[cfg(unix)]
1307        {
1308            use std::os::unix::process::ExitStatusExt;
1309            status.signal() == Some(rustix::process::Signal::KILL.as_raw())
1310        }
1311        #[cfg(not(unix))]
1312        {
1313            let _ = status;
1314            true
1315        }
1316    });
1317    if cleanup.kill_sent && terminated {
1318        ProcessEvent::Killed
1319    } else {
1320        cleanup_failure_event(reason, &cleanup)
1321    }
1322}
1323
1324fn reap_child_in_background(
1325    mut child: std::process::Child,
1326    control: Option<ProcessControl>,
1327    sub_id: SubId,
1328) -> io::Result<()> {
1329    std::thread::Builder::new()
1330        .name("ftui-process-reaper".to_owned())
1331        .spawn(move || match child.wait() {
1332            Ok(status) => {
1333                if let Some(control) = control {
1334                    control.confirm_reaped();
1335                }
1336                tracing::debug!(sub_id, ?status, "background child reaping completed");
1337            }
1338            Err(error) => {
1339                tracing::warn!(sub_id, %error, "background child reaping failed");
1340            }
1341        })
1342        .map(|_| ())
1343}
1344
1345impl<M: Send + 'static> ProcessSubscription<M> {
1346    fn computed_id(&self) -> SubId {
1347        let mut h = DefaultHasher::new();
1348        "ProcessSubscription".hash(&mut h);
1349        self.program.hash(&mut h);
1350        self.args.hash(&mut h);
1351        self.env.hash(&mut h);
1352        self.timeout
1353            .map(|duration| duration.as_nanos())
1354            .hash(&mut h);
1355        self.input.as_ref().map(|input| input.id).hash(&mut h);
1356        self.control
1357            .as_ref()
1358            .map(ProcessControl::generation)
1359            .hash(&mut h);
1360        self.partial_output.hash(&mut h);
1361        self.pty.hash(&mut h);
1362        h.finish()
1363    }
1364
1365    fn refresh_id(&mut self) {
1366        if !self.explicit_id {
1367            self.id = self.computed_id();
1368        }
1369    }
1370
1371    /// Create a new process subscription for the given program.
1372    ///
1373    /// The `make_msg` closure converts [`ProcessEvent`] into your model's
1374    /// message type.
1375    pub fn new(
1376        program: impl Into<String>,
1377        make_msg: impl Fn(ProcessEvent) -> M + Send + Sync + 'static,
1378    ) -> Self {
1379        let mut subscription = Self {
1380            program: program.into(),
1381            args: Vec::new(),
1382            env: Vec::new(),
1383            timeout: None,
1384            input: None,
1385            control: None,
1386            partial_output: false,
1387            pty: false,
1388            id: 0,
1389            explicit_id: false,
1390            make_msg: std::sync::Arc::new(make_msg),
1391        };
1392        subscription.refresh_id();
1393        subscription
1394    }
1395
1396    /// Add a command-line argument.
1397    #[must_use]
1398    pub fn arg(mut self, arg: impl Into<String>) -> Self {
1399        self.args.push(arg.into());
1400        self.refresh_id();
1401        self
1402    }
1403
1404    /// Add multiple command-line arguments.
1405    #[must_use]
1406    pub fn args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
1407        for a in args {
1408            self = self.arg(a);
1409        }
1410        self
1411    }
1412
1413    /// Set an environment variable for the child process.
1414    #[must_use]
1415    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
1416        self.env.push((key.into(), value.into()));
1417        self.refresh_id();
1418        self
1419    }
1420
1421    /// Set a timeout after which the process is killed.
1422    #[must_use]
1423    pub fn timeout(mut self, duration: Duration) -> Self {
1424        self.timeout = Some(duration);
1425        self.refresh_id();
1426        self
1427    }
1428
1429    /// Connect bounded input for this process run.
1430    ///
1431    /// Reuse clones of the same handle when rebuilding subscriptions. A new
1432    /// handle changes the automatic subscription ID. An already-used handle
1433    /// produces an error before spawning; use a new handle for a restart.
1434    #[must_use]
1435    pub fn stdin(mut self, input: ProcessInput) -> Self {
1436        self.input = Some(input);
1437        self.refresh_id();
1438        self
1439    }
1440
1441    /// Attach supervisor-owned interrupt control for this run.
1442    ///
1443    /// Clones preserve the automatic subscription ID. A fresh handle changes
1444    /// it, including when stdin is disabled. A used handle cannot spawn again.
1445    #[must_use]
1446    pub fn control(mut self, control: ProcessControl) -> Self {
1447        self.control = Some(control);
1448        self.refresh_id();
1449        self
1450    }
1451
1452    /// Preview pending stdout/stderr lines before LF or EOF (default: false).
1453    ///
1454    /// Each nonempty preview replaces the prior preview for that stream. It
1455    /// contains the original cumulative valid UTF-8 prefix, including controls;
1456    /// sanitize the whole prefix when rendering, rather than individual pieces.
1457    /// An incomplete UTF-8 scalar and one possible CRLF delimiter are retained
1458    /// until resolved. Completed [`ProcessEvent::Stdout`] and
1459    /// [`ProcessEvent::Stderr`] events remain unchanged, including trailing CR
1460    /// at EOF. Clear previews on completed lines and terminal events.
1461    ///
1462    /// Previews share the bounded, interruptible output queue and the 64 KiB
1463    /// line bound; they can be delayed by backpressure. Earlier prefixes may
1464    /// already be visible when a later read fails UTF-8 or size validation.
1465    /// This does not force an unflushed child to write or provide arbitrary
1466    /// binary streaming. Unix pipe cancellation is independent of this setting;
1467    /// other targets can still block in OS reads. Changing this setting changes
1468    /// the automatic subscription ID.
1469    #[must_use]
1470    pub fn partial_output(mut self, enabled: bool) -> Self {
1471        self.partial_output = enabled;
1472        self.refresh_id();
1473        self
1474    }
1475
1476    /// Run the child on a pseudo-terminal instead of pipes (Unix; default: false).
1477    ///
1478    /// The child's stdout and stderr are the PTY, so `isatty` holds and
1479    /// programs keep their terminal behavior: color, line-buffered output,
1480    /// progress lines. Both streams arrive as [`ProcessEvent::Stdout`] and
1481    /// [`ProcessEvent::StdoutPartial`], and standalone carriage returns (`\r`)
1482    /// rewind the active line so TTY progress updates replace the current
1483    /// preview rather than accumulating across frames. With
1484    /// [`stdin`](Self::stdin), stdin is the PTY as well, each line is written
1485    /// as typed input (chunked with canonical `VEOF` flushes so lines up to
1486    /// [`MAX_PROCESS_LINE_BYTES`] are not truncated by the kernel's 4095-byte
1487    /// canonical buffer), and closing input sends one end-of-file (Ctrl-D).
1488    /// Without it, stdin is `/dev/null`. Echo is off and LF is not translated
1489    /// to CRLF; a child may change that.
1490    ///
1491    /// The child leads a new session with no controlling terminal, so it
1492    /// cannot reach the host terminal through `/dev/tty`. Its process group
1493    /// belongs to the run: [`ProcessControl::request_interrupt`] sends SIGINT
1494    /// to the whole group, as Ctrl-C would. When the leader exits, and before
1495    /// it is reaped, every process left in the group receives SIGKILL, which
1496    /// also lets output reach end-of-file. Cancellation and timeout kill the
1497    /// group the same way. A descendant that starts its own session or group
1498    /// is not followed.
1499    ///
1500    /// The PTY starts at the size given by
1501    /// [`ProcessControl::request_resize`] before spawn, else at the host
1502    /// terminal's size (stdout, then stdin), else 80x24. Off Unix the run ends
1503    /// with [`ProcessEvent::Error`] before spawning. Changing this setting
1504    /// changes the automatic subscription ID.
1505    #[must_use]
1506    pub fn pty(mut self, enabled: bool) -> Self {
1507        self.pty = enabled;
1508        self.refresh_id();
1509        self
1510    }
1511
1512    /// Override the subscription ID (for explicit deduplication control).
1513    #[must_use]
1514    pub fn with_id(mut self, id: SubId) -> Self {
1515        self.id = id;
1516        self.explicit_id = true;
1517        self
1518    }
1519}
1520
1521impl<M: Send + 'static> Subscription<M> for ProcessSubscription<M> {
1522    fn id(&self) -> SubId {
1523        self.id
1524    }
1525
1526    fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal) {
1527        let spawn_start = web_time::Instant::now();
1528        let sub_id = self.id;
1529        let _control_guard = if let Some(control) = &self.control {
1530            let Some(guard) = control.claim() else {
1531                let _ = send_terminal_message(
1532                    &sender,
1533                    &stop,
1534                    self.timeout.map(|timeout| spawn_start + timeout),
1535                    (self.make_msg)(ProcessEvent::Error(
1536                        "control handle was already used; create fresh control for a new run"
1537                            .to_owned(),
1538                    )),
1539                );
1540                return;
1541            };
1542            Some(guard)
1543        } else {
1544            None
1545        };
1546        let input_run = if let Some(input) = &self.input {
1547            let Some(run) = input.claim() else {
1548                if let Some(control) = &self.control {
1549                    control.close();
1550                }
1551                let _ = send_terminal_message(
1552                    &sender,
1553                    &stop,
1554                    self.timeout.map(|timeout| spawn_start + timeout),
1555                    (self.make_msg)(ProcessEvent::Error(
1556                        "stdin handle was already used; create fresh input for a new run"
1557                            .to_owned(),
1558                    )),
1559                );
1560                return;
1561            };
1562            Some(run)
1563        } else {
1564            None
1565        };
1566        let (_input_guard, input_receiver) = input_run.unzip();
1567
1568        let fail_before_spawn = |detail: String| {
1569            if let Some(control) = &self.control {
1570                control.close();
1571            }
1572            if let Some(input) = &self.input {
1573                input.close();
1574            }
1575            tracing::warn!(
1576                target: crate::telemetry_schema::TARGET_PROCESS,
1577                sub_id,
1578                program = %self.program,
1579                error = %detail,
1580                "process spawn failed"
1581            );
1582            let _ = send_terminal_message(
1583                &sender,
1584                &stop,
1585                self.timeout.map(|timeout| spawn_start + timeout),
1586                (self.make_msg.as_ref())(ProcessEvent::Error(detail)),
1587            );
1588        };
1589
1590        let mut cmd = Command::new(&self.program);
1591        cmd.args(&self.args)
1592            .stdout(Stdio::piped())
1593            .stderr(Stdio::piped())
1594            .stdin(if input_receiver.is_some() {
1595                Stdio::piped()
1596            } else {
1597                Stdio::null()
1598            });
1599
1600        for (k, v) in &self.env {
1601            cmd.env(k, v);
1602        }
1603
1604        #[cfg(target_os = "linux")]
1605        {
1606            std::os::linux::process::CommandExt::create_pidfd(&mut cmd, true);
1607        }
1608
1609        #[cfg(unix)]
1610        let pty = if self.pty {
1611            let size = self
1612                .control
1613                .as_ref()
1614                .and_then(ProcessControl::take_resize)
1615                .unwrap_or_else(host_terminal_size);
1616            match prepare_pty(&mut cmd, size, input_receiver.is_some()) {
1617                Ok(pty) => Some(pty),
1618                Err(error) => {
1619                    fail_before_spawn(format!(
1620                        "Failed to open a PTY for '{}': {error}",
1621                        self.program
1622                    ));
1623                    return;
1624                }
1625            }
1626        } else {
1627            None
1628        };
1629        #[cfg(not(unix))]
1630        if self.pty {
1631            fail_before_spawn(format!(
1632                "Failed to spawn '{}': PTY mode requires Unix",
1633                self.program
1634            ));
1635            return;
1636        }
1637
1638        let spawned = cmd.spawn();
1639        // The parent's copies of a PTY slave must close, or the PTY could never
1640        // report end-of-file once the child's side is gone.
1641        drop(cmd);
1642        let mut child = match spawned {
1643            Ok(c) => {
1644                tracing::debug!(
1645                    target: crate::telemetry_schema::TARGET_PROCESS,
1646                    sub_id,
1647                    program = %self.program,
1648                    args = ?self.args,
1649                    pty = self.pty,
1650                    spawn_us = spawn_start.elapsed().as_micros() as u64,
1651                    "process spawned"
1652                );
1653                c
1654            }
1655            Err(e) => {
1656                fail_before_spawn(format!("Failed to spawn '{}': {}", self.program, e));
1657                return;
1658            }
1659        };
1660
1661        if let Some(control) = &self.control {
1662            control.started(child.id());
1663        }
1664
1665        // A PTY run reads, writes, and resizes through the master, and owns
1666        // the child's process group. A pipe run uses the child's own pipes.
1667        #[cfg(unix)]
1668        let (pty_master, pty_output, pty_input, mut group) = match pty {
1669            Some(PtyEndpoints {
1670                master,
1671                output,
1672                input,
1673            }) => (
1674                Some(master),
1675                Some(output),
1676                input,
1677                Some(ProcessGroup::new(&child)),
1678            ),
1679            None => (None, None, None, None),
1680        };
1681        #[cfg(not(unix))]
1682        let mut group: Option<ProcessGroup> = None;
1683
1684        let deadline = self.timeout.map(|t| web_time::Instant::now() + t);
1685        let make_msg_ref = std::sync::Arc::clone(&self.make_msg);
1686        // Use the cancellation token for cooperative stop coordination.
1687        let token = stop.cancellation_token().clone();
1688        let (reader_stop, reader_trigger) = StopSignal::new();
1689        let (input_stop, input_trigger) = StopSignal::new();
1690        let stop_input = || {
1691            if let Some(input) = &self.input {
1692                input.close();
1693            }
1694            input_trigger.stop();
1695        };
1696        let stop_process_io = || {
1697            if let Some(control) = &self.control {
1698                control.close();
1699            }
1700            reader_trigger.stop();
1701            stop_input();
1702        };
1703        let mut input_handle = input_receiver.and_then(|receiver| {
1704            #[cfg(unix)]
1705            if let Some(master) = pty_input {
1706                return Some(std::thread::spawn(move || {
1707                    write_process_input(master, receiver, input_stop, b"\x04")
1708                }));
1709            }
1710            child.stdin.take().map(|stdin| {
1711                std::thread::spawn(move || write_process_input(stdin, receiver, input_stop, b""))
1712            })
1713        });
1714        let readers = LineReaders {
1715            sender: sender.with_stop_signal(reader_stop.clone()),
1716            stop: reader_stop.clone(),
1717            partial_output: self.partial_output,
1718            cr_rewinds: self.pty,
1719            make_msg: std::sync::Arc::clone(&make_msg_ref),
1720        };
1721        let poll_interval = Duration::from_millis(50);
1722        #[cfg(unix)]
1723        let pty_stdout = pty_output
1724            .map(|output| readers.spawn(output, ProcessEvent::Stdout, ProcessEvent::StdoutPartial));
1725        #[cfg(not(unix))]
1726        let pty_stdout = None;
1727        let mut stdout_handle = pty_stdout.or_else(|| {
1728            child.stdout.take().map(|stdout| {
1729                readers.spawn(stdout, ProcessEvent::Stdout, ProcessEvent::StdoutPartial)
1730            })
1731        });
1732        let mut stderr_handle = child
1733            .stderr
1734            .take()
1735            .map(|stderr| readers.spawn(stderr, ProcessEvent::Stderr, ProcessEvent::StderrPartial));
1736
1737        let mut child_wait_error = None;
1738        let mut final_event = loop {
1739            // Reader results bypass the model queue: a full queue must never
1740            // prevent supervising a child whose other stream has failed.
1741            if let Some(error) = take_reader_error(&mut stdout_handle, "stdout")
1742                .or_else(|| take_reader_error(&mut stderr_handle, "stderr"))
1743                .or_else(|| take_reader_error(&mut input_handle, "stdin write failed"))
1744            {
1745                stop_process_io();
1746                break output_failure_event(
1747                    &error,
1748                    &mut child,
1749                    &mut child_wait_error,
1750                    group.as_mut(),
1751                );
1752            }
1753            match try_wait_leader(&mut child, &mut child_wait_error, group.as_mut()) {
1754                Ok(Some(status)) => {
1755                    let event = process_exit_event(status);
1756                    if let ProcessEvent::Exited(code) = &event {
1757                        tracing::debug!(
1758                            target: crate::telemetry_schema::TARGET_PROCESS,
1759                            sub_id,
1760                            exit_code = *code,
1761                            elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1762                            "process exited"
1763                        );
1764                    } else if let ProcessEvent::Signaled(signal) = &event {
1765                        tracing::debug!(
1766                            target: crate::telemetry_schema::TARGET_PROCESS,
1767                            sub_id,
1768                            signal = *signal,
1769                            elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1770                            "process terminated by signal"
1771                        );
1772                    }
1773                    break event;
1774                }
1775                Ok(None) => {}
1776                Err(e) => {
1777                    tracing::warn!(
1778                        target: crate::telemetry_schema::TARGET_PROCESS,
1779                        sub_id,
1780                        error = %e,
1781                        "process wait error"
1782                    );
1783                    stop_process_io();
1784                    break output_failure_event(
1785                        &format!("wait error: {e}"),
1786                        &mut child,
1787                        &mut child_wait_error,
1788                        group.as_mut(),
1789                    );
1790                }
1791            }
1792
1793            if let Some(dl) = deadline
1794                && web_time::Instant::now() >= dl
1795            {
1796                tracing::debug!(
1797                    target: crate::telemetry_schema::TARGET_PROCESS,
1798                    sub_id,
1799                    elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1800                    reason = "timeout",
1801                    "killing process"
1802                );
1803                // Keep the child's pipes open until termination is observed.
1804                // Closing a reader first can turn our kill into SIGPIPE while
1805                // the child is blocked writing to a full model queue.
1806                let event = stopped_process_event(
1807                    "process timed out",
1808                    &mut child,
1809                    &mut child_wait_error,
1810                    group.as_mut(),
1811                );
1812                stop_process_io();
1813                break event;
1814            }
1815
1816            if token.wait_timeout(poll_interval) {
1817                tracing::debug!(
1818                    target: crate::telemetry_schema::TARGET_PROCESS,
1819                    sub_id,
1820                    elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1821                    reason = "cancellation",
1822                    "killing process"
1823                );
1824                let event = stopped_process_event(
1825                    "process canceled",
1826                    &mut child,
1827                    &mut child_wait_error,
1828                    group.as_mut(),
1829                );
1830                stop_process_io();
1831                break event;
1832            }
1833            if let Some(control) = &self.control {
1834                control.dispatch_interrupt(&child, group.as_ref());
1835            }
1836            #[cfg(unix)]
1837            if let (Some(master), Some(group), Some(control)) = (&pty_master, &group, &self.control)
1838                && let Some((cols, rows)) = control.take_resize()
1839                && let Err(error) = resize_pty(master, cols, rows)
1840                    .and_then(|()| group.signal(rustix::process::Signal::WINCH))
1841            {
1842                tracing::debug!(
1843                    target: crate::telemetry_schema::TARGET_PROCESS,
1844                    sub_id,
1845                    cols,
1846                    rows,
1847                    %error,
1848                    "PTY resize was not applied"
1849                );
1850            }
1851        };
1852
1853        if let Some(control) = &self.control {
1854            control.close();
1855            // Closing admission is not proof of cleanup. Only an observed
1856            // reaped status permits a consumer to offer a safe restart.
1857            if matches!(
1858                try_wait_leader(&mut child, &mut child_wait_error, group.as_mut()),
1859                Ok(Some(_))
1860            ) {
1861                control.confirm_reaped();
1862            }
1863        }
1864        stop_input();
1865
1866        if matches!(
1867            final_event,
1868            ProcessEvent::Exited(_) | ProcessEvent::Signaled(_)
1869        ) {
1870            // A child can exit while its reader is waiting for model queue
1871            // capacity. Preserve every line on normal completion, however
1872            // slowly the model drains, while still honoring stop and timeout.
1873            loop {
1874                if let Some(error) = take_reader_error(&mut stdout_handle, "stdout")
1875                    .or_else(|| take_reader_error(&mut stderr_handle, "stderr"))
1876                    .or_else(|| take_reader_error(&mut input_handle, "stdin write failed"))
1877                {
1878                    reader_trigger.stop();
1879                    final_event = output_failure_event(
1880                        &error,
1881                        &mut child,
1882                        &mut child_wait_error,
1883                        group.as_mut(),
1884                    );
1885                    break;
1886                }
1887                if stdout_handle.is_none() && stderr_handle.is_none() {
1888                    break;
1889                }
1890                let interruption = if stop.is_stopped() {
1891                    Some("canceled")
1892                } else if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
1893                    Some("timed out")
1894                } else {
1895                    None
1896                };
1897                if let Some(reason) = interruption {
1898                    reader_trigger.stop();
1899                    final_event = ProcessEvent::Error(format!(
1900                        "output drain {reason} after {final_event:?}; stdout/stderr output is incomplete"
1901                    ));
1902                    break;
1903                }
1904                token.wait_timeout(PROCESS_READER_JOIN_POLL);
1905            }
1906        }
1907
1908        if let Some(handle) = stdout_handle {
1909            let _ = join_reader_thread_bounded(handle, "stdout", sub_id, &reader_trigger);
1910        }
1911        if let Some(handle) = stderr_handle {
1912            let _ = join_reader_thread_bounded(handle, "stderr", sub_id, &reader_trigger);
1913        }
1914        if let Some(handle) = input_handle
1915            && let Some(error) = join_reader_thread_bounded(handle, "stdin", sub_id, &input_trigger)
1916            && matches!(
1917                final_event,
1918                ProcessEvent::Exited(_) | ProcessEvent::Signaled(_)
1919            )
1920        {
1921            final_event =
1922                output_failure_event(&error, &mut child, &mut child_wait_error, group.as_mut());
1923        }
1924
1925        // Keep ownership when foreground cleanup could not confirm reaping.
1926        // A late wait can update restart eligibility, but the error already
1927        // observed by this run remains an error. Pipe runs do not manage
1928        // descendants; a PTY run sweeps its group before reaping the leader.
1929        match try_wait_leader(&mut child, &mut child_wait_error, group.as_mut()) {
1930            Ok(Some(_)) => {
1931                if let Some(control) = &self.control {
1932                    control.confirm_reaped();
1933                }
1934            }
1935            _ if child_wait_error.is_some() && !has_retained_process_handle(&child) => {
1936                tracing::warn!(
1937                    sub_id,
1938                    "further child waits refused: prior wait failed without a retained process handle"
1939                );
1940            }
1941            _ => {
1942                if let Err(error) = reap_child_in_background(child, self.control.clone(), sub_id) {
1943                    final_event = ProcessEvent::Error(format!(
1944                        "{final_event:?}; background reaper could not start: {error}; child may remain unreaped"
1945                    ));
1946                }
1947            }
1948        }
1949
1950        if send_terminal_message(
1951            &sender,
1952            &stop,
1953            deadline,
1954            (make_msg_ref.as_ref())(final_event),
1955        )
1956        .is_err()
1957        {
1958            tracing::warn!(
1959                target: crate::telemetry_schema::TARGET_PROCESS,
1960                sub_id,
1961                "process terminal event was not delivered: queue disconnected or stop/timeout interrupted backpressure"
1962            );
1963        }
1964    }
1965}
1966
1967fn send_terminal_message<M>(
1968    sender: &SubscriptionSender<M>,
1969    stop: &StopSignal,
1970    deadline: Option<Instant>,
1971    mut message: M,
1972) -> Result<(), mpsc::SendError<M>> {
1973    loop {
1974        // Preserve the sender's one immediate attempt after cancellation.
1975        match sender.try_send(message) {
1976            Ok(()) => return Ok(()),
1977            Err(mpsc::TrySendError::Disconnected(message)) => {
1978                return Err(mpsc::SendError(message));
1979            }
1980            Err(mpsc::TrySendError::Full(unsent)) => message = unsent,
1981        }
1982        if stop.is_stopped() || deadline.is_some_and(|deadline| Instant::now() >= deadline) {
1983            return Err(mpsc::SendError(message));
1984        }
1985        stop.wait_timeout(PROCESS_READER_JOIN_POLL);
1986    }
1987}
1988
1989fn process_exit_event(status: std::process::ExitStatus) -> ProcessEvent {
1990    #[cfg(unix)]
1991    {
1992        use std::os::unix::process::ExitStatusExt;
1993
1994        if let Some(signal) = status.signal() {
1995            return ProcessEvent::Signaled(signal);
1996        }
1997    }
1998
1999    ProcessEvent::Exited(status.code().unwrap_or(-1))
2000}
2001
2002fn join_reader_thread_bounded<E: std::fmt::Display + Send + 'static>(
2003    handle: std::thread::JoinHandle<Result<(), E>>,
2004    stream: &'static str,
2005    sub_id: SubId,
2006    reader_trigger: &StopTrigger,
2007) -> Option<String> {
2008    let start = Instant::now();
2009    while !handle.is_finished() {
2010        if start.elapsed() >= PROCESS_READER_JOIN_TIMEOUT {
2011            reader_trigger.stop();
2012            tracing::warn!(
2013                target: crate::telemetry_schema::TARGET_PROCESS,
2014                sub_id,
2015                stream,
2016                timeout_ms = PROCESS_READER_JOIN_TIMEOUT.as_millis() as u64,
2017                "process pipe worker did not exit within timeout; detaching"
2018            );
2019            detach_reader_join(handle, stream);
2020            return Some(format!(
2021                "{stream} worker did not stop; I/O may be incomplete"
2022            ));
2023        }
2024        std::thread::sleep(PROCESS_READER_JOIN_POLL);
2025    }
2026    match handle.join() {
2027        Ok(Ok(())) => None,
2028        Ok(Err(error)) => Some(format!("{stream} I/O failed: {error}")),
2029        Err(_) => Some(format!("{stream} worker panicked")),
2030    }
2031}
2032
2033fn detach_reader_join<E: Send + 'static>(
2034    handle: std::thread::JoinHandle<Result<(), E>>,
2035    stream: &'static str,
2036) {
2037    let _ = std::thread::Builder::new()
2038        .name(format!("ftui-process-{stream}-detached-join"))
2039        .spawn(move || {
2040            let _ = handle.join();
2041        });
2042}
2043
2044#[cfg(test)]
2045mod tests {
2046    use super::*;
2047    use std::sync::mpsc as stdmpsc;
2048    use std::thread;
2049
2050    #[derive(Debug, Clone, PartialEq)]
2051    enum TestMsg {
2052        Proc(ProcessEvent),
2053    }
2054
2055    #[cfg(unix)]
2056    fn spawn_cleanup_probe() -> (
2057        std::process::Child,
2058        std::process::ChildStdin,
2059        io::BufReader<std::process::ChildStdout>,
2060    ) {
2061        let script = "import signal,sys\nsignal.alarm(5)\nprint('READY',flush=True)\nline=sys.stdin.readline()\nprint('RELEASED '+line.removesuffix('\\n'),flush=True)\nraise SystemExit(67)";
2062        let mut command = Command::new("python3");
2063        command
2064            .args(["-u", "-c", script])
2065            .stdin(Stdio::piped())
2066            .stdout(Stdio::piped());
2067        #[cfg(target_os = "linux")]
2068        std::os::linux::process::CommandExt::create_pidfd(&mut command, true);
2069        let mut child = command.spawn().expect("spawn actual cleanup probe");
2070        #[cfg(target_os = "linux")]
2071        std::os::linux::process::ChildExt::pidfd(&child)
2072            .expect("cleanup probe requires retained PID ownership");
2073        // Hold stdin outside Child so a background Child::wait cannot turn the
2074        // test's pending child into a completed child by implicitly closing it.
2075        let stdin = child.stdin.take().unwrap();
2076        let mut output = io::BufReader::new(child.stdout.take().unwrap());
2077        let mut ready = String::new();
2078        output.read_line(&mut ready).unwrap();
2079        assert_eq!(ready, "READY\n");
2080        (child, stdin, output)
2081    }
2082
2083    #[test]
2084    #[cfg(unix)]
2085    fn cleanup_live_child_reports_killed_only_after_sigkill_reaping() {
2086        use std::os::unix::process::ExitStatusExt;
2087
2088        for reason in ["process canceled", "process timed out"] {
2089            let (mut child, _stdin, mut output) = spawn_cleanup_probe();
2090            let mut wait_error = None;
2091            let start = Instant::now();
2092            let event = stopped_process_event(reason, &mut child, &mut wait_error, None);
2093            let elapsed = start.elapsed();
2094            let observed = child.try_wait().unwrap();
2095            let mut tail = String::new();
2096            output.read_to_string(&mut tail).unwrap();
2097            assert_eq!(event, ProcessEvent::Killed);
2098            assert!(elapsed < Duration::from_secs(2) * ftui_core::cx::test_time_scale());
2099            assert_eq!(
2100                observed.unwrap().signal(),
2101                Some(rustix::process::Signal::KILL.as_raw())
2102            );
2103            assert!(tail.is_empty(), "the held input was never released");
2104        }
2105    }
2106
2107    #[test]
2108    #[cfg(unix)]
2109    fn cleanup_already_exited_child_retains_status_instead_of_reporting_killed() {
2110        let (mut child, mut stdin, mut output) = spawn_cleanup_probe();
2111        let mut wait_error = None;
2112        stdin.write_all(b"release\n").unwrap();
2113        drop(stdin);
2114        let mut tail = String::new();
2115        output.read_to_string(&mut tail).unwrap();
2116        let status = reap_child_until(
2117            &mut child,
2118            Instant::now() + Duration::from_secs(2),
2119            &mut wait_error,
2120        )
2121        .unwrap()
2122        .expect("actual natural exit");
2123        assert_eq!(tail, "RELEASED release\n");
2124        assert_eq!(status.code(), Some(67));
2125        let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2126        assert_eq!(cleanup.status.unwrap().code(), Some(67));
2127        assert!(!cleanup.kill_sent);
2128        assert_eq!(cleanup.detail, "child reaped: Exited(67)");
2129        assert_eq!(
2130            stopped_process_event("process canceled", &mut child, &mut wait_error, None),
2131            ProcessEvent::Error(
2132                "process canceled; child reaped: Exited(67); stdout/stderr output is incomplete"
2133                    .to_owned()
2134            )
2135        );
2136    }
2137
2138    #[test]
2139    #[cfg(unix)]
2140    fn cleanup_expired_reap_deadline_leaves_live_child_unconfirmed() {
2141        let (mut child, _stdin, _output) = spawn_cleanup_probe();
2142        let mut wait_error = None;
2143        let control = ProcessControl::new();
2144        let _guard = control.claim().unwrap();
2145        control.started(child.id());
2146        control.close();
2147        let start = Instant::now();
2148        let result = reap_child_until(&mut child, start, &mut wait_error);
2149        let elapsed = start.elapsed();
2150        let still_running = child.try_wait();
2151        let status_before_cleanup = control.status();
2152        // This exercises an explicitly expired helper deadline on a healthy
2153        // child, not an unkillable kernel task. Capture the refusal first;
2154        // the following explicit cleanup must not count as foreground proof.
2155        let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2156        assert!(matches!(result, Ok(None)));
2157        assert!(matches!(still_running, Ok(None)));
2158        assert!(elapsed < Duration::from_secs(1) * ftui_core::cx::test_time_scale());
2159        assert!(status_before_cleanup.closed);
2160        assert!(!status_before_cleanup.can_restart);
2161        assert!(cleanup.kill_sent);
2162        assert!(cleanup.status.is_some());
2163        assert!(!control.status().can_restart);
2164    }
2165
2166    #[test]
2167    #[cfg(unix)]
2168    fn cleanup_background_reaper_confirms_only_after_real_stdin_release() {
2169        let (child, mut stdin, mut output) = spawn_cleanup_probe();
2170        let pid = rustix::process::Pid::from_child(&child);
2171        let control = ProcessControl::new();
2172        let _guard = control.claim().unwrap();
2173        control.started(child.id());
2174        control.close();
2175        let start = Instant::now();
2176        reap_child_in_background(child, Some(control.clone()), 991).unwrap();
2177        assert!(start.elapsed() < Duration::from_secs(1));
2178        // The real child's read cannot finish while this test retains stdin.
2179        thread::sleep(Duration::from_millis(30));
2180        assert!(control.status().closed);
2181        assert!(!control.status().can_restart);
2182        stdin.write_all(b"release\n").unwrap();
2183        drop(stdin);
2184        let mut tail = String::new();
2185        output.read_to_string(&mut tail).unwrap();
2186        let deadline = Instant::now() + Duration::from_secs(2);
2187        while !control.status().can_restart && Instant::now() < deadline {
2188            thread::sleep(Duration::from_millis(5));
2189        }
2190        assert_eq!(tail, "RELEASED release\n");
2191        assert_eq!(
2192            control.status(),
2193            ProcessControlStatus {
2194                pid: None,
2195                closed: true,
2196                can_restart: true,
2197                interrupt: ProcessInterruptStatus::Idle,
2198            }
2199        );
2200        // Independently confirm that the reaper consumed the actual child's
2201        // exit status; an early can_restart update must not hide a zombie.
2202        let subsequent_wait =
2203            rustix::process::waitpid(Some(pid), rustix::process::WaitOptions::NOHANG);
2204        assert_eq!(subsequent_wait.unwrap_err(), rustix::io::Errno::CHILD);
2205        assert_eq!(
2206            control.request_interrupt(),
2207            Err(ProcessControlError::Closed)
2208        );
2209    }
2210
2211    #[test]
2212    #[cfg(target_os = "linux")]
2213    fn cleanup_externally_reaped_child_uses_retained_handle_without_false_killed() {
2214        use rustix::process::{Pid, WaitOptions, waitpid};
2215
2216        let (mut child, mut stdin, mut output) = spawn_cleanup_probe();
2217        let mut wait_error = None;
2218        let pid = Pid::from_child(&child);
2219        let control = ProcessControl::new();
2220        let _guard = control.claim().unwrap();
2221        control.started(child.id());
2222        control.close();
2223        stdin.write_all(b"release\n").unwrap();
2224        drop(stdin);
2225        let deadline = Instant::now() + Duration::from_secs(2);
2226        let externally_reaped = loop {
2227            match waitpid(Some(pid), WaitOptions::NOHANG) {
2228                Ok(Some(observed)) => break observed,
2229                Ok(None) if Instant::now() < deadline => {
2230                    thread::sleep(Duration::from_millis(5));
2231                }
2232                other => {
2233                    // Retained pidfd keeps this failure cleanup safe even if
2234                    // the exact child was reaped outside std::Child.
2235                    let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2236                    panic!("external exact-child wait failed: {other:?}; {cleanup:?}");
2237                }
2238            }
2239        };
2240        let mut tail = String::new();
2241        output.read_to_string(&mut tail).unwrap();
2242        assert_eq!(tail, "RELEASED release\n");
2243        assert_eq!(externally_reaped.0, pid);
2244        assert_eq!(externally_reaped.1.exit_status(), Some(67));
2245        assert!(has_retained_process_handle(&child));
2246        match try_wait_child(&mut child, &mut wait_error) {
2247            Ok(Some(status)) => {
2248                // Newer kernels let std recover the reaped child's status
2249                // through the retained pidfd. This is not ECHILD evidence.
2250                eprintln!("retained pidfd recovered exit67; ECHILD branch not exercised");
2251                assert_eq!(status.code(), Some(67));
2252                assert!(wait_error.is_none());
2253                let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2254                assert_eq!(cleanup.status.unwrap().code(), Some(67));
2255                assert!(!cleanup.kill_sent);
2256                assert_eq!(cleanup.detail, "child reaped: Exited(67)");
2257                assert_eq!(
2258                    stopped_process_event("process canceled", &mut child, &mut wait_error, None),
2259                    ProcessEvent::Error(
2260                        "process canceled; child reaped: Exited(67); stdout/stderr output is incomplete"
2261                            .to_owned()
2262                    )
2263                );
2264            }
2265            Err(error) => {
2266                eprintln!("retained pidfd could not recover exit67; checking actual ECHILD");
2267                assert_eq!(
2268                    error.raw_os_error(),
2269                    Some(rustix::io::Errno::CHILD.raw_os_error())
2270                );
2271                let error_text = error.to_string();
2272                assert_eq!(wait_error.as_deref(), Some(error_text.as_str()));
2273                let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2274                let kill_error =
2275                    io::Error::from_raw_os_error(rustix::io::Errno::SRCH.raw_os_error());
2276                let expected = format!(
2277                    "child wait failed: {error}; child kill failed: {kill_error}; reaping failed: {error}; child may still be running or unreaped"
2278                );
2279                assert!(cleanup.status.is_none());
2280                assert!(!cleanup.kill_sent);
2281                assert_eq!(cleanup.detail, expected);
2282                assert_eq!(
2283                    stopped_process_event("process canceled", &mut child, &mut wait_error, None),
2284                    ProcessEvent::Error(format!(
2285                        "process canceled; {expected}; stdout/stderr output is incomplete"
2286                    ))
2287                );
2288            }
2289            Ok(None) => panic!("the externally reaped child cannot still be running"),
2290        }
2291        assert!(!control.status().can_restart);
2292    }
2293
2294    #[test]
2295    #[cfg(target_os = "linux")]
2296    fn cleanup_sticky_wait_error_refuses_signal_and_repoll_without_retained_handle() {
2297        use rustix::process::{Pid, WaitOptions, waitpid};
2298
2299        let script = "import signal,sys\nsignal.alarm(5)\nprint('READY',flush=True)\nline=sys.stdin.readline()\nprint('RELEASED '+line.removesuffix('\\n'),flush=True)\nraise SystemExit(67)";
2300        let mut command = Command::new("python3");
2301        command
2302            .args(["-u", "-c", script])
2303            .stdin(Stdio::piped())
2304            .stdout(Stdio::piped());
2305        std::os::linux::process::CommandExt::create_pidfd(&mut command, false);
2306        let mut child = command
2307            .spawn()
2308            .expect("spawn actual no-pidfd cleanup probe");
2309        assert!(!has_retained_process_handle(&child));
2310        let pid = Pid::from_child(&child);
2311        let child_id = child.id();
2312        let mut stdin = child.stdin.take().unwrap();
2313        let mut output = io::BufReader::new(child.stdout.take().unwrap());
2314        let mut ready = String::new();
2315        output.read_line(&mut ready).unwrap();
2316        assert_eq!(ready, "READY\n");
2317        let control = ProcessControl::new();
2318        let _guard = control.claim().unwrap();
2319        control.started(child_id);
2320        control.close();
2321
2322        // Inject only the previously observed error state. The child remains
2323        // real and owned; this is not evidence of an actual OS wait failure.
2324        let saved_error = "injected prior wait failure";
2325        let mut wait_error = Some(saved_error.to_owned());
2326        let expected = format!(
2327            "child wait failed: {saved_error}; kill and further waits not attempted without a retained process handle; child may still be running or unreaped"
2328        );
2329        assert_eq!(
2330            try_wait_child(&mut child, &mut wait_error)
2331                .unwrap_err()
2332                .to_string(),
2333            saved_error
2334        );
2335        let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2336        assert!(cleanup.status.is_none());
2337        assert!(!cleanup.kill_sent);
2338        assert_eq!(cleanup.detail, expected);
2339        assert_eq!(
2340            stopped_process_event("process canceled", &mut child, &mut wait_error, None),
2341            ProcessEvent::Error(format!(
2342                "process canceled; {expected}; stdout/stderr output is incomplete"
2343            ))
2344        );
2345        assert!(!control.status().can_restart);
2346
2347        // Exact output after the refusal proves that cleanup did not signal
2348        // this live child. The test, not Child::wait, releases its stdin.
2349        stdin.write_all(b"release\n").unwrap();
2350        drop(stdin);
2351        let mut tail = String::new();
2352        output.read_to_string(&mut tail).unwrap();
2353        assert_eq!(tail, "RELEASED release\n");
2354        let deadline = Instant::now() + Duration::from_secs(2);
2355        loop {
2356            let status = std::fs::read_to_string(format!("/proc/{child_id}/status")).unwrap();
2357            if status.lines().any(|line| line.starts_with("State:\tZ")) {
2358                break;
2359            }
2360            assert!(Instant::now() < deadline, "actual child did not exit");
2361            thread::sleep(Duration::from_millis(5));
2362        }
2363        // The now-waitable child makes a forbidden re-poll observable: only
2364        // the independent exact-child wait below may consume its exit status.
2365        assert_eq!(
2366            reap_child_until(&mut child, Instant::now(), &mut wait_error)
2367                .unwrap_err()
2368                .to_string(),
2369            saved_error
2370        );
2371        let cleanup = cleanup_child(&mut child, &mut wait_error, None);
2372        assert!(cleanup.status.is_none());
2373        assert!(!cleanup.kill_sent);
2374        assert_eq!(cleanup.detail, expected);
2375        assert_eq!(wait_error.as_deref(), Some(saved_error));
2376        let reaped = waitpid(Some(pid), WaitOptions::NOHANG)
2377            .unwrap()
2378            .expect("sticky helpers must leave the exact child waitable");
2379        assert_eq!(reaped.0, pid);
2380        assert_eq!(reaped.1.exit_status(), Some(67));
2381        assert!(!control.status().can_restart);
2382        assert_eq!(
2383            control.request_interrupt(),
2384            Err(ProcessControlError::Closed)
2385        );
2386    }
2387
2388    #[test]
2389    fn control_generation_claim_and_descriptor_identity_are_single_run() {
2390        let control = ProcessControl::new();
2391        assert_eq!(control.generation(), control.clone().generation());
2392        assert_ne!(control.generation(), ProcessControl::new().generation());
2393        assert_eq!(
2394            control.status(),
2395            ProcessControlStatus {
2396                pid: None,
2397                closed: false,
2398                can_restart: true,
2399                interrupt: ProcessInterruptStatus::Idle,
2400            }
2401        );
2402        assert_eq!(
2403            control.request_interrupt(),
2404            Err(if cfg!(unix) {
2405                ProcessControlError::NotRunning
2406            } else {
2407                ProcessControlError::Unsupported
2408            })
2409        );
2410        let descriptor =
2411            || ProcessSubscription::new("child", |event| event).control(control.clone());
2412        let id = descriptor().id();
2413        assert_eq!(id, descriptor().id());
2414        assert_ne!(id, ProcessSubscription::new("child", |event| event).id());
2415        assert_ne!(
2416            id,
2417            ProcessSubscription::new("child", |event| event)
2418                .control(ProcessControl::new())
2419                .id()
2420        );
2421        assert_eq!(
2422            descriptor().with_id(71).control(ProcessControl::new()).id(),
2423            71
2424        );
2425        let guard = control.claim().expect("first claim");
2426        assert!(control.claim().is_none());
2427        drop(descriptor());
2428        assert!(
2429            !control.status().closed,
2430            "unused descriptors do not close the owner"
2431        );
2432        drop(guard);
2433        assert!(control.status().closed);
2434        assert!(control.status().can_restart, "no child was spawned");
2435        assert!(
2436            control.claim().is_none(),
2437            "closed generations cannot be reused"
2438        );
2439    }
2440
2441    #[test]
2442    #[cfg(unix)]
2443    fn control_pending_close_preserves_uncertain_cleanup_and_completed_outcomes() {
2444        // These are state-machine assertions, not evidence of child execution.
2445        let control = ProcessControl::new();
2446        let guard = control.claim().unwrap();
2447        control.started(123);
2448        assert!(!control.status().can_restart);
2449        assert_eq!(control.request_interrupt(), Ok(()));
2450        assert_eq!(
2451            control.request_interrupt(),
2452            Err(ProcessControlError::AlreadyPending)
2453        );
2454        drop(guard);
2455        assert_eq!(
2456            control.status(),
2457            ProcessControlStatus {
2458                pid: None,
2459                closed: true,
2460                can_restart: false,
2461                interrupt: ProcessInterruptStatus::Canceled,
2462            }
2463        );
2464        assert_eq!(
2465            control.request_interrupt(),
2466            Err(ProcessControlError::Closed)
2467        );
2468        control.confirm_reaped();
2469        assert!(control.status().can_restart);
2470        assert_eq!(control.status().interrupt, ProcessInterruptStatus::Canceled);
2471
2472        for outcome in [
2473            ProcessInterruptStatus::Sent,
2474            ProcessInterruptStatus::Failed("delivery failed".to_owned()),
2475        ] {
2476            let control = ProcessControl::new();
2477            let guard = control.claim().unwrap();
2478            control.started(123);
2479            control.state.lock().unwrap().status.interrupt = outcome.clone();
2480            drop(guard);
2481            assert_eq!(control.status().interrupt, outcome);
2482            assert!(!control.status().can_restart);
2483        }
2484    }
2485
2486    #[cfg(unix)]
2487    fn controlled_python(
2488        script: &str,
2489        control: &ProcessControl,
2490    ) -> ProcessSubscription<ProcessEvent> {
2491        ProcessSubscription::new("python3", |event| event)
2492            .args(["-u", "-c", script])
2493            .control(control.clone())
2494            .timeout(Duration::from_secs(5))
2495    }
2496
2497    #[test]
2498    #[cfg(unix)]
2499    fn real_control_interrupt_continues_stdin_and_duplicate_claim_keeps_owner() {
2500        let control = ProcessControl::new();
2501        let input = ProcessInput::new();
2502        let script = "import signal,sys\ncount=0\ndef interrupt(signum,frame):\n global count\n count+=1\n print('INT-ACK',flush=True)\n if count==2:\n  raise SystemExit(0)\nsignal.signal(signal.SIGINT,interrupt)\nprint('READY',flush=True)\nfor line in sys.stdin:\n print('reply='+line.removesuffix('\\n'),flush=True)\nprint('EOF',flush=True)\nwhile True:\n signal.pause()";
2503        let sub = controlled_python(script, &control).stdin(input.clone());
2504        let (sender, receiver) = mpsc::sync_channel(256);
2505        let (stop, trigger) = StopSignal::new();
2506        let handle = thread::spawn(move || {
2507            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2508        });
2509        assert_eq!(
2510            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
2511            ProcessEvent::Stdout("READY".to_owned())
2512        );
2513        let running = control.status();
2514        assert!(running.pid.is_some());
2515        assert!(!running.closed);
2516        assert!(!running.can_restart);
2517
2518        let duplicate = controlled_python("raise SystemExit(99)", &control);
2519        let (duplicate_sender, duplicate_receiver) = mpsc::sync_channel(1);
2520        let (duplicate_stop, _duplicate_trigger) = StopSignal::new();
2521        duplicate.run(
2522            SubscriptionSender::new(duplicate_sender, duplicate_stop.clone()),
2523            duplicate_stop,
2524        );
2525        assert_eq!(
2526            duplicate_receiver.into_iter().collect::<Vec<_>>(),
2527            [ProcessEvent::Error(
2528                "control handle was already used; create fresh control for a new run".to_owned()
2529            )]
2530        );
2531        assert_eq!(
2532            control.status(),
2533            running,
2534            "duplicate claim must not close its owner"
2535        );
2536
2537        control.request_interrupt().unwrap();
2538        assert_eq!(
2539            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
2540            ProcessEvent::Stdout("INT-ACK".to_owned())
2541        );
2542        let deadline = Instant::now() + Duration::from_secs(2);
2543        while control.status().interrupt == ProcessInterruptStatus::Pending
2544            && Instant::now() < deadline
2545        {
2546            thread::sleep(Duration::from_millis(5));
2547        }
2548        assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
2549        assert_eq!(control.status().pid, running.pid);
2550        input
2551            .try_send_line("still alive 🦀 $() \\".to_owned())
2552            .unwrap();
2553        assert_eq!(
2554            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
2555            ProcessEvent::Stdout("reply=still alive 🦀 $() \\".to_owned())
2556        );
2557        input.close();
2558        assert_eq!(
2559            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
2560            ProcessEvent::Stdout("EOF".to_owned())
2561        );
2562        assert_eq!(control.status().pid, running.pid, "EOF only closes stdin");
2563        assert!(!control.status().closed);
2564        control.request_interrupt().unwrap();
2565        let events: Vec<_> = (0..2)
2566            .map(|_| receiver.recv_timeout(Duration::from_secs(5)).unwrap())
2567            .collect();
2568        handle.join().unwrap();
2569        // All positive observations precede any test-requested stop.
2570        trigger.stop();
2571        assert_eq!(
2572            events,
2573            [
2574                ProcessEvent::Stdout("INT-ACK".to_owned()),
2575                ProcessEvent::Exited(0)
2576            ]
2577        );
2578        assert!(receiver.try_recv().is_err());
2579        assert_eq!(
2580            control.status(),
2581            ProcessControlStatus {
2582                pid: None,
2583                closed: true,
2584                can_restart: true,
2585                interrupt: ProcessInterruptStatus::Sent,
2586            }
2587        );
2588        assert_eq!(
2589            control.request_interrupt(),
2590            Err(ProcessControlError::Closed)
2591        );
2592    }
2593
2594    #[test]
2595    fn control_spawn_failure_closes_admission_without_claiming_a_child() {
2596        let control = ProcessControl::new();
2597        let sub =
2598            ProcessSubscription::new("/ftui-process-control-command-does-not-exist", |event| {
2599                event
2600            })
2601            .control(control.clone())
2602            .timeout(Duration::from_secs(2));
2603        let (sender, receiver) = mpsc::sync_channel(1);
2604        let (stop, _trigger) = StopSignal::new();
2605        sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2606        let events: Vec<_> = receiver.into_iter().collect();
2607        assert!(
2608            matches!(events.as_slice(), [ProcessEvent::Error(error)] if error.starts_with("Failed to spawn"))
2609        );
2610        assert_eq!(
2611            control.status(),
2612            ProcessControlStatus {
2613                pid: None,
2614                closed: true,
2615                can_restart: true,
2616                interrupt: ProcessInterruptStatus::Idle,
2617            }
2618        );
2619        assert!(control.claim().is_none());
2620    }
2621
2622    #[test]
2623    #[cfg(target_os = "linux")]
2624    fn control_interrupt_refuses_child_without_retained_pidfd() {
2625        let script = "import signal,sys\nsignal.alarm(5)\nprint('READY',flush=True)\nprint(sys.stdin.readline().removesuffix('\\n'),flush=True)";
2626        let mut command = Command::new("python3");
2627        command
2628            .args(["-u", "-c", script])
2629            .stdin(Stdio::piped())
2630            .stdout(Stdio::piped());
2631        std::os::linux::process::CommandExt::create_pidfd(&mut command, false);
2632        let mut child = command.spawn().unwrap();
2633        let mut output = io::BufReader::new(child.stdout.take().unwrap());
2634        let mut ready = String::new();
2635        output.read_line(&mut ready).unwrap();
2636        let result = interrupt_child(&child);
2637        let mut stdin = child.stdin.take().unwrap();
2638        let written = stdin.write_all(b"STILL-ALIVE\n");
2639        drop(stdin);
2640        let mut tail = String::new();
2641        let read = output.read_to_string(&mut tail);
2642        let status = child.wait().unwrap();
2643        // Refusal and the subsequent actual roundtrip are checked after natural
2644        // completion; no cleanup signal can manufacture successful survival.
2645        let error = result.unwrap_err();
2646        assert_eq!(error.kind(), io::ErrorKind::Unsupported);
2647        assert!(
2648            error
2649                .to_string()
2650                .starts_with("retained pidfd unavailable; interrupt not sent:")
2651        );
2652        assert_eq!(ready, "READY\n");
2653        written.unwrap();
2654        read.unwrap();
2655        assert_eq!(tail, "STILL-ALIVE\n");
2656        assert!(status.success());
2657    }
2658
2659    #[test]
2660    #[cfg(target_os = "linux")]
2661    fn real_control_interrupt_bypasses_full_output_and_blocked_input_queues() {
2662        let control = ProcessControl::new();
2663        let input = ProcessInput::new();
2664        let payload = "x".repeat(MAX_PROCESS_LINE_BYTES);
2665        for _ in 0..PROCESS_INPUT_CAPACITY {
2666            input.try_send_line(payload.clone()).unwrap();
2667        }
2668        let (observed_sender, observed_receiver) = mpsc::channel();
2669        let script = "import os,signal\ncount=0\ndef interrupt(signum,frame):\n global count\n count+=1\n if count==1:\n  os.write(2,b'INT-ACK\\n')\n else:\n  os._exit(73)\nsignal.signal(signal.SIGINT,interrupt)\nprint('READY '+str(os.getpid()),flush=True)\nfor index in range(257):\n print('out:'+str(index),flush=True)\nwhile True:\n signal.pause()";
2670        let sub = ProcessSubscription::new("python3", move |event| {
2671            // These observations precede model-channel admission. They prove
2672            // supervision while full, not delivery of the unaccepted suffix.
2673            if matches!(&event, ProcessEvent::Stdout(line) if line == "out:256")
2674                || matches!(&event, ProcessEvent::Stderr(line) if line == "INT-ACK")
2675                || matches!(&event, ProcessEvent::Error(_))
2676            {
2677                observed_sender.send(event.clone()).unwrap();
2678            }
2679            event
2680        })
2681        .args(["-u", "-c", script])
2682        .stdin(input.clone())
2683        .control(control.clone())
2684        .timeout(Duration::from_secs(5));
2685        let (sender, receiver) = mpsc::sync_channel(256);
2686        let (stop, trigger) = StopSignal::new();
2687        let handle = thread::spawn(move || {
2688            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2689        });
2690        let ProcessEvent::Stdout(ready) = receiver.recv_timeout(Duration::from_secs(5)).unwrap()
2691        else {
2692            panic!("missing actual child readiness");
2693        };
2694        let pid: u32 = ready.strip_prefix("READY ").unwrap().parse().unwrap();
2695        assert_eq!(
2696            observed_receiver
2697                .recv_timeout(Duration::from_secs(5))
2698                .unwrap(),
2699            ProcessEvent::Stdout("out:256".to_owned())
2700        );
2701        // The only stdout reader reached conversion of line 257 after putting
2702        // exactly 256 lines into the undrained channel. The child never reads
2703        // stdin; a maximum-sized write plus LF cannot finish in its pipe.
2704        let mut input_full = false;
2705        for _ in 0..PROCESS_INPUT_CAPACITY + 2 {
2706            match input.try_send_line(payload.clone()) {
2707                Ok(()) => {}
2708                Err(ProcessInputError::Full(line)) => {
2709                    assert_eq!(line, payload);
2710                    input_full = true;
2711                    break;
2712                }
2713                other => panic!("unexpected input admission: {other:?}"),
2714            }
2715        }
2716        assert!(input_full);
2717        let requested_at = Instant::now();
2718        control.request_interrupt().unwrap();
2719        assert_eq!(
2720            observed_receiver
2721                .recv_timeout(Duration::from_secs(2))
2722                .unwrap(),
2723            ProcessEvent::Stderr("INT-ACK".to_owned())
2724        );
2725        let deadline = Instant::now() + Duration::from_secs(2);
2726        while control.status().interrupt == ProcessInterruptStatus::Pending
2727            && Instant::now() < deadline
2728        {
2729            thread::sleep(Duration::from_millis(5));
2730        }
2731        assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
2732        // This is a distinct request after the first handler acknowledgment.
2733        control.request_interrupt().unwrap();
2734        let terminal = observed_receiver.recv_timeout(Duration::from_secs(2));
2735        let status_before_drain = control.status();
2736        let elapsed_before_drain = requested_at.elapsed();
2737        let reaped_before_drain = std::fs::metadata(format!("/proc/{pid}"))
2738            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
2739        // Release backpressure only after capturing the child and supervisor
2740        // observations. Cleanup cannot make those prior observations pass.
2741        let delivered: Vec<_> = receiver.into_iter().collect();
2742        handle.join().unwrap();
2743        trigger.stop();
2744        let terminal = terminal.unwrap();
2745        assert!(
2746            matches!(&terminal, ProcessEvent::Error(error)
2747                if error.starts_with("stdin write failed")
2748                    && error.contains("reaped:")
2749                    && error.contains("Exited(73)")),
2750            "pending stdin must report its actual SIGINT exit and incomplete I/O: {terminal:?}"
2751        );
2752        assert!(
2753            reaped_before_drain,
2754            "child still existed before model drain"
2755        );
2756        assert!(elapsed_before_drain < Duration::from_secs(2));
2757        assert_eq!(
2758            status_before_drain,
2759            ProcessControlStatus {
2760                pid: None,
2761                closed: true,
2762                can_restart: true,
2763                interrupt: ProcessInterruptStatus::Sent,
2764            }
2765        );
2766        let mut expected: Vec<_> = (0..256)
2767            .map(|index| ProcessEvent::Stdout(format!("out:{index}")))
2768            .collect();
2769        expected.push(terminal);
2770        assert_eq!(delivered, expected, "accepted FIFO prefix must survive");
2771        assert_eq!(
2772            control.request_interrupt(),
2773            Err(ProcessControlError::Closed)
2774        );
2775        assert_eq!(
2776            input.try_send_line("late".to_owned()),
2777            Err(ProcessInputError::Closed("late".to_owned()))
2778        );
2779    }
2780
2781    #[test]
2782    #[cfg(unix)]
2783    fn real_control_fresh_generation_restarts_after_terminal_without_stale_interrupts() {
2784        use crate::subscription::SubscriptionManager;
2785        let mut manager = SubscriptionManager::new();
2786        let script = "import signal\ndef interrupt(signum,frame):\n print('INT-EXIT',flush=True)\n raise SystemExit(37)\nsignal.signal(signal.SIGINT,interrupt)\nprint('READY',flush=True)\nwhile True:\n signal.pause()";
2787        let receive = |manager: &SubscriptionManager<(u64, ProcessEvent)>, count: usize| {
2788            let deadline = Instant::now() + Duration::from_secs(5);
2789            let mut events = Vec::new();
2790            while events.len() < count && Instant::now() < deadline {
2791                events.extend(manager.drain_messages());
2792                thread::sleep(Duration::from_millis(5));
2793            }
2794            events
2795        };
2796        let mut previous: Option<(ProcessControl, SubId)> = None;
2797        for _ in 0..2 {
2798            let control = ProcessControl::new();
2799            let generation = control.generation();
2800            let descriptor = || {
2801                ProcessSubscription::new("python3", move |event| (generation, event))
2802                    .args(["-u", "-c", script])
2803                    .control(control.clone())
2804                    .timeout(Duration::from_secs(5))
2805            };
2806            let id = descriptor().id();
2807            if let Some((old, old_id)) = &previous {
2808                assert_ne!(old.generation(), generation);
2809                assert_ne!(*old_id, id);
2810            }
2811            // There is deliberately no intermediate reconcile([]): the fresh
2812            // generation must replace the finished, still-registered old ID.
2813            manager.reconcile(vec![Box::new(descriptor())]);
2814            assert_eq!(
2815                receive(&manager, 1),
2816                [(generation, ProcessEvent::Stdout("READY".to_owned()))]
2817            );
2818            let running = control.status();
2819            if let Some((old, _)) = &previous {
2820                assert_eq!(old.request_interrupt(), Err(ProcessControlError::Closed));
2821                assert_eq!(old.request_interrupt(), Err(ProcessControlError::Closed));
2822                assert_eq!(control.status(), running);
2823            }
2824            manager.reconcile(vec![Box::new(descriptor())]);
2825            assert_eq!(manager.active_count(), 1);
2826            assert_eq!(control.status(), running);
2827            control.request_interrupt().unwrap();
2828            assert_eq!(
2829                receive(&manager, 2),
2830                [
2831                    (generation, ProcessEvent::Stdout("INT-EXIT".to_owned())),
2832                    (generation, ProcessEvent::Exited(37)),
2833                ]
2834            );
2835            assert!(control.status().closed);
2836            assert!(control.status().can_restart);
2837            assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
2838            assert!(manager.drain_messages().is_empty());
2839            previous = Some((control, id));
2840        }
2841        manager.stop_all();
2842    }
2843
2844    #[test]
2845    fn input_admission_bounds_payload_and_returns_rejected_text() {
2846        let input = ProcessInput::new();
2847        let mut overallocated = String::with_capacity(MAX_PROCESS_LINE_BYTES * 8);
2848        overallocated.push_str("tiny");
2849        input.try_send_line(overallocated).unwrap();
2850        for index in 1..PROCESS_INPUT_CAPACITY {
2851            input.try_send_line(index.to_string()).unwrap();
2852        }
2853        assert_eq!(
2854            input.try_send_line("retry 🦀".to_owned()),
2855            Err(ProcessInputError::Full("retry 🦀".to_owned()))
2856        );
2857        let oversized = "x".repeat(MAX_PROCESS_LINE_BYTES + 1);
2858        assert_eq!(
2859            input.try_send_line(oversized.clone()),
2860            Err(ProcessInputError::TooLong(oversized))
2861        );
2862        input.clone().close();
2863        assert_eq!(
2864            input.try_send_line("closed".to_owned()),
2865            Err(ProcessInputError::Closed("closed".to_owned()))
2866        );
2867        let (_guard, receiver) = input.claim().expect("close still permits first run");
2868        assert_eq!(receiver.recv().unwrap().into_string().capacity(), 4);
2869        for index in 1..PROCESS_INPUT_CAPACITY {
2870            assert_eq!(&*receiver.recv().unwrap(), index.to_string());
2871        }
2872        assert!(matches!(receiver.recv(), Err(mpsc::RecvError)));
2873        assert!(input.claim().is_none());
2874    }
2875
2876    #[test]
2877    fn input_identity_and_claim_ownership_survive_descriptor_rebuilds() {
2878        let input = ProcessInput::new();
2879        let sub = || ProcessSubscription::new("sh", |event| event).stdin(input.clone());
2880        let id = sub().id();
2881        assert_eq!(
2882            sub().with_id(7).arg("one").stdin(ProcessInput::new()).id(),
2883            7
2884        );
2885        assert_eq!(id, sub().id());
2886        assert_ne!(id, ProcessSubscription::new("sh", |event| event).id());
2887        assert_ne!(
2888            id,
2889            ProcessSubscription::new("sh", |event| event)
2890                .stdin(ProcessInput::new())
2891                .id()
2892        );
2893        let (guard, receiver) = input.claim().unwrap();
2894        assert!(input.claim().is_none());
2895        drop(sub());
2896        input.try_send_line("still open".to_owned()).unwrap();
2897        assert_eq!(&*receiver.recv().unwrap(), "still open");
2898        drop(guard);
2899        assert_eq!(
2900            input.try_send_line("late".to_owned()),
2901            Err(ProcessInputError::Closed("late".to_owned()))
2902        );
2903    }
2904
2905    #[cfg(unix)]
2906    fn input_process(script: &str, input: &ProcessInput) -> ProcessSubscription<ProcessEvent> {
2907        ProcessSubscription::new("sh", |event| event)
2908            .args(["-c", script])
2909            .stdin(input.clone())
2910            .timeout(Duration::from_secs(5))
2911    }
2912
2913    #[test]
2914    #[cfg(unix)]
2915    fn real_input_roundtrip_eof_and_fresh_run_survive_reconciliation() {
2916        use crate::subscription::SubscriptionManager;
2917        let mut manager = SubscriptionManager::new();
2918        let script = "printf 'pid=%s\\n' \"$$\"; while IFS= read -r line; do printf '%s\\n' \"$line\"; done; printf 'EOF\\n'";
2919        let receive = |manager: &SubscriptionManager<ProcessEvent>, count: usize| {
2920            let deadline = Instant::now() + Duration::from_secs(5);
2921            let mut events = Vec::new();
2922            while events.len() < count && Instant::now() < deadline {
2923                events.extend(manager.drain_messages());
2924                thread::sleep(Duration::from_millis(5));
2925            }
2926            events
2927        };
2928        let mut previous_id = None;
2929        for _ in 0..2 {
2930            let input = ProcessInput::new();
2931            let id = input_process(script, &input).id();
2932            assert_ne!(previous_id, Some(id));
2933            previous_id = Some(id);
2934            manager.reconcile(vec![Box::new(input_process(script, &input))]);
2935            let started = receive(&manager, 1);
2936            assert!(
2937                matches!(started.as_slice(), [ProcessEvent::Stdout(line)] if line.starts_with("pid="))
2938            );
2939            for (text, expected) in [
2940                ("alpha", vec!["alpha"]),
2941                ("🦀 $() \\ literal", vec!["🦀 $() \\ literal"]),
2942                ("", vec![""]),
2943                ("embedded\nline", vec!["embedded", "line"]),
2944            ] {
2945                manager.reconcile(vec![Box::new(input_process(script, &input))]);
2946                input.try_send_line(text.to_owned()).unwrap();
2947                let expected: Vec<_> = expected
2948                    .into_iter()
2949                    .map(|line| ProcessEvent::Stdout(line.to_owned()))
2950                    .collect();
2951                assert_eq!(receive(&manager, expected.len()), expected);
2952            }
2953            input.close();
2954            assert_eq!(
2955                receive(&manager, 2),
2956                [
2957                    ProcessEvent::Stdout("EOF".to_owned()),
2958                    ProcessEvent::Exited(0)
2959                ]
2960            );
2961            assert_eq!(
2962                input.try_send_line("after EOF".to_owned()),
2963                Err(ProcessInputError::Closed("after EOF".to_owned()))
2964            );
2965            assert!(manager.drain_messages().is_empty());
2966        }
2967        manager.stop_all();
2968    }
2969
2970    #[test]
2971    #[cfg(unix)]
2972    fn real_input_drains_full_queue_and_maximum_line_before_eof() {
2973        let input = ProcessInput::new();
2974        let mut expected = Vec::new();
2975        for index in 0..PROCESS_INPUT_CAPACITY {
2976            let line = if index == 0 {
2977                "x".repeat(MAX_PROCESS_LINE_BYTES)
2978            } else {
2979                index.to_string()
2980            };
2981            input.try_send_line(line.clone()).unwrap();
2982            expected.push(ProcessEvent::Stdout(line));
2983        }
2984        assert_eq!(
2985            input.try_send_line("overflow".to_owned()),
2986            Err(ProcessInputError::Full("overflow".to_owned()))
2987        );
2988        input.close();
2989        let sub = input_process("cat", &input);
2990        let (sender, receiver) = mpsc::sync_channel(256);
2991        let (stop, _trigger) = StopSignal::new();
2992        sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2993        expected.push(ProcessEvent::Exited(0));
2994        assert_eq!(receiver.into_iter().collect::<Vec<_>>(), expected);
2995    }
2996
2997    #[test]
2998    #[cfg(unix)]
2999    fn real_input_natural_exit_and_spawn_failure_close_open_ingress() {
3000        for program in ["sh", "/ftui-process-input-command-does-not-exist"] {
3001            let input = ProcessInput::new();
3002            let sub = ProcessSubscription::new(program, |event| event)
3003                .args(["-c", "exit 0"])
3004                .stdin(input.clone())
3005                .timeout(Duration::from_secs(5));
3006            let (sender, receiver) = mpsc::sync_channel(256);
3007            let (stop, _trigger) = StopSignal::new();
3008            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3009            let events: Vec<_> = receiver.into_iter().collect();
3010            if program == "sh" {
3011                assert_eq!(events, [ProcessEvent::Exited(0)]);
3012            } else {
3013                assert!(
3014                    matches!(events.as_slice(), [ProcessEvent::Error(error)] if error.starts_with("Failed to spawn"))
3015                );
3016            }
3017            assert_eq!(
3018                input.try_send_line("late".to_owned()),
3019                Err(ProcessInputError::Closed("late".to_owned()))
3020            );
3021        }
3022    }
3023
3024    #[test]
3025    #[cfg(unix)]
3026    fn input_writer_reports_canceled_pending_line_instead_of_success() {
3027        let input = ProcessInput::new();
3028        input.try_send_line("pending".to_owned()).unwrap();
3029        let (_guard, receiver) = input.claim().unwrap();
3030        let mut child = Command::new("sh")
3031            .args(["-c", "exec sleep 60"])
3032            .stdin(Stdio::piped())
3033            .spawn()
3034            .unwrap();
3035        let (stop, trigger) = StopSignal::new();
3036        trigger.stop();
3037        let result = write_process_input(child.stdin.take().unwrap(), receiver, stop, b"");
3038        child.kill().unwrap();
3039        child.wait().unwrap();
3040        assert_eq!(
3041            result.unwrap_err().to_string(),
3042            "queued stdin was canceled before writing"
3043        );
3044    }
3045
3046    #[test]
3047    #[cfg(target_os = "linux")]
3048    fn real_input_blocked_pipe_does_not_block_admission_or_stop() {
3049        let input = ProcessInput::new();
3050        let sub = input_process("printf '%s\\n' \"$$\"; exec sleep 60", &input);
3051        let (sender, receiver) = mpsc::sync_channel(256);
3052        let (stop, trigger) = StopSignal::new();
3053        let handle =
3054            thread::spawn(move || sub.run(SubscriptionSender::new(sender, stop.clone()), stop));
3055        let ProcessEvent::Stdout(pid) = receiver.recv_timeout(Duration::from_secs(5)).unwrap()
3056        else {
3057            panic!("missing live child PID")
3058        };
3059        let pid: u32 = pid.parse().unwrap();
3060        let payload = "x".repeat(MAX_PROCESS_LINE_BYTES);
3061        let started = Instant::now();
3062        let mut full = false;
3063        for _ in 0..PROCESS_INPUT_CAPACITY + 2 {
3064            match input.try_send_line(payload.clone()) {
3065                Ok(()) => {}
3066                Err(ProcessInputError::Full(unsent)) => {
3067                    assert_eq!(unsent, payload);
3068                    full = true;
3069                    break;
3070                }
3071                other => panic!("unexpected admission: {other:?}"),
3072            }
3073        }
3074        let admission_elapsed = started.elapsed();
3075        // Give the worker time to enter a write exceeding the pipe capacity.
3076        thread::sleep(Duration::from_millis(100));
3077        let retry = input.try_send_line(payload);
3078        let before_stop = Instant::now();
3079        trigger.stop();
3080        handle.join().unwrap();
3081        let stopped_in = before_stop.elapsed();
3082        let reaped = std::fs::metadata(format!("/proc/{pid}"))
3083            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
3084        assert!(full);
3085        assert!(admission_elapsed < Duration::from_secs(1) * ftui_core::cx::test_time_scale());
3086        // One line can move from the queue to the blocked worker after Full.
3087        assert!(matches!(retry, Ok(()) | Err(ProcessInputError::Full(_))));
3088        assert!(stopped_in < Duration::from_secs(2) * ftui_core::cx::test_time_scale());
3089        assert!(reaped, "child must be reaped before test cleanup");
3090        assert_eq!(
3091            input.try_send_line("late".to_owned()),
3092            Err(ProcessInputError::Closed("late".to_owned()))
3093        );
3094        assert_eq!(
3095            receiver.into_iter().collect::<Vec<_>>(),
3096            [ProcessEvent::Killed]
3097        );
3098    }
3099
3100    #[cfg(target_os = "linux")]
3101    fn await_pipe_wait(task: &std::path::Path) {
3102        let deadline = Instant::now() + Duration::from_secs(3);
3103        loop {
3104            let state = std::fs::read_to_string(task.join("wchan")).unwrap();
3105            // Observe an actual kernel pipe/readiness wait before cancellation.
3106            // The blocking implementation reaches pipe_read/pipe_write; the
3107            // interruptible implementation reaches poll_schedule_timeout.
3108            if state.contains("poll") || state.contains("pipe_read") || state.contains("pipe_write")
3109            {
3110                return;
3111            }
3112            assert!(
3113                Instant::now() < deadline,
3114                "worker never waited on its pipe: {state}"
3115            );
3116            thread::sleep(Duration::from_millis(5));
3117        }
3118    }
3119
3120    #[test]
3121    #[cfg(target_os = "linux")]
3122    fn real_output_workers_cancel_while_child_keeps_both_pipes_open() {
3123        // Seed the original blocking-pipe defect as a live negative control;
3124        // the same observer must reject completion before fixture cleanup.
3125        assert_output_worker_lifetime(false);
3126        assert_output_worker_lifetime(true);
3127    }
3128
3129    #[cfg(target_os = "linux")]
3130    fn assert_output_worker_lifetime(nonblocking: bool) {
3131        let script = "import os,signal\nsignal.alarm(8)\nassert os.read(0,1)==b'R'\nassert all(os.get_blocking(fd) for fd in (0,1,2))\nos.write(1,b'out-prefix')\nos.write(2,b'err-prefix')\nsignal.pause()";
3132        let mut child = Command::new("python3")
3133            .args(["-u", "-c", script])
3134            .stdin(Stdio::piped())
3135            .stdout(Stdio::piped())
3136            .stderr(Stdio::piped())
3137            .spawn()
3138            .unwrap();
3139        let stdout = child.stdout.take().unwrap();
3140        let stderr = child.stderr.take().unwrap();
3141        let (stop, trigger) = StopSignal::new();
3142        let (sender, receiver) = mpsc::sync_channel(8);
3143        let (task_sender, task_receiver) = mpsc::channel();
3144        let start_worker = |pipe: Box<dyn ReadPipe>, stream: &'static str| {
3145            let stop = stop.clone();
3146            let sender = sender.clone();
3147            let task_sender = task_sender.clone();
3148            thread::spawn(move || {
3149                let pipe = process_pipe(pipe, stop.clone()).map_err(ProcessReadError::Io)?;
3150                if !nonblocking {
3151                    rustix::io::ioctl_fionbio(&pipe.pipe, false)
3152                        .map_err(|error| ProcessReadError::Io(error.into()))?;
3153                }
3154                task_sender
3155                    .send(std::fs::read_link("/proc/thread-self").unwrap())
3156                    .unwrap();
3157                forward_lines(
3158                    pipe,
3159                    SubscriptionSender::new(sender, stop.clone()),
3160                    stop,
3161                    true,
3162                    false,
3163                    |line| format!("{stream}:line:{line}"),
3164                    |prefix| format!("{stream}:partial:{prefix}"),
3165                )
3166            })
3167        };
3168        let stdout_worker = start_worker(Box::new(stdout), "out");
3169        let stderr_worker = start_worker(Box::new(stderr), "err");
3170        let tasks = [task_receiver.recv().unwrap(), task_receiver.recv().unwrap()];
3171        child.stdin.as_mut().unwrap().write_all(b"R").unwrap();
3172        let mut previews = [
3173            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
3174            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
3175        ];
3176        previews.sort();
3177        assert_eq!(
3178            previews,
3179            ["err:partial:err-prefix", "out:partial:out-prefix"]
3180        );
3181        for task in tasks {
3182            await_pipe_wait(&std::path::Path::new("/proc").join(task));
3183        }
3184        trigger.stop();
3185        let deadline = Instant::now() + Duration::from_secs(2);
3186        while !(stdout_worker.is_finished() && stderr_worker.is_finished())
3187            && Instant::now() < deadline
3188        {
3189            thread::sleep(Duration::from_millis(5));
3190        }
3191        let workers_finished_before_cleanup =
3192            stdout_worker.is_finished() && stderr_worker.is_finished();
3193        let child_alive_before_cleanup = child.try_wait().unwrap().is_none();
3194        child.kill().unwrap();
3195        child.wait().unwrap();
3196        stdout_worker.join().unwrap().unwrap();
3197        stderr_worker.join().unwrap().unwrap();
3198        assert_eq!(
3199            workers_finished_before_cleanup, nonblocking,
3200            "only nonblocking workers should finish before peer cleanup"
3201        );
3202        assert!(child_alive_before_cleanup);
3203        assert!(
3204            receiver.try_iter().next().is_none(),
3205            "cancellation must not complete the pending prefixes as EOF lines"
3206        );
3207    }
3208
3209    #[cfg(target_os = "linux")]
3210    trait ReadPipe: Read + std::os::fd::AsFd + Send {}
3211
3212    #[cfg(target_os = "linux")]
3213    impl<P: Read + std::os::fd::AsFd + Send> ReadPipe for P {}
3214
3215    #[test]
3216    #[cfg(target_os = "linux")]
3217    fn real_input_worker_cancels_full_pipe_and_closes_it_before_child_exits() {
3218        use std::os::unix::process::ChildExt;
3219
3220        let script = "import fcntl,os,signal,sys,time\nsignal.alarm(8)\nfcntl.fcntl(0,fcntl.F_SETPIPE_SZ,4096)\nready=False\ndef release(*args):\n global ready\n ready=True\nsignal.signal(signal.SIGUSR1,release)\nprint('READY',flush=True)\nwhile not ready:\n time.sleep(0.005)\ndata=sys.stdin.buffer.read()\nprint(str(len(data))+':'+str(data==b'x'*len(data))+':'+str(os.get_blocking(0)),flush=True)";
3221        let mut child = Command::new("python3")
3222            .args(["-u", "-c", script])
3223            .stdin(Stdio::piped())
3224            .stdout(Stdio::piped())
3225            .spawn()
3226            .unwrap();
3227        let mut stdout = io::BufReader::new(child.stdout.take().unwrap());
3228        let mut ready = String::new();
3229        stdout.read_line(&mut ready).unwrap();
3230        assert_eq!(ready, "READY\n");
3231        let input = ProcessInput::new();
3232        input
3233            .try_send_line("x".repeat(MAX_PROCESS_LINE_BYTES))
3234            .unwrap();
3235        let (_guard, receiver) = input.claim().unwrap();
3236        let stdin = child.stdin.take().unwrap();
3237        let (stop, trigger) = StopSignal::new();
3238        let (task_sender, task_receiver) = mpsc::channel();
3239        let worker = thread::spawn(move || {
3240            task_sender
3241                .send(std::fs::read_link("/proc/thread-self").unwrap())
3242                .unwrap();
3243            write_process_input(stdin, receiver, stop, b"")
3244        });
3245        await_pipe_wait(&std::path::Path::new("/proc").join(task_receiver.recv().unwrap()));
3246        trigger.stop();
3247        let deadline = Instant::now() + Duration::from_secs(2);
3248        while !worker.is_finished() && Instant::now() < deadline {
3249            thread::sleep(Duration::from_millis(5));
3250        }
3251        let worker_finished_before_release = worker.is_finished();
3252        let child_alive_before_release = child.try_wait().unwrap().is_none();
3253        child
3254            .send_signal(rustix::process::Signal::USR1.as_raw())
3255            .unwrap();
3256        let result = worker.join().unwrap();
3257        let mut output = String::new();
3258        stdout.read_to_string(&mut output).unwrap();
3259        let status = child.wait().unwrap();
3260        assert!(
3261            worker_finished_before_release,
3262            "stdin worker depended on child reading or exiting"
3263        );
3264        assert!(child_alive_before_release);
3265        assert_eq!(
3266            result.unwrap_err().to_string(),
3267            "stdin write canceled before completion"
3268        );
3269        assert!(status.success());
3270        assert_eq!(
3271            output, "4096:True:True\n",
3272            "only the exact written prefix should arrive, without LF, duplication or changed child blocking mode"
3273        );
3274    }
3275
3276    #[test]
3277    #[cfg(target_os = "linux")]
3278    fn real_input_write_failure_reaps_child_despite_full_model_queue() {
3279        let input = ProcessInput::new();
3280        let (observed_tx, observed_rx) = mpsc::channel();
3281        let sub = ProcessSubscription::new("sh", move |event| {
3282            observed_tx.send(event.clone()).unwrap();
3283            event
3284        })
3285        .args(["-c", "exec 0<&-; printf '%s\\n' \"$$\"; exec sleep 60"])
3286        .stdin(input.clone())
3287        .timeout(Duration::from_secs(5));
3288        let (sender, receiver) = mpsc::sync_channel(1);
3289        sender
3290            .send(ProcessEvent::Stdout("prefix".to_owned()))
3291            .unwrap();
3292        let (stop, trigger) = StopSignal::new();
3293        let handle =
3294            thread::spawn(move || sub.run(SubscriptionSender::new(sender, stop.clone()), stop));
3295        let ProcessEvent::Stdout(pid) = observed_rx.recv_timeout(Duration::from_secs(5)).unwrap()
3296        else {
3297            panic!("missing live PID")
3298        };
3299        let pid: u32 = pid.parse().unwrap();
3300        input
3301            .try_send_line("cannot reach closed pipe".to_owned())
3302            .unwrap();
3303        let terminal = observed_rx.recv_timeout(Duration::from_secs(5));
3304        let reaped = std::fs::metadata(format!("/proc/{pid}"))
3305            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
3306        // Observe supervision/reaping before releasing model backpressure.
3307        assert_eq!(
3308            receiver.recv().unwrap(),
3309            ProcessEvent::Stdout("prefix".to_owned())
3310        );
3311        let delivered = receiver.recv_timeout(Duration::from_secs(5));
3312        trigger.stop();
3313        handle.join().unwrap();
3314        let terminal = terminal.unwrap();
3315        assert!(
3316            matches!(&terminal, ProcessEvent::Error(error) if error.starts_with("stdin write failed") && error.contains("reaped:")),
3317            "{terminal:?}"
3318        );
3319        assert_eq!(delivered.unwrap(), terminal);
3320        assert!(reaped, "writer error must reap child before model drains");
3321        assert_eq!(
3322            input.try_send_line("late".to_owned()),
3323            Err(ProcessInputError::Closed("late".to_owned()))
3324        );
3325        assert!(receiver.try_recv().is_err());
3326    }
3327
3328    fn collect_lines(bytes: &[u8], read_capacity: usize) -> Result<Vec<String>, ProcessReadError> {
3329        let mut reader = io::BufReader::with_capacity(read_capacity, bytes);
3330        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3331        let (stop, _trigger) = StopSignal::new();
3332        let mut lines = Vec::new();
3333        while let Some(line) = read_process_line(&mut reader, &mut pending, &stop, None)? {
3334            lines.push(line);
3335        }
3336        Ok(lines)
3337    }
3338
3339    #[test]
3340    fn partial_output_identity_is_stable_and_distinct_from_line_only() {
3341        let plain = ProcessSubscription::new("cat", |event| event);
3342        let enabled = ProcessSubscription::new("cat", |event| event).partial_output(true);
3343        assert_ne!(plain.id(), enabled.id());
3344        assert_eq!(
3345            enabled.id(),
3346            ProcessSubscription::new("cat", |event| event)
3347                .partial_output(true)
3348                .id()
3349        );
3350        assert_eq!(plain.id(), enabled.partial_output(false).id());
3351        assert_eq!(
3352            ProcessSubscription::new("cat", |event| event)
3353                .with_id(42)
3354                .partial_output(true)
3355                .id(),
3356            42
3357        );
3358    }
3359
3360    #[test]
3361    fn partial_prefixes_preserve_utf8_controls_and_crlf_across_read_boundaries() {
3362        let input = "\n🦀é\x1b]2;hidden\x07prompt>\r\ninside\rcarriage\nlast\r";
3363        for capacity in 1..=input.len() {
3364            let mut reader = io::BufReader::with_capacity(capacity, input.as_bytes());
3365            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3366            let (stop, _trigger) = StopSignal::new();
3367            let mut complete = Vec::new();
3368            loop {
3369                let mut previews = Vec::new();
3370                let mut preview = |text: &str| {
3371                    previews.push(text.to_owned());
3372                    true
3373                };
3374                let line = read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview))
3375                    .unwrap();
3376                let Some(line) = line else {
3377                    assert!(previews.is_empty());
3378                    break;
3379                };
3380                let mut length = 0;
3381                for prefix in previews {
3382                    assert!(!prefix.is_empty());
3383                    assert!(line.starts_with(&prefix));
3384                    assert!(prefix.len() > length);
3385                    length = prefix.len();
3386                    assert!(!prefix.contains('\u{fffd}'));
3387                }
3388                complete.push(line);
3389            }
3390            assert_eq!(
3391                complete,
3392                [
3393                    "",
3394                    "🦀é\x1b]2;hidden\x07prompt>",
3395                    "inside\rcarriage",
3396                    "last\r"
3397                ]
3398            );
3399        }
3400    }
3401
3402    #[test]
3403    fn partial_prefix_validation_keeps_line_bounds_and_stop_before_another_read() {
3404        for delimiter in ["", "\n", "\r\n"] {
3405            let input = format!("{}{delimiter}", "x".repeat(MAX_PROCESS_LINE_BYTES));
3406            let mut reader = io::BufReader::with_capacity(8192, input.as_bytes());
3407            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3408            let capacity = pending.capacity();
3409            let (stop, _trigger) = StopSignal::new();
3410            let mut largest = 0;
3411            let mut preview = |prefix: &str| {
3412                assert!(prefix.len() <= MAX_PROCESS_LINE_BYTES);
3413                largest = largest.max(prefix.len());
3414                true
3415            };
3416            let line = read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview))
3417                .unwrap()
3418                .unwrap();
3419            assert_eq!(line.len(), MAX_PROCESS_LINE_BYTES);
3420            assert!(largest > 0);
3421            assert_eq!(pending.capacity(), capacity);
3422        }
3423
3424        for input in [
3425            vec![b'x'; MAX_PROCESS_LINE_BYTES + 1],
3426            b"safe\xff".to_vec(),
3427            b"safe\xf0\x9f".to_vec(),
3428        ] {
3429            let mut reader = io::BufReader::with_capacity(8192, input.as_slice());
3430            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3431            let (stop, _trigger) = StopSignal::new();
3432            let mut preview = |prefix: &str| {
3433                assert!(prefix.len() <= MAX_PROCESS_LINE_BYTES);
3434                assert!(!prefix.contains('\u{fffd}'));
3435                true
3436            };
3437            assert!(matches!(
3438                read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview)),
3439                Err(ProcessReadError::LineTooLong | ProcessReadError::InvalidUtf8(_))
3440            ));
3441            assert!(pending.len() <= MAX_PROCESS_LINE_BYTES + 1);
3442        }
3443
3444        let mut reader = io::BufReader::with_capacity(3, io::Cursor::new(b"pending forever"));
3445        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3446        let (stop, trigger) = StopSignal::new();
3447        let mut preview = |prefix: &str| {
3448            assert_eq!(prefix, "pen");
3449            trigger.stop();
3450            false
3451        };
3452        assert_eq!(
3453            read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview)).unwrap(),
3454            None
3455        );
3456        assert_eq!(reader.get_ref().position(), 3);
3457    }
3458
3459    #[test]
3460    #[cfg(unix)]
3461    fn real_partial_prompt_precedes_reply_and_preserves_split_utf8_controls_and_crlf() {
3462        let input = ProcessInput::new();
3463        let control = ProcessControl::new();
3464        let script = r#"import os,signal,sys
3465signal.alarm(5)
3466os.write(1,b'prompt \xf0\x9f')
3467assert sys.stdin.readline() == 'utf8\n'
3468os.write(1,b'\xa6\x80 \x1b]')
3469assert sys.stdin.readline() == 'osc\n'
3470os.write(1,b'2;hidden\x07 ready>')
3471assert sys.stdin.readline() == 'answer\n'
3472os.write(1,b'\r')
3473os.write(2,b'CR-WRITTEN\n')
3474assert sys.stdin.readline() == 'lf\n'
3475os.write(1,b'\nnormal\r\n')
3476os.write(2,b'err>')
3477assert sys.stdin.readline() == 'err\n'
3478os.write(2,b'\r\n')
3479os.write(1,b'tail\r')
3480"#;
3481        let sub = controlled_python(script, &control)
3482            .stdin(input.clone())
3483            .partial_output(true);
3484        let (sender, receiver) = mpsc::sync_channel(256);
3485        let (stop, _trigger) = StopSignal::new();
3486        let handle = thread::spawn(move || {
3487            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3488        });
3489        let mut previous_length = 0;
3490        for (expected, reply) in [
3491            ("prompt ", "utf8"),
3492            ("prompt 🦀 \x1b]", "osc"),
3493            ("prompt 🦀 \x1b]2;hidden\x07 ready>", "answer"),
3494        ] {
3495            loop {
3496                let ProcessEvent::StdoutPartial(prefix) =
3497                    receiver.recv_timeout(Duration::from_secs(3)).unwrap()
3498                else {
3499                    panic!("expected a pending stdout prefix before the reply");
3500                };
3501                assert!(expected.starts_with(&prefix));
3502                assert!(prefix.len() > previous_length);
3503                previous_length = prefix.len();
3504                if prefix == expected {
3505                    break;
3506                }
3507            }
3508            assert!(!control.status().closed);
3509            // The real child is waiting for this reply: no LF/EOF can unlock
3510            // the expected preview. Disabled previews fail at the first wait.
3511            input.try_send_line(reply.to_owned()).unwrap();
3512        }
3513        loop {
3514            match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
3515                ProcessEvent::StderrPartial(prefix) => assert!("CR-WRITTEN".starts_with(&prefix)),
3516                ProcessEvent::Stderr(line) => {
3517                    assert_eq!(line, "CR-WRITTEN");
3518                    break;
3519                }
3520                event => panic!("unexpected event while CR is held: {event:?}"),
3521            }
3522        }
3523        assert!(matches!(
3524            receiver.recv_timeout(Duration::from_millis(100)),
3525            Err(mpsc::RecvTimeoutError::Timeout)
3526        ));
3527        input.try_send_line("lf".to_owned()).unwrap();
3528        let expected_stdout = ["prompt 🦀 \x1b]2;hidden\x07 ready>", "normal", "tail\r"];
3529        let mut stdout = Vec::new();
3530        loop {
3531            match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
3532                ProcessEvent::Stdout(line) => stdout.push(line),
3533                ProcessEvent::StdoutPartial(prefix) => {
3534                    assert!(expected_stdout[stdout.len()].starts_with(&prefix));
3535                }
3536                ProcessEvent::StderrPartial(prefix) => {
3537                    assert!("err>".starts_with(&prefix));
3538                    if prefix == "err>" {
3539                        break;
3540                    }
3541                }
3542                event => panic!("unexpected event before stderr reply: {event:?}"),
3543            }
3544        }
3545        input.try_send_line("err".to_owned()).unwrap();
3546        let mut stderr = Vec::new();
3547        loop {
3548            match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
3549                ProcessEvent::Stdout(line) => stdout.push(line),
3550                ProcessEvent::Stderr(line) => stderr.push(line),
3551                ProcessEvent::StdoutPartial(prefix) => {
3552                    assert!(expected_stdout[stdout.len()].starts_with(&prefix));
3553                    assert!(!prefix.ends_with('\r'));
3554                }
3555                ProcessEvent::Exited(code) => {
3556                    assert_eq!(code, 0);
3557                    break;
3558                }
3559                event => panic!("unexpected event after reply: {event:?}"),
3560            }
3561        }
3562        handle.join().unwrap();
3563        assert_eq!(stdout, expected_stdout);
3564        assert_eq!(stderr, ["err>"]);
3565        assert!(receiver.try_recv().is_err());
3566        assert!(control.status().can_restart);
3567    }
3568
3569    #[test]
3570    #[cfg(unix)]
3571    fn real_partial_output_is_disabled_by_default_without_changing_completed_lines() {
3572        let input = ProcessInput::new();
3573        let control = ProcessControl::new();
3574        let script = "import os,signal,sys\nsignal.alarm(5)\nos.write(1,b'prompt>')\nos.write(2,b'READY\\n')\nassert sys.stdin.readline()=='reply\\n'\nos.write(1,b'\\r\\nnormal\\n')";
3575        let sub = controlled_python(script, &control).stdin(input.clone());
3576        let (sender, receiver) = mpsc::sync_channel(256);
3577        let (stop, _trigger) = StopSignal::new();
3578        let handle = thread::spawn(move || {
3579            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3580        });
3581        assert_eq!(
3582            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
3583            ProcessEvent::Stderr("READY".to_owned())
3584        );
3585        assert!(matches!(
3586            receiver.recv_timeout(Duration::from_millis(100)),
3587            Err(mpsc::RecvTimeoutError::Timeout)
3588        ));
3589        input.try_send_line("reply".to_owned()).unwrap();
3590        let events: Vec<_> = (0..3)
3591            .map(|_| receiver.recv_timeout(Duration::from_secs(3)).unwrap())
3592            .collect();
3593        handle.join().unwrap();
3594        assert_eq!(
3595            events,
3596            [
3597                ProcessEvent::Stdout("prompt>".to_owned()),
3598                ProcessEvent::Stdout("normal".to_owned()),
3599                ProcessEvent::Exited(0)
3600            ]
3601        );
3602        assert!(receiver.try_recv().is_err());
3603    }
3604
3605    #[test]
3606    #[cfg(unix)]
3607    fn real_partial_queue_backpressure_remains_interruptible() {
3608        let input = ProcessInput::new();
3609        let control = ProcessControl::new();
3610        let (observed_sender, observed_receiver) = mpsc::channel();
3611        let sub = ProcessSubscription::new("python3", move |event| {
3612            if let ProcessEvent::StdoutPartial(prefix) = &event {
3613                observed_sender.send(prefix.clone()).unwrap();
3614            }
3615            event
3616        })
3617        .args(["-u", "-c", "import os,signal,sys\nsignal.alarm(5)\nos.write(1,b'a')\nassert sys.stdin.readline()=='next\\n'\nos.write(1,b'b')\nsignal.pause()"])
3618        .stdin(input.clone())
3619        .control(control.clone())
3620        .partial_output(true)
3621        .timeout(Duration::from_secs(5));
3622        let (sender, receiver) = mpsc::sync_channel(1);
3623        let (stop, trigger) = StopSignal::new();
3624        let handle = thread::spawn(move || {
3625            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3626        });
3627        // Do not drain the first admitted prefix. The second conversion is
3628        // observed before bounded queue admission, not as delivered output.
3629        assert_eq!(
3630            observed_receiver
3631                .recv_timeout(Duration::from_secs(3))
3632                .unwrap(),
3633            "a"
3634        );
3635        input.try_send_line("next".to_owned()).unwrap();
3636        assert_eq!(
3637            observed_receiver
3638                .recv_timeout(Duration::from_secs(3))
3639                .unwrap(),
3640            "ab"
3641        );
3642        let stopped = Instant::now();
3643        trigger.stop();
3644        handle.join().unwrap();
3645        assert!(stopped.elapsed() < Duration::from_secs(2));
3646        assert_eq!(
3647            receiver.into_iter().collect::<Vec<_>>(),
3648            [ProcessEvent::StdoutPartial("a".to_owned())]
3649        );
3650        assert!(control.status().can_restart);
3651    }
3652
3653    #[test]
3654    #[cfg(unix)]
3655    fn real_partial_output_errors_preserve_bounds_and_never_report_success() {
3656        for (payload, reason) in [
3657            ("b'x'*65537", "line exceeds"),
3658            ("b'valid\\xff'", "invalid UTF-8"),
3659            ("b'valid\\xf0\\x9f'", "invalid UTF-8"),
3660        ] {
3661            let control = ProcessControl::new();
3662            let script = format!("import os,signal\nsignal.alarm(5)\nos.write(1,{payload})");
3663            let sub = controlled_python(&script, &control).partial_output(true);
3664            let (sender, receiver) = mpsc::sync_channel(256);
3665            let (stop, _trigger) = StopSignal::new();
3666            let handle = thread::spawn(move || {
3667                sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3668            });
3669            loop {
3670                match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
3671                    ProcessEvent::StdoutPartial(prefix) => {
3672                        assert!(prefix.len() <= MAX_PROCESS_LINE_BYTES);
3673                        assert!(!prefix.contains('\u{fffd}'));
3674                    }
3675                    ProcessEvent::Error(error) => {
3676                        assert!(error.contains(reason), "{error}");
3677                        break;
3678                    }
3679                    event => panic!("invalid output must not succeed: {event:?}"),
3680                }
3681            }
3682            handle.join().unwrap();
3683            assert!(receiver.try_recv().is_err());
3684            assert!(control.status().can_restart);
3685        }
3686    }
3687
3688    #[test]
3689    fn bounded_lines_preserve_delimiters_unicode_and_eof_across_reads() {
3690        let input = "\nalpha\r\n\r\n🦀é\ninside\rcarriage\nlast\r";
3691        let expected = ["", "alpha", "", "🦀é", "inside\rcarriage", "last\r"];
3692        for capacity in 1..=input.len() {
3693            assert_eq!(collect_lines(input.as_bytes(), capacity).unwrap(), expected);
3694            assert!(collect_lines(b"", capacity).unwrap().is_empty());
3695            assert_eq!(collect_lines(b"tail\n", capacity).unwrap(), ["tail"]);
3696        }
3697    }
3698
3699    #[test]
3700    fn bounded_lines_enforce_payload_limit_for_lf_crlf_and_eof() {
3701        for size in [MAX_PROCESS_LINE_BYTES - 1, MAX_PROCESS_LINE_BYTES] {
3702            let payload = "x".repeat(size);
3703            for delimiter in ["", "\n", "\r\n"] {
3704                let input = format!("{payload}{delimiter}");
3705                for capacity in [1, 8192, MAX_PROCESS_LINE_BYTES + 1] {
3706                    assert_eq!(
3707                        collect_lines(input.as_bytes(), capacity).unwrap(),
3708                        [payload.as_str()],
3709                        "size={size}, delimiter={delimiter:?}, read capacity={capacity}"
3710                    );
3711                }
3712            }
3713        }
3714        let unicode = "🦀".repeat(MAX_PROCESS_LINE_BYTES / 4);
3715        assert_eq!(collect_lines(unicode.as_bytes(), 3).unwrap(), [unicode]);
3716        for tail in ["x", "x\n", "x\r\n", "\r"] {
3717            let input = format!("{}{tail}", "x".repeat(MAX_PROCESS_LINE_BYTES));
3718            assert!(matches!(
3719                collect_lines(input.as_bytes(), 8192),
3720                Err(ProcessReadError::LineTooLong)
3721            ));
3722        }
3723    }
3724
3725    #[test]
3726    fn bounded_lines_reject_invalid_utf8_without_lossy_substitution() {
3727        for input in [b"secret\xff\n".as_slice(), b"\xf0\x9f\xa6", b"\xc0\x80\r\n"] {
3728            for capacity in 1..=input.len() {
3729                assert!(matches!(
3730                    collect_lines(input, capacity),
3731                    Err(ProcessReadError::InvalidUtf8(_))
3732                ));
3733            }
3734        }
3735    }
3736
3737    #[test]
3738    fn bounded_lines_stop_reading_before_oversized_input_allocates() {
3739        let input = vec![b'x'; MAX_PROCESS_LINE_BYTES * 16];
3740        let cursor = io::Cursor::new(input);
3741        let mut reader = io::BufReader::with_capacity(8192, cursor);
3742        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3743        let capacity = pending.capacity();
3744        let (stop, trigger) = StopSignal::new();
3745        assert!(matches!(
3746            read_process_line(&mut reader, &mut pending, &stop, None),
3747            Err(ProcessReadError::LineTooLong)
3748        ));
3749        assert!(pending.len() <= MAX_PROCESS_LINE_BYTES + 1);
3750        assert_eq!(pending.capacity(), capacity);
3751        let consumed = reader.get_ref().position();
3752        assert!(consumed <= (MAX_PROCESS_LINE_BYTES + 8192) as u64);
3753        trigger.stop();
3754        assert_eq!(
3755            read_process_line(&mut reader, &mut pending, &stop, None).unwrap(),
3756            None
3757        );
3758        assert_eq!(reader.get_ref().position(), consumed);
3759    }
3760
3761    #[test]
3762    fn bounded_lines_retry_interrupted_reads_and_report_io_failures() {
3763        struct FaultingReader {
3764            calls: usize,
3765        }
3766        impl Read for FaultingReader {
3767            fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
3768                self.calls += 1;
3769                match self.calls {
3770                    1 => Err(io::ErrorKind::Interrupted.into()),
3771                    2 => {
3772                        let bytes = b"good\npartial";
3773                        buffer[..bytes.len()].copy_from_slice(bytes);
3774                        Ok(bytes.len())
3775                    }
3776                    _ => Err(io::Error::other("injected read failure")),
3777                }
3778            }
3779        }
3780        let mut reader = io::BufReader::new(FaultingReader { calls: 0 });
3781        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3782        let (stop, _trigger) = StopSignal::new();
3783        assert_eq!(
3784            read_process_line(&mut reader, &mut pending, &stop, None).unwrap(),
3785            Some("good".to_owned())
3786        );
3787        assert!(matches!(
3788            read_process_line(&mut reader, &mut pending, &stop, None),
3789            Err(ProcessReadError::Io(error)) if error.kind() == io::ErrorKind::Other
3790        ));
3791    }
3792
3793    fn collect_real_process(script: &str) -> Vec<ProcessEvent> {
3794        let sub = ProcessSubscription::new("sh", |event| event).args(["-c", script]);
3795        let (tx, rx) = stdmpsc::sync_channel(256);
3796        let (signal, trigger) = StopSignal::new();
3797        let handle = thread::spawn(move || {
3798            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3799        });
3800        let mut events = Vec::new();
3801        loop {
3802            match rx.recv_timeout(Duration::from_secs(5)) {
3803                Ok(event) => events.push(event),
3804                Err(stdmpsc::RecvTimeoutError::Disconnected) => break,
3805                Err(stdmpsc::RecvTimeoutError::Timeout) => {
3806                    trigger.stop();
3807                    handle.join().expect("stop timed-out child");
3808                    panic!("child supervision stalled after {} events", events.len());
3809                }
3810            }
3811        }
3812        handle.join().expect("supervisor finished");
3813        events
3814    }
3815
3816    #[test]
3817    fn real_process_preserves_complete_lines_and_maximum_payload_on_both_streams() {
3818        let events = collect_real_process(
3819            "printf '\\nalpha\\r\\n🦀é\\nlast\\r'; printf '%065536d\\r\\n' 0 >&2; printf 'tail' >&2",
3820        );
3821        let stdout: Vec<_> = events
3822            .iter()
3823            .filter_map(|event| match event {
3824                ProcessEvent::Stdout(line) => Some(line.as_str()),
3825                _ => None,
3826            })
3827            .collect();
3828        let stderr: Vec<_> = events
3829            .iter()
3830            .filter_map(|event| match event {
3831                ProcessEvent::Stderr(line) => Some(line.as_str()),
3832                _ => None,
3833            })
3834            .collect();
3835        assert_eq!(stdout, ["", "alpha", "🦀é", "last\r"]);
3836        assert_eq!(
3837            stderr,
3838            ["0".repeat(MAX_PROCESS_LINE_BYTES), "tail".to_owned()]
3839        );
3840        assert_eq!(events.len(), 7);
3841        assert_eq!(events.last(), Some(&ProcessEvent::Exited(0)));
3842
3843        let events = collect_real_process("printf '%065536d\\n' 0");
3844        assert_eq!(
3845            events,
3846            [
3847                ProcessEvent::Stdout("0".repeat(MAX_PROCESS_LINE_BYTES)),
3848                ProcessEvent::Exited(0)
3849            ]
3850        );
3851    }
3852
3853    #[test]
3854    fn real_process_invalid_or_oversized_output_reports_one_error() {
3855        for (output, reason) in [
3856            ("printf '\\377\\n'", "invalid UTF-8"),
3857            ("printf '%065537d' 0", "line exceeds 65536 payload bytes"),
3858        ] {
3859            for stream in ["stdout", "stderr"] {
3860                let redirect = if stream == "stderr" { " >&2" } else { "" };
3861                for ending in ["exit 0", "exec sleep 60"] {
3862                    let events = collect_real_process(&format!("{output}{redirect}; {ending}"));
3863                    assert_eq!(events.len(), 1, "one terminal error: {events:?}");
3864                    let ProcessEvent::Error(error) = &events[0] else {
3865                        panic!("reader failure misreported: {events:?}");
3866                    };
3867                    assert!(error.starts_with(&format!("{stream} {reason}")), "{error}");
3868                    assert!(error.contains("reaped:"), "{error}");
3869                    assert!(
3870                        error.ends_with("stdout/stderr output is incomplete"),
3871                        "{error}"
3872                    );
3873                }
3874            }
3875        }
3876    }
3877
3878    #[test]
3879    #[cfg(target_os = "linux")]
3880    fn real_process_reader_failure_reaps_child_while_model_queue_is_full() {
3881        for (output, reason) in [
3882            ("printf '\\377\\n'", "stderr invalid UTF-8:"),
3883            (
3884                "printf '%065537d' 0",
3885                "stderr line exceeds 65536 payload bytes",
3886            ),
3887        ] {
3888            assert_reader_failure_with_full_queue(output, reason);
3889        }
3890    }
3891
3892    #[cfg(target_os = "linux")]
3893    fn child_has_sigstop(pid: rustix::process::Pid) -> rustix::io::Result<bool> {
3894        use rustix::process::{Signal, WaitId, WaitIdOptions, waitid};
3895
3896        // A ptraced child can report /proc state `t` for an unrelated syscall
3897        // stop. Require the actual SIGSTOP event, leaving it waitable so this
3898        // observer never takes child status away from the supervisor.
3899        Ok(waitid(
3900            WaitId::Pid(pid),
3901            WaitIdOptions::STOPPED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
3902        )?
3903        .is_some_and(|status| status.stopping_signal() == Some(Signal::STOP.as_raw())))
3904    }
3905
3906    #[test]
3907    #[cfg(target_os = "linux")]
3908    fn real_process_stop_oracle_rejects_running_child_without_reaping() {
3909        let (mut child, _stdin, _output) = spawn_cleanup_probe();
3910        let observed = child_has_sigstop(rustix::process::Pid::from_child(&child));
3911        let still_running = child.try_wait();
3912        // Retain observations before explicit cleanup; cleanup is not the
3913        // evidence that the stop oracle left a live child under its owner.
3914        let cleanup = cleanup_child(&mut child, &mut None, None);
3915        assert_eq!(observed, Ok(false), "a running child has no SIGSTOP event");
3916        assert!(matches!(still_running, Ok(None)));
3917        assert!(cleanup.kill_sent);
3918        assert_eq!(
3919            cleanup.status.map(process_exit_event),
3920            Some(ProcessEvent::Signaled(
3921                rustix::process::Signal::KILL.as_raw()
3922            ))
3923        );
3924    }
3925
3926    #[cfg(target_os = "linux")]
3927    fn assert_reader_failure_with_full_queue(output: &str, reason: &str) {
3928        let (observed_tx, observed_rx) = stdmpsc::channel();
3929        let sub = ProcessSubscription::new("sh", move |event| {
3930            observed_tx
3931                .send(event.clone())
3932                .expect("observe child and supervision");
3933            event
3934        })
3935        .args([
3936            "-c",
3937            &format!("printf '%s\\n' \"$$\"; kill -STOP \"$$\"; {output} >&2; exec sleep 60"),
3938        ]);
3939        let (tx, rx) = stdmpsc::sync_channel(256);
3940        let prefix: Vec<_> = (0..256)
3941            .map(|index| ProcessEvent::Stdout(format!("accepted-{index}")))
3942            .collect();
3943        for event in &prefix {
3944            tx.send(event.clone()).expect("fill application queue");
3945        }
3946        let (signal, trigger) = StopSignal::new();
3947        let handle = thread::spawn(move || {
3948            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3949        });
3950        // This observer is before the blocked application send. Hold the real
3951        // child stopped until its PID is observed so reader scheduling cannot
3952        // race the PID callback against the other stream's failure.
3953        let first = observed_rx.recv_timeout(Duration::from_secs(5));
3954        let pid = match &first {
3955            Ok(ProcessEvent::Stdout(line)) => line.parse::<u32>().ok(),
3956            _ => None,
3957        };
3958        let Some(pid) = pid else {
3959            trigger.stop();
3960            handle.join().expect("stop child without PID");
3961            panic!("expected actual child PID, got {first:?}");
3962        };
3963        let wait_pid =
3964            rustix::process::Pid::from_raw(i32::try_from(pid).expect("Linux child PID fits i32"))
3965                .expect("child PID is nonzero");
3966        let deadline = Instant::now() + Duration::from_secs(5);
3967        loop {
3968            let stopped = child_has_sigstop(wait_pid);
3969            if matches!(stopped, Ok(true)) {
3970                break;
3971            }
3972            if stopped.is_err() || Instant::now() >= deadline {
3973                trigger.stop();
3974                handle.join().expect("stop child that did not pause");
3975                panic!("child never reported SIGSTOP: {stopped:?}");
3976            }
3977            thread::sleep(Duration::from_millis(5));
3978        }
3979        let retained_stop = child_has_sigstop(wait_pid);
3980        if !matches!(retained_stop, Ok(true)) {
3981            trigger.stop();
3982            handle.join().expect("stop child whose status was consumed");
3983            panic!("SIGSTOP observation must leave status waitable: {retained_stop:?}");
3984        }
3985        let resumed = Command::new("kill")
3986            .args(["-CONT", &pid.to_string()])
3987            .status();
3988        if !resumed
3989            .as_ref()
3990            .is_ok_and(std::process::ExitStatus::success)
3991        {
3992            trigger.stop();
3993            handle.join().expect("stop child that did not resume");
3994            panic!("child resume failed: {resumed:?}");
3995        }
3996        // The other stream must fail and be supervised without any drain.
3997        let mut observed = vec![first.unwrap()];
3998        loop {
3999            match observed_rx.recv_timeout(Duration::from_secs(5)) {
4000                Ok(event) => {
4001                    let terminal = matches!(event, ProcessEvent::Error(_));
4002                    observed.push(event);
4003                    if terminal {
4004                        break;
4005                    }
4006                }
4007                Err(error) => {
4008                    trigger.stop();
4009                    handle.join().expect("stop stalled supervision");
4010                    panic!("full queue hid reader failure: {error:?}");
4011                }
4012            }
4013        }
4014        let terminal = observed.last().unwrap().clone();
4015        // Retain the observations before releasing queue backpressure. This
4016        // detects a live child or unreaped zombie, not just a reported status.
4017        let child_reaped = std::fs::metadata(format!("/proc/{pid}"))
4018            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
4019        let mut received: Vec<_> = (0..256)
4020            .map(|_| rx.recv().expect("accepted prefix"))
4021            .collect();
4022        received.push(
4023            rx.recv_timeout(Duration::from_secs(5))
4024                .expect("terminal error after drain"),
4025        );
4026        trigger.stop();
4027        handle.join().expect("supervisor finished");
4028        assert!(
4029            child_reaped,
4030            "child must be reaped before any model queue drain: {observed:?}"
4031        );
4032        assert!(
4033            matches!(&terminal, ProcessEvent::Error(error)
4034            if error.starts_with(reason)
4035                && error.contains("reaped:")
4036                && error.ends_with("stdout/stderr output is incomplete")),
4037            "{terminal:?}"
4038        );
4039        let mut expected = prefix;
4040        expected.push(terminal);
4041        assert_eq!(received, expected);
4042        assert!(
4043            rx.try_iter().next().is_none(),
4044            "no late reader output or duplicate status"
4045        );
4046        assert!(
4047            observed_rx.try_iter().next().is_none(),
4048            "readers finished before final event"
4049        );
4050    }
4051
4052    #[test]
4053    fn process_event_variants() {
4054        let stdout = ProcessEvent::Stdout("hello".into());
4055        let stderr = ProcessEvent::Stderr("warn".into());
4056        let exited = ProcessEvent::Exited(0);
4057        let signaled = ProcessEvent::Signaled(15);
4058        let killed = ProcessEvent::Killed;
4059        let error = ProcessEvent::Error("oops".into());
4060
4061        assert_eq!(stdout, ProcessEvent::Stdout("hello".into()));
4062        assert_eq!(stderr, ProcessEvent::Stderr("warn".into()));
4063        assert_eq!(exited, ProcessEvent::Exited(0));
4064        assert_eq!(signaled, ProcessEvent::Signaled(15));
4065        assert_eq!(killed, ProcessEvent::Killed);
4066        assert_eq!(error, ProcessEvent::Error("oops".into()));
4067    }
4068
4069    #[test]
4070    fn subscription_id_is_stable() {
4071        let s1: ProcessSubscription<TestMsg> =
4072            ProcessSubscription::new("echo", TestMsg::Proc).arg("hello");
4073        let s2: ProcessSubscription<TestMsg> =
4074            ProcessSubscription::new("echo", TestMsg::Proc).arg("hello");
4075        assert_eq!(s1.id(), s2.id());
4076    }
4077
4078    #[test]
4079    fn different_args_produce_different_ids() {
4080        let s1: ProcessSubscription<TestMsg> =
4081            ProcessSubscription::new("echo", TestMsg::Proc).arg("hello");
4082        let s2: ProcessSubscription<TestMsg> =
4083            ProcessSubscription::new("echo", TestMsg::Proc).arg("world");
4084        assert_ne!(s1.id(), s2.id());
4085    }
4086
4087    #[test]
4088    fn different_programs_produce_different_ids() {
4089        let s1: ProcessSubscription<TestMsg> = ProcessSubscription::new("echo", TestMsg::Proc);
4090        let s2: ProcessSubscription<TestMsg> = ProcessSubscription::new("cat", TestMsg::Proc);
4091        assert_ne!(s1.id(), s2.id());
4092    }
4093
4094    #[test]
4095    fn custom_id_overrides_default() {
4096        let s: ProcessSubscription<TestMsg> =
4097            ProcessSubscription::new("echo", TestMsg::Proc).with_id(42);
4098        assert_eq!(s.id(), 42);
4099    }
4100
4101    #[test]
4102    fn env_changes_affect_subscription_id() {
4103        let s1: ProcessSubscription<TestMsg> =
4104            ProcessSubscription::new("echo", TestMsg::Proc).env("FTUI_TEST_VAR", "a");
4105        let s2: ProcessSubscription<TestMsg> =
4106            ProcessSubscription::new("echo", TestMsg::Proc).env("FTUI_TEST_VAR", "b");
4107        assert_ne!(s1.id(), s2.id());
4108    }
4109
4110    #[test]
4111    fn timeout_changes_affect_subscription_id() {
4112        let s1: ProcessSubscription<TestMsg> =
4113            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_millis(10));
4114        let s2: ProcessSubscription<TestMsg> =
4115            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_millis(20));
4116        assert_ne!(s1.id(), s2.id());
4117    }
4118
4119    #[test]
4120    fn explicit_id_remains_stable_after_builder_changes() {
4121        let s: ProcessSubscription<TestMsg> = ProcessSubscription::new("echo", TestMsg::Proc)
4122            .with_id(42)
4123            .arg("hello")
4124            .env("FTUI_TEST_VAR", "value")
4125            .timeout(Duration::from_millis(10));
4126        assert_eq!(s.id(), 42);
4127    }
4128
4129    #[test]
4130    fn echo_captures_stdout() {
4131        let sub = ProcessSubscription::new("echo", TestMsg::Proc).arg("hello world");
4132        let (tx, rx) = stdmpsc::sync_channel(256);
4133        let (signal, _trigger) = StopSignal::new();
4134
4135        let handle = thread::spawn(move || {
4136            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4137        });
4138
4139        // The child exits by itself. Stopping after a fixed sleep raced that
4140        // exit and reported Killed under load.
4141        handle.join().unwrap();
4142
4143        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4144        let has_stdout = msgs.iter().any(|m| match m {
4145            TestMsg::Proc(ProcessEvent::Stdout(s)) => s.contains("hello world"),
4146            _ => false,
4147        });
4148        assert!(
4149            has_stdout,
4150            "Expected stdout with 'hello world', got: {msgs:?}"
4151        );
4152
4153        let has_exit = msgs
4154            .iter()
4155            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Exited(0))));
4156        assert!(has_exit, "Expected Exited(0), got: {msgs:?}");
4157    }
4158
4159    #[test]
4160    fn nonexistent_program_sends_error() {
4161        let sub =
4162            ProcessSubscription::new("/nonexistent/program/that/should/not/exist", TestMsg::Proc);
4163        let (tx, rx) = stdmpsc::sync_channel(256);
4164        let (signal, _trigger) = StopSignal::new();
4165
4166        let handle = thread::spawn(move || {
4167            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4168        });
4169
4170        handle.join().unwrap();
4171        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4172        let has_error = msgs
4173            .iter()
4174            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Error(_))));
4175        assert!(has_error, "Expected Error event, got: {msgs:?}");
4176    }
4177
4178    #[test]
4179    fn stop_signal_kills_long_running_process() {
4180        let sub = ProcessSubscription::new("sleep", TestMsg::Proc).arg("60");
4181        let (tx, rx) = stdmpsc::sync_channel(256);
4182        let (signal, trigger) = StopSignal::new();
4183        let start = web_time::Instant::now();
4184
4185        let handle = thread::spawn(move || {
4186            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4187        });
4188
4189        // Give it a moment to start, then stop
4190        thread::sleep(Duration::from_millis(100));
4191        trigger.stop();
4192        handle.join().unwrap();
4193        assert!(
4194            start.elapsed() < Duration::from_secs(2),
4195            "stop should kill a quiet process promptly"
4196        );
4197
4198        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4199        let has_killed = msgs
4200            .iter()
4201            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed)));
4202        assert!(has_killed, "Expected Killed event, got: {msgs:?}");
4203    }
4204
4205    #[test]
4206    fn timeout_kills_process() {
4207        let sub = ProcessSubscription::new("sleep", TestMsg::Proc)
4208            .arg("60")
4209            .timeout(Duration::from_millis(100));
4210        let (tx, rx) = stdmpsc::sync_channel(256);
4211        let (signal, _trigger) = StopSignal::new();
4212        let start = web_time::Instant::now();
4213
4214        let handle = thread::spawn(move || {
4215            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4216        });
4217
4218        handle.join().unwrap();
4219        assert!(
4220            start.elapsed() < Duration::from_secs(10),
4221            "timeout should kill a quiet 60s process promptly without waiting for sleep 60"
4222        );
4223        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4224        let has_killed = msgs
4225            .iter()
4226            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed)));
4227        assert!(has_killed, "Expected Killed on timeout, got: {msgs:?}");
4228    }
4229
4230    #[test]
4231    fn env_vars_are_passed() {
4232        let sub =
4233            ProcessSubscription::new("env", TestMsg::Proc).env("FTUI_TEST_VAR", "test_value_42");
4234        let (tx, rx) = stdmpsc::sync_channel(256);
4235        let (signal, _trigger) = StopSignal::new();
4236
4237        let handle = thread::spawn(move || {
4238            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4239        });
4240
4241        handle.join().unwrap();
4242
4243        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4244        let has_var = msgs.iter().any(|m| match m {
4245            TestMsg::Proc(ProcessEvent::Stdout(s)) => s.contains("FTUI_TEST_VAR=test_value_42"),
4246            _ => false,
4247        });
4248        assert!(has_var, "Expected env var in output, got: {msgs:?}");
4249    }
4250
4251    #[test]
4252    fn multiple_args_via_args_method() {
4253        let sub = ProcessSubscription::new("echo", TestMsg::Proc).args(["hello", "world"]);
4254        let (tx, rx) = stdmpsc::sync_channel(256);
4255        let (signal, _trigger) = StopSignal::new();
4256
4257        let handle = thread::spawn(move || {
4258            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4259        });
4260
4261        handle.join().unwrap();
4262
4263        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4264        let has_output = msgs.iter().any(|m| match m {
4265            TestMsg::Proc(ProcessEvent::Stdout(s)) => s.contains("hello world"),
4266            _ => false,
4267        });
4268        assert!(has_output, "Expected combined output, got: {msgs:?}");
4269    }
4270
4271    #[test]
4272    fn stderr_captured() {
4273        // Use sh -c to write to stderr
4274        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
4275            .arg("-c")
4276            .arg("echo error_msg >&2");
4277        let (tx, rx) = stdmpsc::sync_channel(256);
4278        let (signal, _trigger) = StopSignal::new();
4279
4280        let handle = thread::spawn(move || {
4281            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4282        });
4283
4284        handle.join().unwrap();
4285
4286        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4287        let has_stderr = msgs.iter().any(|m| match m {
4288            TestMsg::Proc(ProcessEvent::Stderr(s)) => s.contains("error_msg"),
4289            _ => false,
4290        });
4291        assert!(has_stderr, "Expected stderr output, got: {msgs:?}");
4292    }
4293
4294    #[test]
4295    fn exit_code_captured() {
4296        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
4297            .arg("-c")
4298            .arg("exit 42");
4299        let (tx, rx) = stdmpsc::sync_channel(256);
4300        let (signal, _trigger) = StopSignal::new();
4301
4302        let handle = thread::spawn(move || {
4303            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4304        });
4305
4306        handle.join().unwrap();
4307
4308        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4309        let has_exit = msgs
4310            .iter()
4311            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Exited(42))));
4312        assert!(has_exit, "Expected Exited(42), got: {msgs:?}");
4313    }
4314
4315    #[cfg(unix)]
4316    #[test]
4317    fn signal_exit_is_preserved() {
4318        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
4319            .arg("-c")
4320            .arg("kill -TERM $$");
4321        let (tx, rx) = stdmpsc::sync_channel(256);
4322        let (signal, _trigger) = StopSignal::new();
4323
4324        let handle = thread::spawn(move || {
4325            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4326        });
4327
4328        handle.join().unwrap();
4329
4330        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4331        let has_signal = msgs
4332            .iter()
4333            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Signaled(15))));
4334        assert!(has_signal, "Expected Signaled(15), got: {msgs:?}");
4335    }
4336
4337    // =========================================================================
4338    // PROCESS LIFECYCLE CONTRACT TESTS (bd-3s3yw)
4339    //
4340    // These tests capture the observable process supervision contract that
4341    // the Asupersync migration must preserve.
4342    // =========================================================================
4343
4344    /// CONTRACT: Process subscription uses CancellationToken internally for
4345    /// stop coordination (via StopSignal::cancellation_token()).
4346    #[test]
4347    fn contract_uses_cancellation_token_for_stop() {
4348        let sub = ProcessSubscription::new("sleep", TestMsg::Proc).arg("60");
4349        let (tx, rx) = stdmpsc::sync_channel(256);
4350        let (signal, trigger) = StopSignal::new();
4351
4352        // Verify the cancellation token is accessible
4353        let token = signal.cancellation_token().clone();
4354        assert!(!token.is_cancelled());
4355
4356        let handle = thread::spawn(move || {
4357            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4358        });
4359
4360        thread::sleep(Duration::from_millis(100));
4361
4362        // Stopping via trigger should cancel the token
4363        trigger.stop();
4364        assert!(token.is_cancelled());
4365
4366        handle.join().unwrap();
4367
4368        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4369        assert!(
4370            msgs.iter()
4371                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
4372            "process must be killed on cancellation, got: {msgs:?}"
4373        );
4374    }
4375
4376    /// CONTRACT: Final event is always sent, even on error paths.
4377    /// The subscription must always emit exactly one terminal event
4378    /// (Exited, Signaled, Killed, or Error).
4379    #[test]
4380    fn contract_always_emits_terminal_event() {
4381        // Happy path: process exits normally
4382        {
4383            let sub = ProcessSubscription::new("true", TestMsg::Proc);
4384            let (tx, rx) = stdmpsc::sync_channel(256);
4385            let (signal, _trigger) = StopSignal::new();
4386
4387            let handle = thread::spawn(move || {
4388                sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4389            });
4390
4391            handle.join().unwrap();
4392
4393            let msgs: Vec<TestMsg> = rx.try_iter().collect();
4394            let terminal_events: Vec<_> = msgs
4395                .iter()
4396                .filter(|m| {
4397                    matches!(
4398                        m,
4399                        TestMsg::Proc(
4400                            ProcessEvent::Exited(_)
4401                                | ProcessEvent::Signaled(_)
4402                                | ProcessEvent::Killed
4403                                | ProcessEvent::Error(_)
4404                        )
4405                    )
4406                })
4407                .collect();
4408            assert_eq!(
4409                terminal_events.len(),
4410                1,
4411                "must emit exactly one terminal event, got: {terminal_events:?}"
4412            );
4413        }
4414
4415        // Error path: nonexistent program
4416        {
4417            let sub = ProcessSubscription::new(
4418                "/nonexistent/program/that/should/not/exist",
4419                TestMsg::Proc,
4420            );
4421            let (tx, rx) = stdmpsc::sync_channel(256);
4422            let (signal, _trigger) = StopSignal::new();
4423
4424            let handle = thread::spawn(move || {
4425                sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4426            });
4427
4428            handle.join().unwrap();
4429
4430            let msgs: Vec<TestMsg> = rx.try_iter().collect();
4431            let terminal_events: Vec<_> = msgs
4432                .iter()
4433                .filter(|m| {
4434                    matches!(
4435                        m,
4436                        TestMsg::Proc(
4437                            ProcessEvent::Exited(_)
4438                                | ProcessEvent::Signaled(_)
4439                                | ProcessEvent::Killed
4440                                | ProcessEvent::Error(_)
4441                        )
4442                    )
4443                })
4444                .collect();
4445            assert_eq!(
4446                terminal_events.len(),
4447                1,
4448                "must emit exactly one terminal event on error, got: {terminal_events:?}"
4449            );
4450        }
4451    }
4452
4453    /// CONTRACT: stdout and stderr lines arrive before the terminal event.
4454    /// The output forwarding threads must join before the final event is sent.
4455    #[test]
4456    fn contract_output_precedes_terminal_event() {
4457        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
4458            .arg("-c")
4459            .arg("echo FIRST && echo SECOND >&2 && exit 0");
4460        let (tx, rx) = stdmpsc::sync_channel(256);
4461        let (signal, _trigger) = StopSignal::new();
4462
4463        let handle = thread::spawn(move || {
4464            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4465        });
4466
4467        handle.join().unwrap();
4468
4469        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4470
4471        assert_eq!(
4472            msgs.len(),
4473            3,
4474            "both output lines and one terminal event: {msgs:?}"
4475        );
4476        assert!(msgs.contains(&TestMsg::Proc(ProcessEvent::Stdout("FIRST".to_owned()))));
4477        assert!(msgs.contains(&TestMsg::Proc(ProcessEvent::Stderr("SECOND".to_owned()))));
4478        assert_eq!(msgs.last(), Some(&TestMsg::Proc(ProcessEvent::Exited(0))));
4479
4480        // Find the position of the terminal event
4481        let terminal_pos = msgs
4482            .iter()
4483            .position(|m| {
4484                matches!(
4485                    m,
4486                    TestMsg::Proc(
4487                        ProcessEvent::Exited(_)
4488                            | ProcessEvent::Signaled(_)
4489                            | ProcessEvent::Killed
4490                            | ProcessEvent::Error(_)
4491                    )
4492                )
4493            })
4494            .expect("process must report its terminal event");
4495
4496        // Find positions of stdout/stderr events
4497        let output_positions: Vec<usize> = msgs
4498            .iter()
4499            .enumerate()
4500            .filter_map(|(i, m)| match m {
4501                TestMsg::Proc(ProcessEvent::Stdout(_) | ProcessEvent::Stderr(_)) => Some(i),
4502                _ => None,
4503            })
4504            .collect();
4505
4506        for &out_pos in &output_positions {
4507            assert!(
4508                out_pos < terminal_pos,
4509                "output event at position {out_pos} must precede terminal event at {terminal_pos}"
4510            );
4511        }
4512    }
4513
4514    #[test]
4515    fn real_process_flood_backpressures_and_drains_in_order() {
4516        use crate::subscription::SubscriptionManager;
4517
4518        let (progress_tx, progress_rx) = stdmpsc::channel();
4519        let sub = ProcessSubscription::new("sh", move |event| {
4520            if let ProcessEvent::Stdout(line) = &event
4521                && matches!(line.as_str(), "256" | "257")
4522            {
4523                progress_tx
4524                    .send(line.clone())
4525                    .expect("observe actual child output");
4526            }
4527            TestMsg::Proc(event)
4528        })
4529        .args([
4530            "-c",
4531            "i=0; while [ \"$i\" -lt 1024 ]; do printf '%s\\n' \"$i\"; i=$((i+1)); done",
4532        ]);
4533        let mut manager = SubscriptionManager::new();
4534        manager.reconcile(vec![Box::new(sub)]);
4535
4536        // The conversion callback observes the real 257th line before its
4537        // send. With no manager drain, that send must wait on the full queue.
4538        assert_eq!(
4539            progress_rx
4540                .recv_timeout(Duration::from_secs(5))
4541                .expect("child reached capacity"),
4542            "256"
4543        );
4544        // Hold backpressure longer than the old reader join timeout.
4545        assert_eq!(
4546            progress_rx.recv_timeout(PROCESS_READER_JOIN_TIMEOUT + Duration::from_millis(100)),
4547            Err(stdmpsc::RecvTimeoutError::Timeout),
4548            "the reader must not reach line 257 while 256 messages remain undrained"
4549        );
4550
4551        let mut received = manager.drain_messages();
4552        assert_eq!(
4553            received.len(),
4554            64,
4555            "one runtime turn has a fixed batch budget"
4556        );
4557        assert_eq!(
4558            progress_rx
4559                .recv_timeout(Duration::from_secs(5))
4560                .expect("drain released backpressure"),
4561            "257"
4562        );
4563        let deadline = Instant::now() + Duration::from_secs(10);
4564        while !matches!(
4565            received.last(),
4566            Some(TestMsg::Proc(ProcessEvent::Exited(0)))
4567        ) {
4568            assert!(
4569                Instant::now() < deadline,
4570                "actual child output did not finish: {} messages",
4571                received.len()
4572            );
4573            let batch = manager.drain_messages();
4574            assert!(
4575                batch.len() <= 64,
4576                "every drain must preserve the runtime batch budget"
4577            );
4578            if batch.is_empty() {
4579                thread::sleep(Duration::from_millis(1));
4580            }
4581            received.extend(batch);
4582        }
4583        manager.stop_all();
4584        received.extend(manager.drain_messages());
4585        let mut expected: Vec<_> = (0..1024)
4586            .map(|index| TestMsg::Proc(ProcessEvent::Stdout(index.to_string())))
4587            .collect();
4588        expected.push(TestMsg::Proc(ProcessEvent::Exited(0)));
4589        assert_eq!(
4590            received, expected,
4591            "all real child lines precede exactly one exit"
4592        );
4593        assert!(manager.drain_messages().is_empty());
4594    }
4595
4596    #[test]
4597    fn real_process_full_queue_stop_is_prompt() {
4598        use crate::subscription::SubscriptionManager;
4599
4600        let (capacity_tx, capacity_rx) = stdmpsc::channel();
4601        let (terminal_tx, terminal_rx) = stdmpsc::channel();
4602        let sub = ProcessSubscription::new("sh", move |event| {
4603            if matches!(&event, ProcessEvent::Stdout(line) if line == "256") {
4604                capacity_tx
4605                    .send(())
4606                    .expect("observe actual full-queue output");
4607            }
4608            if matches!(
4609                &event,
4610                ProcessEvent::Killed
4611                    | ProcessEvent::Exited(_)
4612                    | ProcessEvent::Signaled(_)
4613                    | ProcessEvent::Error(_)
4614            ) {
4615                terminal_tx
4616                    .send(event.clone())
4617                    .expect("observe actual child termination");
4618            }
4619            TestMsg::Proc(event)
4620        })
4621        .args([
4622            "-c",
4623            "i=0; while [ \"$i\" -lt 1024 ]; do printf '%s\\n' \"$i\"; i=$((i+1)); done; exec sleep 60",
4624        ]);
4625        let mut manager = SubscriptionManager::new();
4626        manager.reconcile(vec![Box::new(sub)]);
4627        capacity_rx
4628            .recv_timeout(Duration::from_secs(5))
4629            .expect("child reached capacity");
4630
4631        let stop_start = Instant::now();
4632        manager.stop_all();
4633        assert!(
4634            stop_start.elapsed() < Duration::from_secs(2),
4635            "full output queue must not block subscription stop"
4636        );
4637        assert_eq!(
4638            terminal_rx
4639                .recv_timeout(Duration::from_secs(2))
4640                .expect("supervisor reported termination"),
4641            ProcessEvent::Killed
4642        );
4643        assert_eq!(
4644            terminal_rx.recv_timeout(Duration::from_secs(2)),
4645            Err(stdmpsc::RecvTimeoutError::Disconnected),
4646            "the supervisor and reader callbacks must finish before draining"
4647        );
4648
4649        // Cancellation may reject the final status on a full data queue. The
4650        // callback above observes supervision; only these 256 lines were sent.
4651        let mut received = Vec::new();
4652        loop {
4653            let batch = manager.drain_messages();
4654            assert!(batch.len() <= 64);
4655            if batch.is_empty() {
4656                break;
4657            }
4658            received.extend(batch);
4659        }
4660        let expected: Vec<_> = (0..256)
4661            .map(|index| TestMsg::Proc(ProcessEvent::Stdout(index.to_string())))
4662            .collect();
4663        assert_eq!(
4664            received, expected,
4665            "already accepted output remains in FIFO order"
4666        );
4667    }
4668
4669    #[test]
4670    #[cfg(target_os = "linux")]
4671    fn real_process_cancel_kills_blocked_writer_before_closing_pipe() {
4672        assert_blocked_writer_is_killed(false);
4673    }
4674
4675    #[test]
4676    #[cfg(target_os = "linux")]
4677    fn real_process_timeout_kills_blocked_writer_before_closing_pipe() {
4678        assert_blocked_writer_is_killed(true);
4679    }
4680
4681    #[cfg(target_os = "linux")]
4682    fn assert_blocked_writer_is_killed(timeout: bool) {
4683        let (tx, rx) = stdmpsc::sync_channel(256);
4684        let expected: Vec<_> = (0..256)
4685            .map(|index| ProcessEvent::Stdout(format!("accepted-{index}")))
4686            .collect();
4687        for event in &expected {
4688            tx.send(event.clone()).expect("fill application queue");
4689        }
4690        let (observed_tx, observed_rx) = stdmpsc::channel();
4691        let (done_tx, done_rx) = stdmpsc::channel();
4692        // Restore SIGPIPE's default action so premature reader closure has an
4693        // observable terminal status. The child stays inside an actual blocking
4694        // pipe write while the reader waits for model queue capacity.
4695        let script = "import os,signal\nsignal.alarm(15)\nsignal.signal(signal.SIGPIPE,signal.SIG_DFL)\nprint(os.getpid(),flush=True)\nwhile True: os.write(1,b'x'*65536)";
4696        let mut sub = ProcessSubscription::new("python3", move |event| {
4697            observed_tx
4698                .send(event.clone())
4699                .expect("observe process callback before model backpressure");
4700            event
4701        })
4702        .args(["-u", "-c", script]);
4703        if timeout {
4704            sub = sub.timeout(Duration::from_secs(3));
4705        }
4706        let (signal, trigger) = StopSignal::new();
4707        let handle = thread::spawn(move || {
4708            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4709            done_tx.send(()).expect("observe supervisor completion");
4710        });
4711        let first = observed_rx.recv_timeout(Duration::from_secs(5));
4712        let pid = match &first {
4713            Ok(ProcessEvent::Stdout(line)) => line.parse::<u32>().ok(),
4714            _ => None,
4715        };
4716        let Some(pid) = pid else {
4717            trigger.stop();
4718            handle.join().expect("stop child without PID");
4719            panic!("expected actual blocked writer PID, got {first:?}");
4720        };
4721        let deadline = Instant::now() + Duration::from_secs(2);
4722        loop {
4723            let wait = std::fs::read_to_string(format!("/proc/{pid}/wchan")).unwrap_or_default();
4724            if wait.contains("pipe_write") {
4725                break;
4726            }
4727            if Instant::now() >= deadline {
4728                trigger.stop();
4729                handle
4730                    .join()
4731                    .expect("stop child that did not block writing");
4732                panic!("child never entered a blocking pipe write: {wait:?}");
4733            }
4734            thread::sleep(Duration::from_millis(5));
4735        }
4736        if !timeout {
4737            trigger.stop();
4738        }
4739        let done = done_rx.recv_timeout(Duration::from_secs(5));
4740        // Cleanup precedes assertions even when termination failed. No model
4741        // queue slot is released until both the child and workers have stopped.
4742        trigger.stop();
4743        handle.join().expect("join blocked writer supervisor");
4744        assert!(done.is_ok(), "full queue blocked termination: {done:?}");
4745        assert_eq!(
4746            observed_rx.try_iter().collect::<Vec<_>>(),
4747            [ProcessEvent::Killed],
4748            "cancel and timeout must reap SIGKILL, not induce SIGPIPE or EOF"
4749        );
4750        assert!(
4751            std::fs::metadata(format!("/proc/{pid}"))
4752                .is_err_and(|error| error.kind() == io::ErrorKind::NotFound),
4753            "the immediate child must already be reaped"
4754        );
4755        assert_eq!(
4756            rx.try_iter().collect::<Vec<_>>(),
4757            expected,
4758            "the entire previously accepted prefix survives without a drain"
4759        );
4760    }
4761
4762    #[test]
4763    fn real_process_exit_drain_timeout_cannot_block_on_final_status() {
4764        let (tx, rx) = stdmpsc::sync_channel(256);
4765        let expected: Vec<_> = (0..256)
4766            .map(|index| TestMsg::Proc(ProcessEvent::Stdout(format!("queued-{index}"))))
4767            .collect();
4768        // Control the queue state independently of the real child's one-line
4769        // output so this exercises timeout after exit, not a sleeping child.
4770        for message in &expected {
4771            tx.send(message.clone()).expect("fill model queue");
4772        }
4773        let (observed_tx, observed_rx) = stdmpsc::channel();
4774        let (done_tx, done_rx) = stdmpsc::channel();
4775        let sub = ProcessSubscription::new("sh", move |event| {
4776            observed_tx
4777                .send(event.clone())
4778                .expect("observe actual process callbacks");
4779            TestMsg::Proc(event)
4780        })
4781        .args(["-c", "printf 'tail\\n'; exit 42"])
4782        .timeout(Duration::from_millis(500) * ftui_core::cx::test_time_scale());
4783        let (signal, _trigger) = StopSignal::new();
4784        let handle = thread::spawn(move || {
4785            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4786            done_tx.send(()).expect("report completed supervision");
4787        });
4788
4789        assert_eq!(
4790            observed_rx
4791                .recv_timeout(Duration::from_secs(5) * ftui_core::cx::test_time_scale())
4792                .expect("real child output"),
4793            ProcessEvent::Stdout("tail".to_owned())
4794        );
4795        assert_eq!(
4796            observed_rx
4797                .recv_timeout(Duration::from_secs(5) * ftui_core::cx::test_time_scale())
4798                .expect("interrupted output drain"),
4799            ProcessEvent::Error(
4800                "output drain timed out after Exited(42); stdout/stderr output is incomplete"
4801                    .to_owned()
4802            )
4803        );
4804        done_rx
4805            .recv_timeout(Duration::from_secs(2) * ftui_core::cx::test_time_scale())
4806            .expect("a full final-status send must honor the timeout");
4807        handle.join().expect("supervisor thread");
4808        assert_eq!(
4809            observed_rx.recv_timeout(Duration::from_secs(2) * ftui_core::cx::test_time_scale()),
4810            Err(stdmpsc::RecvTimeoutError::Disconnected)
4811        );
4812        assert_eq!(
4813            rx.try_iter().collect::<Vec<_>>(),
4814            expected,
4815            "timeout preserves accepted messages and rejects the unsent tail/status"
4816        );
4817    }
4818
4819    /// CONTRACT: ProcessSubscription ID includes timeout in the hash.
4820    /// Changing timeout creates a different subscription identity.
4821    #[test]
4822    fn contract_id_includes_timeout() {
4823        let s1: ProcessSubscription<TestMsg> =
4824            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_secs(5));
4825        let s2: ProcessSubscription<TestMsg> =
4826            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_secs(10));
4827        let s3: ProcessSubscription<TestMsg> = ProcessSubscription::new("echo", TestMsg::Proc);
4828
4829        assert_ne!(
4830            s1.id(),
4831            s2.id(),
4832            "different timeouts must produce different IDs"
4833        );
4834        assert_ne!(
4835            s1.id(),
4836            s3.id(),
4837            "timeout vs no-timeout must produce different IDs"
4838        );
4839    }
4840
4841    /// CONTRACT: Kill is prompt — process is killed within poll_interval (50ms)
4842    /// of the stop signal, not blocked waiting for process output.
4843    #[test]
4844    fn contract_kill_is_prompt() {
4845        let sub = ProcessSubscription::new("sleep", TestMsg::Proc).arg("60");
4846        let (tx, rx) = stdmpsc::sync_channel(256);
4847        let (signal, trigger) = StopSignal::new();
4848
4849        let handle = thread::spawn(move || {
4850            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4851        });
4852
4853        thread::sleep(Duration::from_millis(100));
4854
4855        let kill_start = web_time::Instant::now();
4856        trigger.stop();
4857        handle.join().unwrap();
4858        let kill_elapsed = kill_start.elapsed();
4859
4860        // The child sleeps 60 s; a prompt kill returns in about one poll
4861        // interval (50 ms). The 5 s bound is a hang guard with room for a
4862        // loaded runner, and it still fails when the kill waited for the
4863        // child (G04.2).
4864        assert!(
4865            kill_elapsed < Duration::from_secs(5) * ftui_core::cx::test_time_scale(),
4866            "kill must complete promptly after the stop signal, took {kill_elapsed:?}"
4867        );
4868
4869        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4870        assert!(
4871            msgs.iter()
4872                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
4873            "must emit Killed event"
4874        );
4875    }
4876
4877    #[test]
4878    #[cfg(target_os = "linux")]
4879    fn real_descendant_output_pipes_close_after_leader_exit_before_fixture_release() {
4880        use rustix::process::{Pid, WaitOptions, set_child_subreaper, waitpid};
4881        use std::net::TcpListener;
4882        use std::path::PathBuf;
4883
4884        const CHILD_ENV: &str = "FTUI_DESCENDANT_PIPE_ISOLATED_TEST";
4885        const TEST_NAME: &str = concat!(
4886            "process_subscription::tests::",
4887            "real_descendant_output_pipes_close_after_leader_exit_before_fixture_release"
4888        );
4889        let isolated_parent = std::env::var(CHILD_ENV)
4890            .ok()
4891            .and_then(|value| value.parse::<i32>().ok());
4892        let isolated_run = isolated_parent.is_some()
4893            && isolated_parent == rustix::process::getppid().map(|pid| pid.as_raw_nonzero().get())
4894            && std::env::args().skip(1).eq([
4895                "--exact",
4896                TEST_NAME,
4897                "--nocapture",
4898                "--test-threads=1",
4899            ]);
4900        if !isolated_run {
4901            // Subreaper state belongs only to this exact-test subprocess. The
4902            // ordinary test runner must not adopt or reap unrelated children.
4903            let mut isolated = Command::new(std::env::current_exe().unwrap())
4904                .args(["--exact", TEST_NAME, "--nocapture", "--test-threads=1"])
4905                .env(CHILD_ENV, std::process::id().to_string())
4906                .stdout(Stdio::piped())
4907                .stderr(Stdio::inherit())
4908                .spawn()
4909                .expect("spawn isolated descendant test");
4910            let deadline = Instant::now() + Duration::from_secs(30);
4911            loop {
4912                if let Some(status) = isolated.try_wait().unwrap() {
4913                    let mut report = String::new();
4914                    isolated
4915                        .stdout
4916                        .take()
4917                        .unwrap()
4918                        .read_to_string(&mut report)
4919                        .unwrap();
4920                    print!("{report}");
4921                    assert!(
4922                        status.success(),
4923                        "isolated descendant test failed: {status}"
4924                    );
4925                    assert!(
4926                        report.contains(&format!("test {TEST_NAME} ... ok"))
4927                            && report.contains("1 passed; 0 failed"),
4928                        "the exact isolated test must execute, not pass with zero selected tests"
4929                    );
4930                    return;
4931                }
4932                if Instant::now() >= deadline {
4933                    isolated.kill().expect("stop timed-out isolated test");
4934                    isolated.wait().expect("reap isolated test");
4935                    panic!("isolated descendant test exceeded its safety deadline");
4936                }
4937                thread::sleep(Duration::from_millis(10));
4938            }
4939        }
4940        // rustix 1.1.3 represents this boolean prctl argument as Option<Pid>.
4941        set_child_subreaper(Pid::from_raw(1)).expect("enable isolated fixture adoption");
4942        let baseline_tasks: Vec<_> = std::fs::read_dir("/proc/self/task")
4943            .unwrap()
4944            .map(|entry| entry.unwrap().path())
4945            .collect();
4946        let await_output_workers = || {
4947            let deadline = Instant::now() + Duration::from_secs(3);
4948            loop {
4949                let mut workers = Vec::new();
4950                for entry in std::fs::read_dir("/proc/self/task").unwrap() {
4951                    let task = entry.unwrap().path();
4952                    if baseline_tasks.contains(&task) {
4953                        continue;
4954                    }
4955                    let state = match std::fs::read_to_string(task.join("wchan")) {
4956                        Ok(state) => state,
4957                        Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
4958                        Err(error) => panic!("cannot inspect actual worker wait: {error}"),
4959                    };
4960                    if state.contains("poll") || state.contains("pipe_read") {
4961                        workers.push(task);
4962                    }
4963                }
4964                if workers.len() == 2 {
4965                    return workers;
4966                }
4967                assert!(
4968                    Instant::now() < deadline,
4969                    "expected two actual output pipe waits, found {workers:?}"
4970                );
4971                thread::sleep(Duration::from_millis(5));
4972            }
4973        };
4974        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
4975        listener.set_nonblocking(true).unwrap();
4976        let script = r#"import os,signal,socket,sys
4977signal.alarm(15)
4978gate_read,gate_write=os.pipe()
4979leader=os.getpid()
4980descendant=os.fork()
4981if descendant:
4982 os.close(gate_write)
4983 assert os.read(gate_read,1)==b'X'
4984 os._exit(42)
4985os.close(gate_read)
4986signal.alarm(15)
4987sock=socket.create_connection(('127.0.0.1',int(sys.argv[1])),timeout=5)
4988sock.sendall((str(leader)+' '+str(os.getpid())+' '+os.readlink('/proc/self/fd/1')+' '+os.readlink('/proc/self/fd/2')+'\n').encode())
4989assert sock.recv(1)==b'B'
4990sock.sendall(('BLOCKING '+str(os.get_blocking(1))+' '+str(os.get_blocking(2))+'\n').encode())
4991os.write(1,b'accepted-out\nheld-out')
4992os.write(2,b'accepted-err\nheld-err')
4993assert sock.recv(1)==b'X'
4994os.write(gate_write,b'X')
4995os.close(gate_write)
4996assert sock.recv(1)==b'R'
4997closed=[]
4998for fd in (1,2):
4999 try:
5000  os.write(fd,b'probe')
5001  closed.append(False)
5002 except BrokenPipeError:
5003  closed.append(True)
5004sock.sendall(('CLOSED '+str(closed[0])+' '+str(closed[1])+'\n').encode())
5005assert sock.recv(1)==b'F'
5006os._exit(7)
5007"#;
5008        let control = ProcessControl::new();
5009        let sub = ProcessSubscription::new("python3", TestMsg::Proc)
5010            .args(["-u", "-c", script])
5011            .arg(listener.local_addr().unwrap().port().to_string())
5012            .control(control.clone());
5013        let (sender, receiver) = stdmpsc::sync_channel(256);
5014        let (stop, trigger) = StopSignal::new();
5015        let supervisor = thread::spawn(move || {
5016            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
5017        });
5018        let deadline = Instant::now() + Duration::from_secs(3);
5019        let socket = loop {
5020            match listener.accept() {
5021                Ok((socket, _)) => break socket,
5022                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
5023                    assert!(Instant::now() < deadline, "descendant did not connect");
5024                    thread::sleep(Duration::from_millis(5));
5025                }
5026                Err(error) => panic!("descendant connection failed: {error}"),
5027            }
5028        };
5029        socket
5030            .set_read_timeout(Some(Duration::from_secs(3)))
5031            .unwrap();
5032        socket
5033            .set_write_timeout(Some(Duration::from_secs(3)))
5034            .unwrap();
5035        let mut socket = io::BufReader::new(socket);
5036        let mut hello = String::new();
5037        socket.read_line(&mut hello).unwrap();
5038        let fields: Vec<_> = hello.split_whitespace().collect();
5039        assert_eq!(fields.len(), 4, "actual descendant identities and pipe IDs");
5040        let leader: u32 = fields[0].parse().unwrap();
5041        let descendant = Pid::from_raw(fields[1].parse().unwrap()).unwrap();
5042        let pipe_ids = [PathBuf::from(fields[2]), PathBuf::from(fields[3])];
5043        assert_ne!(pipe_ids[0], pipe_ids[1]);
5044        assert!(fields[2..].iter().all(|pipe| pipe.starts_with("pipe:[")));
5045        // A real read/readiness wait means both adapters have been configured.
5046        // Only then ask the descendant to inspect its own endpoint flags.
5047        await_output_workers();
5048        socket.get_mut().write_all(b"B").unwrap();
5049        let mut flags = String::new();
5050        socket.read_line(&mut flags).unwrap();
5051        assert_eq!(flags, "BLOCKING True True\n");
5052        let mut accepted = [
5053            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
5054            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
5055        ];
5056        accepted.sort_by_key(|event| matches!(event, TestMsg::Proc(ProcessEvent::Stderr(_))));
5057        assert_eq!(
5058            accepted,
5059            [
5060                TestMsg::Proc(ProcessEvent::Stdout("accepted-out".to_owned())),
5061                TestMsg::Proc(ProcessEvent::Stderr("accepted-err".to_owned())),
5062            ]
5063        );
5064        let workers = await_output_workers();
5065        socket.get_mut().write_all(b"X").unwrap();
5066        let deadline = Instant::now() + Duration::from_secs(3);
5067        while !control.status().can_restart {
5068            assert!(Instant::now() < deadline, "leader was not reaped");
5069            thread::sleep(Duration::from_millis(5));
5070        }
5071        assert!(
5072            std::fs::metadata(format!("/proc/{leader}"))
5073                .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
5074        );
5075        assert!(
5076            waitpid(Some(descendant), WaitOptions::NOHANG)
5077                .unwrap()
5078                .is_none()
5079        );
5080        assert!(workers.iter().all(|task| task.exists()));
5081        trigger.stop();
5082        let deadline = Instant::now() + Duration::from_secs(2);
5083        while (!supervisor.is_finished()
5084            || !workers.iter().all(|task| {
5085                std::fs::metadata(task).is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
5086            }))
5087            && Instant::now() < deadline
5088        {
5089            thread::sleep(Duration::from_millis(5));
5090        }
5091        let supervisor_finished = supervisor.is_finished();
5092        let workers_gone = workers.iter().all(|task| {
5093            std::fs::metadata(task).is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
5094        });
5095        let mut retained_pipes = Vec::new();
5096        for entry in std::fs::read_dir("/proc/self/fd").unwrap() {
5097            match std::fs::read_link(entry.unwrap().path()) {
5098                Ok(target) if pipe_ids.contains(&target) => retained_pipes.push(target),
5099                Ok(_) => {}
5100                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
5101                Err(error) => panic!("cannot inspect retained pipe endpoint: {error}"),
5102            }
5103        }
5104        let descendant_alive = waitpid(Some(descendant), WaitOptions::NOHANG)
5105            .unwrap()
5106            .is_none();
5107        // Capture worker/FD state before any fixture release or child cleanup.
5108        // R only probes the still-live descendant's endpoints; F permits exit.
5109        socket.get_mut().write_all(b"R").unwrap();
5110        let mut closed = String::new();
5111        socket.read_line(&mut closed).unwrap();
5112        let alive_after_probe = waitpid(Some(descendant), WaitOptions::NOHANG)
5113            .unwrap()
5114            .is_none();
5115        socket.get_mut().write_all(b"F").unwrap();
5116        let deadline = Instant::now() + Duration::from_secs(3);
5117        let status = loop {
5118            if let Some((pid, status)) = waitpid(Some(descendant), WaitOptions::NOHANG).unwrap() {
5119                assert_eq!(pid, descendant);
5120                break status;
5121            }
5122            assert!(Instant::now() < deadline, "adopted descendant did not exit");
5123            thread::sleep(Duration::from_millis(5));
5124        };
5125        supervisor.join().unwrap();
5126        assert!(
5127            supervisor_finished,
5128            "supervision depended on fixture release"
5129        );
5130        assert!(workers_gone, "output workers survived canceled pipe reads");
5131        assert!(
5132            retained_pipes.is_empty(),
5133            "retained endpoints: {retained_pipes:?}"
5134        );
5135        assert!(descendant_alive && alive_after_probe);
5136        assert_eq!(closed, "CLOSED True True\n");
5137        assert_eq!(status.exit_status(), Some(7));
5138        assert_eq!(
5139            waitpid(Some(descendant), WaitOptions::NOHANG).unwrap_err(),
5140            rustix::io::Errno::CHILD
5141        );
5142        assert!(
5143            std::fs::metadata(format!("/proc/{}", descendant.as_raw_nonzero()))
5144                .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
5145        );
5146        assert_eq!(
5147            receiver.try_iter().collect::<Vec<_>>(),
5148            [TestMsg::Proc(ProcessEvent::Error(
5149                "output drain canceled after Exited(42); stdout/stderr output is incomplete"
5150                    .to_owned()
5151            ))],
5152            "accepted lines stay exact; pending prefixes must not become EOF lines"
5153        );
5154    }
5155
5156    #[test]
5157    fn stop_signal_does_not_block_when_background_descendant_keeps_pipes_open() {
5158        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
5159            .arg("-c")
5160            .arg("sleep 60 & echo ready; sleep 60");
5161        let (tx, rx) = stdmpsc::sync_channel(256);
5162        let (signal, trigger) = StopSignal::new();
5163
5164        let handle = thread::spawn(move || {
5165            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
5166        });
5167
5168        let mut msgs = Vec::new();
5169        let ready_deadline = Instant::now() + Duration::from_secs(10);
5170        while Instant::now() < ready_deadline {
5171            match rx.recv_timeout(Duration::from_millis(100)) {
5172                Ok(msg) => {
5173                    let is_ready =
5174                        matches!(&msg, TestMsg::Proc(ProcessEvent::Stdout(s)) if s == "ready");
5175                    msgs.push(msg);
5176                    if is_ready {
5177                        break;
5178                    }
5179                }
5180                Err(stdmpsc::RecvTimeoutError::Timeout) => {}
5181                Err(stdmpsc::RecvTimeoutError::Disconnected) => break,
5182            }
5183        }
5184
5185        let stop_start = web_time::Instant::now();
5186        trigger.stop();
5187        handle.join().unwrap();
5188
5189        assert!(
5190            stop_start.elapsed() < Duration::from_secs(10),
5191            "stop should not block behind inherited stdout/stderr pipes"
5192        );
5193
5194        msgs.extend(rx.try_iter());
5195        assert!(
5196            msgs.iter()
5197                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
5198            "expected Killed event, got: {msgs:?}"
5199        );
5200    }
5201
5202    #[test]
5203    fn timeout_does_not_block_when_background_descendant_keeps_pipes_open() {
5204        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
5205            .arg("-c")
5206            .arg("sleep 60 & sleep 60")
5207            .timeout(Duration::from_millis(200));
5208        let (tx, rx) = stdmpsc::sync_channel(256);
5209        let (signal, _trigger) = StopSignal::new();
5210        let start = web_time::Instant::now();
5211
5212        let handle = thread::spawn(move || {
5213            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
5214        });
5215
5216        handle.join().unwrap();
5217
5218        assert!(
5219            start.elapsed() < Duration::from_secs(10),
5220            "timeout should not block behind inherited stdout/stderr pipes"
5221        );
5222
5223        let msgs: Vec<TestMsg> = rx.try_iter().collect();
5224        assert!(
5225            msgs.iter()
5226                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
5227            "expected Killed event, got: {msgs:?}"
5228        );
5229    }
5230
5231    #[cfg(unix)]
5232    fn shell(script: &str) -> ProcessSubscription<ProcessEvent> {
5233        // Non-interactive background test runners (e.g. remote SSH jobs) can
5234        // start `cargo test` with `SIGINT = SIG_IGN`, which POSIX `sh` refuses
5235        // to override in `trap ... INT`. Resetting `SIGINT` to `SIG_DFL` before
5236        // `execvp("sh", ...)` preserves the exact process/PGID while ensuring
5237        // shell traps behave identically to an interactive terminal.
5238        ProcessSubscription::new("python3", |event| event)
5239            .args([
5240                "-c",
5241                "import os, signal, sys; signal.signal(signal.SIGINT, signal.SIG_DFL); os.execvp('sh', ['sh', '-c', sys.argv[1]])",
5242                script,
5243            ])
5244            .timeout(Duration::from_secs(10))
5245    }
5246
5247    #[cfg(unix)]
5248    fn pty_shell(script: &str) -> ProcessSubscription<ProcessEvent> {
5249        shell(script).pty(true)
5250    }
5251
5252    #[cfg(unix)]
5253    fn start_process(
5254        sub: ProcessSubscription<ProcessEvent>,
5255    ) -> (
5256        stdmpsc::Receiver<ProcessEvent>,
5257        StopTrigger,
5258        thread::JoinHandle<()>,
5259    ) {
5260        let (sender, events) = stdmpsc::sync_channel(16 * 1024);
5261        let (stop, trigger) = StopSignal::new();
5262        let handle =
5263            thread::spawn(move || sub.run(SubscriptionSender::new(sender, stop.clone()), stop));
5264        (events, trigger, handle)
5265    }
5266
5267    #[cfg(unix)]
5268    fn is_terminal_event(event: &ProcessEvent) -> bool {
5269        matches!(
5270            event,
5271            ProcessEvent::Exited(_)
5272                | ProcessEvent::Signaled(_)
5273                | ProcessEvent::Killed
5274                | ProcessEvent::Error(_)
5275        )
5276    }
5277
5278    /// Events up to and including the first that satisfies `done`.
5279    #[cfg(unix)]
5280    fn events_until(
5281        events: &stdmpsc::Receiver<ProcessEvent>,
5282        done: impl Fn(&ProcessEvent) -> bool,
5283    ) -> Vec<ProcessEvent> {
5284        let deadline = Instant::now() + Duration::from_secs(10);
5285        let mut seen = Vec::new();
5286        loop {
5287            match events.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
5288                Ok(event) => {
5289                    let finished = done(&event);
5290                    seen.push(event);
5291                    if finished {
5292                        return seen;
5293                    }
5294                }
5295                Err(error) => panic!("expected event did not arrive ({error:?}); saw {seen:?}"),
5296            }
5297        }
5298    }
5299
5300    #[cfg(unix)]
5301    fn run_to_end(sub: ProcessSubscription<ProcessEvent>) -> Vec<ProcessEvent> {
5302        let (events, _trigger, handle) = start_process(sub);
5303        let seen = events_until(&events, is_terminal_event);
5304        handle.join().expect("supervisor finished");
5305        seen
5306    }
5307
5308    #[cfg(unix)]
5309    fn stdout(lines: &[&str]) -> Vec<ProcessEvent> {
5310        lines
5311            .iter()
5312            .map(|line| ProcessEvent::Stdout((*line).to_owned()))
5313            .collect()
5314    }
5315
5316    /// The PID printed as `<prefix><pid>` in `event`.
5317    #[cfg(target_os = "linux")]
5318    fn printed_pid(event: &ProcessEvent, prefix: &str) -> i32 {
5319        match event {
5320            ProcessEvent::Stdout(line) => line
5321                .strip_prefix(prefix)
5322                .and_then(|pid| pid.parse().ok())
5323                .unwrap_or_else(|| panic!("expected {prefix}<pid>, got {line:?}")),
5324            other => panic!("expected {prefix}<pid>, got {other:?}"),
5325        }
5326    }
5327
5328    /// A process that exited, or was killed and awaits reaping, is gone.
5329    #[cfg(target_os = "linux")]
5330    fn process_is_gone(pid: i32) -> bool {
5331        std::fs::read_to_string(format!("/proc/{pid}/stat")).map_or(true, |stat| {
5332            stat.rsplit_once(')')
5333                .is_some_and(|(_, rest)| rest.trim_start().starts_with('Z'))
5334        })
5335    }
5336
5337    #[cfg(target_os = "linux")]
5338    fn wait_until_gone(pid: i32) -> bool {
5339        let deadline = Instant::now() + Duration::from_secs(5);
5340        while Instant::now() < deadline {
5341            if process_is_gone(pid) {
5342                return true;
5343            }
5344            thread::sleep(Duration::from_millis(10));
5345        }
5346        false
5347    }
5348
5349    #[test]
5350    #[cfg(unix)]
5351    fn pty_child_sees_a_terminal_on_stdout_and_stderr_and_lf_stays_lf() {
5352        let script = "for fd in 0 1 2; do if [ -t $fd ]; then echo \"fd$fd=tty\"; \
5353                      else echo \"fd$fd=other\"; fi; done; echo to-stderr >&2; printf 'crlf\\r\\n'";
5354        assert_eq!(
5355            run_to_end(pty_shell(script)),
5356            [
5357                stdout(&["fd0=other", "fd1=tty", "fd2=tty", "to-stderr", "crlf"]),
5358                vec![ProcessEvent::Exited(0)]
5359            ]
5360            .concat(),
5361            "stdin is /dev/null without input; stderr shares the PTY; ONLCR would leave \"crlf\\r\""
5362        );
5363
5364        // Planted negative: the same child over pipes sees no terminal at all.
5365        let piped = run_to_end(shell(script));
5366        for expected in [
5367            ProcessEvent::Stdout("fd1=other".to_owned()),
5368            ProcessEvent::Stdout("fd2=other".to_owned()),
5369            ProcessEvent::Stderr("to-stderr".to_owned()),
5370            ProcessEvent::Exited(0),
5371        ] {
5372            assert!(
5373                piped.contains(&expected),
5374                "{expected:?} missing from {piped:?}"
5375            );
5376        }
5377    }
5378
5379    #[test]
5380    #[cfg(unix)]
5381    fn pty_input_is_typed_without_echo_and_close_sends_one_eof() {
5382        let input = ProcessInput::new();
5383        let script = "[ -t 0 ] && echo stdin=tty; \
5384                      while IFS= read -r line; do echo \"got:$line\"; done; echo eof";
5385        let (events, _trigger, handle) = start_process(pty_shell(script).stdin(input.clone()));
5386        assert_eq!(
5387            events_until(&events, |event| event
5388                == &ProcessEvent::Stdout("stdin=tty".to_owned())),
5389            stdout(&["stdin=tty"])
5390        );
5391        input.try_send_line("alpha".to_owned()).unwrap();
5392        input.try_send_line("🦀 beta $HOME".to_owned()).unwrap();
5393        input.close();
5394        assert_eq!(
5395            events_until(&events, is_terminal_event),
5396            [
5397                stdout(&["got:alpha", "got:🦀 beta $HOME", "eof"]),
5398                vec![ProcessEvent::Exited(0)]
5399            ]
5400            .concat(),
5401            "an echoing PTY would repeat each typed line before its reply"
5402        );
5403        handle.join().unwrap();
5404    }
5405
5406    #[test]
5407    #[cfg(unix)]
5408    fn pty_input_closed_after_the_child_exits_is_not_an_error() {
5409        let input = ProcessInput::new();
5410        input.try_send_line("never read".to_owned()).unwrap();
5411        // The child exits without reading. Closing input then finds no slave
5412        // to deliver end-of-file to, which must not turn the exit into an error.
5413        assert_eq!(
5414            run_to_end(pty_shell("echo bye").stdin(input)),
5415            [stdout(&["bye"]), vec![ProcessEvent::Exited(0)]].concat()
5416        );
5417    }
5418
5419    #[test]
5420    #[cfg(unix)]
5421    fn pty_size_follows_resize_requests_before_and_during_the_run() {
5422        let control = ProcessControl::new();
5423        control.request_resize(100, 30).unwrap();
5424        let script = "stty size <&1; trap 'stty size <&1; exit 7' WINCH; echo ready; \
5425                      while :; do sleep 0.05; done";
5426        let (events, _trigger, handle) = start_process(pty_shell(script).control(control.clone()));
5427        assert_eq!(
5428            events_until(&events, |event| event
5429                == &ProcessEvent::Stdout("ready".to_owned())),
5430            stdout(&["30 100", "ready"])
5431        );
5432        control.request_resize(120, 40).unwrap();
5433        assert_eq!(
5434            events_until(&events, is_terminal_event),
5435            [stdout(&["40 120"]), vec![ProcessEvent::Exited(7)]].concat(),
5436            "the new size must be set before SIGWINCH reaches the child"
5437        );
5438        handle.join().unwrap();
5439    }
5440
5441    #[test]
5442    #[cfg(unix)]
5443    fn resize_requests_coalesce_clamp_and_close_with_the_run() {
5444        let control = ProcessControl::new();
5445        control.request_resize(0, 0).unwrap();
5446        assert_eq!(control.take_resize(), Some((1, 1)));
5447        control.request_resize(80, 24).unwrap();
5448        control.request_resize(132, 50).unwrap();
5449        assert_eq!(control.take_resize(), Some((132, 50)));
5450        assert_eq!(control.take_resize(), None);
5451        control.close();
5452        assert_eq!(
5453            control.request_resize(80, 24),
5454            Err(ProcessControlError::Closed)
5455        );
5456    }
5457
5458    #[test]
5459    #[cfg(unix)]
5460    fn pty_interrupt_reaches_every_process_in_the_group() {
5461        // The inner shell is a separate process in the outer one's group. A
5462        // trapped SIGINT ends its `wait` at once; unsignaled, it waits out one
5463        // bounded sleep, so the pipe-mode run neither leaks it nor depends on
5464        // how fast a loaded host spawns processes.
5465        let script = "trap 'echo parent-int; exit 4' INT; \
5466                      sh -c 'trap \"echo child-int; exit 5\" INT; echo ready; \
5467                      sleep 2 & wait $!'; echo unreachable";
5468        let interrupted = |sub: ProcessSubscription<ProcessEvent>| {
5469            let control = ProcessControl::new();
5470            let (events, _trigger, handle) = start_process(sub.control(control.clone()));
5471            events_until(&events, |event| {
5472                event == &ProcessEvent::Stdout("ready".to_owned())
5473            });
5474            control.request_interrupt().unwrap();
5475            let rest = events_until(&events, is_terminal_event);
5476            handle.join().unwrap();
5477            assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
5478            rest
5479        };
5480        assert_eq!(
5481            interrupted(pty_shell(script)),
5482            [
5483                stdout(&["child-int", "parent-int"]),
5484                vec![ProcessEvent::Exited(4)]
5485            ]
5486            .concat()
5487        );
5488        // Planted negative: over pipes only the immediate child is signaled,
5489        // so the inner shell finishes its loop without ever seeing SIGINT.
5490        assert_eq!(
5491            interrupted(shell(script)),
5492            [stdout(&["parent-int"]), vec![ProcessEvent::Exited(4)]].concat()
5493        );
5494    }
5495
5496    #[test]
5497    #[cfg(target_os = "linux")]
5498    fn pty_cancel_kills_the_whole_group_and_pipe_cancel_does_not() {
5499        let script = "sleep 30 & echo \"bg=$!\"; while :; do sleep 0.05; done";
5500        let canceled = |sub: ProcessSubscription<ProcessEvent>| {
5501            let (events, trigger, handle) = start_process(sub);
5502            let started = events_until(&events, |event| matches!(event, ProcessEvent::Stdout(_)));
5503            let background = printed_pid(&started[0], "bg=");
5504            trigger.stop();
5505            handle.join().unwrap();
5506            (background, events.try_iter().collect::<Vec<_>>())
5507        };
5508
5509        let (background, rest) = canceled(pty_shell(script));
5510        assert_eq!(rest, [ProcessEvent::Killed]);
5511        assert!(
5512            wait_until_gone(background),
5513            "background member {background} survived its PTY run"
5514        );
5515
5516        // Planted negative: a pipe run kills only its immediate child.
5517        let (background, rest) = canceled(shell(script));
5518        assert_eq!(rest, [ProcessEvent::Killed]);
5519        let survived = !process_is_gone(background);
5520        let _ = rustix::process::kill_process(
5521            rustix::process::Pid::from_raw(background).expect("positive PID"),
5522            rustix::process::Signal::KILL,
5523        );
5524        assert!(survived, "the pipe-mode contrast no longer holds");
5525    }
5526
5527    #[test]
5528    #[cfg(target_os = "linux")]
5529    fn pty_leader_exit_ends_lingering_group_members_and_output() {
5530        let start = Instant::now();
5531        let events = run_to_end(pty_shell("sleep 30 & echo \"bg=$!\"; echo done"));
5532        // A member holding the PTY open would otherwise delay end-of-file by 30 s.
5533        assert!(
5534            start.elapsed() < Duration::from_secs(5),
5535            "run took {:?}",
5536            start.elapsed()
5537        );
5538        assert_eq!(
5539            events[1..],
5540            [stdout(&["done"]), vec![ProcessEvent::Exited(0)]].concat()
5541        );
5542        let background = printed_pid(&events[0], "bg=");
5543        assert!(
5544            wait_until_gone(background),
5545            "background member {background} outlived its leader"
5546        );
5547    }
5548
5549    #[test]
5550    #[cfg(unix)]
5551    fn pty_delivers_ten_thousand_lines_in_order_like_pipes() {
5552        let expected: Vec<_> = (1..=10_000)
5553            .map(|line| ProcessEvent::Stdout(line.to_string()))
5554            .chain([ProcessEvent::Exited(0)])
5555            .collect();
5556        for (mode, sub) in [
5557            ("pty", pty_shell("seq 1 10000")),
5558            ("pipe", shell("seq 1 10000")),
5559        ] {
5560            let start = Instant::now();
5561            let events = run_to_end(sub);
5562            eprintln!("{mode}: 10000 lines in {:?}", start.elapsed());
5563            assert!(
5564                events == expected,
5565                "{mode} run delivered {} events",
5566                events.len()
5567            );
5568        }
5569    }
5570
5571    #[test]
5572    #[cfg(unix)]
5573    fn pty_progress_carriage_returns_over_64k_rewind_without_line_too_long() {
5574        // 1. Reader-level check across arbitrary chunk sizes, including leading
5575        // CR, repeated CRs, CRLF, and >100 KiB of CR-delimited progress frames.
5576        let mut stream = Vec::new();
5577        for step in 1..=5_000 {
5578            stream.extend_from_slice(format!("\rprogress {step:04} of 5000").as_bytes());
5579        }
5580        stream.extend_from_slice(b"\r\ndone\r\n");
5581        assert!(stream.len() > 100 * 1024);
5582
5583        for capacity in [1, 7, 64, 8192] {
5584            let mut reader = io::BufReader::with_capacity(capacity, stream.as_slice());
5585            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
5586            let (stop, _trigger) = StopSignal::new();
5587            let mut last_preview = String::new();
5588            let mut preview = |prefix: &str| {
5589                last_preview.clear();
5590                last_preview.push_str(prefix);
5591                true
5592            };
5593            let first =
5594                read_process_line_mode(&mut reader, &mut pending, &stop, true, Some(&mut preview))
5595                    .unwrap();
5596            assert_eq!(first.as_deref(), Some("progress 5000 of 5000"));
5597            assert_eq!(last_preview, "progress 5000 of 5000");
5598            let second =
5599                read_process_line_mode(&mut reader, &mut pending, &stop, true, None).unwrap();
5600            assert_eq!(second.as_deref(), Some("done"));
5601            assert_eq!(
5602                read_process_line_mode(&mut reader, &mut pending, &stop, true, None).unwrap(),
5603                None
5604            );
5605        }
5606
5607        // 2. Real PTY child emitting >100 KiB of CR-delimited progress updates
5608        // before LF completes normally without LineTooLong termination.
5609        let script = "python3 -u -c 'import sys; \
5610            [sys.stdout.write(f\"step {i:04d}-{\"x\"*20}\\r\") for i in range(1, 4001)]; \
5611            sys.stdout.write(\"step 4000-done\\r\\n\")'";
5612        let events = run_to_end(pty_shell(script).partial_output(true));
5613        assert!(
5614            events
5615                .iter()
5616                .any(|e| matches!(e, ProcessEvent::StdoutPartial(p) if p.starts_with("step "))),
5617            "expected partial progress previews, got {events:?}"
5618        );
5619        let completed: Vec<_> = events
5620            .iter()
5621            .filter(|e| !matches!(e, ProcessEvent::StdoutPartial(_)))
5622            .cloned()
5623            .collect();
5624        assert_eq!(
5625            completed,
5626            vec![
5627                ProcessEvent::Stdout("step 4000-done".to_owned()),
5628                ProcessEvent::Exited(0),
5629            ]
5630        );
5631    }
5632
5633    #[test]
5634    #[cfg(unix)]
5635    fn pty_input_delivers_lines_over_4095_bytes_without_canonical_truncation() {
5636        let input = ProcessInput::new();
5637        let long_line = format!("{}{}", "a".repeat(6_000), "b".repeat(6_000));
5638        let script = "python3 -u -c 'import sys; \
5639            line = sys.stdin.readline().rstrip(\"\\n\"); \
5640            print(f\"len={len(line)} head={line[:4]} mid={line[5998:6002]} tail={line[-4:]}\"); \
5641            print(f\"eof={sys.stdin.read() == \"\"}\")'";
5642        let (events, _trigger, handle) = start_process(pty_shell(script).stdin(input.clone()));
5643        input.try_send_line(long_line).unwrap();
5644        input.close();
5645        assert_eq!(
5646            events_until(&events, is_terminal_event),
5647            [
5648                stdout(&["len=12000 head=aaaa mid=aabb tail=bbbb", "eof=True"]),
5649                vec![ProcessEvent::Exited(0)]
5650            ]
5651            .concat()
5652        );
5653        handle.join().unwrap();
5654    }
5655
5656    #[test]
5657    #[cfg(unix)]
5658    fn process_subscription_delivers_stdout_stderr_exit_in_order() {
5659        let events = run_to_end(shell("echo out; echo err 1>&2; exit 7"));
5660        assert!(events.contains(&ProcessEvent::Stdout("out".to_owned())));
5661        assert!(events.contains(&ProcessEvent::Stderr("err".to_owned())));
5662        assert_eq!(events.last(), Some(&ProcessEvent::Exited(7)));
5663    }
5664
5665    #[test]
5666    #[cfg(unix)]
5667    fn process_subscription_forwards_stdin() {
5668        let input = ProcessInput::new();
5669        let sub = ProcessSubscription::new("cat", |event| event)
5670            .stdin(input.clone())
5671            .timeout(Duration::from_secs(10));
5672        let (events, trigger, handle) = start_process(sub);
5673        input.try_send_line("hello".to_owned()).unwrap();
5674        let seen = events_until(&events, |e| e == &ProcessEvent::Stdout("hello".to_owned()));
5675        assert!(seen.contains(&ProcessEvent::Stdout("hello".to_owned())));
5676        let stop_start = Instant::now();
5677        trigger.stop();
5678        let tail = events_until(&events, is_terminal_event);
5679        handle.join().unwrap();
5680        assert!(
5681            stop_start.elapsed() < Duration::from_secs(5),
5682            "stop must complete promptly, tail={tail:?}"
5683        );
5684    }
5685
5686    #[test]
5687    #[cfg(unix)]
5688    fn process_subscription_kills_child_on_stop() {
5689        let control = ProcessControl::new();
5690        let sub = ProcessSubscription::new("sleep", |event| event)
5691            .arg("30")
5692            .control(control.clone())
5693            .timeout(Duration::from_secs(10));
5694        let (events, trigger, handle) = start_process(sub);
5695        let deadline = Instant::now() + Duration::from_secs(5);
5696        let pid = loop {
5697            if let Some(pid) = control.status().pid {
5698                break pid;
5699            }
5700            assert!(Instant::now() < deadline, "sleep child did not report pid");
5701            thread::sleep(Duration::from_millis(5));
5702        };
5703        trigger.stop();
5704        let tail = events_until(&events, is_terminal_event);
5705        handle.join().unwrap();
5706        assert!(
5707            tail.contains(&ProcessEvent::Killed),
5708            "expected Killed event, got {tail:?}"
5709        );
5710        let raw_pid = rustix::process::Pid::from_raw(pid as i32).expect("valid pid");
5711        assert!(
5712            rustix::process::test_kill_process(raw_pid).is_err(),
5713            "child pid {pid} must be reaped after stop"
5714        );
5715    }
5716}