Skip to main content

agentmux_srv/server/
shell_handlers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4#[cfg(windows)]
5use agentmux_common::win32::NoWindow;
6use std::sync::Arc;
7
8use crate::backend::rpc::engine::WshRpcEngine;
9use crate::backend::rpc_types::{
10    COMMAND_SHELL_EXEC, COMMAND_SHELL_STOP, COMMAND_SHELL_STATUS,
11    CommandShellExecData, ShellExecResult, CommandShellStopData, CommandShellStatusData,
12    ShellStopResult, ShellStatusResult,
13};
14use crate::backend::base::{expand_home_dir_safe, msys_to_windows_path};
15
16use super::AppState;
17
18/// 300s process timeout matches the frontend's RPC timeout so
19/// the client sees a clean error rather than a silent EC-TIME.
20const TIMEOUT_SECS: u64 = 300;
21/// 1 MB cap per stream — bounds memory for runaway commands
22/// (`! yes`, `! dd if=/dev/zero`).
23const MAX_OUTPUT: u64 = 1_000_000;
24
25/// Shared output formatter: if we accumulated more than MAX_OUTPUT
26/// bytes, the stream was truncated — append a notice.
27fn format_output(bytes: Vec<u8>, cap: u64) -> String {
28    if bytes.len() > cap as usize {
29        let s = String::from_utf8_lossy(&bytes[..cap as usize]);
30        format!("{s}…[output capped at {cap} bytes]")
31    } else {
32        String::from_utf8_lossy(&bytes).into_owned()
33    }
34}
35
36/// shellstop → tree-kill a running persistent shell node (Phase 3). Invoked
37/// by the UI stop button on a running PersistentShellBlock. The runner then
38/// publishes a `stopped` exit event.
39pub(crate) fn shell_stop(state: &AppState, req: CommandShellStopData) -> Result<ShellStopResult, String> {
40    let registry = &state.shell_sessions;
41    let stopped = registry.stop(&req.shell_id);
42    tracing::info!(shell_id = %req.shell_id, stopped, "shellstop");
43    Ok(ShellStopResult { stopped })
44}
45
46/// shellstatus → query a shell's current running state. Used by
47/// useShellNodeStream to resolve the TRUE status of a shell whose
48/// `shell_node_create` event is being replayed on pane mount/reconnect
49/// (persist:64 ring), instead of assuming "running" — the frontend can't
50/// otherwise tell a live spawn apart from a replay of an already-long-
51/// exited shell, which was flashing stale rows in the Activity Dock.
52/// See docs/retro/retro-activity-dock-stale-shell-flash-on-load-2026-08-22.md.
53///
54/// Reports `known: false` (rather than collapsing into `running: false`,
55/// like the MCP-facing HTTP route does) when no registry entry exists yet
56/// — the shell may simply not have finished spawning/registering (see
57/// `get_status_if_known`'s doc comment for the exact race this closes:
58/// reagent P1 on PR #2770, a genuinely live shell misreported as already
59/// exited). The frontend treats `known: false` as "don't correct."
60pub(crate) fn shell_status(state: &AppState, req: CommandShellStatusData) -> Result<ShellStatusResult, String> {
61    Ok(match state.shell_sessions.get_status_if_known(&req.shell_id) {
62        Some(s) => ShellStatusResult {
63            known: true,
64            running: s.running,
65            exit_code: s.exit_code,
66            line_count: s.line_count,
67        },
68        // `known: false` with running/exit_code/line_count zeroed.
69        // Not `Default::default()`: the zeros here are filler for
70        // "we have nothing to say", and spelling them out keeps
71        // that distinct from a shell that genuinely exited 0.
72        None => ShellStatusResult {
73            known: false,
74            running: false,
75            exit_code: None,
76            line_count: 0,
77        },
78    })
79}
80
81/// Runs `command` in the agent's container and collects both streams, capped
82/// at `MAX_OUTPUT + 1` bytes each. Returns the exec id (for the exit code) and
83/// the two buffers.
84async fn container_exec_collect(
85    cm: &crate::backend::container::ContainerManager,
86    container_name: &str,
87    command: &str,
88) -> Result<(String, Vec<u8>, Vec<u8>), String> {
89    let session = cm.exec(
90        container_name,
91        &["sh".to_string(), "-c".to_string(), command.to_string()],
92        None, // container's own working directory (host path invalid inside)
93        &[],  // no extra env vars for !cmd
94        false, // no stdin — `!cmd` output-only; see ContainerManager::exec
95    ).await.map_err(|e| format!("shellexec: container exec failed: {e}"))?;
96
97    let exec_id = session.exec_id.clone();
98    // No stdin needed for !cmd — drop to signal EOF immediately.
99    drop(session.input);
100
101    let mut stdout_buf: Vec<u8> = Vec::new();
102    let mut stderr_buf: Vec<u8> = Vec::new();
103
104    use futures_util::StreamExt as _;
105    use bollard::container::LogOutput;
106
107    let timeout_result = tokio::time::timeout(
108        std::time::Duration::from_secs(TIMEOUT_SECS),
109        async {
110            let mut output = std::pin::pin!(session.output);
111            while let Some(item) = output.next().await {
112                match item {
113                    Err(e) => return Err(format!(
114                        "shellexec: container output read: {e}"
115                    )),
116                    Ok(log) => match log {
117                        LogOutput::StdOut { message } => {
118                            // Accumulate MAX_OUTPUT+1 bytes (the +1 sentinel lets
119                            // format_output distinguish "exactly at cap" from
120                            // "truncated", matching the host branch's take logic).
121                            let cap = (MAX_OUTPUT + 1) as usize;
122                            let take = cap
123                                .saturating_sub(stdout_buf.len())
124                                .min(message.len());
125                            stdout_buf.extend_from_slice(&message[..take]);
126                        }
127                        LogOutput::StdErr { message } => {
128                            let cap = (MAX_OUTPUT + 1) as usize;
129                            let take = cap
130                                .saturating_sub(stderr_buf.len())
131                                .min(message.len());
132                            stderr_buf.extend_from_slice(&message[..take]);
133                        }
134                        _ => {} // StdIn / Console frames not relevant here
135                    }
136                }
137            }
138            Ok(())
139        }
140    ).await;
141
142    if timeout_result.is_err() {
143        // Kill the in-container process so it doesn't linger after
144        // timeout. Mirrors the host branch's process-group SIGKILL.
145        // signal_exec_process runs `pkill -KILL -f <pattern>` inside
146        // the container; fire-and-forget (non-match is not an error).
147        //
148        // Pattern is "sh -c <command>" (the full cmdline we spawned),
149        // not just the command — a bare command like "python" or "sh"
150        // would over-match the agent's own running processes.
151        let kill_pattern = format!("sh -c {command}");
152        cm.signal_exec_process(container_name, &kill_pattern, true).await.ok();
153        return Err(format!("shellexec: timed out after {TIMEOUT_SECS}s"));
154    }
155    timeout_result.unwrap()?;
156    Ok((exec_id, stdout_buf, stderr_buf))
157}
158
159/// ── Container agents ─────────────────────────────────────────
160async fn shell_exec_container(
161    state: &AppState,
162    cmd: &CommandShellExecData,
163    block: &crate::backend::obj::Block,
164) -> Result<ShellExecResult, String> {
165    let cm = state.container_manager.get_or_explain().await.map_err(|e| format!("shellexec: {e}"))?;
166
167    let agent_id = crate::backend::obj::meta_get_string(
168        &block.meta, "agentId", "",
169    );
170    if agent_id.is_empty() {
171        return Err("shellexec: container agent missing agentId in block meta".to_string());
172    }
173    let container_name =
174        crate::backend::container::container_name_for_slug(&agent_id);
175
176    let (exec_id, stdout_buf, stderr_buf) = container_exec_collect(&cm, &container_name, &cmd.command).await?;
177
178    // The output stream closing does not carry the exit status —
179    // retrieve it separately via inspect_exec.
180    let exit_code = cm.inspect_exec(&exec_id).await
181        .ok()
182        .flatten()
183        .unwrap_or(1) as i32;
184
185    tracing::debug!(
186        block_id = %cmd.blockid,
187        container = %container_name,
188        exit_code,
189        "ShellExec container done",
190    );
191
192    let result = ShellExecResult {
193        exit_code,
194        stdout: format_output(stdout_buf, MAX_OUTPUT),
195        stderr: format_output(stderr_buf, MAX_OUTPUT),
196    };
197    Ok(result)
198}
199
200/// The working directory a host `!cmd` runs in: absolute, symlinks resolved.
201fn host_working_dir(working_dir: &str) -> Result<Option<std::path::PathBuf>, String> {
202    if working_dir.is_empty() {
203        return Ok(None);
204    }
205    // Convert MSYS/Git-Bash paths like /c/Users/... to C:\Users\...
206    // before expansion. Without this, canonicalize() fails on Windows
207    // with os error 267 (ERROR_DIRECTORY) — same fix applied to the
208    // persistent shell node in d89c1458.
209    let native = msys_to_windows_path(working_dir);
210    let expanded = expand_home_dir_safe(&native);
211    // Reject non-absolute paths to prevent relative traversal
212    // (e.g. "../etc") from resolving against the sidecar's cwd.
213    // expand_home_dir_safe turns "~" into an absolute home path;
214    // anything still relative after expansion is suspicious.
215    if !expanded.is_absolute() {
216        return Err(format!(
217            "shellexec: working_dir must be absolute, got: {}",
218            expanded.display()
219        ));
220    }
221    // Canonicalize to resolve all symlinks before handing the
222    // path to the shell. Without this a symlinked working_dir
223    // would silently run the shell in the symlink target
224    // (potentially outside the agent workspace), matching the
225    // symlink-escape protection in writeagentconfig.
226    let canonical = expanded.canonicalize()
227        .map_err(|e| format!(
228            "shellexec: cannot resolve working directory '{}': {e}",
229            expanded.display()
230        ))?;
231    Ok(Some(canonical))
232}
233
234/// The `sh -c <command>` process for a host `!cmd`, with its stdio, kill and
235/// process-group settings.
236fn host_command(shell: std::path::PathBuf, command: &str, cwd: Option<&std::path::Path>) -> tokio::process::Command {
237    let mut proc = {
238        let mut c = tokio::process::Command::new(&shell);
239        c.args(["-c", command]);
240        // shellexec runs arbitrary agent-supplied commands and, per
241        // the note below, fires on every MCP Shell tool call — so a
242        // build started this way would otherwise adopt this
243        // instance's channel and data dir. Same class as
244        // shell_node.rs; see backend::pane_env.
245        crate::backend::pane_env::sanitize_process_command(&mut c);
246        // CREATE_NO_WINDOW: console-flash suppression — on Windows
247        // this `sh` is Git Bash (console-subsystem), and srv is
248        // launched windowless, so without the flag every shellexec
249        // pops a console window. This is the highest-frequency
250        // console-flash site (fires on every MCP Shell tool call).
251        // See crates/common/src/cli.rs.
252        #[cfg(windows)]
253        {
254            c.no_window();
255        }
256        c
257    };
258    // stdin MUST NOT be inherited. srv's own stdin is the
259    // launcher's lifeline pipe, with a thread parked in a blocking
260    // read on it (bootstrap::install_shutdown_handlers). Git Bash's
261    // MSYS runtime queries its inherited stdin at startup, and on
262    // Windows that query waits behind srv's pending read — forever,
263    // so every `!cmd` hung until the 300s timeout, `!echo hi`
264    // included. A one-shot command has no input anyway; null gives
265    // `!cat` an EOF instead of a read on srv's lifeline.
266    proc.stdin(std::process::Stdio::null());
267    proc.stdout(std::process::Stdio::piped());
268    proc.stderr(std::process::Stdio::piped());
269    // kill_on_drop: when the timeout fires the Child future is
270    // dropped; without this flag the OS process keeps running
271    // (e.g. `! sleep 1000` would linger indefinitely).
272    proc.kill_on_drop(true);
273    // Unix: put the shell in its own process group so that compound
274    // commands (`! a | b`, `! foo &`) are in the same group and can
275    // all be killed at once on timeout.  kill_on_drop only kills the
276    // direct sh child; without process_group(0), grandchildren
277    // get reparented to init and outlive the timeout.
278    #[cfg(unix)]
279    {
280        proc.process_group(0);
281    }
282    if let Some(dir) = cwd {
283        proc.current_dir(dir);
284    }
285    proc
286}
287
288/// Reads both streams (capped) and waits for the child, all under the
289/// timeout. The outer `Err` is the timeout.
290async fn collect_host_output(
291    child: &mut tokio::process::Child,
292    stdout_pipe: &mut tokio::process::ChildStdout,
293    stderr_pipe: &mut tokio::process::ChildStderr,
294    stdout_buf: &mut Vec<u8>,
295    stderr_buf: &mut Vec<u8>,
296) -> Result<Result<std::process::ExitStatus, String>, tokio::time::error::Elapsed> {
297    use tokio::io::AsyncReadExt as _;
298    // Each stream's capped-read and drain run in the SAME concurrent
299    // branch.  A two-phase approach (cap-read all, then drain all)
300    // deadlocks: when stdout exceeds the cap, its read_to_end returns
301    // but the process is now blocked on write() to a full pipe, so it
302    // never writes to stderr, so stderr's read_to_end never gets EOF.
303    // Both reads block, the drain phase is never reached, and the whole
304    // handler hangs for the full 300 s timeout.
305    //
306    // Solution: read MAX_OUTPUT+1 sentinel bytes per stream (≤ MAX_OUTPUT
307    // → complete; MAX_OUTPUT+1 → truncated), then immediately drain the
308    // remainder.  stdout and stderr pipelines run concurrently with each
309    // other, and with child.wait().
310    tokio::time::timeout(
311        std::time::Duration::from_secs(TIMEOUT_SECS),
312        async {
313            let (sout, serr, wait) = tokio::join!(
314                // stdout branch: cap-read then drain
315                async {
316                    let mut take = (&mut *stdout_pipe).take(MAX_OUTPUT + 1);
317                    take.read_to_end(stdout_buf).await
318                        .map_err(|e| format!("shellexec: stdout read: {e}"))?;
319                    drop(take); // release &mut borrow so stdout_pipe is usable
320                    let mut sink = tokio::io::sink();
321                    tokio::io::copy(&mut *stdout_pipe, &mut sink).await
322                        .map_err(|e| format!("shellexec: drain stdout: {e}"))?;
323                    Ok::<(), String>(())
324                },
325                // stderr branch: cap-read then drain
326                async {
327                    let mut take = (&mut *stderr_pipe).take(MAX_OUTPUT + 1);
328                    take.read_to_end(stderr_buf).await
329                        .map_err(|e| format!("shellexec: stderr read: {e}"))?;
330                    drop(take);
331                    let mut sink = tokio::io::sink();
332                    tokio::io::copy(&mut *stderr_pipe, &mut sink).await
333                        .map_err(|e| format!("shellexec: drain stderr: {e}"))?;
334                    Ok::<(), String>(())
335                },
336                child.wait(),
337            );
338            sout?;
339            serr?;
340            wait.map_err(|e| format!("shellexec: wait: {e}"))
341        }
342    )
343    .await
344}
345
346/// ── Host agents ───────────────────────────────────────────────
347async fn shell_exec_host(cmd: &CommandShellExecData) -> Result<ShellExecResult, String> {
348    let cwd = host_working_dir(&cmd.working_dir)?;
349
350    // Use sh -c on all platforms: agents run in a bash environment
351    // (Git Bash on Windows, sh on Unix) so Unix commands like ls/pwd/grep
352    // work consistently. cmd /C would exit 1 for any non-Windows command.
353    // On Windows `sh` is located rather than assumed to be on PATH —
354    // an Explorer-launched build's PATH has only Git\cmd, which has
355    // no sh.exe. See backend::posix_shell.
356    let shell = crate::backend::posix_shell::resolve_posix_shell()
357        .map_err(|e| format!("shellexec: {e}"))?;
358    let mut proc = host_command(shell.clone(), &cmd.command, cwd.as_deref());
359
360    // Joins the agent's tracker before it runs: a `!cmd` that
361    // backgrounds a child ends with the agent (agent_teardown spec §6.5).
362    let mut child = crate::backend::process_tracker::registry::spawn_tracked(&cmd.blockid, &mut proc, crate::backend::process_tracker::registry::Join::Adopted)
363        .map_err(|e| format!("shellexec: spawn failed ({}): {e}", shell.display()))?;
364
365    // Capture the PID before taking stdout/stderr (id() requires
366    // the Child to still have its stdio handles on some platforms).
367    #[cfg(unix)]
368    let child_pgid = child.id().map(|id| id as libc::pid_t);
369
370    let mut stdout_pipe = child.stdout.take().expect("stdout piped");
371    let mut stderr_pipe = child.stderr.take().expect("stderr piped");
372
373    let mut stdout_buf: Vec<u8> = Vec::new();
374    let mut stderr_buf: Vec<u8> = Vec::new();
375
376    let timeout_result = collect_host_output(&mut child, &mut stdout_pipe, &mut stderr_pipe, &mut stdout_buf, &mut stderr_buf).await;
377
378    // On timeout: kill_on_drop kills the direct sh child, but
379    // compound commands (`! a | b`, `! foo &`) fork grandchildren
380    // in the same process group.  Kill the whole group so they don't
381    // linger.  (Unix only; on Windows the job-object approach is a
382    // separate follow-up since tokio doesn't expose it yet.)
383    #[cfg(unix)]
384    if timeout_result.is_err() {
385        if let Some(pgid) = child_pgid {
386            // SAFETY: kill() is async-signal-safe; negative pid
387            // addresses the process group with id=pgid.
388            unsafe { libc::kill(-pgid, libc::SIGKILL); }
389        }
390    }
391
392    let status = timeout_result
393        .map_err(|_| format!("shellexec: timed out after {TIMEOUT_SECS}s"))??;
394
395    let result = ShellExecResult {
396        exit_code: status.code().unwrap_or(1),
397        stdout: format_output(stdout_buf, MAX_OUTPUT),
398        stderr: format_output(stderr_buf, MAX_OUTPUT),
399    };
400    Ok(result)
401}
402
403/// shellexec → run a shell command and return output.
404/// Invoked by the `!cmd` prefix in the agent pane composer.
405///
406/// Host agents:      sh -c <cmd> in the agent's working directory (all platforms;
407///                   Git Bash provides sh on Windows, located by
408///                   backend::posix_shell).
409/// Container agents: docker exec <container> sh -c <cmd> via bollard.
410///                   The host cmd:cwd is not valid inside the container — the
411///                   command runs in the container's own working directory.
412pub(crate) async fn shell_exec(state: &AppState, cmd: CommandShellExecData) -> Result<ShellExecResult, String> {
413    // Log block_id at info; keep the command at debug so secrets
414    // passed as CLI args (API tokens, passwords) don't land in
415    // ~/.agentmux/logs/ in plaintext.
416    tracing::info!(block_id = %cmd.blockid, "ShellExec");
417    tracing::debug!(command = %cmd.command, "ShellExec command");
418
419    let block: crate::backend::obj::Block = state.mstore
420        .get(&cmd.blockid)
421        .map_err(|e| format!("shellexec: load block: {e}"))?
422        .ok_or_else(|| format!("shellexec: block {} not found", cmd.blockid))?;
423    let agent_mode = crate::backend::obj::meta_get_string(
424        &block.meta, "agentMode", "host",
425    );
426
427    if crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(&agent_mode).is_container() {
428        return shell_exec_container(state, &cmd, &block).await;
429    }
430    shell_exec_host(&cmd).await
431}
432
433pub fn register_shell_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
434    let s = state.clone();
435    engine.register_typed(COMMAND_SHELL_STOP, move |req: CommandShellStopData, _ctx| {
436        let s = s.clone();
437        async move { shell_stop(&s, req) }
438    });
439
440    let s = state.clone();
441    engine.register_typed(COMMAND_SHELL_STATUS, move |req: CommandShellStatusData, _ctx| {
442        let s = s.clone();
443        async move { shell_status(&s, req) }
444    });
445
446    let s = state.clone();
447    engine.register_typed(COMMAND_SHELL_EXEC, move |cmd: CommandShellExecData, _ctx| {
448        let s = s.clone();
449        async move { shell_exec(&s, cmd).await }
450    });
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    /// All three shell commands record their request and response types.
458    ///
459    /// `shellstop` and `shellstatus` previously answered inline
460    /// `json!({..})` literals, so the registry would have recorded `Value` for
461    /// both -- which is the shape of drift this migration exists to close.
462    #[tokio::test]
463    async fn register_typed_records_every_shell_command() {
464        let state = crate::server::tests::test_state();
465        let (engine, _rx) = WshRpcEngine::new();
466        register_shell_handlers(&engine, &state);
467        let schema = engine.schema_json();
468        let rows = schema.as_array().unwrap();
469        let find = |cmd: &str| {
470            rows.iter()
471                .find(|r| r["command"] == cmd)
472                .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
473        };
474
475        for (cmd, req, resp) in [
476            (COMMAND_SHELL_EXEC, "CommandShellExecData", "ShellExecResult"),
477            (COMMAND_SHELL_STOP, "CommandShellStopData", "ShellStopResult"),
478            (COMMAND_SHELL_STATUS, "CommandShellStatusData", "ShellStatusResult"),
479        ] {
480            let row = find(cmd);
481            assert_eq!(row["requestName"], req, "{cmd} request");
482            assert_eq!(row["responseName"], resp, "{cmd} response");
483        }
484    }
485
486    /// `exit_code` is always PRESENT and null, never omitted.
487    ///
488    /// The hand-written stub typed it `exit_code?: number`, but both arms of
489    /// the handler write the key unconditionally -- the unknown arm literally
490    /// wrote `"exit_code": null`. The generated type says `number | null`,
491    /// which is the honest shape, and this is the half of that claim TypeScript
492    /// cannot check.
493    ///
494    /// It matters here more than usual: `known: false` must stay
495    /// distinguishable from `running: false` (reagent P1 on #2770 -- collapsing
496    /// them misreported a live, still-registering shell as failed for its
497    /// entire run), and a caller reaching for `exit_code === undefined` as a
498    /// proxy for "unknown" would get the wrong answer either way.
499    #[test]
500    fn shellstatus_always_sends_exit_code_even_when_null() {
501        let unknown = ShellStatusResult {
502            known: false,
503            running: false,
504            exit_code: None,
505            line_count: 0,
506        };
507        let v = serde_json::to_value(&unknown).unwrap();
508        assert!(
509            v.get("exit_code").is_some(),
510            "exit_code must be present-and-null, not omitted: {v}",
511        );
512        assert!(v["exit_code"].is_null());
513        assert_eq!(v["known"], false);
514
515        let exited = ShellStatusResult {
516            known: true,
517            running: false,
518            exit_code: Some(0),
519            line_count: 12,
520        };
521        let v = serde_json::to_value(&exited).unwrap();
522        assert_eq!(v["exit_code"], 0, "a real exit 0 is not the same as unknown");
523        assert_eq!(v["known"], true);
524    }
525
526    use crate::backend::rpc_types::RpcMessage;
527    use crate::backend::shell_node::ShellStatusInfo;
528    use parking_lot::Mutex;
529
530    // Seed a shell status directly (mirrors shell_node.rs's own
531    // register_running_for_block/register_exited test helpers) — avoids
532    // spawning a real child process just to exercise the RPC handler's
533    // JSON shape.
534    fn seed_status(state: &AppState, shell_id: &str, running: bool, exit_code: Option<i32>) {
535        let (tx, _rx) = tokio::sync::oneshot::channel::<()>();
536        let status = Arc::new(Mutex::new(ShellStatusInfo {
537            running,
538            exit_code,
539            line_count: 3,
540            ..Default::default()
541        }));
542        state.shell_sessions.register_full(shell_id.to_string(), tx, None, status);
543    }
544
545    async fn call_shellstatus(state: &AppState, shell_id: &str) -> serde_json::Value {
546        let (engine, mut output_rx) = WshRpcEngine::new();
547        register_shell_handlers(&engine, state);
548        engine.handle_message(RpcMessage {
549            command: "shellstatus".to_string(),
550            reqid: "req-shellstatus".to_string(),
551            data: Some(serde_json::json!({ "shell_id": shell_id })),
552            ..Default::default()
553        });
554        let resp = tokio::time::timeout(std::time::Duration::from_secs(1), output_rx.recv())
555            .await
556            .unwrap()
557            .unwrap();
558        resp.data.unwrap()
559    }
560
561    #[tokio::test]
562    async fn shellstatus_reports_running_shell() {
563        let state = crate::server::tests::test_state();
564        seed_status(&state, "sh-running", true, None);
565        let data = call_shellstatus(&state, "sh-running").await;
566        assert_eq!(data["known"], serde_json::json!(true));
567        assert_eq!(data["running"], serde_json::json!(true));
568        assert_eq!(data["line_count"], serde_json::json!(3));
569        assert!(data.get("exit_code").map_or(true, |v| v.is_null()));
570    }
571
572    #[tokio::test]
573    async fn shellstatus_reports_exited_shell_with_exit_code() {
574        let state = crate::server::tests::test_state();
575        seed_status(&state, "sh-exited", false, Some(0));
576        let data = call_shellstatus(&state, "sh-exited").await;
577        assert_eq!(data["known"], serde_json::json!(true));
578        assert_eq!(data["running"], serde_json::json!(false));
579        assert_eq!(data["exit_code"], serde_json::json!(0));
580    }
581
582    #[tokio::test]
583    async fn shellstatus_reports_exited_err_shell() {
584        let state = crate::server::tests::test_state();
585        seed_status(&state, "sh-failed", false, Some(1));
586        let data = call_shellstatus(&state, "sh-failed").await;
587        assert_eq!(data["known"], serde_json::json!(true));
588        assert_eq!(data["running"], serde_json::json!(false));
589        assert_eq!(data["exit_code"], serde_json::json!(1));
590    }
591
592    // Reagent P1 on PR #2770: a shell with no registry entry at all — either
593    // a genuinely unknown id, OR (the actual race that motivated this)
594    // `shell_node_create` was published but the runner hasn't reached
595    // `register_full` yet (still spawning the child process). Both look
596    // identical to this handler, and BOTH must report `known: false`, not
597    // the same shape as a genuinely exited shell — otherwise a live shell
598    // caught in that race gets misreported as failed for its entire run
599    // (ShellChunkAppend never restores a status once set).
600    #[tokio::test]
601    async fn shellstatus_unknown_id_reports_known_false() {
602        let state = crate::server::tests::test_state();
603        let data = call_shellstatus(&state, "sh-never-existed").await;
604        assert_eq!(data["known"], serde_json::json!(false));
605        assert_eq!(data["running"], serde_json::json!(false));
606        assert!(data.get("exit_code").map_or(true, |v| v.is_null()));
607    }
608
609    fn insert_block(state: &AppState, block_id: &str, meta: &[(&str, &str)]) {
610        let mut m = crate::backend::obj::MetaMapType::new();
611        for (k, v) in meta {
612            m.insert(k.to_string(), serde_json::json!(v));
613        }
614        let mut block = crate::backend::obj::Block {
615            oid: block_id.to_string(),
616            parentoref: String::new(),
617            version: 0,
618            runtimeopts: None,
619            stickers: None,
620            meta: m,
621            subblockids: None,
622        };
623        state.mstore.insert(&mut block).unwrap();
624    }
625
626    fn exec_req(block_id: &str, command: &str, working_dir: &str) -> CommandShellExecData {
627        serde_json::from_value(serde_json::json!({ "blockid": block_id, "command": command, "working_dir": working_dir })).unwrap()
628    }
629
630    /// The handlers run without the engine: stop answers whether a shell was
631    /// stopped, and status keeps `known: false` apart from `running: false`.
632    #[tokio::test]
633    async fn shell_stop_and_status_answer_directly() {
634        let state = crate::server::tests::test_state();
635        assert!(!shell_stop(&state, serde_json::from_value(serde_json::json!({ "shell_id": "never" })).unwrap()).unwrap().stopped);
636
637        seed_status(&state, "sh-direct", false, Some(2));
638        let known = shell_status(&state, serde_json::from_value(serde_json::json!({ "shell_id": "sh-direct" })).unwrap()).unwrap();
639        assert!(known.known && !known.running);
640        assert_eq!(known.exit_code, Some(2));
641        let unknown = shell_status(&state, serde_json::from_value(serde_json::json!({ "shell_id": "sh-unknown" })).unwrap()).unwrap();
642        assert!(!unknown.known && unknown.exit_code.is_none() && unknown.line_count == 0);
643    }
644
645    #[tokio::test]
646    async fn shell_exec_of_a_missing_block_is_an_error() {
647        let state = crate::server::tests::test_state();
648        let err = shell_exec(&state, exec_req("no-such-block", "echo hi", "")).await.unwrap_err();
649        assert_eq!(err, "shellexec: block no-such-block not found");
650    }
651
652    #[tokio::test]
653    async fn shell_exec_refuses_a_relative_working_directory() {
654        let state = crate::server::tests::test_state();
655        insert_block(&state, "exec-rel", &[]);
656        let err = shell_exec(&state, exec_req("exec-rel", "echo hi", "../etc")).await.unwrap_err();
657        assert!(err.starts_with("shellexec: working_dir must be absolute"), "{err}");
658    }
659
660    /// A container agent with no agentId in its block meta is refused before any exec.
661    #[tokio::test]
662    async fn shell_exec_of_a_container_block_without_an_agent_id_is_refused() {
663        let state = crate::server::tests::test_state();
664        insert_block(&state, "exec-container", &[("agentMode", "container")]);
665        let err = shell_exec(&state, exec_req("exec-container", "echo hi", "")).await.unwrap_err();
666        // Either there is no container runtime on this host, or the agentId check fires.
667        assert!(err.starts_with("shellexec:"), "{err}");
668    }
669
670    #[cfg(unix)]
671    #[tokio::test]
672    async fn shell_exec_runs_a_host_command_and_reports_streams_and_exit_code() {
673        let state = crate::server::tests::test_state();
674        insert_block(&state, "exec-host", &[]);
675        let dir = tempfile::tempdir().unwrap();
676        let wd = dir.path().canonicalize().unwrap();
677        let out = shell_exec(&state, exec_req("exec-host", "pwd; echo err >&2; exit 3", wd.to_str().unwrap())).await.unwrap();
678        assert_eq!(out.exit_code, 3);
679        assert_eq!(out.stdout.trim(), wd.to_string_lossy());
680        assert_eq!(out.stderr.trim(), "err");
681    }
682
683    /// Output past the cap is cut and says so, without hanging on the full pipe.
684    #[cfg(unix)]
685    #[tokio::test]
686    async fn shell_exec_caps_runaway_output() {
687        let state = crate::server::tests::test_state();
688        insert_block(&state, "exec-cap", &[]);
689        let out = shell_exec(&state, exec_req("exec-cap", "head -c 1500000 /dev/zero | tr '\\0' a", "")).await.unwrap();
690        assert_eq!(out.exit_code, 0);
691        assert!(out.stdout.ends_with("…[output capped at 1000000 bytes]"), "tail: {:?}", &out.stdout[out.stdout.len().saturating_sub(40)..]);
692    }
693}