Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
start_io.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `start` that open and wire the PTY: marking the pane running with its input
5//! channel, opening the PTY, spawning the child, taking the reader and writer, and starting the
6//! output reader and flusher.
7
8use portable_pty::{native_pty_system, CommandBuilder, PtyPair};
9use tokio::sync::mpsc;
10
11use super::super::{BlockInputUnion, STATUS_DONE, STATUS_RUNNING};
12use super::controller::ShellController;
13use super::lifecycle::{run_pty_output_flusher, PtyReadChunk};
14use super::pty::PTY_CHANNEL_CAPACITY;
15
16/// The PTY's reader and writer.
17pub(super) type PtyIo = (
18    Box<dyn std::io::Read + Send>,
19    Box<dyn std::io::Write + Send>,
20);
21
22impl ShellController {
23    /// Marks the pane running, creates its input channel and publishes the status. Returns the
24    /// receiving end for the input task.
25    pub(super) fn mark_running(&self, conn_name: &str) -> mpsc::UnboundedReceiver<BlockInputUnion> {
26        // Update status to running.
27        {
28            let mut inner = self.inner.lock().unwrap();
29            Self::set_status(&mut inner, STATUS_RUNNING);
30            inner.conn_name = conn_name.to_string();
31        }
32
33        // Create input channel. Unbounded: input must never be silently
34        // dropped on burst (the paste-truncation bug). See SHELL_INPUT_CH_SIZE.
35        let (input_tx, input_rx) = mpsc::unbounded_channel();
36        {
37            let mut inner = self.inner.lock().unwrap();
38            inner.input_tx = Some(input_tx);
39            inner.input_seq_next = 0;
40            inner.input_seq_buf.clear();
41        }
42
43        // Publish "running" only AFTER `input_tx` exists, so the event is a
44        // truthful readiness signal: a frontend that resizes the PTY the instant
45        // it sees "running" will not hit `send_input`'s "controller is not
46        // running" guard (which fires while `input_tx` is None). The channel is
47        // unbounded, so a resize enqueued before the input task spawns is
48        // buffered, not lost.
49        // See docs/analysis/AGENT_PANE_PTY_RESIZE_RACE_2026_06_16.md.
50        self.publish_status();
51        input_rx
52    }
53
54    /// Opens the PTY at the size the pane asked for.
55    pub(super) fn open_pty(&self, rt_opts: &Option<serde_json::Value>) -> Result<PtyPair, String> {
56        // Real PTY path.
57        //
58        // Open the PTY at the size the frontend computed from the pane (passed
59        // as `rtopts.termsize` on the resync), so the agent CLI and its tools
60        // wrap correctly from the very first byte. The earlier code always
61        // opened at a fixed 200 cols and relied on a post-spawn resize RPC to
62        // correct it — but that RPC races controller startup and could fail
63        // outright, leaving output wrapped at 200 all session. Seeding the size
64        // here removes that race; `pty_size_from_rt_opts` falls back to the
65        // historical 25x200 when no size was supplied (e.g. programmatic
66        // spawns). See docs/analysis/AGENT_PANE_PTY_RESIZE_RACE_2026_06_16.md.
67        let pty_system = native_pty_system();
68        let pty_size = self.spawn_pty_size(rt_opts);
69
70        let pair = pty_system.openpty(pty_size).map_err(|e| {
71            tracing::error!(block_id = %self.block_id, error = %e, "failed to open PTY");
72            let mut inner = self.inner.lock().unwrap();
73            Self::set_status(&mut inner, STATUS_DONE);
74            inner.proc_exit_code = -1;
75            inner.input_tx = None;
76            self.unlock_run();
77            format!("failed to open PTY: {e}")
78        })?;
79        tracing::info!(block_id = %self.block_id, rows = pty_size.rows, cols = pty_size.cols, "PTY opened");
80        Ok(pair)
81    }
82
83    /// Spawns `cmd` on the PTY's slave side; a failure ends the start and frees the run lock.
84    pub(super) fn spawn_child(
85        &self,
86        pair: &PtyPair,
87        mut cmd: CommandBuilder,
88        cmd_str: &str,
89        is_agent: bool,
90    ) -> Result<Box<dyn portable_pty::Child + Send + Sync>, String> {
91        if is_agent {
92            crate::backend::process_tracker::registry::place_pty_spawn(&self.block_id, &mut cmd);
93        }
94        let child = pair.slave.spawn_command(cmd).map_err(|e| {
95            tracing::error!(block_id = %self.block_id, error = %e, cmd = %cmd_str, "spawn failed");
96            let mut inner = self.inner.lock().unwrap();
97            Self::set_status(&mut inner, STATUS_DONE);
98            inner.proc_exit_code = -1;
99            inner.input_tx = None;
100            self.unlock_run();
101            format!("failed to spawn command: {e}")
102        })?;
103        tracing::info!(block_id = %self.block_id, "process spawned successfully");
104        Ok(child)
105    }
106
107    /// The PTY's reader and writer; a failure kills the child and ends the start.
108    pub(super) fn take_pty_io(
109        &self,
110        pair: &PtyPair,
111        child: &mut Box<dyn portable_pty::Child + Send + Sync>,
112    ) -> Result<PtyIo, String> {
113        // Get reader/writer from master
114        let reader = pair.master.try_clone_reader().map_err(|e| {
115            let _ = child.kill();
116            let mut inner = self.inner.lock().unwrap();
117            Self::set_status(&mut inner, STATUS_DONE);
118            inner.proc_exit_code = -1;
119            inner.input_tx = None;
120            self.unlock_run();
121            format!("failed to clone PTY reader: {e}")
122        })?;
123
124        let writer = pair.master.take_writer().map_err(|e| {
125            let _ = child.kill();
126            let mut inner = self.inner.lock().unwrap();
127            Self::set_status(&mut inner, STATUS_DONE);
128            inner.proc_exit_code = -1;
129            inner.input_tx = None;
130            self.unlock_run();
131            format!("failed to take PTY writer: {e}")
132        })?;
133        Ok((reader, writer))
134    }
135
136    /// Starts the blocking PTY reader and the coalescing flusher it feeds. Returns the flusher's
137    /// handle and a weak sender for the post-exit flush barrier.
138    pub(super) fn start_output(
139        &self,
140        reader: Box<dyn std::io::Read + Send>,
141        is_agent: bool,
142    ) -> (tokio::task::JoinHandle<()>, mpsc::WeakSender<PtyReadChunk>) {
143        // Spawn PTY read task (blocking I/O → spawn_blocking) + a companion
144        // coalescing flusher (async task). Split in two, connected by an
145        // mpsc channel, so the actual OS-level `read()` loop's blocking
146        // semantics are untouched (this file supports both Unix and
147        // Windows PTYs and that boundary is not something to risk getting
148        // subtly wrong per-platform) while the expensive per-chunk work —
149        // file write, WebSocket broadcast, OSC/translation — is batched.
150        // See docs/reports/REPORT_RENDERER_CPU_UNBATCHED_PTY_OUTPUT_2026_09_11.md.
151        let block_id_read = self.block_id.clone();
152        let block_id_flush = self.block_id.clone();
153        let broker_read = self.broker.clone();
154        let broker_flush = self.broker.clone();
155        let inner_read = self.inner.clone();
156        let filestore_flush = self.filestore.clone();
157        let is_agent_read = is_agent;
158        let is_agent_flush = is_agent;
159        // Bounded (reagentx P1 on PR #3206) — see PTY_CHANNEL_CAPACITY's own
160        // doc comment for why: an unbounded channel here would let a
161        // sustained fast producer grow queued memory without limit if the
162        // flusher ever falls behind the read rate.
163        let (pty_tx, pty_rx) = mpsc::channel::<PtyReadChunk>(PTY_CHANNEL_CAPACITY);
164        // Kept for the post-exit flush barrier (see the wait/cleanup task).
165        //
166        // A WEAK sender, emphatically not a clone. ReAgent P1 (round 3) on PR
167        // #3261: an mpsc channel closes only once EVERY `Sender` is dropped, so
168        // a strong clone held by the wait task keeps the channel open for as
169        // long as that task lives — which is precisely across the window where
170        // the task waits for the flusher to end. `flusher_handle` could then
171        // never resolve, on any platform, making the "prefer true EOF" fast
172        // path dead code and silently applying the fallback's residual race to
173        // every exit everywhere. An earlier revision of this very comment
174        // claimed a clone "does NOT keep the channel open"; that was simply
175        // wrong.
176        //
177        // `WeakSender` does not count towards keeping the channel alive, and
178        // `upgrade()` returning `None` is itself the answer the barrier wants:
179        // the channel is closed, so everything in it was drained.
180        let barrier_tx: tokio::sync::mpsc::WeakSender<PtyReadChunk> = pty_tx.downgrade();
181
182        super::pty_tasks::spawn_pty_reader(
183            reader,
184            pty_tx,
185            inner_read,
186            broker_read,
187            is_agent_read,
188            block_id_read,
189        );
190
191        // Coalescing flusher: batches whatever chunks the read loop above
192        // has already queued (bounded by PTY_COALESCE_MAX_BYTES, and never
193        // waiting for more to arrive) before doing the
194        // actual file write + broadcast + translation — once per batch
195        // instead of once per (up to 4KB) PTY read. A standalone fn (not
196        // inlined into the spawn) so it can be driven directly in tests
197        // with a synthetic channel, no real PTY required.
198        //
199        // Handle kept (reagentx P1 on PR #3206, third round): the wait
200        // task below must await this before publishing STATUS_DONE — see
201        // its own comment for why.
202        let flusher_handle = tokio::spawn(run_pty_output_flusher(
203            pty_rx,
204            broker_flush,
205            block_id_flush,
206            filestore_flush,
207            is_agent_flush,
208        ));
209        (flusher_handle, barrier_tx)
210    }
211}