Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
spawn.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `spawn_process`: builds the CLI argv/env, spawns the child, and starts the
5//! per-session I/O tasks (stdin writer, stdout reader, stderr reader, waiter).
6//! The stdin writer runs inline; the other three bodies live in
7//! `stderr_reader.rs`, `stdout_reader.rs` and `process_waiter.rs`.
8
9use super::*;
10
11/// Whether a spawn resumes with `--fork-session`: the resume gate placed a
12/// copy to fork from, the session grew outside AgentMux (`fork_next`), or the
13/// launch itself asks to (a quick fork from the picker carries the flag in
14/// its own args). One answer for the duplicate-session guard and for the
15/// fork's bookkeeping, so the two can't disagree.
16pub(super) fn spawn_forks(fork_copy: bool, fork_next: bool, cli_args: &[String]) -> bool {
17    fork_copy || fork_next || cli_args.iter().any(|a| a == "--fork-session")
18}
19
20impl PersistentSubprocessController {
21    /// Spawn the persistent CLI process. Called only while the caller
22    /// holds the exclusive spawn claim (`spawning_in_progress`, see
23    /// `decide_send_action`) — never directly.
24    pub(super) fn spawn_process(
25        &self,
26        config: PersistentSpawnConfig,
27        resume_retry_payload: Option<persistent_resume::QueuedRetryEntry>,
28    ) -> Result<(), String> {
29        let mut launch = self.start_child(&config, resume_retry_payload)?;
30        let pipes = self.take_pipes(&config, &mut launch)?;
31        let msg_rx = self.mark_running(&mut launch, pipes.kill_tx);
32        let registered = self.register_spawn(&config, &launch);
33        let sent_prompts = self.start_stdin_writer(&mut launch, pipes.stdin, msg_rx);
34        let stdout_task = self.spawn_stdout_reader(pipes.stdout, &config, &launch, &registered, sent_prompts);
35        self.spawn_status_heartbeat();
36        self.spawn_waiter(launch, pipes.kill_rx, pipes.stderr_reader_handle, stdout_task, &registered);
37
38        Ok(())
39    }
40}
41
42impl PersistentSubprocessController {
43    /// Hydrate the captured session id from the config when we don't have one yet (fresh controller after a
44    /// forced restart, e.g. a /model change, or the picker reattach path). Mirrors
45    /// `SubprocessController::hydrate_session_id_from_config` so the respawn resumes the same conversation
46    /// instead of starting blank.
47    pub(super) fn hydrate_session_id_from_config(&self, config: &PersistentSpawnConfig) {
48        if config.session_id.is_empty() {
49            return;
50        }
51        let mut inner = self.inner.lock().unwrap();
52        // Not a retired one (`Agents fresh`): a config prepared before the transition still names it.
53        if inner.session_id.is_none() && inner.resume_poisoned.as_deref() != Some(config.session_id.as_str()) {
54            inner.session_id = Some(config.session_id.clone());
55        }
56    }
57}
58
59impl PersistentSubprocessController {
60    /// A first spawn with no session id onto a pane that renders prior history continues that history's
61    /// session instead of pairing it with a blank model (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md
62    /// §1.1, §5 P0a). Returns the session the history belongs to when `--resume` can't reach it here, for
63    /// the resume gate to relocate. `inherited` is the parent session a fork inherited.
64    pub(super) fn continue_first_spawn_history(&self, config: &PersistentSpawnConfig, inherited: Option<&str>) -> Option<String> {
65        // First spawn with no id, onto a pane that renders prior history:
66        // continue that history's session instead of pairing it with a blank
67        // model (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §1.1, §5 P0a).
68        // A session live in another pane is left alone — adopting it would
69        // turn a plain open into the held-elsewhere refusal below.
70        let first_spawn_without_sid = {
71            let inner = self.inner.lock().unwrap();
72            inner.session_id.is_none() && inner.spawn_generation == 0
73        };
74        // The session the pane's history belongs to when `--resume` can't
75        // reach it here: the resume gate may relocate it (spec §4.3).
76        let mut unreachable_history_session: Option<String> = None;
77        // A fork's history is a copy of its parent's, ending in the parent's
78        // session; that session is continued as a fork (below), so its parent
79        // being live is no reason to start blank.
80        if first_spawn_without_sid {
81            if let Some(sid) = self.find_continuation_session_id(config) {
82                if inherited == Some(sid.as_str()) || self.session_held_elsewhere(&sid).is_none() {
83                    tracing::info!(
84                        block_id = %self.block_id,
85                        session_id = %sid,
86                        "continuity: first spawn has no session id; continuing the session this pane's history belongs to"
87                    );
88                    self.inner.lock().unwrap().session_id = Some(sid);
89                } else {
90                    tracing::info!(
91                        block_id = %self.block_id,
92                        session_id = %sid,
93                        "continuity: prior session is live in another pane; starting fresh"
94                    );
95                }
96            } else if !config.resume_flag.is_empty() {
97                unreachable_history_session = pane_history_session_id(
98                    self.filestore.as_deref(),
99                    self.mstore.as_deref(),
100                    &self.block_id,
101                    &config.session_id_field,
102                )
103                .filter(|sid| self.session_held_elsewhere(sid).is_none());
104            }
105        }
106        unreachable_history_session
107    }
108
109    /// The CLI's argv for this spawn, and the claims that go with it: `--resume <sid>` when there is a
110    /// session and the provider supports it, `--fork-session` when the spawn forks, the agent's memory
111    /// reconciled into its folder, and the per-session spawn lock held until the caller drops
112    /// [`ResumeSpawn::claim`] (once its `current_pid` is set). Refused when another live process holds the
113    /// session.
114    pub(super) fn resume_spawn(&self, config: &PersistentSpawnConfig) -> Result<ResumeSpawn, String> {
115        // Append `--resume <sid>` when we have a session id and the provider
116        // supports simple-flag resume — same construction as
117        // SubprocessController::spawn_turn. This is what makes a model/effort
118        // change (which respawns the persistent CLI with new flags) preserve the
119        // conversation. cli_args carries the runtime flags (model/effort/perm)
120        // already rebuilt by the frontend (useAgentCommands buildRuntimeArgs).
121        let mut spawn_args = config.cli_args.clone();
122        // Recorded so the stderr reader can tell "No conversation found" apart
123        // from an unrelated CLI error, and so it knows exactly which id to
124        // poison against the stdout reader's own capture (`stdout_reader.rs`) — a
125        // provider that echoes back whatever --resume it was given as its
126        // first stdout line, even when that id turns out to be unreachable.
127        let mut attempted_resume_sid: Option<String> = None;
128        // One session, one process. Resuming a session another live process
129        // is still running on — the agent's other pane, or one that is
130        // closing and hasn't exited yet — puts two CLIs on one transcript.
131        // Refuse instead: the user closes the other one (or waits the few
132        // seconds a close takes) and tries again. Covers every reopen path
133        // (picker reattach, a new agent's launch, MCP), not just `agent.open`
134        // (SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md §4.7).
135        // A spawn that forks reads the session and writes a new one, so a
136        // live process on it is no conflict: a fork started while its parent
137        // runs (the fork-isolation report in #4744, F5). `spawn_forks` says
138        // when; a quick fork from the picker was refused here while its
139        // parent ran, because only the gate's own marks counted.
140        let requested_sid = if config.resume_flag.is_empty() {
141            None
142        } else {
143            let inner = self.inner.lock().unwrap();
144            if spawn_forks(inner.fork_copy.is_some(), inner.fork_next, &config.cli_args) {
145                None
146            } else {
147                inner.session_id.clone()
148            }
149        };
150        // Check and claim must be one step: the check reads other
151        // controllers' `current_pid`, which a concurrent resume of the same
152        // session only sets further down this function. Held from here until
153        // this spawn's `current_pid` is set (or it returns early), so two
154        // reopens of one session — two picker clicks, picker + MCP — can't
155        // both pass. Keyed by session (reagent P1 on #3421): a fixed stripe
156        // of locks chosen by hashing the session id — every reopen of one
157        // session takes the same lock, unrelated agents' resume respawns
158        // almost never share one, and memory stays bounded (a per-session map
159        // would grow forever — reagent P2). Only resume spawns take one;
160        // `spawn_process` is synchronous, and no caller holds an `inner` lock
161        // across it.
162        // The agent's memory is in its folder before the provider reads it.
163        // Runs before the resume claim below, not under it: a pass can take
164        // up to its one-second budget, and that lock is meant to be held only
165        // briefly (reagent P1 on #3721). Not for a session already live in
166        // another pane — that spawn is about to be refused, and its pass
167        // would run beside the live provider writing the same folder. (A
168        // second pass for the agent at the same moment skips on its lease.)
169        if requested_sid.as_deref().is_none_or(|sid| self.session_held_elsewhere(sid).is_none()) {
170            self.reconcile_memory_before_spawn(config);
171        }
172        let resume_claim = requested_sid.as_deref().map(lock_resume_spawn);
173        if let Some(sid) = requested_sid.as_deref() {
174            if let Some((other, closing)) = self.session_held_elsewhere(sid) {
175                return Err(held_elsewhere_error(&other, closing));
176            }
177        }
178        // Set when the resume gate relocated the session this spawn resumes
179        // (spec §4.3): the copy it placed, which the fork reads and never
180        // writes.
181        let mut relocated_copy: Option<crate::backend::continuity_relocate::Relocated> = None;
182        // This spawn resumes with `--fork-session` (relocated, or the session
183        // grew outside AgentMux, spec §4.4).
184        let mut forked = false;
185        {
186            let mut inner = self.inner.lock().unwrap();
187            let fork_copy = inner.fork_copy.take();
188            let fork_next = std::mem::take(&mut inner.fork_next);
189            if let Some(sid) = inner.session_id.clone() {
190                if !config.resume_flag.is_empty() {
191                    spawn_args.push(config.resume_flag.clone());
192                    spawn_args.push(sid.clone());
193                    if spawn_forks(fork_copy.is_some(), fork_next, &config.cli_args) {
194                        // The launch's own args may carry it already (a fork
195                        // launched from the picker); once is enough.
196                        if !spawn_args.iter().any(|a| a == "--fork-session") {
197                            spawn_args.push("--fork-session".to_string());
198                        }
199                        relocated_copy = fork_copy.clone();
200                        forked = true;
201                    }
202                    attempted_resume_sid = Some(sid);
203                }
204            }
205            if relocated_copy.is_none() {
206                if let Some(copy) = fork_copy {
207                    crate::backend::continuity_relocate::remove(&copy);
208                }
209            }
210        }
211        Ok(ResumeSpawn { spawn_args, attempted_resume_sid, relocated_copy, forked, claim: resume_claim })
212    }
213
214    /// Install the new process as the controller's current one: bumps `spawn_generation`, clears the
215    /// per-spawn flags the previous process left, and feeds the resume state machine. Returns the new
216    /// generation and the effects of superseding a prior one, with the child handed back. Refused (and the
217    /// child killed) when a Stop cancelled a config restart's replacement while it was starting.
218    ///
219    /// The tentative resume-retry payload is stashed here, synchronously, before any background task
220    /// exists: a process that dies fast enough would otherwise let the process waiter take it while it is
221    /// still `None`, losing the retry for the very case it exists to catch (#2360). It is keyed on the exact
222    /// sid this spawn attempted, so `poison_resume`'s later confirmation is unambiguous.
223    pub(super) fn install_new_process(
224        &self,
225        mut child: tokio::process::Child,
226        config: &PersistentSpawnConfig,
227        attempted_resume_sid: &Option<String>,
228        resume_retry_payload: Option<persistent_resume::QueuedRetryEntry>,
229    ) -> Result<(tokio::process::Child, u64, Vec<persistent_resume::ResumeEffect>), String> {
230        let mut inner = self.inner.lock().unwrap();
231        // A config restart's replacement is installed only if no Stop has
232        // cancelled it, decided in this acquisition: before it, a Stop has
233        // no `kill_tx` to reach the child through (codex P1 on #3990).
234        if let Err(e) = Self::commit_restart_spawn_locked(&mut inner) {
235            drop(inner);
236            let _ = agentmux_common::process::start_kill_child_and_group(&mut child);
237            tokio::spawn(async move {
238                let _ = child.wait().await;
239            });
240            tracing::info!(
241                block_id = %self.block_id,
242                "config restart: a stop landed while the replacement was starting — killed it"
243            );
244            return Err(e);
245        }
246        // The replacement process is here, so the quiesce window is over —
247        // messages may take `DeliverDirect` against this new `stdin_tx`
248        // again. Cleared unconditionally rather than only when set: any
249        // spawn ends the window by definition, whatever opened it.
250        inner.restart_pending = false;
251        // Same for a stop request: it targeted the process this spawn
252        // replaces.
253        inner.stop_pending = false;
254        // …and for a config restart's pending replacement: this spawn is
255        // it (or supersedes it), so no exit handler may start another.
256        inner.config_restart_generation = None;
257        inner.restart_spawn_for = None;
258        // …and any deferred restart is moot now, for the same reason: this
259        // spawn read `cmd:args` fresh from block meta, so the new config is
260        // already applied and there is nothing left to restart FOR.
261        //
262        // This is what stops a leak (reagent P1 on PR #2858):
263        // `restart_when_idle` is consumed at the `is_result_frame` turn
264        // end, but a generation that dies abnormally instead — a user
265        // Stop/SIGINT, a crash, a permanently-failed turn resolving via
266        // `ProcessExited` + `PublishDone` — never reaches that branch. The
267        // stale `true` would then ride into an unrelated later generation
268        // and kill a healthy process at the end of some future turn.
269        // Clearing per-spawn scopes the flag to the generation that
270        // requested it, which is the only one it ever meant anything for.
271        inner.restart_when_idle = false;
272        inner.spawn_generation += 1;
273        crate::backend::mcp_rewrite::remember_workdir(&self.block_id, &config.working_dir);
274        // Requests parked for the user belong to the process that asked: a new process is not
275        // waiting on them. Left in place, an abandoned question would read the new turns as
276        // `waiting` (`Controller::awaiting_user_reply`).
277        super::input::forget_parked_requests(&mut inner);
278        // Any spawn consumes or invalidates an adopted leftover
279        // candidate — it only ever meant "for the very next spawn".
280        inner.leftover_resume_candidate = None;
281        let generation = inner.spawn_generation;
282        let effects = match (attempted_resume_sid.clone(), resume_retry_payload) {
283            (Some(sid), Some(retry_json)) => {
284                inner.apply_resume_event(persistent_resume::ResumeEvent::SpawnedWithResume {
285                    generation,
286                    attempted_sid: sid,
287                    retry: persistent_resume::RetryPayload { config: config.clone(), messages: vec![retry_json] },
288                })
289            }
290            // `--resume <sid>` WAS attempted, just with no message of
291            // our own to seed the retry batch with — the eager-resume
292            // path (issue #3463), which revives a session with nothing
293            // queued rather than in response to a message. codex P1 on
294            // PR #3513: routing this to `SpawnedFresh` below (the
295            // catch-all's original behavior) discarded `attempted_sid`
296            // entirely, leaving `NotTracking` in place for a spawn that
297            // in fact has an unconfirmed `--resume` in flight. If that
298            // resume turns out to be stale and a direct message arrives
299            // before the failure is detected, `MessageAppendedToRetryBatch`
300            // below has nothing to append it to and no retry ever fires
301            // when the doomed process exits — the message is silently
302            // lost. An empty `messages` starts the SAME `AwaitingOutcome`
303            // tracking a seeded resume gets; `MessageAppendedToRetryBatch`
304            // (`DeliverDirect`, below) is what fills it in as messages
305            // actually arrive. Never reachable before eager resume
306            // existed — every other caller either omits `--resume`
307            // entirely (`respawn_once_for_leftover_queue` clears
308            // `session_id` first) or always has a real payload
309            // (`BecomeSpawner`, `retry_after_resume_failure`).
310            (Some(sid), None) => {
311                inner.apply_resume_event(persistent_resume::ResumeEvent::SpawnedWithResume {
312                    generation,
313                    attempted_sid: sid,
314                    retry: persistent_resume::RetryPayload { config: config.clone(), messages: vec![] },
315                })
316            }
317            (None, _) => inner.apply_resume_event(persistent_resume::ResumeEvent::SpawnedFresh { generation }),
318        };
319        Ok((child, generation, effects))
320    }
321
322    /// This process is on the recorded model place: its first turn decides a model change waiting on it.
323    pub(super) fn arm_route_trial(&self) {
324        if let Some(mstore) = self.mstore.as_ref() {
325            crate::backend::model_gateway::trial::arm_for_block(mstore, &self.block_id);
326        }
327    }
328
329    /// This fresh spawn can supersede a prior generation still awaiting its outcome with a held error line
330    /// (`resolve_superseded_generation`, reachable via `respawn_once_for_leftover_queue`): flush it now,
331    /// outside the lock, like every other `ResumeEffect` call site, or the error disappears (#2368).
332    pub(super) fn flush_superseded_effects(&self, effects: Vec<persistent_resume::ResumeEffect>) {
333        for effect in effects {
334            match effect {
335                persistent_resume::ResumeEffect::FlushErrorLine(line)
336                | persistent_resume::ResumeEffect::PersistImmediately(line) => {
337                    self.flush_error_line_now(line);
338                }
339                other => {
340                    tracing::warn!(
341                        block_id = %self.block_id,
342                        effect = ?other,
343                        "unexpected ResumeEffect from a fresh spawn superseding a prior generation"
344                    );
345                }
346            }
347        }
348    }
349
350    /// Say, in the transcript and before any of this process's own output lands, that it starts with none
351    /// of the conversation the pane is about to display (`fresh_start_needs_disclosure` decides when).
352    /// Returns the continuation packet that rides on its first message when AgentMux's own record is
353    /// carried across.
354    pub(super) fn disclose_fresh_start(&self, attempted_resume_sid: &Option<String>, my_generation: u64, had_retry_payload: bool) -> Option<String> {
355        // This process starts with none of the conversation the pane is about
356        // to display — say so, in the transcript, before any of its own output
357        // lands. See `fresh_start_needs_disclosure` for why
358        // `persistent_resume`'s `SpawnedFresh` can't decide this itself.
359        //
360        // `attempted_sid` is empty: there was no id to attempt, which is the
361        // whole point. The frontend renders that as "—" rather than a blank
362        // (`DocumentRow.tsx`'s session-outcome body).
363        let mut continuation: Option<String> = None;
364        let fresh_onto_history = attempted_resume_sid.is_none() && self.has_prior_transcript();
365        // An `Agents fresh` start carries the agent's handoff alone: the packet
366        // tells the model to continue as if uninterrupted, the opposite of what
367        // it asked for. The old session stays searchable.
368        let by_choice = crate::backend::context_reading::take_fresh_by_choice(&self.block_id);
369        if fresh_onto_history && !by_choice {
370            // The provider can't give this process the conversation the pane
371            // shows, so AgentMux's own record rides on its first message
372            // (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.4). On any
373            // generation, not just the first: a resume the CLI rejected falls
374            // through to here within the same launch (§4.2, "fall through,
375            // don't fail"), and its retry needs the record as much as a
376            // first spawn does. The disclosure above stays first-spawn-only;
377            // the retry path emits its own.
378            continuation = self.carry_continuation();
379        }
380        // After the packet is built, so the disclosure can say whether this
381        // fresh session was given the record ("continued") or not.
382        // Also for a start the agent asked for (generation > 1): the pane's
383        // marker, its meter reset and the memory fallback follow from it.
384        if fresh_onto_history && (by_choice || fresh_start_needs_disclosure(attempted_resume_sid.as_deref(), my_generation)) {
385            tracing::info!(
386                block_id = %self.block_id,
387                continued = continuation.is_some(),
388                "spawned with no --resume while prior history exists — disclosing a fresh start"
389            );
390            // Idle when no message flows with this spawn (the same test as the
391            // turn-active check below).
392            // A start the agent asked for always has its handoff in flight.
393            let idle_start = !by_choice && !had_retry_payload && self.inner.lock().unwrap().pending_send_messages.is_empty();
394            self.emit_fresh_outcome_now(String::new(), continuation.is_some(), idle_start);
395        }
396        continuation
397    }
398
399    /// Auto-register with the muxbus reactive handler so inter-agent messages reach this persistent
400    /// (no-PTY) agent (#1470); delivery is routed through the controller-aware MessageSender. Returns the
401    /// nonce this spawn's exit handler cleans up by: its own, unless registration was skipped, in which case
402    /// whichever nonce is on record (#3084).
403    pub(super) fn register_with_muxbus(&self, agent_id_for_muxbus: &Option<String>, agent_uid_for_registry: &Option<String>, my_registration_nonce: u64) -> u64 {
404        // Defaults to this spawn's own nonce; overridden below if
405        // registration is skipped (reagent P1 on PR #3084 — see the `Err`
406        // arm just below for why `my_registration_nonce` alone is wrong
407        // once a skip is possible).
408        let mut exit_cleanup_nonce = my_registration_nonce;
409        if let Some(ref agent_id) = agent_id_for_muxbus {
410            // `_with_nonce` variants record this spawn's process-wide
411            // registration nonce so this exact spawn's exit-handler can
412            // compare-and-remove its own registrations instead of
413            // blindly wiping a fallback respawn's (or replacement
414            // controller's) fresh ones (issue #2363; codex P1 on PR
415            // #2500 for why not the controller-local generation).
416            // `try_register_agent_with_nonce`, not the plain
417            // `register_agent_with_nonce` — this spawn can be running on the
418            // same thread as an in-flight `inject_message` (the
419            // reactive-delivery fallback's synchronous respawn), and that
420            // call already holds this same handler's lock. The plain
421            // version would re-lock it on that thread and deadlock the
422            // reactive handler process-wide. See
423            // `ReactiveHandler::try_register_agent_with_nonce`'s doc comment
424            // and `docs/incident/INCIDENT_2026_09_07_BACKEND_UPTIME_TIMER_FROZEN.md`.
425            match crate::backend::reactive::get_global_handler()
426                .try_register_agent_full(
427                    agent_id,
428                    &self.block_id,
429                    Some(&self.tab_id),
430                    my_registration_nonce,
431                    // Also park `agent_id` (== AGENTMUX_AGENT_ID here) as the
432                    // block's STABLE name binding, kept when `input.rs`'s
433                    // Register-tail replaces the display binding with the
434                    // live display name on this agent's very first turn —
435                    // otherwise nothing would be left to answer a jekt
436                    // tagged with the stable ID. See
437                    // `INCIDENT_2026_09_09_JEKT_STABLE_ID_ALIAS.md`.
438                    Some(agent_id.as_str()),
439                    // Identity M2: the key. Carried from the env, never
440                    // looked up here — nothing new is read under the
441                    // handler's lock (spec §4.4.4 Q5).
442                    agent_uid_for_registry.as_deref(),
443                    "registration.no_uid.spawn",
444                )
445            {
446                Ok(()) => {
447                    tracing::info!(
448                        block_id = %self.block_id,
449                        agent_id = %agent_id,
450                        "muxbus: auto-registered persistent agent"
451                    );
452                    mirror_registration_to_files(agent_id, &self.block_id, my_registration_nonce);
453                }
454                Err(e) => {
455                    tracing::warn!(
456                        block_id = %self.block_id,
457                        agent_id = %agent_id,
458                        error = %e,
459                        "muxbus: persistent auto-register failed"
460                    );
461                    // reagent P1 on PR #3084: registration was skipped, so
462                    // `my_registration_nonce` was never written to the
463                    // handler. Using it as this spawn's exit-time cleanup
464                    // key would always mismatch whatever nonce IS on
465                    // record, making the exit-handler wrongly conclude "a
466                    // newer respawn already took over" and skip BOTH the
467                    // reactive-handler unregister and the cloud_subscriber
468                    // deregister — leaking both on every skip. Target
469                    // whichever nonce is actually on record instead, so
470                    // this spawn's own eventual exit can still correctly
471                    // clean it up. `registration_nonce == 0` (no nonce on
472                    // record at all) is handled safely by
473                    // `unregister_block_if_nonce` itself — it never
474                    // matches, so this degrades to today's no-cleanup
475                    // behavior rather than a wrong one.
476                    //
477                    // `try_get_agent_by_block`, NOT the plain
478                    // `get_agent_by_block` — this Err arm is reached
479                    // precisely when we might be on the same thread as an
480                    // in-flight `inject_message` (reagent P0 on PR #3084,
481                    // caught after the first attempt used the blocking
482                    // version here and reproduced INCIDENT_2026_09_07's
483                    // exact deadlock). In that reentrant case this
484                    // correctly returns `None` after its own retry budget
485                    // instead of hanging forever; `exit_cleanup_nonce`
486                    // then simply stays at its default, same safe
487                    // no-cleanup degradation as before this fix existed.
488                    if let Some(current) = nonce_on_record(&self.block_id) {
489                        exit_cleanup_nonce = current;
490                    }
491                }
492            }
493        }
494        exit_cleanup_nonce
495    }
496
497    /// The task that writes messages to the CLI's stdin, one JSON line each. Only the first user message
498    /// carries the continuation packet; the pane's record keeps it as typed. A closed channel or a write
499    /// error ends the task, dropping stdin so the process gets EOF.
500    pub(super) fn spawn_stdin_writer(
501        stdin: tokio::process::ChildStdin,
502        mut msg_rx: mpsc::Receiver<String>,
503        continuation: Option<String>,
504        sent_prompts_write: crate::backend::cli_native::sent::SentPrompts,
505    ) {
506        tokio::spawn(async move {
507            let mut stdin = stdin;
508            let mut continuation = continuation;
509            while let Some(msg) = msg_rx.recv().await {
510                // Only this write carries the packet; the pane's record keeps
511                // the message as typed. Control responses pass through.
512                let msg = match continuation
513                    .as_deref()
514                    .and_then(|packet| crate::backend::continuity::prefix_user_message(&msg, packet))
515                {
516                    Some(with_packet) => {
517                        continuation = None;
518                        with_packet
519                    }
520                    None => msg,
521                };
522                let msg = sent_prompts_write.tag(&msg);
523                if let Err(e) = stdin.write_all(msg.as_bytes()).await {
524                    tracing::warn!("persistent stdin write error: {}", e);
525                    break;
526                }
527                if let Err(e) = stdin.write_all(b"\n").await {
528                    tracing::warn!("persistent stdin newline error: {}", e);
529                    break;
530                }
531                if let Err(e) = stdin.flush().await {
532                    tracing::warn!("persistent stdin flush error: {}", e);
533                    break;
534                }
535            }
536            // Channel closed or write error → stdin drops → process gets EOF
537            drop(stdin);
538        });
539    }
540}
541
542/// What `resume_spawn` decides for one spawn.
543pub(super) struct ResumeSpawn {
544    pub(super) spawn_args: Vec<String>,
545    /// The session this spawn resumes (or forks), if any; the stderr and stdout readers poison it when the
546    /// CLI rejects it.
547    pub(super) attempted_resume_sid: Option<String>,
548    /// A relocated resume's copy, removed once the fork reports its id.
549    pub(super) relocated_copy: Option<crate::backend::continuity_relocate::Relocated>,
550    /// This spawn resumes with `--fork-session`.
551    pub(super) forked: bool,
552    /// The per-session spawn lock: held until this spawn's `current_pid` is set, so two reopens of one
553    /// session can't both pass the duplicate-session check.
554    pub(super) claim: Option<std::sync::MutexGuard<'static, ()>>,
555}
556
557/// The spawn lock for one session. A stripe of locks chosen by hashing the session id: every reopen of one
558/// session takes the same lock, unrelated agents' resume respawns almost never share one, and memory stays
559/// bounded (a per-session map would grow forever). Only resume spawns take one; `spawn_process` is
560/// synchronous, and no caller holds an `inner` lock across it.
561fn lock_resume_spawn(sid: &str) -> std::sync::MutexGuard<'static, ()> {
562    const STRIPES: usize = 64;
563    static RESUME_SPAWN_LOCKS: [Mutex<()>; STRIPES] = [const { Mutex::new(()) }; STRIPES];
564    let stripe = {
565        use std::hash::{Hash, Hasher};
566        let mut h = std::collections::hash_map::DefaultHasher::new();
567        sid.hash(&mut h);
568        (h.finish() as usize) % STRIPES
569    };
570    RESUME_SPAWN_LOCKS[stripe].lock().unwrap_or_else(|e| e.into_inner())
571}
572
573/// The registration nonce on record for a block, `None` when there is none or the handler is busy.
574/// `try_get_agent_by_block`, NOT the plain `get_agent_by_block`: this runs when registration was skipped,
575/// which is exactly when we might be on the same thread as an in-flight `inject_message`, and the blocking
576/// version reproduced INCIDENT_2026_09_07's deadlock (#3084). In that reentrant case it returns `None` after
577/// its own retry budget instead of hanging.
578fn nonce_on_record(block_id: &str) -> Option<u64> {
579    crate::backend::reactive::get_global_handler().try_get_agent_by_block(block_id).map(|current| current.registration_nonce)
580}
581
582/// Write the registration to the cross-instance (Tier-2) file registry and its host-global sibling (Tier
583/// 2b, #1916): the auto-register path bypasses the HTTP register handler, which does this for the others.
584fn mirror_registration_to_files(agent_id: &str, block_id: &str, my_registration_nonce: u64) {
585    let Ok(local_url) = std::env::var("AGENTMUX_LOCAL_URL") else { return };
586    let data_dir = crate::backend::base::get_mux_data_dir();
587    crate::backend::reactive::registry::write_with_nonce(&data_dir, agent_id, &local_url, block_id, my_registration_nonce);
588    crate::backend::reactive::registry::write_shared_from_env_with_nonce(agent_id, &local_url, block_id, my_registration_nonce);
589}