Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
pty_tasks.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The two small tasks around a shell's PTY: the blocking reader that turns its output
5//! into chunks for the flusher, and the input task that feeds it keystrokes, resizes
6//! and signals.
7
8use std::io::Read as _;
9use std::sync::{Arc, Mutex};
10use std::time::Instant;
11
12use portable_pty::PtySize;
13use tokio::sync::mpsc;
14
15use super::controller::ShellControllerInner;
16use super::lifecycle::PtyReadChunk;
17use super::pty::PTY_READ_BUF_SIZE;
18use crate::backend::mps;
19
20/// Reads the PTY on a blocking thread and sends each read, with OSC sequences stripped
21/// for an agent pane, to the flusher. Ends at EOF, dropping `pty_tx` to close the channel.
22pub(super) fn spawn_pty_reader(
23    reader: Box<dyn std::io::Read + Send>,
24    pty_tx: mpsc::Sender<PtyReadChunk>,
25    inner_read: Arc<Mutex<ShellControllerInner>>,
26    broker_read: Option<Arc<mps::Broker>>,
27    is_agent_read: bool,
28    block_id_read: String,
29) {
30    tokio::task::spawn_blocking(move || {
31        let mut reader = reader;
32        let mut buf = [0u8; PTY_READ_BUF_SIZE];
33
34        // OSC extractor: only for agent panes. Terminal panes forward
35        // raw bytes to xterm.js which handles OSC natively — stripping
36        // there would suppress the native window-title update. Agent
37        // panes don't use xterm.js; OSC bytes in FileStore corrupt the
38        // document renderer, so we extract and strip them here. Kept
39        // in THIS (per-read) loop rather than the flusher: it is
40        // cheap, and its own internal state must see every read in
41        // order exactly as they arrive — moving it to the batched side
42        // would change nothing about correctness but would mean
43        // holding it across an .await, so it stays here for simplicity.
44        let mut osc_extractor: Option<crate::backend::osc_extractor::OscExtractor> =
45            if is_agent_read {
46                Some(crate::backend::osc_extractor::OscExtractor::new())
47            } else {
48                None
49            };
50
51        loop {
52            match reader.read(&mut buf) {
53                Ok(0) => break, // EOF
54                Ok(n) => {
55                    inner_read.lock().unwrap().last_pty_output = Some(Instant::now());
56                    if broker_read.is_some() {
57                        let raw = &buf[..n];
58
59                        // Extract OSC sequences from agent-pane output.
60                        // `cleaned` has OSC bytes removed; `osc_events` carries
61                        // any normalised Claude Code title strings found in this chunk.
62                        let mut cleaned_storage: Vec<u8> = Vec::new();
63                        let mut osc_events: Vec<crate::backend::osc_extractor::OscEvent> =
64                            Vec::new();
65                        if let Some(ref mut ext) = osc_extractor {
66                            let (cleaned, evs) = ext.feed(raw);
67                            cleaned_storage = cleaned;
68                            osc_events = evs;
69                        }
70                        let chunk: &[u8] = if osc_extractor.is_some() {
71                            &cleaned_storage
72                        } else {
73                            raw
74                        };
75
76                        // `blocking_send`, not `send` — this closure runs
77                        // on a `spawn_blocking` thread, not async, and a
78                        // bounded channel's plain `send` is itself async.
79                        // Blocks THIS (already-dedicated-to-blocking)
80                        // thread once the channel is full, which is
81                        // exactly the backpressure PTY_CHANNEL_CAPACITY's
82                        // doc comment describes — never the async runtime.
83                        //
84                        // Best-effort beyond that: if the flusher task is
85                        // gone (block torn down mid-read), there is
86                        // nothing useful to do with this chunk — the PTY
87                        // read loop itself must keep draining so the
88                        // child process's stdout never backs up.
89                        let _ = pty_tx.blocking_send(PtyReadChunk {
90                            ack: None,
91                            data: chunk.to_vec(),
92                            osc_events,
93                        });
94                    }
95                }
96                Err(e) => {
97                    tracing::debug!("PTY read error for {}: {}", block_id_read, e);
98                    break;
99                }
100            }
101        }
102        // `pty_tx` drops here, closing the channel — the flusher below
103        // sees `recv()` return `None` once it has drained everything
104        // already sent, flushes any final partial batch, and exits.
105        // (Still true with the barrier handle in play: that one is a
106        // `WeakSender`, which does not keep the channel open. It must stay
107        // weak — see its own comment above.)
108    });
109}
110
111/// Routes the input channel to the PTY writer, resizes and signals. Owns the writer and the
112/// master: dropping them closes the PTY, which makes the child exit.
113pub(super) fn spawn_input_task(
114    writer: Box<dyn std::io::Write + Send>,
115    master: Box<dyn portable_pty::MasterPty + Send>,
116    input_rx: mpsc::UnboundedReceiver<crate::backend::blockcontroller::BlockInputUnion>,
117) {
118    tokio::spawn(async move {
119        let mut writer = writer;
120        let mut input_rx = input_rx;
121        while let Some(input) = input_rx.recv().await {
122            if let Some(data) = input.input_data {
123                use std::io::Write;
124                if let Err(e) = writer.write_all(&data) {
125                    tracing::debug!("PTY write error: {}", e);
126                    break;
127                }
128            }
129            if let Some(ref size) = input.term_size {
130                let pty_size = PtySize {
131                    rows: size.rows as u16,
132                    cols: size.cols as u16,
133                    pixel_width: 0,
134                    pixel_height: 0,
135                };
136                if let Err(e) = master.resize(pty_size) {
137                    tracing::debug!("PTY resize error: {}", e);
138                }
139            }
140            if input.sig_name.is_some() {
141                // Drop writer + master to close PTY, which terminates the child
142                break;
143            }
144        }
145        // writer and master drop here → PTY closes → child gets EOF/terminates
146    });
147}