Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
mod.rs

1// Copyright 2025, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! SubprocessController: manages agent CLI as stateless per-turn subprocess invocations.
5//!
6//! Architecture:
7//!   Each user message spawns a fresh `claude -p` process.
8//!   Multi-turn continuity uses `--resume <session-id>`.
9//!   The process reads one JSON message from stdin, runs the agentic loop,
10//!   streams NDJSON on stdout, then exits.
11//!
12//! State machine:
13//!   INIT ─(spawn)─> RUNNING ─(process exits)─> DONE
14//!   DONE ─(new message)─> RUNNING (re-spawn with --resume)
15//!
16//! I/O model (2 async tasks per turn):
17//! 1. stdout_reader: piped stdout → .jsonl persistence + MPS blockfile events on "output" subject
18//! 2. process_waiter: wait for exit, update status, publish lifecycle event
19//!
20//! ## Module layout
21//!
22//! This module was split from a single ~1770-line `subprocess` file into a
23//! directory so each piece of the (large) turn state machines could live in
24//! its own file:
25//!   - `mod.rs` (this file): spawn config, inner state, controller struct +
26//!     bookkeeping (`new`/lock helpers/status snapshot/publish), and
27//!     `impl Controller for SubprocessController`.
28//!   - `session`: session-id capture/hydration state machine.
29//!   - `host_spawn`: `spawn_turn` — host-subprocess turn via `std::process`,
30//!     in named phases.
31//!   - `container_spawn`: `spawn_container_turn` — Docker-exec turn via
32//!     `bollard`, plus its `publish_line` output helper.
33//!   - `tests` (cfg(test)): unit tests, mostly session-id focused.
34//!   - `turn_tests` (cfg(test)): what a host turn does, with a stub CLI.
35//!
36//! `host_spawn` and `container_spawn` are `impl SubprocessController` blocks
37//! in their own files — Rust allows multiple `impl <Type>` blocks across
38//! files/modules for the same type. `spawn_container_turn` takes a request in its
39//! file and runs the accepted turn through the steps in `container_spawn_steps`.
40
41use std::collections::{HashMap, VecDeque};
42use std::sync::atomic::{AtomicBool, Ordering};
43use std::sync::{Arc, Mutex};
44
45use super::health::TurnActivityTracker;
46use crate::backend::message_origin::RecordOrigin;
47use super::{BlockControllerRuntimeStatus, BlockInputUnion, Controller, STATUS_INIT};
48use crate::backend::eventbus::EventBus;
49use crate::backend::storage::filestore::FileStore;
50use crate::backend::storage::store::Store;
51use crate::backend::mps;
52
53// `pub(crate)` (not private): `argv::build_side_question_argv` is reused by
54// the `/btw` side-question turn builder in
55// `server/agent_handlers/side_question.rs`, outside this module. Every
56// other item in `argv` keeps its own narrower visibility.
57pub mod argv;
58pub mod codex_compact;
59pub mod codex_context;
60pub mod codex_usage;
61pub mod codex_mcp;
62pub mod codex_fresh;
63pub mod gemini_mcp;
64pub mod container_spawn;
65mod first_turn_hold;
66pub mod host_spawn;
67pub(crate) mod replace;
68pub use replace::forget_left_for_replacement;
69pub mod session;
70#[cfg(test)]
71mod tests;
72#[cfg(test)]
73mod turn_tests;
74
75/// MPS file subject name for subprocess output (replaces "term" from PTY).
76pub const SUBPROCESS_OUTPUT_SUBJECT: &str = "output";
77
78pub const BLOCK_CONTROLLER_SUBPROCESS: &str = "subprocess";
79
80/// Configuration for spawning a subprocess turn.
81#[derive(Debug, Clone, Default)]
82pub struct SubprocessSpawnConfig {
83    /// CLI executable (e.g., "claude").
84    pub cli_command: String,
85    /// CLI arguments (e.g., ["-p", "--output-format", "stream-json", ...]).
86    pub cli_args: Vec<String>,
87    /// Working directory for the subprocess.
88    pub working_dir: String,
89    /// Environment variables to set.
90    pub env_vars: HashMap<String, String>,
91    /// The user's JSON message to write to stdin.
92    pub message: String,
93    /// Flag used to resume a previous session, e.g. "--resume" (Claude), "-r" (Gemini).
94    /// Empty string means this provider does not support simple-flag resume.
95    pub resume_flag: String,
96    /// Resume argv strategy: `none`, `flag`, or `codex-exec`.
97    /// Empty preserves compatibility with blocks created before this metadata
98    /// existed by inferring `flag` from a non-empty `resume_flag`.
99    pub resume_strategy: String,
100    /// When non-empty, the flag that passes the prompt as an argument
101    /// (`<cli> -p <prompt>`) instead of on stdin; stdin then gets nothing.
102    /// From `agent:prompt_arg_flag`, see `ProviderConfig::prompt_arg_flag`.
103    pub prompt_arg_flag: String,
104    /// JSON field name in the CLI's init event that contains the session/thread ID.
105    /// e.g. "session_id" (Claude/Gemini) or "thread_id" (Codex).
106    pub session_id_field: String,
107    /// Optional client-supplied message id. Echoed back via the
108    /// `agent-message-accepted` event when this config transitions from
109    /// queued → running so the frontend can pair the event with a
110    /// pending `PendingMessage`. None means no feedback is emitted.
111    pub message_id: Option<String>,
112    /// Session id to hydrate `inner.session_id` with BEFORE the first
113    /// turn — used by the picker "My Agents" reattach path. The
114    /// caller reads this from `block.meta["agent:sessionid"]` which
115    /// the frontend pre-populates from the prior block's session id
116    /// when launching with `continueOfInstanceId`. Without this
117    /// hydration `spawn_turn` would only see the captured session id
118    /// AFTER the first turn — meaning the first turn always launches
119    /// the CLI fresh (no `--resume <sid>`) and starts a new
120    /// conversation that re-injects the startup context.
121    ///
122    /// Empty / `None` means "no prior session" (greenfield launch).
123    ///
124    /// Best-effort, not authoritative: if the hydrated id is stale,
125    /// the CLI's stdout-emitted session id always overwrites it at
126    /// capture time (see `spawn_turn`'s stdout-reader block). The
127    /// reattach turn passes the (possibly stale) hydrated id via
128    /// `--resume`; the CLI either accepts it or starts a new
129    /// session and emits its own id, which then becomes the in-
130    /// memory authority for every subsequent turn.
131    pub session_id: Option<String>,
132    /// The registry's `instance_id` (`block.meta["agentId"]`) for this
133    /// agent — the cross-process session-lease key (see
134    /// `registry::LeaseStore`; NOT `session_id` above, which can be
135    /// `None` on a greenfield first turn). Empty string disables
136    /// leasing for this spawn (e.g. the container-mode branch in this
137    /// PR — see `host_spawn::spawn_turn`'s own doc comment).
138    pub instance_id: String,
139    /// Where `message` came from and the notes that went with it, for the
140    /// record of it ([`UserRecordSink`]). `None` stores it with no origin: a
141    /// reader then takes it as untyped, never as the human.
142    pub record: Option<crate::backend::message_origin::RecordOrigin>,
143}
144
145/// Whether this turn is AgentMux's own `/compact` of a Claude agent: the one the agent asked for with `Agents compact` or
146/// the srv backstop sent (both are system turns). A person's own `/compact` is an ordinary message.
147pub(super) fn is_agentmux_compaction(config: &SubprocessSpawnConfig) -> bool {
148    let message = config.message.trim();
149    let is_compact = message == "/compact" || message.strip_prefix("/compact").is_some_and(|rest| rest.starts_with(char::is_whitespace));
150    is_compact
151        && config.resume_strategy != "codex-exec"
152        && config.record.as_ref().is_some_and(|r| r.origin.kind == crate::backend::blockcontroller::health::TriggerKind::System)
153}
154
155/// Where a message waiting for the running turn goes in the queue, and whether that is ahead of messages already
156/// waiting. A compaction runs next: the context it shrinks only grows while the messages ahead of it run, so it goes
157/// behind the compactions already waiting (their order is kept) and in front of everything else. Any other message
158/// goes to the back, in the order it was sent.
159fn queue_position(queue: &VecDeque<SubprocessSpawnConfig>, config: &SubprocessSpawnConfig) -> (usize, bool) {
160    if !is_agentmux_compaction(config) {
161        return (queue.len(), false);
162    }
163    let waiting = queue.iter().take_while(|queued| is_agentmux_compaction(queued)).count();
164    (waiting, waiting < queue.len())
165}
166
167/// Inner state protected by mutex.
168struct SubprocessControllerInner {
169    /// Current process status.
170    proc_status: String,
171    /// Process exit code from the most recent turn.
172    proc_exit_code: i32,
173    /// Status version counter (incremented on each change).
174    status_version: i32,
175    /// Session ID captured from the first `system/init` message.
176    session_id: Option<String>,
177    /// PID of the currently running subprocess (None if idle).
178    current_pid: Option<u32>,
179    /// Handle to kill the current subprocess.
180    kill_tx: Option<tokio::sync::oneshot::Sender<bool>>,
181    /// Messages queued while a turn is in progress.
182    /// Drained sequentially after the current turn exits.
183    pending_messages: VecDeque<SubprocessSpawnConfig>,
184    /// Messages that were queued behind a turn when the agent was stopped. A stop stays a stop: they
185    /// do not run on their own (which would start the agent again and flip it back to wanted
186    /// running); the next turn that is accepted queues them right behind itself, in the order they were sent.
187    held_after_stop: VecDeque<SubprocessSpawnConfig>,
188    /// Messages that were queued behind a turn when `stop_for_replace` ended it: the replacement runs them
189    /// (see `replace.rs`).
190    queued_for_replacement: VecDeque<SubprocessSpawnConfig>,
191    /// Session ids the agent ended on purpose (`Agents fresh`, `codex_fresh`):
192    /// a queued message or a stale `agent:sessionid` that still names one must
193    /// not resume it.
194    retired_sessions: Vec<String>,
195    /// A fresh container agent waiting for its Session Context block before its first turn (first_turn_hold.rs).
196    session_context_gate: first_turn_hold::SessionContextGate,
197}
198
199/// SubprocessController manages per-turn subprocess lifecycle for agent blocks.
200///
201/// Unlike `ShellController` which maintains a long-running PTY process,
202/// `SubprocessController` spawns a fresh process for each user turn.
203/// Multi-turn continuity comes from `--resume <session-id>`.
204pub struct SubprocessController {
205    #[allow(dead_code)]
206    tab_id: String,
207    block_id: String,
208    /// Prevents concurrent spawns.
209    run_lock: Arc<AtomicBool>,
210    /// Protected inner state.
211    inner: Arc<Mutex<SubprocessControllerInner>>,
212    /// MPS broker for publishing events (blockfile, controllerstatus).
213    broker: Option<Arc<mps::Broker>>,
214    /// Event bus for obj:update broadcasts.
215    event_bus: Option<Arc<EventBus>>,
216    /// AgentMux object store for block metadata persistence.
217    mstore: Option<Arc<Store>>,
218    /// FileStore for write-through persistence of output lines (Phase 1.3).
219    filestore: Option<Arc<FileStore>>,
220    /// Per-block turn-activity tracker.
221    health_monitor: Arc<TurnActivityTracker>,
222    /// Weak self-reference for queue drain. Set by `set_self_ref` after
223    /// the controller is wrapped in Arc.
224    self_ref: Mutex<Option<std::sync::Weak<Self>>>,
225    /// Cross-process session-ownership lease store. `None` when the
226    /// shared registry can't be resolved (CI / unusual envs) — leasing
227    /// degrades to a no-op in that case, same convention as
228    /// `shared_agent_registry()` elsewhere. See
229    /// `docs/retro/RETRO_DEV_BUILD_SHARED_AGENT_SESSION_COLLISION_2026_07_29.md`.
230    lease_store: Option<Arc<crate::registry::LeaseStore>>,
231    /// This process's boot id — the lease owner id. See `AppState::boot_id`.
232    boot_id: Arc<str>,
233    /// Container agents: what a turn does before its `docker exec` (start the
234    /// container, install the CLI). Set by the handler that accepts a message,
235    /// run at the start of the turn's own task, so it is not cut short with the
236    /// request. `None` for a host agent.
237    container_startup: Mutex<Option<StartupStep>>,
238    /// How the last accepted message was launched (host process or container exec), so a replacement can launch
239    /// what the replaced controller had queued the same way.
240    adapter: Mutex<Option<Arc<dyn crate::backend::runtime_adapter::RuntimeAdapter>>>,
241    /// The replaced controller's run lock, until the replacement has waited for its killed turn to exit.
242    left_old_run_lock: Mutex<Option<Arc<AtomicBool>>>,
243    /// The container, and the command, the last container turn ran with (replace.rs).
244    container_context: Mutex<Option<replace::ContainerContext>>,
245}
246
247/// A container turn's first step: ready the container. `Err` carries the text
248/// the pane has already been shown; the turn ends without running.
249pub type StartupStep =
250    Arc<dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>> + Send + Sync>;
251
252impl SubprocessController {
253    /// Create a new SubprocessController.
254    ///
255    /// `registry`/`boot_id` back the cross-process session-ownership
256    /// lease (see `lease_store` field doc). Passing `registry: None`
257    /// (or a registry whose root can't be opened as a `LeaseStore`,
258    /// which is logged and degrades the same way) disables leasing
259    /// for every turn this controller spawns — used by test call
260    /// sites that don't need a real registry.
261    pub fn new(
262        tab_id: String,
263        block_id: String,
264        broker: Option<Arc<mps::Broker>>,
265        event_bus: Option<Arc<EventBus>>,
266        mstore: Option<Arc<Store>>,
267        filestore: Option<Arc<FileStore>>,
268        registry: Option<Arc<crate::registry::Registry>>,
269        boot_id: Arc<str>,
270    ) -> Self {
271        let health_monitor = Arc::new(TurnActivityTracker::for_block(block_id.clone(), broker.as_ref()));
272        let lease_store = registry.and_then(|r| {
273            crate::registry::LeaseStore::open(r.root())
274                .map(Arc::new)
275                .map_err(|e| {
276                    tracing::warn!(
277                        block_id = %block_id,
278                        error = %e,
279                        "subprocess controller: failed to open lease store — leasing disabled for this controller"
280                    );
281                })
282                .ok()
283        });
284        let left = replace::take_left_for_replacement(&block_id);
285        let (held, queued, session_id, adapter, old_run_lock, container) = match left {
286            Some(l) => (l.held, l.queued, l.session_id, l.adapter, l.old_run_lock, l.container),
287            None => Default::default(),
288        };
289        Self {
290            tab_id,
291            block_id,
292            run_lock: Arc::new(AtomicBool::new(false)),
293            container_startup: Mutex::new(None),
294            adapter: Mutex::new(adapter),
295            left_old_run_lock: Mutex::new(old_run_lock),
296            container_context: Mutex::new(container),
297            inner: Arc::new(Mutex::new(SubprocessControllerInner {
298                proc_status: STATUS_INIT.to_string(),
299                proc_exit_code: 0,
300                status_version: 0,
301                session_id,
302                current_pid: None,
303                kill_tx: None,
304                pending_messages: queued,
305                held_after_stop: held,
306                queued_for_replacement: VecDeque::new(),
307                retired_sessions: Vec::new(),
308                session_context_gate: Default::default(),
309            })),
310            broker,
311            event_bus,
312            mstore,
313            filestore,
314            health_monitor,
315            self_ref: Mutex::new(None),
316            lease_store,
317            boot_id,
318        }
319    }
320
321    /// Store a weak self-reference so the process_waiter can drain queued
322    /// messages by calling spawn_turn after the current turn exits.
323    /// Must be called after wrapping in Arc.
324    pub fn set_self_ref(self: &Arc<Self>) {
325        *self.self_ref.lock().unwrap() = Some(Arc::downgrade(self));
326    }
327
328    /// Try to acquire the run lock. Returns false if a turn is already in progress.
329    fn try_lock_run(&self) -> bool {
330        self.run_lock
331            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
332            .is_ok()
333    }
334
335    /// Release the run lock.
336    fn unlock_run(&self) {
337        self.run_lock.store(false, Ordering::SeqCst);
338    }
339
340    /// Update process status and increment version (must hold inner lock).
341    fn set_status(inner: &mut SubprocessControllerInner, status: &str) {
342        inner.proc_status = status.to_string();
343        inner.status_version += 1;
344    }
345
346    /// Build a `BlockControllerRuntimeStatus` snapshot from inner state.
347    ///
348    /// Factored out of 4+ verbatim-duplicated struct literals (one here, one
349    /// in `host_spawn`'s process_waiter, two in `container_spawn`'s
350    /// running/done/failure transitions) — an audit finding from the
351    /// modularization pass. `turn_active` is passed explicitly because call
352    /// sites disagree on its value: `get_status_snapshot` reads the live
353    /// health-monitor flag, while every turn-completion / exec-failure site
354    /// always publishes `false` (the turn is over by construction at that
355    /// point).
356    fn build_status_snapshot(
357        inner: &SubprocessControllerInner,
358        block_id: &str,
359        turn_active: bool,
360    ) -> BlockControllerRuntimeStatus {
361        BlockControllerRuntimeStatus {
362            durable: false,
363            blockid: block_id.to_string(),
364            version: inner.status_version,
365            shellprocstatus: inner.proc_status.clone(),
366            shellprocconnname: "local".to_string(),
367            shellprocexitcode: inner.proc_exit_code,
368            shellprocpid: None,
369            shellprocname: String::new(),
370            spawn_ts_ms: None,
371            is_agent_pane: false,
372            turn_active,
373        }
374    }
375
376    /// Get the runtime status (snapshot).
377    fn get_status_snapshot(&self) -> BlockControllerRuntimeStatus {
378        let inner = self.inner.lock().unwrap();
379        Self::build_status_snapshot(&inner, &self.block_id, self.health_monitor.is_active_turn())
380    }
381
382    /// Publish current controller status via the MPS broker.
383    fn publish_status(&self) {
384        if let Some(ref broker) = self.broker {
385            let status = self.get_status_snapshot();
386            super::publish_controller_status(broker, &status);
387        }
388    }
389
390    /// Emit `agent-message-accepted` for the given config, if it carries
391    /// a `message_id`. Called from `spawn_turn` / `spawn_container_turn`;
392    /// a queued message gets here too, when the process-waiter task's drain
393    /// calls that same spawn function for it. No-op if the config
394    /// has no id, or the broker isn't configured.
395    fn emit_message_accepted(&self, config: &SubprocessSpawnConfig) {
396        let Some(id) = config.message_id.as_deref() else { return };
397        let Some(ref broker) = self.broker else { return };
398        super::publish_message_accepted(broker, &self.block_id, id);
399        tracing::info!(
400            block_id = %self.block_id,
401            message_id = %id,
402            "emitted agent-message-accepted"
403        );
404    }
405
406    /// Queue `config` behind the running process, and tell the pane what it waits for (`what` names the path in
407    /// the log).
408    fn queue_behind_running_process(&self, config: SubprocessSpawnConfig, what: &str) {
409        let (message_id, ahead) = {
410            let mut inner = self.inner.lock().unwrap();
411            self.insert_queued(&mut inner, config, what)
412        };
413        self.emit_message_queued(message_id.as_deref(), ahead);
414    }
415
416    /// Put `config` in the queue, under the lock the caller already holds: where it went (`ahead` messages in front of
417    /// it) and its message id, for the notice [`Self::emit_message_queued`] sends once the lock is released.
418    fn insert_queued(&self, inner: &mut SubprocessControllerInner, config: SubprocessSpawnConfig, what: &str) -> (Option<String>, usize) {
419        let message_id = config.message_id.clone();
420        let (ahead, jumped) = queue_position(&inner.pending_messages, &config);
421        tracing::info!(block_id = %self.block_id, queue_depth = inner.pending_messages.len() + 1, jumped, "{what} — message queued");
422        inner.pending_messages.insert(ahead, config);
423        (message_id, ahead)
424    }
425
426    /// Emit `agent-message-queued` for a message that has to wait for the running process, if it carries a
427    /// `message_id`: the pane says what it waits for and how many are ahead of it. `ahead` is the number of messages
428    /// already queued in front of it.
429    fn emit_message_queued(&self, message_id: Option<&str>, ahead: usize) {
430        let Some(id) = message_id else { return };
431        let Some(ref broker) = self.broker else { return };
432        super::publish_message_queued(broker, &self.block_id, id, ahead);
433    }
434
435    /// A handle that writes the user's message to the transcript — see
436    /// [`UserRecordSink`]. Cloned out so the delivery paths (the stdin writer
437    /// thread, the container exec task) can write it once the prompt has
438    /// actually reached the CLI.
439    ///
440    /// `shown_by_pane`: the pane typed this message and already shows it (the
441    /// turn carries the pane's `message_id`). A message from anywhere else (a
442    /// jekt, a broadcast, a schedule, the app API) is not on screen, so its
443    /// record is published for the pane to show.
444    pub(super) fn user_record_sink(&self, shown_by_pane: bool, record: Option<RecordOrigin>) -> UserRecordSink {
445        UserRecordSink {
446            shown_by_pane,
447            record,
448            broker: self.broker.clone(),
449            block_id: self.block_id.clone(),
450            filestore: self.filestore.clone(),
451            mstore: self.mstore.clone(),
452        }
453    }
454
455    /// Get the stored session ID (if any).
456    #[allow(dead_code)]
457    pub fn session_id(&self) -> Option<String> {
458        self.inner.lock().unwrap().session_id.clone()
459    }
460
461    /// Whether a turn is running (or being started): a message sent now is queued behind it.
462    pub fn turn_in_flight(&self) -> bool {
463        self.run_lock.load(Ordering::SeqCst)
464    }
465
466    /// Move the messages queued behind the running turn to the held list (see
467    /// `SubprocessControllerInner::held_after_stop`).
468    fn hold_queue_for_stop(&self) {
469        let mut inner = self.inner.lock().unwrap();
470        if inner.pending_messages.is_empty() {
471            return;
472        }
473        tracing::info!(
474            block_id = %self.block_id,
475            held = inner.pending_messages.len(),
476            "agent stopped: messages queued behind its turn are held, not run"
477        );
478        let queued = std::mem::take(&mut inner.pending_messages);
479        inner.held_after_stop.extend(queued);
480    }
481
482    /// [`Self::try_lock_run`] for a turn that is about to start: once it holds the lock, the messages a stop held
483    /// are queued behind it (see [`Self::release_held_behind_this_turn`]).
484    fn take_run_lock_for_turn(&self) -> bool {
485        let locked = self.try_lock_run();
486        if locked {
487            self.release_held_behind_this_turn();
488        }
489        locked
490    }
491
492    /// A turn has been accepted: the messages a stop held go to the front of the queue, so they run
493    /// right after it, in the order they were sent. They are in the ordinary queue from here, so a turn
494    /// that fails to start does not lose them.
495    fn release_held_behind_this_turn(&self) {
496        let mut inner = self.inner.lock().unwrap();
497        while let Some(held) = inner.held_after_stop.pop_back() {
498            inner.pending_messages.push_front(held);
499        }
500    }
501
502    /// Stop the currently running subprocess.
503    pub fn stop_subprocess(&self, force: bool) -> Result<(), String> {
504        let kill_tx = {
505            let mut inner = self.inner.lock().unwrap();
506            let kill_tx = inner.kill_tx.take();
507            // No process to kill yet: a message that waits for the Session Context block is what the interrupt is for.
508            if kill_tx.is_none() {
509                first_turn_hold::cancel_wait(&mut inner, &self.block_id);
510            }
511            kill_tx
512        };
513        match kill_tx {
514            Some(tx) => {
515                let _ = tx.send(force);
516                Ok(())
517            }
518            None => Ok(()), // No running process
519        }
520    }
521}
522
523impl Controller for SubprocessController {
524    fn start(
525        &self,
526        _block_meta: super::super::obj::MetaMapType,
527        _rt_opts: Option<serde_json::Value>,
528        _force: bool,
529    ) -> Result<(), String> {
530        // SubprocessController doesn't auto-start on resync.
531        // Turns are initiated by SubprocessSpawnCommand / AgentInputCommand.
532        tracing::info!(
533            block_id = %self.block_id,
534            "subprocess controller registered (no auto-start)"
535        );
536        Ok(())
537    }
538
539    fn stop(&self, _graceful: bool, new_status: &str) -> Result<(), String> {
540        // A stop keeps what was queued behind the turn it ends: taken before the kill, so the
541        // process-waiter's drain finds nothing to run.
542        self.hold_queue_for_stop();
543        // Stop any running subprocess
544        self.stop_subprocess(true)?;
545
546        let mut inner = self.inner.lock().unwrap();
547        if inner.proc_status != new_status {
548            Self::set_status(&mut inner, new_status);
549        }
550
551        Ok(())
552    }
553
554    /// A replace is not a user's stop: what was queued behind the turn goes to the replacement to run, not into
555    /// `held_after_stop` (replace.rs).
556    fn stop_for_replace(&self, new_status: &str) -> Result<(), String> {
557        self.stop_keeping_queue_for_replacement(new_status)
558    }
559
560    fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
561        self.get_status_snapshot()
562    }
563
564    fn send_input(&self, input: BlockInputUnion, _seq: Option<u64>) -> Result<(), String> {
565        // SubprocessController doesn't accept raw PTY input — user messages
566        // go through spawn_turn() (via AgentInputCommand RPC).
567        //
568        // Signals ARE accepted though: the agent-pane composer's Esc
569        // handler sends SIGINT via `ControllerInputCommand({signame:"SIGINT"})`
570        // when the user wants to cancel an in-flight turn. Route that to
571        // `stop_subprocess(force=true)` so the current subprocess is
572        // killed via `kill_tx`. Without this, Esc was silently rejected
573        // and the agent kept running.
574        if let Some(sig) = input.sig_name.as_deref() {
575            if sig == "SIGINT" || sig == "SIGTERM" {
576                tracing::info!(
577                    block_id = %self.block_id,
578                    sig = %sig,
579                    "subprocess controller: received signal, killing current turn"
580                );
581                return self.stop_subprocess(true);
582            }
583            return Err(format!(
584                "subprocess controller: unsupported signal {sig} (only SIGINT/SIGTERM)"
585            ));
586        }
587        if input.input_data.is_some() {
588            return Err("subprocess controller does not accept raw input; use AgentInputCommand".to_string());
589        }
590        // Term resize / other input types: accepted-no-op.
591        Ok(())
592    }
593
594    fn turn_tracker(&self) -> Option<Arc<TurnActivityTracker>> {
595        Some(Arc::clone(&self.health_monitor))
596    }
597
598    fn controller_type(&self) -> &str {
599        BLOCK_CONTROLLER_SUBPROCESS
600    }
601
602    fn block_id(&self) -> &str {
603        &self.block_id
604    }
605
606    fn as_any(&self) -> &dyn std::any::Any {
607        self
608    }
609}
610
611/// Output formats whose CLI never writes the user's prompt into its own
612/// output, so the transcript would otherwise hold no record of it. Gemini's
613/// CLI echoes the prompt itself (rendered since #3620) — a second record would
614/// show the message twice on replay. ACP and the Codex App Server run through
615/// other controllers.
616pub(crate) fn persists_user_record(output_format: &str) -> bool {
617    matches!(
618        output_format,
619        // agy-stream-json: `agy` doesn't echo the prompt either.
620        "claude-stream-json" | "codex-json" | "kimi-stream-json" | "agy-stream-json" | "qwen-stream-json"
621    )
622}
623
624/// Output formats whose CLI writes the user's prompt into its own output.
625pub(crate) fn echoes_prompt(output_format: &str) -> bool {
626    output_format == "gemini-json"
627}
628
629/// The transcript record for a user message: the same shape the persistent
630/// Claude controller writes, which every replay translator reads.
631pub(crate) fn user_record(message: &str) -> serde_json::Value {
632    serde_json::json!({
633        "type": "user",
634        "message": { "role": "user", "content": message }
635    })
636}
637
638/// [`user_record`] for a message no pane typed: `amx.via` says so, and the pane
639/// shows a live record that carries it (`injectedOrigin`, translator.ts).
640pub(crate) fn injected_user_record(message: &str) -> serde_json::Value {
641    let mut record = user_record(message);
642    record["amx"] = serde_json::json!({ "via": "inject" });
643    record
644}
645
646/// Writes the user's message to the transcript, as the record the persistent
647/// Claude controller writes for each stdin line (Phase 5a-3c): a
648/// `{"type":"user","message":{...}}` line in the block's file and the agent's
649/// global zone, published as an `echo: "stdin"` event — the pane already shows
650/// the message (its `agent-message-accepted` node), so the event only keeps
651/// its stream gap-free. A message the pane did not type (`shown_by_pane` false:
652/// a jekt, a broadcast, a schedule) is published as a plain record instead, so
653/// the pane shows it as an incoming turn, as it does for a Claude agent. Without
654/// it these CLIs' transcripts hold no trace of
655/// what the user sent: gone on reload, absent from History, and a turn the
656/// live feed can't roll off
657/// (SPEC_AGENT_PANE_BOUNDED_LIVE_WINDOW_MIGRATION_2026_09_23.md §6.9).
658///
659/// Written only AFTER the prompt was delivered — the stdin write succeeded,
660/// or the container exec started — like the persistent controller's
661/// delivery-before-persistence order: a failed spawn, pipe or exec must not
662/// leave the transcript claiming a turn that never happened (Codex review).
663/// Only for output formats whose CLI doesn't echo the prompt itself (see
664/// [`persists_user_record`]).
665pub(super) struct UserRecordSink {
666    shown_by_pane: bool,
667    /// Where the message came from; `None` stores it with no origin (untyped).
668    record: Option<RecordOrigin>,
669    broker: Option<Arc<mps::Broker>>,
670    block_id: String,
671    filestore: Option<Arc<FileStore>>,
672    mstore: Option<Arc<Store>>,
673}
674
675impl UserRecordSink {
676    pub(super) fn write(&self, message: &str) {
677        let Some(store) = self.mstore.as_ref() else {
678            return;
679        };
680        let Ok(block) = store.must_get::<crate::backend::obj::Block>(&self.block_id) else {
681            return;
682        };
683        let format = crate::backend::obj::meta_get_string(&block.meta, "agentOutputFormat", "");
684        if !persists_user_record(&format) {
685            // The CLI echoes the prompt itself: the echo is stored with this origin when it comes.
686            if let (true, Some(record)) = (echoes_prompt(&format), self.record.as_ref()) {
687                crate::backend::transcript::origin_ledger::expect(&self.block_id, message, record.clone());
688            }
689            return;
690        }
691        super::prompt_record::PromptRecords { broker: self.broker.clone(), filestore: self.filestore.clone(), mstore: self.mstore.clone() }
692            .write(&self.block_id, message, self.shown_by_pane, self.record.as_ref());
693    }
694}