Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
container_pane.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! A container agent's Shell drawer runs in its container, never on the host.
4//!
5//! The drawer's shell is a sub-block of the agent's pane. When that pane belongs to a container agent
6//! (`agentMode` "container"), the shell is `docker exec -it <container> bash` in the agent's workspace
7//! mount, so what the person types runs where the agent's own commands run. The CLI is pointed at the
8//! daemon the container manager found (`DOCKER_HOST`; a Podman socket speaks Docker's API), not at whatever
9//! context the CLI would pick. If docker or the container is not there, the exec fails and says so in the
10//! terminal: it never falls back to a host shell. An explicit SSH or WSL connection on the shell wins over this.
11
12use portable_pty::CommandBuilder;
13
14use crate::backend::container::{container_of_meta, CONTAINER_WORKSPACE_DIR};
15use crate::backend::obj;
16use crate::backend::storage::store::Store;
17
18/// The container a shell sub-block belongs in: that of the container agent whose pane is its parent.
19pub(super) fn container_for(store: &Store, block_id: &str) -> Option<String> {
20    let block = store.get::<obj::Block>(block_id).ok().flatten()?;
21    let parent = store.get::<obj::Block>(block.parentoref.strip_prefix("block:")?).ok().flatten()?;
22    container_of_meta(&parent.meta)
23}
24
25/// The shell's own `cmd:env` (the identity an agent's `PtyShell` child may carry), less the names that are
26/// host paths and so mean nothing in a container. Passed by name: the value travels in the `docker` process's
27/// environment, never its argv, where `ps` and `docker top` would show it.
28fn carried_env(env: &std::collections::HashMap<String, String>) -> Vec<(&str, &str)> {
29    let mut out: Vec<_> = env
30        .iter()
31        .filter(|(k, _)| !crate::backend::agent_env_scope::host_only(k))
32        .map(|(k, v)| (k.as_str(), v.as_str()))
33        .collect();
34    out.sort_unstable();
35    out
36}
37
38fn exec_args(container: &str, carried: &[(&str, &str)]) -> Vec<String> {
39    let mut args: Vec<String> = ["exec", "-it", "-w", CONTAINER_WORKSPACE_DIR, "-e", "TERM=xterm-256color", "-e", "COLORTERM=truecolor"]
40        .map(String::from)
41        .to_vec();
42    for (name, _) in carried {
43        args.extend(["-e".to_string(), name.to_string()]);
44    }
45    args.extend([container.to_string(), "bash".to_string()]);
46    args
47}
48
49/// `docker exec` into `container`, run on a PTY like an SSH pane's `ssh`.
50pub(super) fn command(container: &str, block_id: &str, env: &std::collections::HashMap<String, String>) -> CommandBuilder {
51    tracing::info!(block_id, container, "container shell spawn");
52    let carried = carried_env(env);
53    let mut c = CommandBuilder::new("docker");
54    c.args(exec_args(container, &carried));
55    crate::backend::pane_env::sanitize_pty_command(&mut c);
56    for (name, value) in carried {
57        c.env(name, value);
58    }
59    if let Some(host) = crate::backend::container::runtime::docker_host_in_use() {
60        // A set context beats DOCKER_HOST, so it goes.
61        c.env_remove("DOCKER_CONTEXT");
62        c.env("DOCKER_HOST", host);
63    }
64    c
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70    use crate::backend::obj::MetaMapType;
71
72    fn meta(pairs: &[(&str, &str)]) -> MetaMapType {
73        pairs.iter().map(|(k, v)| (k.to_string(), serde_json::json!(v))).collect()
74    }
75
76    #[test]
77    fn a_container_agents_pane_names_its_container() {
78        let m = meta(&[("agentMode", "container"), ("agentId", "3f2a-agent")]);
79        assert_eq!(container_of_meta(&m).as_deref(), Some("agentmux-3f2a-agent"));
80    }
81
82    #[test]
83    fn a_native_agent_or_a_pane_with_no_agent_gets_no_container() {
84        assert_eq!(container_of_meta(&meta(&[("agentMode", "native"), ("agentId", "a")])), None);
85        assert_eq!(container_of_meta(&meta(&[("agentId", "a")])), None);
86        assert_eq!(container_of_meta(&meta(&[("agentMode", "container")])), None);
87    }
88
89    fn block(store: &Store, parent: &str, meta: MetaMapType) -> String {
90        let oid = uuid::Uuid::new_v4().to_string();
91        let mut b = obj::Block { oid: oid.clone(), parentoref: parent.to_string(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
92        store.insert(&mut b).unwrap();
93        oid
94    }
95
96    /// The drawer's shell is a sub-block of the agent's pane: a container agent's gets the container, a
97    /// native agent's and a plain pane's do not.
98    #[test]
99    fn the_shell_sub_block_of_a_container_agents_pane_runs_in_its_container() {
100        let store = Store::open_in_memory().unwrap();
101        let container_pane = block(&store, "tab:t1", meta(&[("view", "agent"), ("agentMode", "container"), ("agentId", "a1")]));
102        let native_pane = block(&store, "tab:t1", meta(&[("view", "agent"), ("agentMode", "native"), ("agentId", "a2")]));
103        let shell_of = |pane: &str| block(&store, &format!("block:{pane}"), meta(&[("view", "term"), ("controller", "shell")]));
104        assert_eq!(container_for(&store, &shell_of(&container_pane)).as_deref(), Some("agentmux-a1"));
105        assert_eq!(container_for(&store, &shell_of(&native_pane)), None);
106        assert_eq!(container_for(&store, &block(&store, "tab:t1", meta(&[("view", "term")]))), None, "a pane in a tab is not a drawer shell");
107    }
108
109    #[test]
110    fn the_shell_is_an_interactive_exec_in_the_workspace_mount() {
111        let args = exec_args("agentmux-x", &[]);
112        assert_eq!(&args[..4], ["exec", "-it", "-w", "/workspace"]);
113        assert_eq!(&args[args.len() - 2..], ["agentmux-x", "bash"], "the container, then the shell, last");
114    }
115
116    #[test]
117    fn the_shells_identity_env_goes_in_by_name_never_by_value() {
118        let env = std::collections::HashMap::from([("AGENTMUX_AGENT_ID".to_string(), "a1".to_string()), ("AGENTMUX_AGENT_TOKEN".to_string(), "s3cret".to_string())]);
119        let carried = carried_env(&env);
120        let args = exec_args("agentmux-x", &carried);
121        assert!(args.iter().any(|a| a == "AGENTMUX_AGENT_ID"), "{args:?}");
122        assert!(!args.iter().any(|a| a.contains("a1") || a.contains("s3cret")), "no value in argv: {args:?}");
123        assert_eq!(&args[args.len() - 2..], ["agentmux-x", "bash"]);
124    }
125}