Skip to main content

agentmux_srv_core/backend/
shell_node.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! ShellNodeRunner — spawns a shell command and streams output to the
5//! frontend as `shell_chunk` MPS events scoped to the agent's block.
6//!
7//! Launched by `handle_shell_create` (server/mod.rs) via `tokio::spawn`.
8//! The runner is fire-and-forget; the HTTP handler returns the `shell_id`
9//! to the MCP caller immediately while output streams asynchronously.
10//!
11//! Phase 2 of SPEC_PERSISTENT_SHELL_NODE_2026_06_11.md. Uses
12//! `tokio::process::Command` with captured pipes (no PTY in this phase;
13//! PTY support is a Phase 3 follow-up that requires portable-pty wiring
14//! similar to the existing ShellController).
15
16#[cfg(windows)]
17use agentmux_common::win32::NoWindow;
18use std::collections::{HashMap, VecDeque};
19use std::sync::Arc;
20use parking_lot::Mutex;
21use serde::Serialize;
22use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter};
23use tokio::sync::{mpsc, oneshot};
24
25use crate::backend::mps::Broker;
26use agentmux_common::api_types::ShellInputFailure;
27
28use agentmux_common::time::now_ms_u64 as now_ms;
29
30/// How much of a job's cleaned output is kept for the agent that ran it.
31const TAIL_LINES: usize = 400;
32const TAIL_LINE_CHARS: usize = 4000;
33
34/// Live status of a running (or recently exited) shell. Updated by
35/// `ShellNodeRunner` as output arrives and on exit.
36///
37/// `block_id`/`cmd`/`title`/`started_at` are populated once at spawn (see
38/// `ShellNodeRunner::run`) and never change — kept here (rather than a
39/// separate lookup) so `list_active` (SPEC_SWARM_LONG_RUNNING_PROCESS_
40/// ROWS_2026_07_20) can answer "which shells belong to block X" from the
41/// same map `get_status`/`ShellStatus` already query, with no new registry
42/// or second source of truth.
43#[derive(Clone, Default)]
44pub struct ShellStatusInfo {
45    pub running: bool,
46    pub exit_code: Option<i32>,
47    pub line_count: u64,
48    pub block_id: String,
49    pub cmd: String,
50    pub title: String,
51    pub started_at: u64,
52    /// The last lines of a job that was given Vault secrets, already cleaned of them:
53    /// kept only for such a job, so the agent that ran it can read the result.
54    pub tail: Option<Arc<Mutex<VecDeque<String>>>>,
55    /// A line of `tail` was cut to the per-line limit: the output is not whole.
56    pub tail_clipped: bool,
57    /// The entries a `capture` stored, once the job ended.
58    pub captured: Vec<String>,
59    /// Why a `capture` failed, and so why the output was withheld.
60    pub withheld: Option<String>,
61}
62
63/// Snapshot of one currently-running shell for the Swarm pane's per-agent
64/// long-running-process rows. See `ShellSessionRegistry::list_active`.
65/// Carries `block_id` (unfiltered list — same shape as `subagent.ListActive`/
66/// `ActiveSubagent.parent_block_id`) so the Swarm pane's `buildTree()` groups
67/// by block client-side in one pass, instead of one RPC call per tracked
68/// agent block.
69#[derive(Clone, Serialize)]
70pub struct ShellSummary {
71    pub shell_id: String,
72    pub block_id: String,
73    pub cmd: String,
74    pub title: String,
75    pub started_at: u64,
76    pub line_count: u64,
77}
78
79// Per-shell registry entry: stop handle + optional stdin channel (Phase 3b).
80// The stdin_tx is an mpsc sender to a relay task that owns the real ChildStdin.
81// Sending text is non-blocking (unbounded channel); the relay handles the
82// actual write. When all senders are dropped, the channel closes, the relay
83// exits, ChildStdin is dropped, and the child sees EOF on stdin.
84struct ShellEntry {
85    stop_tx: oneshot::Sender<()>,
86    // None for entries created by unit tests (no relay task / ChildStdin).
87    stdin_tx: Option<mpsc::UnboundedSender<String>>,
88}
89
90/// Per-shell stop handles + status. `ShellStop` fires the oneshot; `ShellInput`
91/// sends to the stdin relay; `ShellStatus` reads the live status arc.
92/// Lives in `AppState.shell_sessions`.
93/// Max number of EXITED shell statuses retained for post-exit ShellStatus
94/// queries. Running shells are always kept regardless of this cap; only
95/// exited entries beyond it are evicted oldest-first. Bounds memory for
96/// long-lived sidecars that spawn many short shells.
97const MAX_EXITED_STATUS: usize = 512;
98
99#[derive(Default)]
100pub struct ShellSessionRegistry {
101    shells: Mutex<HashMap<String, ShellEntry>>,
102    // Status entries persist after exit so ShellStatus can query final
103    // exit_code/line_count. Exited entries are capped at MAX_EXITED_STATUS
104    // (oldest-first eviction via status_order); running entries are never
105    // evicted. stop_all() clears everything on srv shutdown.
106    status_map: Mutex<HashMap<String, Arc<Mutex<ShellStatusInfo>>>>,
107    // Spawn-order queue of shell_ids, used to evict the oldest exited status
108    // entries first when over the cap.
109    status_order: Mutex<VecDeque<String>>,
110}
111
112impl ShellSessionRegistry {
113    pub fn new() -> Arc<Self> {
114        Arc::new(Self::default())
115    }
116
117    // Used by unit tests — registers a stop handle with no stdin relay/status.
118    #[cfg(test)]
119    fn insert(&self, shell_id: String, tx: oneshot::Sender<()>) {
120        self.shells.lock().insert(shell_id, ShellEntry { stop_tx: tx, stdin_tx: None });
121    }
122
123    // Full registration called by the runner after spawning the child.
124    // stdin_tx is None when capture_stdin is false (stdin is /dev/null).
125    // Returns shell_ids evicted by the prune pass — the caller (which holds
126    // the Broker, unlike this registry) purges their `shell:<id>` persisted
127    // MuxEvent history so the broker's persist_map key set stays bounded
128    // in step with this registry's own MAX_EXITED_STATUS cap.
129    //
130    // `pub(crate)` (rather than private) so `server::shell_handlers`'s own
131    // tests can seed a running/exited shell directly, without spawning a
132    // real child process, to exercise the `shellstatus` RPC handler's JSON
133    // shape end-to-end for both branches — the same pre-tested primitive
134    // this module's own tests already use, not duplicated logic.
135    pub fn register_full(
136        &self,
137        shell_id: String,
138        stop_tx: oneshot::Sender<()>,
139        stdin_tx: Option<mpsc::UnboundedSender<String>>,
140        status: Arc<Mutex<ShellStatusInfo>>,
141    ) -> Vec<String> {
142        self.shells.lock().insert(shell_id.clone(), ShellEntry { stop_tx, stdin_tx });
143        self.status_map.lock().insert(shell_id.clone(), status);
144        self.status_order.lock().push_back(shell_id);
145        // Bound retained exited statuses; every spawn is a natural prune trigger.
146        self.prune_exited_statuses()
147    }
148
149    /// Evict oldest EXITED status entries beyond `MAX_EXITED_STATUS`. Running
150    /// shells are always retained (their status is read live via ShellStatus).
151    /// Also drops any order-queue ids whose status entry is already gone.
152    /// Returns the shell_ids actually evicted (status entry removed) so the
153    /// caller can purge their broker-side persisted history too.
154    fn prune_exited_statuses(&self) -> Vec<String> {
155        let mut map = self.status_map.lock();
156        let mut order = self.status_order.lock();
157        let mut evicted = Vec::new();
158        let mut exited = map
159            .values()
160            .filter(|arc| !arc.lock().running)
161            .count();
162        let mut i = 0;
163        while exited > MAX_EXITED_STATUS && i < order.len() {
164            let id = order[i].clone();
165            match map.get(&id) {
166                // Exited entry over the cap → evict it.
167                Some(arc) if !arc.lock().running => {
168                    map.remove(&id);
169                    order.remove(i);
170                    exited -= 1;
171                    evicted.push(id);
172                }
173                // Still running → keep in place, advance.
174                Some(_) => i += 1,
175                // Stale order id (already removed) → drop from queue.
176                None => {
177                    order.remove(i);
178                }
179            }
180        }
181        evicted
182    }
183
184    /// Request stop of a running shell. Returns false if unknown or already exited.
185    /// Dropping the stdin_tx here closes the relay channel → ChildStdin drops →
186    /// child sees EOF, unblocking any stdin-reading process before the kill.
187    pub fn stop(&self, shell_id: &str) -> bool {
188        // Do NOT remove from status_map here — the runner task is still live
189        // and will persist the final exit status after child.wait() returns.
190        if let Some(entry) = self.shells.lock().remove(shell_id) {
191            // stdin_tx dropped here → relay closes → child gets stdin EOF
192            let _ = entry.stop_tx.send(());
193            true
194        } else {
195            false
196        }
197    }
198
199    /// Called by the runner on natural exit (stdout/stderr closed). Removes the
200    /// shells entry (dropping stdin_tx → child gets stdin EOF). Status entry is
201    /// intentionally kept so ShellStatus can query the final exit code/line count.
202    fn remove(&self, shell_id: &str) {
203        self.shells.lock().remove(shell_id);
204        // status_map entry is NOT removed — it persists so get_status() can
205        // return the final running:false / exit_code / line_count after exit.
206    }
207
208    /// Stop every running shell. For srv-shutdown cleanup.
209    pub fn stop_all(&self) -> usize {
210        self.status_map.lock().clear();
211        self.status_order.lock().clear();
212        let drained: Vec<_> = self.shells.lock().drain().map(|(_, e)| e.stop_tx).collect();
213        let n = drained.len();
214        for tx in drained {
215            let _ = tx.send(());
216        }
217        n
218    }
219
220    /// Resolve where a `ShellInput` write should go, distinguishing two
221    /// failure modes:
222    /// - `Ok(tx)`            — running with captured stdin
223    /// - `Err(StdinNotCaptured)` — running but created without capture_stdin
224    /// - `Err(NotRunning)`   — unknown id or already exited
225    pub fn resolve_stdin(
226        &self,
227        shell_id: &str,
228    ) -> Result<mpsc::UnboundedSender<String>, ShellInputFailure> {
229        let shells = self.shells.lock();
230        match shells.get(shell_id) {
231            Some(entry) => match &entry.stdin_tx {
232                Some(tx) => Ok(tx.clone()),
233                None => Err(ShellInputFailure::StdinNotCaptured),
234            },
235            None => Err(ShellInputFailure::NotRunning),
236        }
237    }
238
239    /// Return a snapshot of the shell's status. Returns `running: false` if unknown.
240    /// Existing, documented contract for `POST /api/v1/shell/status` (the MCP
241    /// `ShellStatus` tool) — do not change: an agent calling this for an id
242    /// it doesn't recognize expects a plain "not running" answer, not an error.
243    pub fn get_status(&self, shell_id: &str) -> ShellStatusInfo {
244        self.status_map.lock()
245            .get(shell_id)
246            .map(|arc| arc.lock().clone())
247            .unwrap_or_default()
248    }
249
250    /// Like [`Self::get_status`], but `None` when no entry exists at all —
251    /// distinguishing "genuinely unknown" from "known, and not running."
252    ///
253    /// Needed by the `shellstatus` RPC command (unlike the MCP tool above,
254    /// which is fine collapsing "unknown" into "not running"): `register_full`
255    /// only runs after the runner task spawns the child process, but
256    /// `shell_node_create` is published to the frontend BEFORE that task is
257    /// even scheduled (`handle_shell_create` in server/mod.rs). A caller that
258    /// checks status immediately after seeing `shell_node_create` can race
259    /// ahead of registration — reagent P1 on PR #2770: collapsing that race
260    /// window into `running: false` was indistinguishable from a genuinely
261    /// already-exited shell, so a fast, still-registering, genuinely LIVE
262    /// shell (e.g. a real `task dev`) could be shown as failed in the
263    /// Activity Dock for its entire run.
264    pub fn get_status_if_known(&self, shell_id: &str) -> Option<ShellStatusInfo> {
265        self.status_map.lock().get(shell_id).map(|arc| arc.lock().clone())
266    }
267
268    /// List every currently-RUNNING shell across all blocks — the Swarm
269    /// pane's data source for its per-agent long-running-process rows
270    /// (SPEC_SWARM_LONG_RUNNING_PROCESS_ROWS_2026_07_20). Unfiltered, like
271    /// `subagent.ListActive`/`ListDispatches` — the Swarm pane fetches once
272    /// and groups by `block_id` client-side in `buildTree()`, rather than
273    /// one RPC per tracked agent block. Exited shells are intentionally
274    /// excluded: Phase 1's scope is "what's happening now," not a shell
275    /// history view.
276    pub fn list_active(&self) -> Vec<ShellSummary> {
277        self.status_map
278            .lock()
279            .iter()
280            .filter_map(|(shell_id, arc)| {
281                let s = arc.lock();
282                if s.running {
283                    Some(ShellSummary {
284                        shell_id: shell_id.clone(),
285                        block_id: s.block_id.clone(),
286                        cmd: s.cmd.clone(),
287                        title: s.title.clone(),
288                        started_at: s.started_at,
289                        line_count: s.line_count,
290                    })
291                } else {
292                    None
293                }
294            })
295            .collect()
296    }
297}
298
299/// Kill the entire process tree rooted at `pid`. `Child::kill` / `kill_on_drop`
300/// only reap the wrapper shell (`cmd /C` / `sh -c`); a `task dev` spawns
301/// `task.exe` → `cargo`/`node` grandchildren that survive otherwise.
302///
303/// Scoped strictly to OUR `pid` — never by image name. Killing `task.exe`
304/// by name is the cross-instance hazard that let agent "Mazs" nuke peer
305/// dev servers (see SPEC_PERSISTENT_SHELL_PHASE3_STOP §1).
306fn kill_tree(pid: u32) {
307    // Group-kill with SIGTERM → 300ms → SIGKILL escalation on Unix (the child
308    // is spawned via process_group(0), so the negative-pid signal reaches its
309    // descendants); `taskkill /F /T /PID` on Windows. The implementation is
310    // shared with the other by-PID kill sites in `agentmux_common::process`.
311    agentmux_common::process::kill_process_group(pid);
312}
313
314pub struct ShellNodeRunner {
315    pub shell_id: String,
316    pub block_id: String,
317    pub cmd: String,
318    /// Caller-supplied display title, defaulting to `cmd` — mirrors
319    /// `handle_shell_create`'s own `title` local, threaded through so
320    /// `ShellStatusInfo`/`list_active` can show it without a second lookup.
321    pub title: String,
322    pub cwd: Option<String>,
323    /// The program and arguments when the command runs elsewhere: `wsl.exe`
324    /// for a WSL distro (`remote::wsl::launch`), `ssh` for an SSH host
325    /// (`remote::ssh::launch_exec`). `None` runs it here through `cmd`/`sh`.
326    pub launch: Option<(String, Vec<String>)>,
327    /// The askpass secret of an SSH command (`remote::askpass`), revoked when
328    /// this runner ends, however it ends.
329    pub askpass_secret: Option<String>,
330    pub extra_env: HashMap<String, String>,
331    pub broker: Arc<Broker>,
332    /// Stop registry — the runner registers its `shell_id` here so
333    /// `ShellStop` can tree-kill it, and removes itself on natural exit.
334    pub registry: Arc<ShellSessionRegistry>,
335    /// If true, pipe stdin and start the relay task so ShellInput() works.
336    /// If false (default), stdin is /dev/null — avoids blocking programs that
337    /// read stdin to EOF (e.g. `cat` with no args).
338    pub capture_stdin: bool,
339    /// Takes the Vault values the command was given out of its output, before
340    /// anything is published (spec section 7.2).
341    pub scrubber: Option<Arc<crate::backend::vault::scrub::Scrubber>>,
342    /// A Vault value for its stdin (`stdin_secret`): written with a newline, then
343    /// stdin is closed. Never with `capture_stdin`.
344    pub stdin_once: Option<zeroize::Zeroizing<String>>,
345    /// The folder of its Vault secret files, removed when this runner ends, however
346    /// it ends.
347    pub secret_dir: Option<crate::backend::vault::files::SecretDir>,
348    /// Values its output goes into the Vault as (`capture`): the output is held
349    /// until it ends, and published only once they are taken out of it.
350    pub capture: Option<crate::backend::vault::capture::Job>,
351}
352
353/// `cmd`, a command line, run the way a person's terminal runs it: `sh -c` on Unix, and on Windows cmd.exe
354/// reading the line as typed. `Command::args` would quote the whole line as ONE argument and backslash-escape
355/// the quotes inside it, which cmd.exe does not read: `--reason "two words"` reached the program as
356/// `--reason \"two` `words\"`. The line goes in raw, between the one pair of quotes `/S` takes off.
357fn local_command(cmd: &str) -> tokio::process::Command {
358    #[cfg(windows)]
359    {
360        use std::os::windows::process::CommandExt;
361        let mut c = tokio::process::Command::new("cmd");
362        c.as_std_mut().args(["/S", "/C"]).raw_arg(format!("\"{cmd}\""));
363        c
364    }
365    #[cfg(not(windows))]
366    {
367        let mut c = tokio::process::Command::new("sh");
368        c.args(["-c", cmd]);
369        c
370    }
371}
372
373impl ShellNodeRunner {
374    pub async fn run(mut self) {
375        let shell_id = self.shell_id.clone();
376        let block_id = self.block_id.clone();
377        let broker = self.broker.clone();
378
379        let _askpass = self.askpass_secret.clone().map(crate::backend::remote::askpass::Revoke);
380        let mut child_cmd = if let Some((program, args)) = &self.launch {
381            let mut c = tokio::process::Command::new(program);
382            c.args(args);
383            c
384        } else {
385            local_command(&self.cmd)
386        };
387
388        // This runner backs POST /api/v1/shell/create — the MCP `Shell` tool,
389        // which CLAUDE.md names as the way for an agent to launch `task dev` /
390        // `task package`. Without this it inherited agentmux-srv's full
391        // AGENTMUX_* environment, so a build started here adopted the LAUNCHING
392        // instance's channel and data dir: the exact failure this is meant to
393        // prevent, on the most likely path for it to happen. Missed by the
394        // first revision of the fix and caught in review (ReAgent P0 on #3326).
395        crate::backend::pane_env::sanitize_process_command(&mut child_cmd);
396
397        // Only set the working directory if it actually exists. The cwd is
398        // normalized upstream (handle_shell_create → base::normalize_working_dir),
399        // but a stale or mistyped path would otherwise make the spawn fail hard
400        // with os error 267 (ERROR_DIRECTORY) on Windows. Like the agent-CLI
401        // spawn (blockcontroller/core.rs::apply_working_dir, which skips
402        // `current_dir` when the directory is missing and can't be created),
403        // warn via a system chunk and run in the server's cwd rather than
404        // killing the shell before it starts.
405        if let Some(ref cwd) = self.cwd {
406            if std::path::Path::new(cwd).is_dir() {
407                child_cmd.current_dir(cwd);
408            } else {
409                publish_chunk(
410                    &broker,
411                    &block_id,
412                    &shell_id,
413                    "system",
414                    &format!("[cwd not found: {cwd} — running in the server's working directory]"),
415                    now_ms(),
416                );
417            }
418        }
419        for (k, v) in &self.extra_env {
420            child_cmd.env(k, v);
421        }
422
423        child_cmd.stdout(std::process::Stdio::piped());
424        child_cmd.stderr(std::process::Stdio::piped());
425        // stdin: piped only when capture_stdin=true (opt-in). Default is null so
426        // programs that read stdin to EOF (e.g. `cat` with no args) don't block
427        // forever. When piped, a relay task forwards ShellInput() writes; when all
428        // senders drop the relay exits, ChildStdin drops, and the child sees EOF.
429        if self.capture_stdin || self.stdin_once.is_some() {
430            child_cmd.stdin(std::process::Stdio::piped());
431        } else {
432            child_cmd.stdin(std::process::Stdio::null());
433        }
434        // Windows: suppress the console window that Windows auto-creates for
435        // CUI-subsystem processes (cmd.exe). stdout/stderr are piped so no
436        // output is lost — the window was decorative noise only.
437        #[cfg(windows)]
438        {
439            child_cmd.no_window();
440        }
441        // Backstop: reap the wrapper shell if this runner task is ever dropped.
442        child_cmd.kill_on_drop(true);
443        // Unix: own process group so kill_tree can signal the whole group
444        // (-pgid). Windows uses taskkill /T on the pid instead.
445        #[cfg(unix)]
446        {
447            child_cmd.process_group(0);
448        }
449
450        // Joins the agent's tracker before it runs, so the shell and everything
451        // it starts (`task dev` → task.exe/node) end with the agent on every
452        // teardown path (agent_teardown spec §6.5).
453        let mut child = match crate::backend::process_tracker::registry::spawn_tracked(&block_id, &mut child_cmd, crate::backend::process_tracker::registry::Join::Adopted) {
454            Ok(c) => c,
455            Err(e) => {
456                publish_chunk(&broker, &block_id, &shell_id, "system", &format!("[spawn error: {e}]"), now_ms());
457                publish_exit(&broker, &block_id, &shell_id, 1, false, now_ms());
458                return;
459            }
460        };
461
462        let pid = child.id();
463        tracing::info!(shell_id = %shell_id, pid = ?pid, capture_stdin = self.capture_stdin, "shell.spawn");
464
465        // A Vault value for stdin: written, then stdin is dropped, so the command sees
466        // the end of its input and nothing else can be typed there.
467        if let Some(value) = self.stdin_once.take() {
468            if !self.capture_stdin {
469                if let Some(mut writer) = child.stdin.take() {
470                    tokio::spawn(async move {
471                        let _ = writer.write_all(value.as_bytes()).await;
472                        let _ = writer.write_all(b"\n").await;
473                        let _ = writer.flush().await;
474                    });
475                }
476            }
477        }
478
479        // Spawn stdin relay only when capture_stdin=true.
480        let stdin_tx: Option<mpsc::UnboundedSender<String>> = if self.capture_stdin {
481            let child_stdin = child.stdin.take().expect("stdin piped");
482            let (tx, mut rx) = mpsc::unbounded_channel::<String>();
483            tokio::spawn(async move {
484                let mut writer = BufWriter::new(child_stdin);
485                while let Some(text) = rx.recv().await {
486                    if writer.write_all(text.as_bytes()).await.is_err() { break; }
487                    if writer.flush().await.is_err() { break; }
488                }
489                // All senders dropped or write error → ChildStdin dropped → child EOF
490            });
491            Some(tx)
492        } else {
493            None
494        };
495
496        let status_arc = Arc::new(Mutex::new(ShellStatusInfo {
497            running: true,
498            exit_code: None,
499            line_count: 0,
500            block_id: block_id.clone(),
501            cmd: self.cmd.clone(),
502            title: self.title.clone(),
503            started_at: now_ms(),
504            tail: (self.scrubber.is_some() || self.capture.is_some()).then(|| Arc::new(Mutex::new(VecDeque::new()))),
505            ..Default::default()
506        }));
507        let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
508        let evicted = self.registry.register_full(
509            shell_id.clone(),
510            cancel_tx,
511            stdin_tx,
512            Arc::clone(&status_arc),
513        );
514        for evicted_id in evicted {
515            broker.purge_scope(&format!("shell:{evicted_id}"));
516        }
517        let kill_task = tokio::spawn(async move {
518            match cancel_rx.await {
519                Ok(()) => {
520                    if let Some(pid) = pid {
521                        let _ = tokio::task::spawn_blocking(move || kill_tree(pid)).await;
522                    }
523                    true // stopped by request
524                }
525                Err(_) => false, // sender dropped → natural exit
526            }
527        });
528
529        let stdout = child.stdout.take().expect("stdout piped");
530        let stderr = child.stderr.take().expect("stderr piped");
531
532        // Collect both stdout and stderr into a single ordered channel.
533        // Each task owns its half of the pipe; the channel closes when both
534        // tasks finish, at which point the main loop exits and we wait for exit.
535        type Line = (&'static str, String, u64);
536        let (tx, mut rx) = mpsc::unbounded_channel::<Line>();
537
538        let tx_out = tx.clone();
539        let t_stdout = tokio::spawn(async move {
540            let mut lines = BufReader::new(stdout).lines();
541            while let Ok(Some(line)) = lines.next_line().await {
542                let ts = now_ms();
543                let _ = tx_out.send(("stdout", line, ts));
544            }
545        });
546
547        let tx_err = tx.clone();
548        let t_stderr = tokio::spawn(async move {
549            let mut lines = BufReader::new(stderr).lines();
550            while let Ok(Some(line)) = lines.next_line().await {
551                let ts = now_ms();
552                let _ = tx_err.send(("stderr", line, ts));
553            }
554        });
555
556        // Drop original sender so channel closes once both reader tasks finish.
557        drop(tx);
558
559        let mut line_count: u64 = 0;
560        // With `capture`, nothing is published until the command has ended and the
561        // values are in the Vault: until then srv can't know which line holds one.
562        let mut held: Vec<Line> = Vec::new();
563        let mut held_bytes = 0usize;
564        let mut held_cut = false;
565        while let Some((kind, content, ts)) = rx.recv().await {
566            line_count += 1;
567            status_arc.lock().line_count = line_count;
568            if self.capture.is_some() {
569                if held_bytes + content.len() + 1 > crate::backend::vault::capture::MAX_HELD {
570                    held_cut = true;
571                } else {
572                    held_bytes += content.len() + 1;
573                    held.push((kind, content, ts));
574                }
575                continue;
576            }
577            let clean = match &self.scrubber {
578                Some(s) => s.scrub(&content),
579                None => std::borrow::Cow::Borrowed(content.as_str()),
580            };
581            emit(&status_arc, &broker, &block_id, &shell_id, kind, &clean, ts);
582        }
583
584        let _ = tokio::join!(t_stdout, t_stderr);
585
586        // Drop our stop handle (no-op if ShellStop already removed it) so the
587        // natural-exit path lets `kill_task` resolve.
588        self.registry.remove(&shell_id);
589
590        let exit_code = match child.wait().await {
591            Ok(status) => status.code().unwrap_or(-1),
592            Err(_) => -1,
593        };
594
595        if let Some(job) = self.capture.take() {
596            self.publish_captured(job, held, held_cut, exit_code, &status_arc).await;
597        }
598
599        let was_stopped = kill_task.await.unwrap_or(false);
600        tracing::info!(shell_id = %shell_id, exit_code, was_stopped, line_count, "shell.exit");
601
602        // Persist final status in the status_map so ShellStatus can still query it.
603        {
604            let mut s = status_arc.lock();
605            s.running = false;
606            s.exit_code = Some(exit_code);
607            s.line_count = line_count;
608        }
609
610        publish_exit(&broker, &block_id, &shell_id, exit_code, was_stopped, now_ms());
611    }
612}
613
614impl ShellNodeRunner {
615    /// Runs the capture on the held output, then publishes it cleaned of the
616    /// values, or, if the capture failed, one line saying it is withheld and why.
617    async fn publish_captured(&self, mut job: crate::backend::vault::capture::Job, held: Vec<(&'static str, String, u64)>, cut: bool, exit_code: i32, status: &Arc<Mutex<ShellStatusInfo>>) {
618        use crate::backend::vault::capture::Outcome;
619        let given = |line: &str| -> String {
620            match &self.scrubber {
621                Some(s) => s.scrub(line).into_owned(),
622                None => line.to_string(),
623            }
624        };
625        let stdout = zeroize::Zeroizing::new(held.iter().filter(|l| l.0 == "stdout").map(|l| l.1.as_str()).collect::<Vec<_>>().join("\n"));
626        let output = zeroize::Zeroizing::new(held.iter().map(|l| given(&l.1)).collect::<Vec<_>>().join("\n"));
627        let lines = held.len();
628        // The command has run: a capture that finds nothing gives the pace back itself.
629        job.reservation.settle();
630        let (store, capture) = (job.store.clone(), job.capture.clone());
631        let outcome = tokio::task::spawn_blocking(move || capture.finish(&store, &stdout, &output, cut, exit_code))
632            .await
633            .unwrap_or_else(|e| Outcome::Withheld { why: format!("the capture stopped: {e}"), kept_as: None });
634        (job.changed)();
635        match outcome {
636            Outcome::Stored { ids, scrubber, short } => {
637                // The values it was given and the ones it printed, in one scrubber.
638                let all = match &self.scrubber {
639                    Some(given) => given.merged(&scrubber),
640                    None => scrubber,
641                };
642                match crate::backend::vault::capture::clean_held(&held, &all, &short) {
643                    Ok(lines) => {
644                        for (kind, clean, ts) in lines {
645                            emit(status, &self.broker, &self.block_id, &self.shell_id, kind, &clean, ts);
646                        }
647                    }
648                    Err(why) => {
649                        let line = format!("The values went into the Vault, but the output ({lines} lines) is withheld: {why}.");
650                        emit(status, &self.broker, &self.block_id, &self.shell_id, "system", &line, now_ms());
651                        status.lock().withheld = Some(why);
652                    }
653                }
654                status.lock().captured = ids;
655            }
656            Outcome::Withheld { why, kept_as } => {
657                let kept = match &kept_as {
658                    Some(id) => format!(" The person can open it in the Vault as [vault:{id}]."),
659                    None => String::new(),
660                };
661                let line = format!("The output ({lines} lines) is withheld: the capture failed: {why}.{kept}");
662                emit(status, &self.broker, &self.block_id, &self.shell_id, "system", &line, now_ms());
663                status.lock().withheld = Some(why);
664            }
665        }
666    }
667}
668
669/// Publishes one cleaned line, and keeps it in the job's tail when it has one.
670fn emit(status: &Arc<Mutex<ShellStatusInfo>>, broker: &Broker, block_id: &str, shell_id: &str, kind: &str, clean: &str, ts: u64) {
671    {
672        let mut s = status.lock();
673        if s.tail.is_some() && clean.chars().count() > TAIL_LINE_CHARS {
674            s.tail_clipped = true;
675        }
676        if let Some(tail) = &s.tail {
677            let mut t = tail.lock();
678            if t.len() >= TAIL_LINES {
679                t.pop_front();
680            }
681            t.push_back(clean.chars().take(TAIL_LINE_CHARS).collect());
682        }
683    }
684    publish_chunk(broker, block_id, shell_id, kind, clean, ts);
685}
686
687// Every shell_chunk / exit event is published under a SINGLE scope:
688//   - `shell:<shell_id>`  → a per-shell persistence ring buffer (1024 entries).
689//
690// Single-scope delivery (chosen over the fallback of strengthening the reducer's
691// dedup): an earlier design also published every chunk under `block:<block_id>`
692// for "live" delivery, so output produced before the frontend's `shell:<id>`
693// subscription established (the common case — process spawn + first lines beat
694// the WS resub round-trip) arrived LIVE via the block scope AND then again in the
695// replay burst when the broker replayed the whole `shell:<id>` ring on first
696// subscribe. The reducer's last-chunk-only `isDuplicate` let those non-adjacent
697// dups through → doubled output (full duplication on WS reconnect).
698//
699// Now chunks/exit go ONLY to `shell:<shell_id>`. The frontend subscribes to that
700// scope when it sees the (block-scoped, persist:64) `shell_node_create`. Because
701// the broker persists the ring regardless of subscribers (mps.rs persist_event
702// runs inside publish whenever persist>0), any output produced before the
703// subscription establishes is retained in the persist:1024 ring and replayed
704// exactly once on subscribe (guarded by the broker's per-route+event+scope
705// `replayed` set). No chunk is ever delivered via two paths → no duplication.
706//
707// This still preserves the reason the per-shell ring was introduced: each shell
708// has its OWN ring, so a chatty shell can't evict another shell's `exit` event
709// (the bug that left a sibling's row stuck `running` after a remount when all
710// shells shared the block ring).
711fn shell_scopes(shell_id: &str) -> Vec<String> {
712    vec![format!("shell:{shell_id}")]
713}
714
715/// `shell_chunk`: one line a Shell command wrote, or its exit. Scoped `shell:<shell_id>`.
716#[derive(Debug, Clone, Serialize, ts_rs::TS)]
717#[ts(export, export_to = "../../../frontend/types/rpc/")]
718#[serde(tag = "op", rename_all = "lowercase")]
719pub enum ShellChunkEvent {
720    Chunk {
721        shell_id: String,
722        #[ts(type = r#""stdout" | "stderr" | "system""#)]
723        kind: String,
724        content: String,
725        #[ts(type = "number")]
726        timestamp: u64,
727    },
728    Exit {
729        shell_id: String,
730        exit_code: i32,
731        /// The exit was caused by ShellStop (tree-killed), so the frontend shows the grey
732        /// "stopped" status instead of exited-err.
733        stopped: bool,
734        #[ts(type = "number")]
735        timestamp: u64,
736    },
737}
738
739/// `shell_node_create`: a Shell command started, so the agent pane adds its row before the first
740/// chunk. Scoped `block:<agent block>`.
741#[derive(Debug, Clone, Serialize, ts_rs::TS)]
742#[ts(export, export_to = "../../../frontend/types/rpc/")]
743pub struct ShellNodeCreateEvent {
744    pub shell_id: String,
745    pub cmd: String,
746    pub cwd: Option<String>,
747    pub title: String,
748    #[ts(type = "number")]
749    pub timestamp: u64,
750}
751
752fn publish_chunk(broker: &Broker, _block_id: &str, shell_id: &str, kind: &str, content: &str, ts: u64) {
753    let event = ShellChunkEvent::Chunk { shell_id: shell_id.to_string(), kind: kind.to_string(), content: content.to_string(), timestamp: ts };
754    broker.publish_event::<crate::backend::mps_events::ShellChunk>(&event, shell_scopes(shell_id), 1024);
755}
756
757#[cfg(test)]
758mod tests {
759    // A real process, so ignored like the other real-process tests in this crate:
760    // run with `cargo test -p agentmux-srv-core --lib a_runner_with_a_scrubber -- --ignored`.
761    #[tokio::test]
762    #[ignore]
763    async fn a_runner_with_a_scrubber_publishes_the_output_without_the_value() {
764        use crate::backend::vault::scrub::Scrubber;
765        const VALUE: &str = "sk_live_abcdefgh1234";
766        let broker = Arc::new(Broker::new());
767        let registry = ShellSessionRegistry::new();
768        let runner = ShellNodeRunner {
769            shell_id: "scrub-1".into(),
770            block_id: "block-1".into(),
771            cmd: format!("echo token={VALUE} && echo fine"),
772            title: "t".into(),
773            cwd: None,
774            launch: None,
775            askpass_secret: None,
776            extra_env: HashMap::new(),
777            broker: Arc::clone(&broker),
778            registry,
779            capture_stdin: false,
780            scrubber: Some(Arc::new(Scrubber::new(&[("api-key-x".to_string(), VALUE.to_string())]))),
781            stdin_once: None,
782            secret_dir: None,
783            capture: None,
784        };
785        runner.run().await;
786        let events = broker.read_event_history(crate::backend::mps::EVENT_SHELL_CHUNK, "shell:scrub-1", 20);
787        let text = events.iter().map(|e| e.data.clone().unwrap_or_default().to_string()).collect::<Vec<_>>().join("
788");
789        assert!(text.contains("token=[vault:api-key-x]") && text.contains("fine"), "{text}");
790        assert!(!text.contains(VALUE), "{text}");
791    }
792
793    // A real process too: `cargo test -p agentmux-srv-core --lib a_runner_with_a_capture -- --ignored`.
794    #[tokio::test]
795    #[ignore]
796    async fn a_runner_with_a_capture_publishes_only_once_the_value_is_in_the_vault() {
797        use agentmux_common::api_types::{CaptureFrom, CaptureInto, CaptureRule};
798        use crate::backend::vault::{capture, seal};
799        const VALUE: &str = "ghp_abcdefgh12345678";
800        seal::use_test_key();
801        let store = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
802        store.apply_identity_schema_for_tests().unwrap();
803        let run = |id: &str, pattern: &str| {
804            let rule = CaptureRule { into: CaptureInto { kind: Some("api-key".into()), label: Some(format!("Token {id}")), ..Default::default() }, from: CaptureFrom::Regex(pattern.into()) };
805            let cmd = format!("echo token={VALUE} && echo fine");
806            let plan = capture::plan(&store, &[rule], "Agent2-6", &cmd).unwrap();
807            ShellNodeRunner {
808                shell_id: id.into(),
809                block_id: "block-1".into(),
810                cmd,
811                title: "t".into(),
812                cwd: None,
813                launch: None,
814                askpass_secret: None,
815                extra_env: HashMap::new(),
816                broker: Arc::new(Broker::new()),
817                registry: ShellSessionRegistry::new(),
818                capture_stdin: false,
819                scrubber: None,
820                stdin_once: None,
821                secret_dir: None,
822                capture: Some(capture::Job { capture: plan, store: Arc::clone(&store), changed: Box::new(|| {}), reservation: Default::default() }),
823            }
824        };
825        let published = |broker: &Broker, id: &str| {
826            let events = broker.read_event_history(crate::backend::mps::EVENT_SHELL_CHUNK, &format!("shell:{id}"), 20);
827            events.iter().map(|e| e.data.clone().unwrap_or_default().to_string()).collect::<Vec<_>>().join("\n")
828        };
829
830        let r = run("cap-1", r"token=(\S+)");
831        let (broker, registry) = (Arc::clone(&r.broker), Arc::clone(&r.registry));
832        r.run().await;
833        let text = published(&broker, "cap-1");
834        assert!(text.contains("token=[vault:api-key-token-cap-1]") && text.contains("fine"), "{text}");
835        assert!(!text.contains(VALUE), "{text}");
836        assert_eq!(registry.get_status("cap-1").captured, ["api-key-token-cap-1"]);
837
838        let r = run("cap-2", r"key=(\S+)");
839        let (broker, registry) = (Arc::clone(&r.broker), Arc::clone(&r.registry));
840        r.run().await;
841        let text = published(&broker, "cap-2");
842        assert!(text.contains("withheld: the capture failed: the regex matched nothing"), "{text}");
843        assert!(!text.contains(VALUE) && !text.contains("fine"), "{text}");
844        assert_eq!(registry.get_status("cap-2").withheld.as_deref(), Some("the regex matched nothing"));
845    }
846
847    use super::*;
848
849    /// Runs `line` through [`local_command`] in a folder holding a script that prints each of its first three
850    /// arguments in brackets, and returns what it printed.
851    async fn args_seen_by_script(line: &str) -> String {
852        // A folder of its own per call: the tests run in parallel.
853        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
854        let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
855        let dir = std::env::temp_dir().join(format!("amx-local-command-{}-{n}", std::process::id()));
856        std::fs::create_dir_all(&dir).unwrap();
857        let (name, body) = if cfg!(windows) {
858            ("args.bat", "@echo off\r\necho [%~1][%~2][%~3]\r\n")
859        } else {
860            ("args.sh", "printf '[%s][%s][%s]' \"$1\" \"$2\" \"$3\"\n")
861        };
862        std::fs::write(dir.join(name), body).unwrap();
863        // The script by its full path: cmd does not look in the current folder when the person has turned that off.
864        let script = dir.join(name).display().to_string();
865        let line = if cfg!(windows) { line.replace("SCRIPT", &script) } else { line.replace("SCRIPT", &format!("sh {script}")) };
866        let out = local_command(&line).current_dir(&dir).output().await.unwrap();
867        let _ = std::fs::remove_dir_all(&dir);
868        let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
869        if text.is_empty() {
870            return format!("(no output; {}; stderr: {})", out.status, String::from_utf8_lossy(&out.stderr).trim());
871        }
872        text
873    }
874
875    #[tokio::test]
876    async fn a_quoted_argument_with_spaces_is_one_argument_without_its_quotes() {
877        assert_eq!(args_seen_by_script(r#"SCRIPT "two words" x y"#).await, "[two words][x][y]");
878        assert_eq!(args_seen_by_script(r#"SCRIPT --reason "two words" -- "#).await, "[--reason][two words][--]");
879    }
880
881    #[tokio::test]
882    async fn quotes_inside_an_argument_and_an_apostrophe_survive() {
883        assert_eq!(args_seen_by_script(r#"SCRIPT "it's here" "a=b c" z"#).await, "[it's here][a=b c][z]");
884    }
885
886    #[tokio::test]
887    async fn a_command_line_with_two_commands_runs_both() {
888        let out = local_command("echo one && echo two").output().await.unwrap();
889        let text = String::from_utf8_lossy(&out.stdout);
890        let lines: Vec<&str> = text.lines().map(str::trim).collect();
891        assert_eq!(lines, ["one", "two"]);
892    }
893
894    #[test]
895    fn shell_events_serialize_as_before() {
896        let chunk = ShellChunkEvent::Chunk { shell_id: "s1".into(), kind: "stdout".into(), content: "ok".into(), timestamp: 5 };
897        assert_eq!(
898            serde_json::to_value(&chunk).unwrap(),
899            serde_json::json!({ "shell_id": "s1", "op": "chunk", "kind": "stdout", "content": "ok", "timestamp": 5 })
900        );
901        let exit = ShellChunkEvent::Exit { shell_id: "s1".into(), exit_code: 1, stopped: true, timestamp: 6 };
902        assert_eq!(
903            serde_json::to_value(&exit).unwrap(),
904            serde_json::json!({ "shell_id": "s1", "op": "exit", "exit_code": 1, "stopped": true, "timestamp": 6 })
905        );
906        let created = ShellNodeCreateEvent { shell_id: "s1".into(), cmd: "npm test".into(), cwd: None, title: "npm test".into(), timestamp: 7 };
907        assert_eq!(
908            serde_json::to_value(&created).unwrap(),
909            serde_json::json!({ "shell_id": "s1", "cmd": "npm test", "cwd": null, "title": "npm test", "timestamp": 7 })
910        );
911    }
912
913    #[tokio::test]
914    async fn stop_signals_then_is_idempotent() {
915        let reg = ShellSessionRegistry::new();
916        let (tx, rx) = oneshot::channel::<()>();
917        reg.insert("s1".to_string(), tx);
918        assert!(reg.stop("s1")); // fires the channel
919        assert!(rx.await.is_ok());
920        assert!(!reg.stop("s1")); // second stop: unknown id
921    }
922
923    #[tokio::test]
924    async fn remove_drops_sender_without_signalling() {
925        let reg = ShellSessionRegistry::new();
926        let (tx, rx) = oneshot::channel::<()>();
927        reg.insert("s2".to_string(), tx);
928        reg.remove("s2"); // natural-exit path
929        assert!(rx.await.is_err()); // sender dropped → Err, not Ok
930        assert!(!reg.stop("s2"));
931    }
932
933    #[tokio::test]
934    async fn stop_all_fires_every_handle() {
935        let reg = ShellSessionRegistry::new();
936        let (tx1, rx1) = oneshot::channel::<()>();
937        let (tx2, rx2) = oneshot::channel::<()>();
938        reg.insert("a".to_string(), tx1);
939        reg.insert("b".to_string(), tx2);
940        reg.stop_all();
941        assert!(rx1.await.is_ok());
942        assert!(rx2.await.is_ok());
943    }
944
945    fn register_exited(reg: &ShellSessionRegistry, id: &str, running: bool) {
946        let (tx, _rx) = oneshot::channel::<()>();
947        let status = Arc::new(Mutex::new(ShellStatusInfo {
948            running,
949            exit_code: if running { None } else { Some(0) },
950            line_count: 1,
951            ..Default::default()
952        }));
953        // _rx is intentionally dropped; we only exercise the status-map cap.
954        reg.register_full(id.to_string(), tx, None, status);
955    }
956
957    #[tokio::test]
958    async fn exited_statuses_are_capped_oldest_first() {
959        let reg = ShellSessionRegistry::new();
960        let total = MAX_EXITED_STATUS + 10;
961        for i in 0..total {
962            register_exited(&reg, &format!("s{i}"), false);
963        }
964        // Never exceeds the cap.
965        assert_eq!(reg.status_map.lock().len(), MAX_EXITED_STATUS);
966        // Oldest 10 evicted → get_status returns default (exit_code None).
967        assert!(reg.get_status("s0").exit_code.is_none());
968        assert!(reg.get_status("s9").exit_code.is_none());
969        // Newest retained with its real exit code.
970        assert_eq!(reg.get_status(&format!("s{}", total - 1)).exit_code, Some(0));
971    }
972
973    #[tokio::test]
974    async fn running_statuses_are_never_evicted() {
975        let reg = ShellSessionRegistry::new();
976        let total = MAX_EXITED_STATUS + 5;
977        for i in 0..total {
978            register_exited(&reg, &format!("r{i}"), true); // all running
979        }
980        // Running shells exceed the exited cap but none are evicted.
981        assert_eq!(reg.status_map.lock().len(), total);
982        assert!(reg.get_status("r0").running);
983    }
984
985    fn register_running_for_block(reg: &ShellSessionRegistry, id: &str, block_id: &str, cmd: &str) {
986        let (tx, _rx) = oneshot::channel::<()>();
987        let status = Arc::new(Mutex::new(ShellStatusInfo {
988            running: true,
989            block_id: block_id.to_string(),
990            cmd: cmd.to_string(),
991            title: cmd.to_string(),
992            started_at: 1_000,
993            ..Default::default()
994        }));
995        reg.register_full(id.to_string(), tx, None, status);
996    }
997
998    #[tokio::test]
999    async fn list_active_returns_only_running_shells_across_all_blocks() {
1000        let reg = ShellSessionRegistry::new();
1001        register_running_for_block(&reg, "s1", "block-a", "npm run dev");
1002        register_running_for_block(&reg, "s2", "block-b", "task dev");
1003        register_exited(&reg, "s3", false); // exited — must not appear
1004
1005        let mut active = reg.list_active();
1006        active.sort_by(|a, b| a.shell_id.cmp(&b.shell_id));
1007
1008        assert_eq!(active.len(), 2);
1009        assert_eq!(active[0].shell_id, "s1");
1010        assert_eq!(active[0].block_id, "block-a");
1011        assert_eq!(active[0].cmd, "npm run dev");
1012        assert_eq!(active[1].shell_id, "s2");
1013        assert_eq!(active[1].block_id, "block-b");
1014    }
1015}
1016
1017fn publish_exit(broker: &Broker, _block_id: &str, shell_id: &str, exit_code: i32, stopped: bool, ts: u64) {
1018    let event = ShellChunkEvent::Exit { shell_id: shell_id.to_string(), exit_code, stopped, timestamp: ts };
1019    broker.publish_event::<crate::backend::mps_events::ShellChunk>(&event, shell_scopes(shell_id), 1024);
1020}