Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
wait_task.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The task that watches a shell's PTY child: it reaps the child, lets the output
5//! flusher drain, hands the pane back (status, run lock, registrations) and, if the
6//! pane was set to close on exit, closes it.
7
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, Mutex};
10
11use super::super::{BlockControllerRuntimeStatus, STATUS_DONE, STATUS_RUNNING};
12use super::controller::{ShellController, ShellControllerInner};
13use super::lifecycle::{flush_barrier, release_lease_if_current, PtyReadChunk};
14use super::pty::{FLUSHER_BARRIER_TIMEOUT, FLUSHER_EOF_GRACE};
15use crate::backend::eventbus::EventBus;
16use crate::backend::mps;
17use crate::backend::storage::filestore::FileStore;
18use crate::backend::storage::store::Store;
19
20/// Everything the wait task needs from `start`, moved in when it is spawned.
21pub(super) struct ExitWatch {
22    pub(super) child: Box<dyn portable_pty::Child + Send + Sync>,
23    /// The askpass secret lives exactly as long as the shell.
24    pub(super) askpass_guard: Option<crate::backend::remote::askpass::Revoke>,
25    /// The SSH connection name and destination, for an SSH pane.
26    pub(super) ssh: Option<(String, String)>,
27    pub(super) inner: Arc<Mutex<ShellControllerInner>>,
28    pub(super) close_on_exit: bool,
29    pub(super) close_on_exit_delay_ms: u64,
30    pub(super) block_id: String,
31    pub(super) tab_id: String,
32    pub(super) agent_id: Option<String>,
33    pub(super) broker: Option<Arc<mps::Broker>>,
34    pub(super) filestore: Option<Arc<FileStore>>,
35    pub(super) mstore: Option<Arc<Store>>,
36    pub(super) event_bus: Option<Arc<EventBus>>,
37    pub(super) run_lock: Arc<AtomicBool>,
38    pub(super) flusher_handle: tokio::task::JoinHandle<()>,
39    pub(super) barrier_tx: tokio::sync::mpsc::WeakSender<PtyReadChunk>,
40}
41
42/// What `start` hands over to build an [`ExitWatch`]; the rest comes from the controller.
43pub(super) struct ExitParts {
44    pub(super) child: Box<dyn portable_pty::Child + Send + Sync>,
45    /// The askpass secret lives exactly as long as the shell.
46    pub(super) askpass_guard: Option<crate::backend::remote::askpass::Revoke>,
47    pub(super) ssh: Option<(String, String)>,
48    pub(super) agent_id: Option<String>,
49    pub(super) close_on_exit: bool,
50    pub(super) close_on_exit_delay_ms: u64,
51    pub(super) flusher_handle: tokio::task::JoinHandle<()>,
52    pub(super) barrier_tx: tokio::sync::mpsc::WeakSender<PtyReadChunk>,
53}
54
55impl ShellController {
56    /// The exit watcher for a started shell: the pieces `start` made, plus the controller's own state.
57    pub(super) fn exit_watch(&self, parts: ExitParts) -> ExitWatch {
58        let ExitParts {
59            child,
60            askpass_guard,
61            ssh,
62            agent_id,
63            close_on_exit,
64            close_on_exit_delay_ms,
65            flusher_handle,
66            barrier_tx,
67        } = parts;
68        ExitWatch {
69            child,
70            askpass_guard,
71            ssh,
72            inner: Arc::clone(&self.inner),
73            close_on_exit,
74            close_on_exit_delay_ms,
75            block_id: self.block_id.clone(),
76            tab_id: self.tab_id.clone(),
77            agent_id,
78            broker: self.broker.clone(),
79            filestore: self.filestore.clone(),
80            mstore: self.mstore.clone(),
81            event_bus: self.event_bus.clone(),
82            run_lock: Arc::clone(&self.run_lock),
83            flusher_handle,
84            barrier_tx,
85        }
86    }
87}
88
89impl ExitWatch {
90    pub(super) fn spawn(self) {
91        tokio::spawn(self.run());
92    }
93
94    async fn run(self) {
95        let ExitWatch {
96            child,
97            askpass_guard: askpass_guard_wait,
98            ssh: ssh_wait,
99            inner: inner_wait,
100            close_on_exit,
101            close_on_exit_delay_ms,
102            block_id: block_id_wait,
103            tab_id: tab_id_wait,
104            agent_id: agent_id_wait,
105            broker: broker_wait,
106            filestore: filestore_note,
107            mstore: mstore_wait,
108            event_bus: event_bus_wait,
109            run_lock,
110            flusher_handle,
111            barrier_tx,
112        } = self;
113        let (exit_code, raw_exit_code) = reap_child(child, block_id_wait.clone()).await;
114        drop(askpass_guard_wait);
115        // An SSH pane that lost its connection stays, saying so (ssh_pane).
116        let lost_note = ssh_wait.as_ref().and_then(|(conn, dest)| {
117            let stopped_by_srv = inner_wait.lock().unwrap().proc_status != STATUS_RUNNING;
118            super::ssh_pane::ended(conn, dest, raw_exit_code, stopped_by_srv)
119        });
120        let close_on_exit = close_on_exit && lost_note.is_none();
121
122        tracing::info!(block_id = %block_id_wait, exit_code = exit_code, "process exited");
123
124        drain_flusher(close_on_exit, flusher_handle, barrier_tx, &block_id_wait).await;
125
126        // After the drain above, so it comes after ssh's own last words.
127        if let (Some(text), Some(broker)) = (lost_note, broker_wait.clone()) {
128            super::ssh_pane::write_note(broker, filestore_note, block_id_wait.clone(), text).await;
129        }
130
131        // Kept for the close-on-exit step, after the teardown has taken the originals.
132        let block_id_for_close = block_id_wait.clone();
133        let tab_id_for_close = tab_id_wait.clone();
134        // Identity of THIS controller instance, for the still-the-current-controller
135        // check in `close_pane_later`.
136        let inner_for_close = Arc::clone(&inner_wait);
137
138        // `Teardown::run` does its work on a blocking thread: registry::remove and
139        // the rest do synchronous file I/O, which doesn't belong on an async worker.
140        Teardown {
141            block_id: block_id_wait,
142            agent_id: agent_id_wait,
143            inner: inner_wait,
144            mstore: mstore_wait,
145            event_bus: event_bus_wait,
146            broker: broker_wait,
147            run_lock,
148            exit_code,
149        }
150        .run()
151        .await;
152
153        if close_on_exit {
154            close_pane_later(
155                close_on_exit_delay_ms,
156                block_id_for_close,
157                tab_id_for_close,
158                inner_for_close,
159            );
160        }
161    }
162}
163
164/// Reaps the child on a blocking thread: it depends only on the direct child exiting, never
165/// on PTY EOF. Gives the pane's exit code (0, 1 or -1) and the raw code for an SSH pane.
166async fn reap_child(
167    child: Box<dyn portable_pty::Child + Send + Sync>,
168    block_id_wait: String,
169) -> (i32, Option<u32>) {
170    let block_id_reap = block_id_wait.clone();
171    tokio::task::spawn_blocking(move || {
172        let mut child = child;
173        match child.wait() {
174            // The pane keeps its 0 / 1 / -1; the raw code is for an
175            // SSH pane, where 255 means ssh could not connect.
176            Ok(status) => (
177                if status.success() { 0 } else { 1 },
178                Some(status.exit_code()),
179            ),
180            Err(e) => {
181                tracing::warn!("wait error for block {}: {}", block_id_reap, e);
182                (-1, None)
183            }
184        }
185    })
186    .await
187    .expect("PTY child wait task panicked")
188}
189
190/// Waits, bounded, for the output flusher to drain what the child wrote last.
191async fn drain_flusher(
192    close_on_exit: bool,
193    flusher_handle: tokio::task::JoinHandle<()>,
194    barrier_tx: tokio::sync::mpsc::WeakSender<PtyReadChunk>,
195    block_id_wait: &str,
196) {
197    // Bounded wait for the flusher to drain trailing output — see
198    // `FLUSHER_DRAIN_TIMEOUT`'s own doc comment for why this must be
199    // bounded. Deliberately does NOT `abort()` on timeout (reagentx
200    // P1, same round, on the timeout+abort version of this fix):
201    // the flusher (consumer) and the PTY read loop (producer,
202    // `spawn_blocking` doing a raw, un-cancellable OS-level
203    // `reader.read()`) are separate tasks, unlike persistent/stdout_reader.rs's
204    // single combined reader task. Aborting only the flusher would
205    // stop it draining `pty_tx` — but the read loop, still blocked
206    // in real OS I/O, cannot be interrupted by tokio's cooperative
207    // cancellation and keeps running regardless, so the leaked
208    // thread is NOT reclaimed either way. Aborting would only add a
209    // regression on top: every later `blocking_send` finds the
210    // receiver gone and is silently discarded, permanently losing
211    // any further output from a still-live descendant with no log
212    // at the point of loss. Simply letting `flusher_handle` drop
213    // here (no `abort()`) detaches it — the flusher and its read
214    // loop keep running independently in the background, still
215    // persisting and broadcasting whatever the descendant produces
216    // next, and exit naturally once the PTY genuinely reaches EOF.
217    //
218    // Two signals, strongest first (ReAgent P1 on PR #3261).
219    //
220    // The flusher task ENDING is the strong one: it only ends when the
221    // channel closes, which only happens once the read loop observed
222    // true EOF and dropped its sender — so every byte the child ever
223    // produced is both enqueued and committed. Wherever EOF actually
224    // arrives (Linux, macOS) this resolves in milliseconds and the
225    // guarantee is exactly what it was before the barrier existed.
226    //
227    // The barrier is the fallback, for where EOF never comes at all:
228    // on Windows ConPTY's console host outlives the direct child, so
229    // the read loop stays blocked in a read that never returns and the
230    // task can never end. Waiting on it there always burned the full
231    // ceiling (§12) — the second a human sees after typing `exit`.
232    //
233    // Residual, stated plainly: the barrier cannot order against a
234    // chunk the read loop has read but not yet enqueued, so on the
235    // fallback path a final chunk racing it can land after
236    // STATUS_DONE. Pre-PR behaviour on that same path was also
237    // best-effort (it timed out and detached), so this trades grace
238    // for responsiveness rather than trading away a guarantee that was
239    // ever actually held there. Where the guarantee WAS held — EOF
240    // platforms — it still is.
241    //
242    // Total worst case stays FLUSHER_DRAIN_TIMEOUT: the two waits
243    // split that budget rather than each taking it (ReAgent P2).
244    if close_on_exit {
245        drop(flusher_handle);
246    } else {
247        match tokio::time::timeout(FLUSHER_EOF_GRACE, flusher_handle).await {
248            Ok(Ok(())) => {}
249            Ok(Err(e)) => {
250                tracing::warn!(
251                    block_id = %block_id_wait,
252                    error = %e,
253                    "PTY output flusher task panicked or was cancelled before completing; \
254                     proceeding with pane teardown anyway — some trailing output may be missing"
255                );
256            }
257            Err(_) => {
258                // No EOF within the grace — assume it is never coming
259                // (ConPTY) and settle for the bounded barrier.
260                // `None` means every sender is gone — the channel
261                // closed and the flusher drained it, which is the
262                // guarantee the barrier exists to obtain.
263                let barrier = match barrier_tx.upgrade() {
264                    Some(tx) => flush_barrier(&tx, FLUSHER_BARRIER_TIMEOUT).await,
265                    None => Ok(()),
266                };
267                if barrier.is_err() {
268                    tracing::warn!(
269                        block_id = %block_id_wait,
270                        timeout = ?FLUSHER_BARRIER_TIMEOUT,
271                        "PTY output flush barrier went unanswered after process exit (a                                  wedged flusher, or a background descendant still holding the PTY                                  open?) — proceeding with pane teardown; the flusher and its read                                  loop stay detached and running, so later output is still not lost,                                  but some trailing output may land after STATUS_DONE"
272                    );
273                }
274            }
275        }
276    }
277}
278
279/// What the blocking part of a pane's teardown needs.
280struct Teardown {
281    block_id: String,
282    agent_id: Option<String>,
283    inner: Arc<Mutex<ShellControllerInner>>,
284    mstore: Option<Arc<Store>>,
285    event_bus: Option<Arc<EventBus>>,
286    broker: Option<Arc<mps::Broker>>,
287    run_lock: Arc<AtomicBool>,
288    exit_code: i32,
289}
290
291impl Teardown {
292    /// Unregisters the pane, releases its lease, publishes DONE and frees the run lock.
293    async fn run(self) {
294        let Teardown {
295            block_id: block_id_wait,
296            agent_id: agent_id_wait,
297            inner: inner_wait,
298            mstore: mstore_wait,
299            event_bus: event_bus_wait,
300            broker: broker_wait,
301            run_lock,
302            exit_code,
303        } = self;
304        tokio::task::spawn_blocking(move || {
305            unregister_pane(&block_id_wait, agent_id_wait.as_deref());
306
307            // Release any PtyShell agent lease this block still holds.
308            //
309            // The lease (`blockcontroller::agent_lock`) locks a human out
310            // of their own keyboard while an agent drives the pane's
311            // shell, and it is deliberately time-bounded so it always
312            // lapses on its own. But "the shell this lease belongs to has
313            // exited" is a stronger signal than the clock: there is
314            // nothing left to collide with, and holding the lock for the
315            // remainder of its window would drop keystrokes aimed at
316            // whatever comes next in this pane. Matters most for the
317            // exact case that motivated close-on-exit
318            // (SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md §10): a human
319            // typing `exit` in a shell an agent was using must not have
320            // their following keystrokes swallowed by a lease for a PTY
321            // that is already gone.
322            //
323            // Guarded on this task still belonging to the REGISTERED
324            // controller, the same `Arc::ptr_eq` identity check the
325            // close-on-exit check in `close_pane_later` already uses, and for the same
326            // reason (Codex P1 / ReAgent P1 on PR #3249): a force-restart
327            // (`resync_controller` → `stop_for_replace`) kills this child
328            // and registers a REPLACEMENT controller for the same
329            // block_id. This wait task belongs to the OLD one. Without
330            // the guard it would fire afterwards and clear a lease the
331            // agent had legitimately taken on the NEW shell, letting
332            // human input race the agent's writes on a pane that never
333            // stopped being driven. Leases are keyed by block_id, so a
334            // stale task cannot tell its own lease from its successor's —
335            // controller identity is what distinguishes them.
336            //
337            // Check-then-act, like its precedent: a replacement
338            // registered in the window between this check and the remove
339            // would still lose its lease. Same residual race the
340            // close-on-exit guard accepts, and self-correcting here — the
341            // agent's next write re-takes the lease, since
342            // `lock_shell_for_agent` runs before every one.
343            release_lease_if_current(&block_id_wait, &inner_wait, &mstore_wait, &event_bus_wait);
344
345            // Update inner state
346            {
347                let mut inner = inner_wait.lock().unwrap();
348                inner.proc_exit_code = exit_code;
349                ShellController::set_status(&mut inner, STATUS_DONE);
350                inner.input_tx = None;
351            }
352
353            publish_done(&inner_wait, &broker_wait, &block_id_wait);
354
355            // Release run lock
356            run_lock.store(false, Ordering::SeqCst);
357        })
358        .await
359        .expect("PTY wait/cleanup task panicked");
360    }
361}
362
363/// Closes the pane after `close_on_exit_delay_ms`, if this controller is still the registered one.
364fn close_pane_later(
365    close_on_exit_delay_ms: u64,
366    block_id_for_close: String,
367    tab_id_for_close: String,
368    inner_for_close: Arc<Mutex<ShellControllerInner>>,
369) {
370    // Close-on-exit (SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md
371    // §10): fire-and-forget, deliberately AFTER STATUS_DONE is
372    // published and `run_lock` is released by `Teardown::run` — closing the
373    // pane doesn't need to block or gate either of those.
374    //
375    // Reached promptly after the child is reaped: for a CLOSING
376    // pane the flusher-drain wait (`drain_flusher`) is skipped outright (§13),
377    // so none of `FLUSHER_DRAIN_TIMEOUT` is paid here, and
378    // `close_on_exit_delay_ms` defaults to 0. A pane that is NOT
379    // closing still takes the full ordered drain wait — now
380    // bounded at 1s rather than the original 10s (§12), because
381    // that ceiling turned out to be reached on essentially every
382    // ordinary exit on Windows (ConPTY's console host outlives
383    // the direct child, so the read loop never sees EOF) and it
384    // gates `STATUS_DONE` publication, i.e. every
385    // STATUS_DONE-driven affordance — a pane's "done" icon,
386    // `PtyShellStatus`'s `running: false` — not just this one.
387    //
388    // NOT gated on the flusher-drain outcome logged by `drain_flusher`.
389    // An earlier version of this code skipped closing whenever the
390    // flusher timed out, reasoning that a still-live background
391    // descendant might have more output coming. Live-tested on
392    // Windows (this PR) and found to backfire completely: the
393    // 10s `FLUSHER_DRAIN_TIMEOUT` was hit on essentially EVERY
394    // plain `cmd.exe` exit, not as a rare edge case — ConPTY's own
395    // console-host process routinely outlives the direct child by
396    // design, so gating on this made close-on-exit silently never
397    // fire on the one platform this was tested on. Simply closing
398    // regardless matches what actually happens next either way:
399    // the flusher and its read loop are ALREADY left running
400    // detached in the background (see `drain_flusher`), so any
401    // genuinely-still-arriving trailing output keeps being
402    // persisted to the block's file exactly as it would if the
403    // pane stayed open — closing the pane just stops anyone from
404    // looking at it, the same as closing any other terminal app's
405    // window while a background job still has an open handle.
406    tokio::spawn(async move {
407        tokio::time::sleep(std::time::Duration::from_millis(close_on_exit_delay_ms)).await;
408        // Only close if THIS controller is still the one
409        // registered for the block (Codex P1 on PR #3230).
410        //
411        // A process exit is not by itself evidence that the
412        // pane should close — the child also dies when the
413        // controller is deliberately replaced. `resync_controller`'s
414        // force-restart path (the terminal's own refresh
415        // action, `forcerestart: true`) calls
416        // `stop_for_replace`, which kills this child, then
417        // registers a REPLACEMENT controller for the same
418        // block. This wait task belongs to the OLD controller
419        // and still carries `close_on_exit == true`, so
420        // without this check reaping that killed child would
421        // delete the pane — and with it the freshly
422        // registered replacement — instead of completing the
423        // restart. The delay widens the same window for
424        // an explicitly-configured `cmd:closeonexitdelay`:
425        // restarting an exited shell during it must cancel the
426        // close, which re-checking AFTER the sleep is what
427        // makes true.
428        //
429        // Registry identity is the discriminator, and it
430        // covers the whole replace sequence: during it the old
431        // entry is removed (`remove_controller_entry_only`)
432        // and a new one registered, so this lookup finds
433        // either nothing or a DIFFERENT controller — both
434        // correctly skip. A natural exit leaves this
435        // controller registered and untouched, so it matches
436        // and the close proceeds.
437        let still_current = super::super::get_controller(&block_id_for_close)
438            .and_then(|ctrl| {
439                ctrl.as_any()
440                    .downcast_ref::<ShellController>()
441                    .map(|sc| Arc::ptr_eq(&sc.inner, &inner_for_close))
442            })
443            .unwrap_or(false);
444        if !still_current {
445            tracing::info!(
446                block_id = %block_id_for_close,
447                "close-on-exit: controller was replaced or removed since this \
448                 process exited (restart in flight?) — skipping pane close"
449            );
450            return;
451        }
452        super::super::close_on_exit(tab_id_for_close, block_id_for_close);
453    });
454}
455
456/// Takes the pane out of the per-pane metrics, the jekt registry and the cloud subscriber.
457fn unregister_pane(block_id_wait: &str, agent_id: Option<&str>) {
458    // Unregister PID from per-pane metrics
459    super::super::pidregistry::unregister(block_id_wait);
460
461    // Deregister from jekt — removes the agent_id → block_id mapping so
462    // subsequent jekt attempts fall back to MessageBus rather than a dead PTY.
463    crate::backend::reactive::get_global_handler().unregister_block(block_id_wait);
464    // Every file registered for this block, under whatever name it is filed by: the one removal by name
465    // below misses an entry a turn wrote for the pane's current name.
466    {
467        let data_dir = crate::backend::base::get_mux_data_dir();
468        crate::backend::reactive::registry::remove_for_block(&data_dir, block_id_wait, None);
469        crate::backend::reactive::registry::remove_shared_for_block_from_env(block_id_wait, None);
470    }
471
472    // Also remove from cross-instance file registry and cloud subscriber, unless another live pane
473    // still answers to the name. An agent's own tool shell carries the agent's id, so its exit must
474    // not unsubscribe the agent's running pane from cloud messages.
475    if let Some(agent_id) = agent_id {
476        let still_held = crate::backend::reactive::get_global_handler().has_live_name(agent_id);
477        if drop_name_state_on_exit(still_held) {
478            let data_dir = crate::backend::base::get_mux_data_dir();
479            crate::backend::reactive::registry::remove(&data_dir, agent_id);
480            crate::backend::reactive::registry::remove_shared_from_env(agent_id);
481            if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
482                sub.remove_agent(agent_id);
483            }
484        } else {
485            tracing::info!(block_id = %block_id_wait, agent = %agent_id, "shell pane exit: another live pane holds the agent's name — keeping its registry entry and cloud subscription");
486        }
487    }
488}
489
490/// Whether an exiting pane takes down the name-keyed state (file registry entry, cloud
491/// subscription) for its agent: only when no other live pane still answers to the name.
492fn drop_name_state_on_exit(name_still_held: bool) -> bool {
493    !name_still_held
494}
495
496#[cfg(test)]
497mod name_state_tests {
498    use super::drop_name_state_on_exit;
499
500    #[test]
501    fn an_exiting_shell_leaves_the_name_alone_while_a_pane_holds_it() {
502        assert!(!drop_name_state_on_exit(true), "the agent's pane still runs: keep its subscription");
503        assert!(drop_name_state_on_exit(false), "nobody holds the name: take its state down");
504    }
505}
506
507/// Publishes the pane's DONE status to the broker, if there is one.
508fn publish_done(
509    inner_wait: &Arc<Mutex<ShellControllerInner>>,
510    broker_wait: &Option<Arc<mps::Broker>>,
511    block_id_wait: &str,
512) {
513    // Publish done status
514    if let Some(ref broker) = broker_wait {
515        let status = {
516            let inner = inner_wait.lock().unwrap();
517            BlockControllerRuntimeStatus {
518                durable: false,
519                blockid: block_id_wait.to_string(),
520                version: inner.status_version,
521                shellprocstatus: inner.proc_status.clone(),
522                shellprocconnname: inner.conn_name.clone(),
523                shellprocexitcode: inner.proc_exit_code,
524                // Kept on the exit status too, so the drawer's
525                // info line can still say which PID exited.
526                shellprocpid: inner.child_pid,
527                shellprocname: inner.shell_name.clone(),
528                spawn_ts_ms: inner.spawn_ts_ms,
529                is_agent_pane: inner.is_agent_pane,
530                turn_active: false,
531            }
532        };
533        super::super::publish_controller_status(broker, &status);
534    }
535}