agentmux_srv_core/backend/blockcontroller/shell/start_steps.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps `start` takes before it opens a PTY: refusing a connection AgentMux cannot run,
5//! the test-only mock connection, whether the pane closes when its process exits, the memory
6//! gate for a new agent, and what a WSL or SSH pane needs.
7
8use super::super::STATUS_DONE;
9use super::controller::ShellController;
10use crate::backend::obj::{self, MetaMapType};
11use crate::backend::shellexec::ShellProc;
12
13/// What a pane on a WSL distro or an SSH host needs, decided from its connection name.
14pub(super) struct RemotePlan {
15 pub(super) wsl_distro: Option<String>,
16 pub(super) ssh_plan: Option<(std::path::PathBuf, crate::backend::remote::conn::SshDest)>,
17 pub(super) askpass_secret: Option<String>,
18 pub(super) askpass_guard: Option<crate::backend::remote::askpass::Revoke>,
19}
20
21impl ShellController {
22 /// A pane on a connection AgentMux cannot run gets an error, not a local shell under a remote name.
23 pub(super) fn check_connection_available(
24 &self,
25 block_meta: &MetaMapType,
26 ) -> Result<(), String> {
27 // A pane on a connection AgentMux cannot run must not quietly get a
28 // local shell under a remote name: it gets no shell, and its connection
29 // overlay says why (SPEC_REMOTE_TERMINALS_AND_DURABLE_SESSIONS_2026_10_02.md).
30 // WSL runs on Windows (P1); SSH wherever the system `ssh` is (P2). The
31 // test-only mock factory keeps its own path.
32 if self.conn_factory.lock().unwrap().is_none() {
33 let conn = Self::get_conn_name(block_meta);
34 match crate::backend::remote::ConnTarget::parse(&conn) {
35 Ok(target) if target.is_local() => {}
36 #[cfg(windows)]
37 Ok(crate::backend::remote::ConnTarget::Wsl(_)) => {}
38 Ok(crate::backend::remote::ConnTarget::Ssh(_))
39 if crate::backend::remote::ssh::binary().is_some() => {}
40 Ok(crate::backend::remote::ConnTarget::Ssh(_)) => {
41 return Err(crate::backend::remote::ssh::missing_binary_message());
42 }
43 Ok(target) => {
44 return Err(format!(
45 "connection {} is not available yet: this version of AgentMux runs local terminals only",
46 target.name()
47 ));
48 }
49 Err(e) => return Err(format!("connection {conn:?}: {e}")),
50 }
51 }
52 Ok(())
53 }
54
55 /// The test-only mock path: a synchronous `ConnInterface` from the factory, with no PTY.
56 pub(super) fn run_mock_connection(
57 &self,
58 conn_name: String,
59 block_meta: &MetaMapType,
60 ) -> Result<(), String> {
61 // Mock path: use ConnInterface factory (synchronous, for tests)
62 let conn_result = {
63 let factory = self.conn_factory.lock().unwrap();
64 factory.as_ref().unwrap()(&conn_name, block_meta)
65 };
66
67 let mut conn = match conn_result {
68 Ok(c) => c,
69 Err(e) => {
70 let mut inner = self.inner.lock().unwrap();
71 Self::set_status(&mut inner, STATUS_DONE);
72 inner.proc_exit_code = -1;
73 inner.input_tx = None;
74 self.unlock_run();
75 return Err(format!("failed to create connection: {e}"));
76 }
77 };
78
79 if let Err(e) = conn.start() {
80 let mut inner = self.inner.lock().unwrap();
81 Self::set_status(&mut inner, STATUS_DONE);
82 inner.proc_exit_code = -1;
83 inner.input_tx = None;
84 self.unlock_run();
85 return Err(format!("failed to start process: {e}"));
86 }
87
88 let mut shell_proc = ShellProc::new(conn_name, conn);
89 let _done_rx = shell_proc.take_done_rx();
90 let exit_code = shell_proc.wait_and_signal();
91
92 {
93 let mut inner = self.inner.lock().unwrap();
94 inner.proc_exit_code = exit_code;
95 Self::set_status(&mut inner, STATUS_DONE);
96 inner.input_tx = None;
97 }
98 self.publish_status();
99 self.unlock_run();
100 Ok(())
101 }
102
103 /// Whether the pane closes itself when its process exits.
104 pub(super) fn closes_on_exit(&self, block_meta: &MetaMapType) -> bool {
105 // Close-on-exit (SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md §10-11):
106 // resolved from `block_meta` now, while it's still in scope, for
107 // the exit watcher (`wait_task`) to act on once the process actually
108 // exits. See `effective_close_on_exit`'s own doc comment for the
109 // per-controller-type default. (`should_close_on_exit_force` is
110 // deliberately NOT read here — see its own doc comment for why no
111 // call site uses it.)
112 //
113 // Forced off for a SUB-block — a block whose `parentoref` names
114 // another BLOCK (`block:<id>`): an agent's composer-drawer shell
115 // (`AgentShellSubblock.tsx`, via `createsubblock`) or a
116 // `PtyShellCreate`-spawned headless shell. Those are not
117 // independent panes, and closing one via
118 // `sagas::delete_block::run` leaves the parent's own
119 // `term:shellsubblockid` pointer dangling (a field that saga knows
120 // nothing about), after which the drawer's own "attach or create"
121 // logic silently recreates a fresh shell — reproducing the
122 // original respawn loop by a different route (§11).
123 //
124 // A TOP-LEVEL pane's `parentoref` names its owning TAB
125 // (`tab:<id>`, set by `wcore::block`/`persist_subscriber`) — NOT
126 // empty. Checking `!parentoref.is_empty()` here (as the first cut
127 // of §11 did) therefore disabled close-on-exit for *every* pane,
128 // including the plain `Terminal` widget this feature exists for —
129 // the regression the reporter hit as "still hangs" (§12). Match
130 // on the `block:` prefix specifically, the same discriminator
131 // `websocket.rs`'s `strip_prefix("block:")` already uses.
132 let is_sub_block = self
133 .mstore
134 .as_ref()
135 .and_then(|store| store.get::<obj::Block>(&self.block_id).ok().flatten())
136 .map(|b| b.parentoref.starts_with("block:"))
137 .unwrap_or(false);
138 Self::effective_close_on_exit(block_meta, &self.controller_type) && !is_sub_block
139 }
140
141 /// The reason a new agent pane may not start under memory pressure, if there is one.
142 pub(super) fn agent_spawn_refusal(&self, cmd_str: &str) -> Option<String> {
143 // Pillar 3 — commit-aware admission control, extended to the interactive
144 // agent pane. The drone Agent block's one-shot spawn (`agents::runner::
145 // run_agent`) already refuses to start another `claude.exe` when system
146 // commit headroom is below the reserve, to avoid tipping the box into a
147 // Chromium OOM abort (0xE0000008). That gate covered only the drone path;
148 // this interactive PTY spawn is the OTHER (likely more common) place a
149 // fresh agent CLI process gets started, and previously had no protection
150 // at all. Reuse the same pure decision + reserve lookup here, gated on
151 // `is_agent` so plain shell/cmd panes are unaffected — only a new
152 // claude/codex/gemini process is refused under commit pressure.
153 // See SPEC_WIN10_PAGEFILE_OOM_CRASH_2026_06_29.md, PR #1853.
154 if let Err(e) = crate::agents::runner::admit_spawn(
155 crate::backend::sysinfo::available_commit_gb(),
156 crate::agents::runner::agent_commit_reserve_gb(),
157 ) {
158 tracing::warn!(
159 block_id = %self.block_id,
160 cmd = %cmd_str,
161 error = %e,
162 "admission gate: refusing interactive agent spawn under commit pressure"
163 );
164 return Some(format!(
165 "memory full — not enough memory to start a new agent right now, free up memory and try again ({e})"
166 ));
167 }
168 None
169 }
170
171 /// What a WSL or SSH pane needs: the distro, the `ssh` to run and an askpass grant for an agent's SSH shell.
172 pub(super) fn remote_plan(&self, conn_name: &str, block_meta: &MetaMapType) -> RemotePlan {
173 // A WSL pane runs `wsl.exe -d <distro>` (Windows only; `check_connection_available`
174 // refuses it elsewhere). Its cwd is a path inside the distro, passed as
175 // `--cd`, never set as the Windows working directory by `start`.
176 let wsl_distro = match crate::backend::remote::ConnTarget::parse(conn_name) {
177 Ok(crate::backend::remote::ConnTarget::Wsl(d)) if cfg!(windows) => Some(d),
178 _ => None,
179 };
180 // An SSH pane runs the system `ssh` (remote::ssh). Its cwd is a path on
181 // the remote host, handed to the remote shell, never set by `start`. An
182 // agent's (its PtyShell, marked in the block meta) needs one that forces askpass.
183 let ssh_plan = match crate::backend::remote::ConnTarget::parse(conn_name) {
184 Ok(crate::backend::remote::ConnTarget::Ssh(dest)) => {
185 let agents = !obj::meta_get_string(
186 block_meta,
187 crate::backend::remote::askpass::META_KEY_AGENT_BLOCK,
188 "",
189 )
190 .is_empty();
191 if agents {
192 crate::backend::remote::ssh::binary()
193 } else {
194 crate::backend::remote::ssh::binary_for_user()
195 }
196 .map(|path| (path, dest))
197 }
198 _ => None,
199 };
200 // An agent's SSH PtyShell (`http_pty_shell.rs` marks it): a secret for
201 // its ssh's prompts, revoked when this shell's wait task ends.
202 let askpass_secret = ssh_plan.as_ref().and_then(|_| {
203 let agent_block = obj::meta_get_string(
204 block_meta,
205 crate::backend::remote::askpass::META_KEY_AGENT_BLOCK,
206 "",
207 );
208 (!agent_block.is_empty()).then(|| {
209 crate::backend::remote::askpass::grant(
210 crate::backend::remote::askpass::AskpassGrant {
211 agent_block_id: agent_block,
212 agent: obj::meta_get_string(
213 block_meta,
214 crate::backend::remote::askpass::META_KEY_AGENT,
215 "",
216 ),
217 connection: conn_name.to_string(),
218 user_pane: false,
219 },
220 )
221 })
222 });
223 let askpass_guard = askpass_secret
224 .clone()
225 .map(crate::backend::remote::askpass::Revoke);
226 RemotePlan {
227 wsl_distro,
228 ssh_plan,
229 askpass_secret,
230 askpass_guard,
231 }
232 }
233}
234
235/// Whether the command is a known agent CLI, or the block has an agent id. Worked out before the
236/// spawn so the commit-aware admission gate can use it, and reused after it to set
237/// `inner.is_agent_pane`.
238pub(super) fn is_agent_pane(cmd_str: &str, has_agent_id: bool) -> bool {
239 let cmd = cmd_str.to_lowercase();
240 has_agent_id
241 || ["claude", "codex", "gemini"]
242 .iter()
243 .any(|name| cmd.contains(name))
244}
245
246/// The program's name for the UI, taken before the command is consumed by the spawn: the
247/// process tracker can't supply it, because it omits each block's root process (#3430), and
248/// for this sub-block the root IS the shell.
249pub(super) fn program_name(cmd: &portable_pty::CommandBuilder) -> String {
250 cmd.get_argv()
251 .first()
252 .map(|p| {
253 std::path::Path::new(p)
254 .file_stem()
255 .map(|s| s.to_string_lossy().into_owned())
256 .unwrap_or_else(|| p.to_string_lossy().into_owned())
257 })
258 .unwrap_or_default()
259}