Skip to main content

agentmux_srv/server/
http_pty_shell_create.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `handle_pty_shell_create`, one function each, in the order the handler runs them:
5//! where the shell runs, the SSH consent, the reuse of the pane's existing shell, the new shell's
6//! block, the atomic claim of the pane's one shell pointer, the controller start and its rollback.
7//! Moved out of the handler without a change in behaviour. A child module of `http_pty_shell.rs`.
8
9// The `Err` is the response that ends the request early, built at most once per call.
10#![allow(clippy::result_large_err)]
11
12use super::app_api::connections::{self, AgentTarget};
13use super::*;
14
15type Early = axum::response::Response;
16
17/// `POST /api/v1/ptyshell/create`, step by step. `Err` carries a response that ends the call early:
18/// a refusal, or the attachment to the pane's existing shell.
19pub(super) async fn create_pty_shell(state: &AppState, req: &PtyShellCreateRequest) -> Result<Early, Early> {
20    let (target, connection) = resolve_connection(state, req).await?;
21    let ssh_agent = ssh_gate(state, req, &target, &connection).await?;
22    if let Some(resp) = attach_to_pointed_shell(state, req, &connection).await {
23        return Ok(resp);
24    }
25
26    let child_id = uuid::Uuid::new_v4().to_string();
27    let mut meta = shell_block_meta(state, req, &target, &connection);
28    add_ssh_and_cwd_meta(state, req, &target, &ssh_agent, &mut meta);
29    let (runtimeopts, rt_opts_json) = initial_geometry(req);
30    let block = crate::backend::obj::Block {
31        oid: child_id.clone(),
32        parentoref: format!("block:{}", req.agent_block_id),
33        meta,
34        runtimeopts,
35        ..Default::default()
36    };
37    let block = claim_shell_block(state, req, block, &child_id, &connection).await?;
38
39    if let Err(e) = start_shell_controller(state, &block, rt_opts_json) {
40        roll_back_failed_spawn(state, req, &child_id);
41        return Err((
42            StatusCode::INTERNAL_SERVER_ERROR,
43            Json(json!({ "error": format!("ptyshell.create: spawn: {e}") })),
44        )
45            .into_response());
46    }
47
48    // baseline_len=0: a genuinely new block has no prior "term" file content
49    // to accidentally match against (see
50    // `try_attach_to_existing_shell`'s identical baseline logic for why this matters at all).
51    answer_conpty_handshake_if_seen(state, &child_id, 0).await;
52
53    // NOTE: the shellsubblockid pointer is already persisted — the atomic
54    // claim transaction (`claim_shell_block`) sets it on the parent in the same
55    // transaction as the insert, which is also strictly more correct than
56    // a separate post-hoc write here would be (no window where the block
57    // exists but isn't yet pointed to).
58    tracing::info!(block_id = %child_id, parent_id = %req.agent_block_id, "ptyshell.create: fresh");
59    Ok((StatusCode::OK, Json(PtyShellCreateResponse { shell_id: child_id })).into_response())
60}
61
62/// Where the shell runs and its connection name, or the refusal. A refused connection fails the call
63/// with its reason rather than opening a local shell.
64pub(super) async fn resolve_connection(state: &AppState, req: &PtyShellCreateRequest) -> Result<(AgentTarget, String), Early> {
65    // Where the shell runs, checked the way a pane's connection is: a refused
66    // one fails the call with its reason rather than opening a local shell.
67    let target = match connections::for_agent(&state.broker, req.connection.as_deref()).await {
68        Ok(t) => t,
69        Err(e) => {
70            return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response());
71        }
72    };
73    let connection = match &target {
74        AgentTarget::Local => "local".to_string(),
75        AgentTarget::Wsl(d) => crate::backend::remote::ConnTarget::Wsl(d.clone()).name(),
76        AgentTarget::Ssh(dest) => dest.name(),
77    };
78    Ok((target, connection))
79}
80
81/// The agent that consents for an SSH shell (empty for any other connection), after the checks that come
82/// before anything is asked.
83pub(super) async fn ssh_gate(state: &AppState, req: &PtyShellCreateRequest, target: &AgentTarget, connection: &str) -> Result<String, Early> {
84    // An SSH host runs with the user's identity: their consent first, and the
85    // askpass helper must exist, since its prompts may never reach the
86    // terminal the agent reads (`remote::askpass`).
87    let mut ssh_agent = String::new();
88    if let AgentTarget::Ssh(_) = target {
89        if crate::backend::remote::askpass::program().is_none() {
90            let e = "this AgentMux has no askpass helper (agentmux-bashwrap) to run an agent's SSH shell with";
91            return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response());
92        }
93        ssh_agent = match connections::verified_agent(state, &req.agent_block_id, req.auth.as_ref()) {
94            Ok(a) => a,
95            Err(e) => return Err((StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response()),
96        };
97        // A running shell on another connection is refused before anything
98        // is asked: consent (and an "always") for a shell that then cannot
99        // start would be a grant the user gave for nothing.
100        if let Some(conflict) = running_shell_conflict(state, &req.agent_block_id, connection) {
101            return Err(conflict);
102        }
103        if let Err(e) = connections::consent_for_ssh(state, &req.agent_block_id, &ssh_agent, connection, "an interactive terminal").await {
104            return Err((StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response());
105        }
106    }
107    Ok(ssh_agent)
108}
109
110/// The pane's existing shell, if its pointer still resolves to one that can be handed out.
111pub(super) async fn attach_to_pointed_shell(state: &AppState, req: &PtyShellCreateRequest, connection: &str) -> Option<Early> {
112    let existing_id = state
113        .mstore
114        .get::<crate::backend::obj::Block>(&req.agent_block_id)
115        .ok()
116        .flatten()
117        .and_then(|b| {
118            b.meta
119                .get(META_KEY_SHELL_SUBBLOCK_ID)
120                .and_then(|v| v.as_str())
121                .map(str::to_string)
122        });
123
124    // Reuse path: the pointer exists and still resolves to a real block.
125    // Deliberately ignores req.cwd/rows/cols here — an already-running
126    // shell's cwd can't change after spawn, and geometry is a separate,
127    // legitimate post-hoc operation via PtyShellResize, not a create-time
128    // parameter for a process that already has a size.
129    let id = existing_id?;
130    let attached = try_attach_to_existing_shell(state, &req.agent_block_id, &id, connection).await;
131    // `None` here means either a stale pointer (the block was deleted
132    // some other way — rare) or, as of this PR, the pane's shell
133    // having already exited (the common case this PR fixes — see
134    // `try_attach_to_existing_shell`'s own doc comment). Either way,
135    // fall through to creating a fresh one, same as if none existed.
136    attached
137}
138
139/// The new shell block's meta: the headless `term` shape, the agent's env guards, the automatic shell,
140/// and the connection.
141pub(super) fn shell_block_meta(state: &AppState, req: &PtyShellCreateRequest, target: &AgentTarget, connection: &str) -> crate::backend::obj::MetaMapType {
142    let remote = !matches!(target, AgentTarget::Local);
143    let mut meta = crate::backend::obj::MetaMapType::new();
144    // Which srv run created this shell: a block with no controller is one this
145    // run is still starting (a concurrent create), not one left from before a
146    // restart (`try_attach_to_existing_shell`).
147    meta.insert(META_KEY_PTYSHELL_BOOT_ID.to_string(), json!(&*state.boot_id));
148    // The agent's plain-`gh` guard, as its Shell and its own CLI get it: the
149    // agent types into this shell, so `gh` here must not act as the user.
150    let mut agent_env: std::collections::HashMap<String, String> = state
151        .mstore
152        .get::<crate::backend::obj::Block>(&req.agent_block_id)
153        .ok()
154        .flatten()
155        .map(|b| crate::backend::blockcontroller::cmd_env_of(&b.meta))
156        .unwrap_or_default();
157    // Its current slug, not a persisted one, names the guard directory, and
158    // the shell gets the identity it may carry (`pty_child_identity_env`).
159    crate::server::agent_handlers::identity_env::carry_block_slug_identity_env(&state.mstore, &req.agent_block_id, &mut agent_env);
160    let child_env = crate::server::agent_handlers::identity_env::pty_child_identity_env(&agent_env);
161    if !child_env.is_empty() {
162        meta.insert(blockcontroller::META_KEY_CMD_ENV.to_string(), serde_json::Value::Object(child_env));
163    }
164    meta.insert(
165        crate::backend::gh_guard::META_KEY_PTYSHELL_GH_CONFIG_DIR.to_string(),
166        json!(crate::backend::gh_guard::guard_dir_for_target(&agent_env, remote)),
167    );
168    // And the publish guard's git hooks, so a push typed here is scanned too.
169    // Local shells only: the hooks directory is a host path, which a WSL distro
170    // or an SSH host can't run (pushes from there aren't guarded).
171    let local = matches!(target, AgentTarget::Local);
172    if let Some(hooks) = local.then(|| crate::backend::publish_guard::hooks_dir_for(&agent_env, |k| std::env::var(k).ok())).flatten() {
173        meta.insert(
174            crate::backend::publish_guard::META_KEY_PTYSHELL_GIT_HOOKS_PATH.to_string(),
175            json!(hooks.to_string_lossy()),
176        );
177    }
178    // And the git settings that keep the folder's own configuration from running a program, for an agent in a
179    // folder a container agent can write. A host path again, so local shells only.
180    let in_shared_folder = state
181        .mstore
182        .get::<crate::backend::obj::Block>(&req.agent_block_id)
183        .ok()
184        .flatten()
185        .is_some_and(|b| crate::backend::mcp_folder_rule::folder_of(&b.meta).is_some());
186    if local && in_shared_folder {
187        meta.insert(crate::backend::git_program_settings::META_KEY_PTYSHELL_GIT_PROGRAM_SETTINGS.to_string(), json!(true));
188    }
189    meta.insert("view".to_string(), json!("term"));
190    meta.insert(
191        blockcontroller::META_KEY_CONTROLLER.to_string(),
192        json!(blockcontroller::BLOCK_CONTROLLER_SHELL),
193    );
194    // An agent's shell doesn't follow the user's default-shell setting
195    // (term:localshellpath and term:localshellopts are for their terminals):
196    // pin it to the automatic shell with no extra arguments. Only macOS and
197    // Linux reach that branch; Windows runs cmd.exe below.
198    meta.insert(
199        blockcontroller::META_KEY_TERM_LOCAL_SHELL_PATH.to_string(),
200        json!(crate::backend::shells::automatic().display().to_string()),
201    );
202    meta.insert(blockcontroller::META_KEY_TERM_LOCAL_SHELL_OPTS.to_string(), json!([]));
203    // Force cmd.exe directly on Windows rather than the "shell" controller's
204    // default pwsh/powershell auto-detection (`backend::shells::automatic`,
205    // which tries pwsh first). Discovered live, not assumed: PowerShell's
206    // PSReadLine issues a cursor-position query (`ESC[6n`, Device Status
207    // Report) on interactive startup and blocks forever waiting for a
208    // `ESC[row;colR` reply — which only a real terminal emulator answering
209    // on the other end provides (xterm.js does, for the `term` widget /
210    // AgentShellSubblock's human-facing sessions). This facility has no
211    // terminal emulator reading the byte stream, only a raw capture, so
212    // every PtyShell() would otherwise hang before printing even its first
213    // prompt. cmd.exe has no such startup handshake. Non-Windows shells
214    // (bash/zsh via $SHELL) aren't affected — left as the "shell"
215    // controller's own default. This is a known-narrow mitigation, not a
216    // general fix: any OTHER program that queries terminal capabilities via
217    // escape sequences and blocks for a reply would hit the same class of
218    // issue — see docs/specs/SPEC_AGENT_INTERACTIVE_PTY_SHELL_API_2026_09_10.md §5.
219    //
220    // A WSL shell is the distro's own login shell (`wsl.exe -d`), which has no
221    // such handshake, and `cmd.exe` would be looked up inside the distro.
222    #[cfg(windows)]
223    if !remote {
224        meta.insert(blockcontroller::META_KEY_CMD.to_string(), json!("cmd.exe"));
225        meta.insert("cmd:interactive".to_string(), json!(true));
226    }
227    if remote {
228        meta.insert(blockcontroller::META_KEY_CONNECTION.to_string(), json!(connection));
229    }
230    meta
231}
232
233/// The SSH agent's identity and the working directory, onto the new shell's meta.
234pub(super) fn add_ssh_and_cwd_meta(
235    state: &AppState,
236    req: &PtyShellCreateRequest,
237    target: &AgentTarget,
238    ssh_agent: &str,
239    meta: &mut crate::backend::obj::MetaMapType,
240) {
241    let remote = !matches!(target, AgentTarget::Local);
242    // If the caller didn't supply a cwd, fall back to the agent block's own
243    // cmd:cwd — the project directory the agent pane was launched with.
244    // Mirrors `handle_shell_create`'s identical fallback (Codex P1 on PR
245    // #3177): without this, the PTY spawns in agentmux-srv's own cwd
246    // (typically the portable runtime/ dir), not the agent's worktree.
247    //
248    // In WSL the cwd is a distro path, kept as given; no Windows fallback.
249    if let AgentTarget::Ssh(_) = target {
250        let agent = ssh_agent.to_string();
251        meta.insert(crate::backend::remote::askpass::META_KEY_AGENT_BLOCK.to_string(), json!(req.agent_block_id));
252        meta.insert(crate::backend::remote::askpass::META_KEY_AGENT.to_string(), json!(agent));
253    }
254    if remote {
255        if let Some(cwd) = req.cwd.as_deref().filter(|c| !c.trim().is_empty()) {
256            meta.insert(blockcontroller::META_KEY_CMD_CWD.to_string(), json!(cwd));
257        }
258    }
259    let effective_cwd = req.cwd.clone().or_else(|| {
260        state
261            .mstore
262            .get::<crate::backend::obj::Block>(&req.agent_block_id)
263            .ok()
264            .flatten()
265            .and_then(|b| {
266                let cwd = crate::backend::obj::meta_get_string(&b.meta, "cmd:cwd", "");
267                if cwd.is_empty() { None } else { Some(cwd) }
268            })
269    });
270    let effective_cwd = effective_cwd.filter(|_| !remote);
271    if let Some(cwd) = &effective_cwd {
272        // Same MSYS→native normalization createsubblock's WS handler applies —
273        // the PTY spawn path reads cmd:cwd raw with no conversion, so a
274        // Git-Bash-style path would otherwise fail with os error 267 on
275        // Windows.
276        match crate::backend::base::normalize_working_dir(cwd)
277            .filter(|p| std::path::Path::new(p).is_absolute())
278        {
279            Some(norm) => {
280                meta.insert(blockcontroller::META_KEY_CMD_CWD.to_string(), json!(norm));
281            }
282            None => {
283                tracing::warn!(
284                    raw_cwd = %cwd,
285                    "ptyshell.create: invalid or non-absolute cwd, dropping (no cwd)"
286                );
287            }
288        }
289    }
290}
291
292/// The caller's initial PTY geometry, if it gave one, as runtime options and as the JSON the resync takes.
293pub(super) fn initial_geometry(req: &PtyShellCreateRequest) -> (Option<crate::backend::obj::RuntimeOpts>, Option<serde_json::Value>) {
294    // Initial PTY geometry, if the caller specified one — otherwise
295    // `resync_controller`'s own fallback (25x200) applies. Both `rows`/`cols`
296    // being absent is the common case; either one alone still takes effect
297    // (see `pty_size_from_rt_opts`'s per-field guards).
298    let runtimeopts = if req.rows.is_none() && req.cols.is_none() {
299        None
300    } else {
301        Some(crate::backend::obj::RuntimeOpts {
302            termsize: crate::backend::obj::TermSize {
303                rows: req.rows.unwrap_or(25) as i64,
304                cols: req.cols.unwrap_or(200) as i64,
305            },
306            ..Default::default()
307        })
308    };
309    let rt_opts_json = runtimeopts.as_ref().map(|rt| {
310        json!({ "termsize": { "rows": rt.termsize.rows, "cols": rt.termsize.cols } })
311    });
312    (runtimeopts, rt_opts_json)
313}
314
315/// Tell subscribed frontends the agent's block changed (its shell pointer or its sub-blocks).
316fn broadcast_agent_block_update(state: &AppState, agent_block_id: &str, parent: &crate::backend::obj::Block) {
317    let update = crate::backend::obj::MuxObjUpdate {
318        updatetype: "update".into(),
319        otype: "block".into(),
320        oid: agent_block_id.to_string(),
321        obj: Some(crate::backend::obj::mux_obj_to_value(parent)),
322    };
323    state.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&update, format!("block:{}", agent_block_id)));
324}
325
326/// Insert the new shell block and point the agent's block at it, unless another call got there first,
327/// in which case that call's shell is attached to instead (`Err` carries the response to return).
328pub(super) async fn claim_shell_block(
329    state: &AppState,
330    req: &PtyShellCreateRequest,
331    mut block: crate::backend::obj::Block,
332    child_id: &str,
333    connection: &str,
334) -> Result<crate::backend::obj::Block, Early> {
335    // Atomic claim-or-lose (Codex P2 on PR #3194): without this, two
336    // concurrent `PtyShell` calls that both observe an unset
337    // `term:shellsubblockid` (the check in
338    // `attach_to_pointed_shell` is NOT authoritative — it's a plain read, before this point) would each
339    // insert their own block and race to overwrite the other's pointer
340    // write, leaving one controller registered but orphaned from the
341    // pointer that's supposed to track it, and the two callers ending up
342    // attached to DIFFERENT shells despite both believing they're on "the
343    // pane's one shell." `with_tx` holds the store's single connection
344    // lock for its whole closure, so re-checking the pointer INSIDE it,
345    // atomically with the insert+link+set that follows, serializes any
346    // concurrent `PtyShell` call against this same agent_block_id.
347    //
348    // Does NOT close the equivalent race against the FRONTEND's own
349    // `createsubblock` path (`AgentShellSubblock.tsx`'s "no
350    // existingSubBlockId yet" branch): that's a separate, non-transactional
351    // multi-step RPC sequence (create, then a follow-up `SetMetaCommand`)
352    // this backend call has no visibility into or ability to serialize
353    // against. A human opening the drawer for the very first time on a
354    // pane in the same narrow window as an agent's first `PtyShell` call
355    // on that pane can still each end up with their own shell — a real,
356    // documented, accepted gap (see the spec's §10 for the full
357    // reasoning), not silently ignored, just out of scope for what a
358    // single backend transaction can enforce unilaterally.
359    let claim = state.mstore.with_tx(|tx| {
360        let mut parent = tx.must_get::<crate::backend::obj::Block>(&req.agent_block_id)?;
361        if let Some(winner_id) = parent
362            .meta
363            .get(META_KEY_SHELL_SUBBLOCK_ID)
364            .and_then(|v| v.as_str())
365        {
366            return Ok(Some(winner_id.to_string()));
367        }
368        tx.insert(&mut block)?;
369        parent.subblockids.get_or_insert_with(Vec::new).push(child_id.to_string());
370        parent
371            .meta
372            .insert(META_KEY_SHELL_SUBBLOCK_ID.to_string(), json!(child_id));
373        tx.update(&mut parent)?;
374        Ok(None)
375    });
376
377    match claim {
378        // We lost the race — someone else's transaction committed the
379        // pointer first. Pivot to reusing THEIRS rather than proceeding
380        // with the block we prepared but never actually inserted.
381        Ok(Some(winner_id)) => {
382            if let Some(resp) = try_attach_to_existing_shell(state, &req.agent_block_id, &winner_id, connection).await {
383                return Err(resp);
384            }
385            insert_after_lost_claim(state, req, block, child_id)
386        }
387        Ok(None) => {
388            // We won the claim and the parent's meta changed (inside the
389            // transaction, via a raw `tx.update`, which — unlike
390            // `broadcast_meta_update` — does NOT itself notify any
391            // subscribed frontend). Broadcast now so a drawer already open
392            // (or opened moments later) actually sees the pointer reactively
393            // instead of only on its next unrelated refetch.
394            if let Ok(Some(parent)) = state.mstore.get::<crate::backend::obj::Block>(&req.agent_block_id) {
395                broadcast_agent_block_update(state, &req.agent_block_id, &parent);
396            }
397            Ok(block)
398        }
399        Err(e) => Err((
400            StatusCode::INTERNAL_SERVER_ERROR,
401            Json(json!({ "error": format!("ptyshell.create: claim: {e}") })),
402        )
403            .into_response()),
404    }
405}
406
407/// The winner's shell is gone or had exited: create ours for real, as the won-claim path would have.
408fn insert_after_lost_claim(
409    state: &AppState,
410    req: &PtyShellCreateRequest,
411    mut block: crate::backend::obj::Block,
412    child_id: &str,
413) -> Result<crate::backend::obj::Block, Early> {
414    // Winner's block vanished between the transaction and now, OR
415    // (as of this PR) resolved to a shell that had already exited.
416    // Both stay exceedingly unlikely to land HERE specifically:
417    // `try_attach_to_existing_shell` now clears the parent's
418    // pointer itself the moment it finds an exited shell (see its
419    // own comment on the `RESYNC_ERR_ALREADY_EXITED` branch), so
420    // the common "human typed `exit`, then something calls
421    // PtyShellCreate again" case is intercepted one level up — the
422    // CLAIM transaction (`claim_shell_block`) reads the pointer as already-cleared
423    // and takes the plain `Ok(None)` fresh-insert path, never
424    // reaching this branch at all. Getting here for an exited
425    // shell specifically requires a genuine concurrent-call race
426    // (two callers both observe the stale pointer before either
427    // one's clear commits) — same rarity class as the pre-existing
428    // deleted-out-from-under-us case this comment originally
429    // described, not the common case. `block` was only ever
430    // prepared in memory: the
431    // `with_tx` closure's `tx.insert` never ran for it (that only
432    // happens in the `Ok(None)` arm, when WE win the claim), so it
433    // has no backing row. Falling through with it as-is would send
434    // `resync_controller` a phantom block and return a `shell_id`
435    // with nothing in the store behind it — every later
436    // PtyShellInput/Read/Status/Stop call against it would then
437    // fail ownership/lookup checks (ReAgent P2 on PR #3194).
438    //
439    // Actually create it for real instead, mirroring what the
440    // `Ok(None)` arm does inside its transaction — just as a plain
441    // sequence, since we're no longer inside that transaction.
442    let insert_result = (|| -> Result<(), crate::backend::storage::error::StoreError> {
443        state.mstore.insert(&mut block)?;
444        let mut parent = state
445            .mstore
446            .must_get::<crate::backend::obj::Block>(&req.agent_block_id)?;
447        parent
448            .subblockids
449            .get_or_insert_with(Vec::new)
450            .push(child_id.to_string());
451        parent
452            .meta
453            .insert(META_KEY_SHELL_SUBBLOCK_ID.to_string(), json!(child_id));
454        state.mstore.update(&mut parent)?;
455        Ok(())
456    })();
457    if let Err(e) = insert_result {
458        return Err((
459            StatusCode::INTERNAL_SERVER_ERROR,
460            Json(json!({ "error": format!("ptyshell.create: fallback insert: {e}") })),
461        )
462            .into_response());
463    }
464    if let Ok(Some(parent)) = state
465        .mstore
466        .get::<crate::backend::obj::Block>(&req.agent_block_id)
467    {
468        broadcast_agent_block_update(state, &req.agent_block_id, &parent);
469    }
470    Ok(block)
471}
472
473/// Start the shell's controller; the PTY is live when this returns.
474pub(super) fn start_shell_controller(state: &AppState, block: &crate::backend::obj::Block, rt_opts_json: Option<serde_json::Value>) -> Result<(), String> {
475    let registry = state.mstore.shared_agent_registry();
476    blockcontroller::resync_controller(
477        block,
478        "ptyshell", // headless — no real tab; only used for tracing/scoping.
479        rt_opts_json,
480        false,
481        true, // respawn_if_done — irrelevant here, this block is always freshly inserted (STATUS_INIT), never STATUS_DONE
482        Some(Arc::clone(&state.broker)),
483        Some(Arc::clone(&state.event_bus)),
484        Some(Arc::clone(&state.mstore)),
485        Some(Arc::clone(&state.filestore)),
486        Some(Arc::clone(&state.id_store)),
487        Some(Arc::clone(&state.identity_store)),
488        registry,
489        state.boot_id.clone(),
490        &state.auth_key,
491        Some(Arc::clone(&state.config_watcher)),
492    )
493}
494
495/// A failed spawn leaves nothing behind: the block, its link in the agent's block and the pointer go.
496pub(super) fn roll_back_failed_spawn(state: &AppState, req: &PtyShellCreateRequest, child_id: &str) {
497    // Roll back — the block was already inserted and linked into the
498    // parent's subblockids by the claim (#3177): without this,
499    // a failed spawn leaves a stale block + parent link + (possibly)
500    // registered controller behind that the caller has no way to clean
501    // up, since it never received a `shell_id` to call PtyShellStop with.
502    crate::sagas::agent_teardown::discard(child_id);
503    let _ = state.mstore.delete::<crate::backend::obj::Block>(child_id);
504    if let Ok(mut parent) = state
505        .mstore
506        .must_get::<crate::backend::obj::Block>(&req.agent_block_id)
507    {
508        let mut changed = false;
509        if let Some(ids) = parent.subblockids.as_mut() {
510            let before = ids.len();
511            ids.retain(|id| id != child_id);
512            changed |= ids.len() != before;
513        }
514        // The pointer was already persisted before `resync_controller`
515        // ran — either inside the atomic claim's own transaction, or by
516        // the "winner vanished" fallback (`insert_after_lost_claim`) — so unlinking
517        // `subblockids` alone isn't enough: without also clearing it
518        // here, `term:shellsubblockid` is left pointing at a block that
519        // was just deleted, and a human opening the composer drawer in
520        // this exact window (`agent-view.tsx`'s
521        // `existingSubBlockId={block()?.meta?.["term:shellsubblockid"]}`)
522        // attaches to nothing instead of getting a working shell
523        // (ReAgent P1, round 3 on PR #3194).
524        if parent.meta.get(META_KEY_SHELL_SUBBLOCK_ID).and_then(|v| v.as_str()) == Some(child_id)
525        {
526            parent.meta.remove(META_KEY_SHELL_SUBBLOCK_ID);
527            changed = true;
528        }
529        if changed {
530            let _ = state.mstore.update(&mut parent);
531            broadcast_agent_block_update(state, &req.agent_block_id, &parent);
532        }
533    }
534}