Skip to main content

agentmux_srv_core/backend/blockcontroller/
mod.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Block controller: manages lifecycle of each block (terminal, command, web app).
5//! Port of Go's pkg/blockcontroller/blockcontroller.go.
6
7//!
8//! Architecture:
9//! - Global controller registry maps block_id → Controller
10//! - Each controller manages the lifecycle of one block
11//! - ShellController handles "shell" and "cmd" block types
12//! - Controllers dispatch I/O between the user and the process/service
13
14pub mod acp;
15pub mod acp_prelaunch;
16pub mod acp_mcp;
17pub mod agent_lock;
18pub mod app_server;
19mod app_server_input;
20pub mod app_server_controller;
21pub mod app_server_protocol;
22pub mod core;
23pub mod durable_mode;
24pub mod durable_ssh;
25pub mod health;
26pub mod loop_stop;
27pub mod msp;
28pub mod msp_protocol;
29pub mod msp_session;
30pub mod persistent;
31pub mod persistent_resume;
32pub mod pidregistry;
33pub mod prompt_record;
34pub mod resync_lock;
35pub mod resync_steps;
36pub mod process_tree;
37pub mod session_agent;
38pub mod session_recovery;
39pub mod session_stats;
40pub mod shell;
41pub(crate) mod stderr_log;
42pub mod subprocess;
43pub mod term_size;
44pub mod watchdog;
45
46use std::any::Any;
47use std::collections::HashMap;
48use std::sync::{Arc, RwLock};
49
50use serde::{Deserialize, Serialize};
51
52use super::eventbus::EventBus;
53use super::message_origin::{MessageOrigin, RecordOrigin};
54use super::obj::{Block, MetaMapType, TermSize};
55use super::storage::filestore::FileStore;
56use super::storage::store::Store;
57use super::mps::Broker;
58
59// ---- Controller status constants (match Go) ----
60
61pub const STATUS_INIT: &str = "init";
62pub const STATUS_RUNNING: &str = "running";
63pub const STATUS_DONE: &str = "done";
64
65/// Sentinel error string `resync_controller` returns when it declines to
66/// respawn a `STATUS_DONE` controller because its caller passed
67/// `respawn_if_done: false` (see that parameter's own doc comment). Callers
68/// that want to treat "already exited" differently from a genuine failure
69/// (e.g. `try_attach_to_existing_shell` falling through to a fresh shell
70/// instead of surfacing a 500) match on this exact string rather than
71/// parsing every other possible error message `resync_controller` can
72/// return.
73pub const RESYNC_ERR_ALREADY_EXITED: &str = "resync_controller: controller already exited (respawn suppressed)";
74
75// ---- Controller type constants (match Go) ----
76
77pub const BLOCK_CONTROLLER_SHELL: &str = "shell";
78pub const BLOCK_CONTROLLER_CMD: &str = "cmd";
79pub const BLOCK_CONTROLLER_SUBPROCESS: &str = "subprocess";
80pub const BLOCK_CONTROLLER_PERSISTENT: &str = "persistent";
81pub const BLOCK_CONTROLLER_ACP: &str = "acp";
82/// Muse Code over MSP (`muse serve`): msp.rs.
83pub const BLOCK_CONTROLLER_MSP: &str = "msp";
84pub const BLOCK_CONTROLLER_APP_SERVER: &str = "app-server";
85
86// ---- Block metadata key constants (match Go) ----
87
88pub const META_KEY_CONTROLLER: &str = "controller";
89pub const META_KEY_CONNECTION: &str = "connection";
90pub const META_KEY_CMD: &str = "cmd";
91pub const META_KEY_CMD_CWD: &str = "cmd:cwd";
92#[allow(dead_code)]
93pub const META_KEY_CMD_SHELL: &str = "cmd:shell";
94pub const META_KEY_CMD_ARGS: &str = "cmd:args";
95pub const META_KEY_CMD_ENV: &str = "cmd:env";
96/// On an agent block: the block id of its shell drawer, the headless terminal
97/// the drawer, the agent's PtyShell and a paired device's pane list share.
98pub const META_KEY_SHELL_SUBBLOCK_ID: &str = "term:shellsubblockid";
99
100/// A meta value that is an object of strings, or a JSON string encoding one,
101/// as a string map. Non-string values are skipped; any other shape is empty.
102pub fn meta_string_map(meta: &MetaMapType, key: &str) -> HashMap<String, String> {
103    match meta.get(key) {
104        Some(serde_json::Value::Object(values)) => values
105            .iter()
106            .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
107            .collect(),
108        Some(serde_json::Value::String(s)) => serde_json::from_str(s).unwrap_or_default(),
109        _ => HashMap::new(),
110    }
111}
112
113/// A block's `cmd:env` as a string map. The frontend writes an object; the
114/// JSON-string form is accepted too, so every spawn path reads the same env.
115pub fn cmd_env_of(meta: &MetaMapType) -> HashMap<String, String> {
116    meta_string_map(meta, META_KEY_CMD_ENV)
117}
118
119/// A line from AgentMux in a terminal pane's output: dimmed, in brackets, on a
120/// line of its own, so it reads as AgentMux's and not the shell's.
121pub fn pane_note(text: &str) -> Vec<u8> {
122    format!("\r\n\x1b[2m[{text}]\x1b[0m\r\n").into_bytes()
123}
124
125/// The agent id an env map names: `AGENTMUX_AGENT_ID`, else the legacy
126/// `WAVEMUX_AGENT_ID`, trimmed, skipping blank values.
127pub(crate) fn agent_id_from_env<'a>(lookup: impl Fn(&str) -> Option<&'a str>) -> Option<String> {
128    ["AGENTMUX_AGENT_ID", "WAVEMUX_AGENT_ID"]
129        .into_iter()
130        .filter_map(lookup)
131        .map(str::trim)
132        .find(|v| !v.is_empty())
133        .map(str::to_string)
134}
135#[allow(dead_code)]
136pub const META_KEY_CMD_JWT: &str = "cmd:jwt";
137pub const META_KEY_CMD_RUN_ON_START: &str = "cmd:runonstart";
138pub const META_KEY_CMD_RUN_ONCE: &str = "cmd:runonce";
139pub const META_KEY_CMD_CLEAR_ON_START: &str = "cmd:clearonstart";
140pub const META_KEY_CMD_CLOSE_ON_EXIT: &str = "cmd:closeonexit";
141pub const META_KEY_CMD_CLOSE_ON_EXIT_FORCE: &str = "cmd:closeonexitforce";
142pub const META_KEY_CMD_CLOSE_ON_EXIT_DELAY: &str = "cmd:closeonexitdelay";
143#[allow(dead_code)]
144pub const META_KEY_CMD_INIT_SCRIPT: &str = "cmd:initscript";
145#[allow(dead_code)]
146pub const META_KEY_CMD_INIT_SCRIPT_BASH: &str = "cmd:initscript.bash";
147#[allow(dead_code)]
148pub const META_KEY_CMD_INIT_SCRIPT_ZSH: &str = "cmd:initscript.zsh";
149#[allow(dead_code)]
150pub const META_KEY_CMD_INIT_SCRIPT_FISH: &str = "cmd:initscript.fish";
151#[allow(dead_code)]
152pub const META_KEY_CMD_INIT_SCRIPT_PWSH: &str = "cmd:initscript.pwsh";
153pub const META_KEY_TERM_LOCAL_SHELL_PATH: &str = "term:localshellpath";
154pub const META_KEY_TERM_LOCAL_SHELL_OPTS: &str = "term:localshellopts";
155
156// ---- Default timeouts ----
157
158/// Default controller operation timeout in milliseconds.
159#[allow(dead_code)]
160pub const DEFAULT_TIMEOUT_MS: u64 = 2000;
161
162/// Grace period before forceful kill in milliseconds.
163#[allow(dead_code)]
164pub const DEFAULT_GRACEFUL_KILL_WAIT_MS: u64 = 400;
165
166// ---- Input union (matches Go's BlockInputUnion) ----
167
168/// Input sent to a block controller.
169/// Can be raw terminal data, a signal, or a resize event.
170#[derive(Debug, Clone)]
171pub struct BlockInputUnion {
172    /// Raw terminal input bytes (base64 decoded from wire format).
173    pub input_data: Option<Vec<u8>>,
174    /// Signal name (e.g., "SIGTERM", "SIGINT").
175    pub sig_name: Option<String>,
176    /// Terminal resize event.
177    pub term_size: Option<TermSize>,
178}
179
180impl BlockInputUnion {
181    pub fn data(data: Vec<u8>) -> Self {
182        Self {
183            input_data: Some(data),
184            sig_name: None,
185            term_size: None,
186        }
187    }
188
189    pub fn signal(name: &str) -> Self {
190        Self {
191            input_data: None,
192            sig_name: Some(name.to_string()),
193            term_size: None,
194        }
195    }
196
197    pub fn resize(size: TermSize) -> Self {
198        Self {
199            input_data: None,
200            sig_name: None,
201            term_size: Some(size),
202        }
203    }
204}
205
206fn is_false(v: &bool) -> bool {
207    !v
208}
209
210// ---- Runtime status (matches Go's BlockControllerRuntimeStatus) ----
211
212/// Runtime status of a block controller, sent to the UI.
213#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
214#[ts(export, export_to = "../../../frontend/types/rpc/")]
215pub struct BlockControllerRuntimeStatus {
216    pub blockid: String,
217    #[serde(default)]
218    pub version: i32,
219    #[serde(default, skip_serializing_if = "String::is_empty")]
220    #[ts(optional, as = "Option<String>")]
221    pub shellprocstatus: String,
222    #[serde(default, skip_serializing_if = "String::is_empty")]
223    #[ts(optional, as = "Option<String>")]
224    pub shellprocconnname: String,
225    #[serde(default)]
226    pub shellprocexitcode: i32,
227    /// A durable SSH pane (`durable_ssh`): its shell lives on the host.
228    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
229    #[ts(optional, as = "Option<bool>")]
230    pub durable: bool,
231    /// Unix timestamp (ms) when the process was spawned; None until first spawn.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    #[ts(optional, type = "number")]
234    pub spawn_ts_ms: Option<i64>,
235    /// PID of the controller's own child process. Set by the shell
236    /// controller, which is the one the UI needs it for: the agent pane's
237    /// Shell drawer identifies its shell by PID (see
238    /// docs/specs/SPEC_AGENT_SHELL_DRAWER_INFO_PANEL_2026_09_19.md §4.1).
239    /// None before the first spawn, and for controllers that don't set it.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    #[ts(optional)]
242    pub shellprocpid: Option<u32>,
243    /// Program name of that child (`pwsh`, `bash`, …). The process tracker
244    /// can't supply it — it omits each block's root process by design, and
245    /// for a shell sub-block the root IS the shell.
246    #[serde(default, skip_serializing_if = "String::is_empty")]
247    #[ts(optional, as = "Option<String>")]
248    pub shellprocname: String,
249    /// True if this pane is running an agent CLI (e.g. claude, codex, gemini, kimi, openclaw, pi).
250    #[serde(default, skip_serializing_if = "is_false")]
251    #[ts(optional, as = "Option<bool>")]
252    pub is_agent_pane: bool,
253    /// True if a turn is currently in flight (message sent, no terminating
254    /// `"result"` event observed yet). For `PersistentSubprocessController`
255    /// this is the only signal that distinguishes "actively generating a
256    /// turn" from "process alive, idle between turns" — `shellprocstatus`
257    /// stays `"running"` for the whole process lifetime either way. Backed
258    /// by `TurnActivityTracker.active_turn` (see `blockcontroller/health.rs`).
259    /// Frontend seeds `TurnPhase` from this at mount instead of always
260    /// defaulting to `Idle` — see
261    /// docs/specs/REPORT_AGENT_PANE_STATE_RECONCILIATION_2026_07_07.md
262    /// Finding 1.
263    #[serde(default, skip_serializing_if = "is_false")]
264    #[ts(optional, as = "Option<bool>")]
265    pub turn_active: bool,
266}
267
268// ---- Controller trait ----
269
270/// How a [`Controller::shutdown`] ended. Logged per closed agent
271/// (spec §9.8) — a provider that is often `Killed` needs a better shutdown or
272/// a longer grace period.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub enum StopOutcome {
275    /// No process was running (lazy controller never spawned, or already gone).
276    NotRunning,
277    /// Stopped the immediate way (default impl) — no wait, no verdict.
278    Stopped,
279    /// The process exited on its own before the deadline.
280    Exited,
281    /// The process was still alive at the deadline and was killed.
282    Killed,
283}
284
285impl StopOutcome {
286    pub fn as_str(&self) -> &'static str {
287        match self {
288            Self::NotRunning => "not_running",
289            Self::Stopped => "stopped",
290            Self::Exited => "exited",
291            Self::Killed => "killed",
292        }
293    }
294}
295
296pub type ShutdownFuture = std::pin::Pin<Box<dyn std::future::Future<Output = StopOutcome> + Send>>;
297
298/// Grace period for closing agents: one deadline per close, shared by every
299/// agent it stops (spec §9.2). Matches the kill task's long-standing 5s.
300pub const SHUTDOWN_GRACE: std::time::Duration = std::time::Duration::from_secs(5);
301
302/// Trait for block controllers. Each block type has its own implementation.
303/// Port of Go's `blockcontroller.Controller` interface.
304pub trait Controller: Send + Sync {
305    /// Start the controller. May spawn background tasks.
306    /// `force` restarts even if already running.
307    fn start(
308        &self,
309        block_meta: MetaMapType,
310        rt_opts: Option<serde_json::Value>,
311        force: bool,
312    ) -> Result<(), String>;
313
314    /// Stop the controller.
315    /// `graceful` waits for process to exit; `new_status` is the target state.
316    fn stop(&self, graceful: bool, new_status: &str) -> Result<(), String>;
317
318    /// Stop this controller because it's being REPLACED by a new one for
319    /// the same block (session restart / resync's `needs_replace` path),
320    /// NOT because the block itself is being closed. Must terminate this
321    /// controller's own CLI process so it doesn't linger, but — unlike
322    /// `stop()` — must NOT reach any declared-background descendant the
323    /// process may have spawned (e.g. a `task dev` instance launched via
324    /// `run_in_background: true`); those must survive the replace. See
325    /// docs/specs/SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md.
326    ///
327    /// Default delegates to `stop()` — correct for any controller type
328    /// with no subprocess tree of its own to be careful about (nothing to
329    /// preserve, so the two calls are equivalent). Only `ShellController`
330    /// overrides this today.
331    fn stop_for_replace(&self, new_status: &str) -> Result<(), String> {
332        self.stop(true, new_status)
333    }
334
335    /// Stop gracefully because the block is being CLOSED: end any turn in
336    /// progress, ask the process to exit, force-kill at `deadline`. The
337    /// returned future resolves once the process has actually exited (or
338    /// there was none). Does NOT drop the block's process tracker — the
339    /// caller does that after this resolves, so nothing the agent started
340    /// outlives it. See
341    /// docs/specs/SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md §9.3.
342    ///
343    /// Default: today's immediate stop. Right for controllers with no agent
344    /// session worth ending cleanly (shells, cmd, per-turn subprocess) and for
345    /// providers whose exit behaviour hasn't been measured yet (ACP,
346    /// app-server — §9.3 requires that before they get a graceful path).
347    fn shutdown(&self, _deadline: std::time::Instant) -> ShutdownFuture {
348        let _ = self.stop(true, STATUS_DONE);
349        Box::pin(async { StopOutcome::Stopped })
350    }
351
352    /// Get the current runtime status.
353    fn get_runtime_status(&self) -> BlockControllerRuntimeStatus;
354
355    /// Send input (terminal data, signal, or resize) to the controller.
356    /// `seq` is the per-TermViewModel monotonic counter; `None` means fire-and-forget (no ordering).
357    fn send_input(&self, input: BlockInputUnion, seq: Option<u64>) -> Result<(), String>;
358
359    /// End the turn in progress the way the harness itself is asked to, leaving its process and session up. The default is
360    /// the Stop button's: `send_input(SIGINT)`, which kills the process (the session resumes at the next message).
361    fn interrupt_turn(&self) -> Result<(), String> {
362        self.send_input(BlockInputUnion::signal("SIGINT"), None)
363    }
364
365    /// Get the controller type (e.g., "shell", "cmd").
366    fn controller_type(&self) -> &str;
367
368    /// Get the block ID.
369    #[allow(dead_code)]
370    fn block_id(&self) -> &str;
371
372    /// This block's own live, spawn-time-captured jekt/muxbus identity, if
373    /// it has one — an independent source of truth for the recipient-
374    /// identity check in `ReactiveHandler::inject_message_inner`, deliberately
375    /// NOT derived from `ReactiveHandler`'s own `name_to_blocks`/`agent_info`
376    /// maps (checking a registry against itself would be a tautology and
377    /// catch nothing). Default `None` for controller types that aren't
378    /// jekt-addressable at all (e.g. plain terminals) — only `ShellController`
379    /// and `PersistentSubprocessController` currently override this, mirroring
380    /// the two paths that already resolve a jekt-registration identity at
381    /// spawn time (`resolve_agent_id_for_jekt`, `muxbus_agent_id_from_env`).
382    fn agent_id(&self) -> Option<String> {
383        None
384    }
385
386    /// What started this agent's current turn (SPEC_AGENT_SELF_QUIT §6.3), if
387    /// the controller tracks it. `None` = unknown, which never counts as the
388    /// user — the safe answer for controllers that can't tell (ACP, App
389    /// Server, subprocess: both origins reach them through one method).
390    fn turn_provenance(&self) -> Option<health::TurnProvenance> {
391        None
392    }
393
394    /// This controller's turn tracker, for the turn ledger's bookkeeping from
395    /// outside the controller (a held message's join hint). `None` for
396    /// controllers that track no turns.
397    fn turn_tracker(&self) -> Option<std::sync::Arc<health::TurnActivityTracker>> {
398        None
399    }
400
401    /// When this agent last wrote output (unix ms), for the watchdog's idle
402    /// limit. Read from the turn tracker, which the persistent, subprocess,
403    /// ACP, MSP and App Server controllers stamp from their stdout or protocol
404    /// frames; `None` for controllers that don't. The shell controller reports
405    /// its PTY output itself (`ShellController::last_output_secs_ago`).
406    fn last_output_ms(&self) -> Option<i64> {
407        self.turn_tracker().and_then(|t| t.last_output_ms())
408    }
409
410    /// Whether this agent holds a request parked for the user's answer (an
411    /// AskUserQuestion, a tool permission or an approval). srv's own record,
412    /// so it holds whether or not any window shows the pane; the watchdog
413    /// never counts that wait as idle. The persistent and App Server
414    /// controllers park such requests. ACP and MSP answer theirs at once
415    /// (`acp::reply_to_agent_request`, `msp_protocol`), so they never wait.
416    fn awaiting_user_reply(&self) -> bool {
417        false
418    }
419
420    /// What waits in this agent, as a paired device is told it
421    /// (SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md §2): the request parked for the
422    /// user's answer, by id and kind, and how many of the person's messages wait to be sent. Never their text: a
423    /// queued message is the person's draft until it is sent.
424    fn pending_for_devices(&self) -> PendingFacts {
425        PendingFacts::default()
426    }
427
428    /// Refresh this block's own captured jekt/muxbus identity (see
429    /// [`agent_id`](Controller::agent_id)'s doc comment). Called whenever
430    /// `ReactiveHandler::register_agent`/`register_agent_with_nonce`
431    /// (re-)registers THIS block's block_id under a (possibly different)
432    /// agent_id, so the two independently-written copies never drift apart
433    /// (#2697: `agent_id()` was captured once at spawn and never
434    /// refreshed, while the registry's name bindings get re-keyed on every
435    /// `register_agent` call — e.g. `handle_reactive_register`'s
436    /// frontend-initiated HTTP path — causing a legitimately renamed or
437    /// reconfigured agent's own messages to be falsely rejected as an
438    /// identity mismatch). Default no-op for controller types that don't
439    /// override [`agent_id`](Controller::agent_id) either.
440    fn set_agent_id(&self, _id: Option<String>) {}
441
442    /// This block's STABLE jekt identity — `AGENTMUX_AGENT_ID` as captured
443    /// once at spawn, never refreshed. Distinct from [`agent_id`](Controller::agent_id),
444    /// which tracks the LIVE, renameable display name and is deliberately
445    /// refreshed every turn (see that method's doc comment on #2697).
446    /// AGENTMUX_AGENT_ID is embedded verbatim in PR-body tags specifically
447    /// because it does NOT change if the agent is later renamed — but
448    /// `ReactiveHandler`'s registry only tracks one key per block, and
449    /// every turn's `agent_id()` refresh evicts whatever this block was
450    /// previously registered under. `ReactiveHandler::inject_message_inner`'s
451    /// recipient-identity check (#2695) uses this alongside `agent_id()` so
452    /// a jekt addressed to the stable ID is validated correctly even after
453    /// the primary registry key has moved on to the live display name. See
454    /// `INCIDENT_2026_09_09_JEKT_STABLE_ID_ALIAS.md`. Default `None`,
455    /// mirroring `agent_id`'s default — only `PersistentSubprocessController`
456    /// currently overrides this.
457    fn stable_agent_id(&self) -> Option<String> {
458        None
459    }
460    /// Identity M2: this block's UID (`db_agents.id`) as carried in its
461    /// spawn env (`AGENTMUX_AGENT_UID`, set by `build_persistent_spawn_env`
462    /// since M1a), captured once at spawn like [`stable_agent_id`]. Backs the
463    /// registry's UID confirmer: consulted only for targets that resolved by
464    /// UID, and `None` — a registered-but-not-yet-spawned controller, or a
465    /// block with no row — is "unverifiable", not a mismatch. Default
466    /// `None`; only `PersistentSubprocessController` overrides this.
467    fn stable_agent_uid(&self) -> Option<String> {
468        None
469    }
470
471    /// Downcast support for concrete controller types.
472    fn as_any(&self) -> &dyn Any;
473}
474
475/// What [`Controller::pending_for_devices`] reports.
476#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
477pub struct PendingFacts {
478    /// The request waiting for the user's answer, if any (the first by id when there are several).
479    #[serde(skip_serializing_if = "Option::is_none")]
480    pub open: Option<PendingRequest>,
481    /// How many of the person's messages wait to be sent to the agent.
482    pub queued: usize,
483}
484
485/// A request parked for the user's answer: its id as the transcript names it (the tool use, or the App Server's
486/// item), and its kind: `question` (a question for the person) or `approval` (a tool or command to allow).
487#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
488pub struct PendingRequest {
489    pub id: String,
490    pub kind: &'static str,
491}
492
493// ---- Global controller registry ----
494
495/// Thread-safe global controller registry.
496/// Maps block_id → Arc<dyn Controller>.
497static CONTROLLER_REGISTRY: std::sync::LazyLock<RwLock<HashMap<String, Arc<dyn Controller>>>> =
498    std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
499
500/// Get a controller by block ID.
501pub fn get_controller(block_id: &str) -> Option<Arc<dyn Controller>> {
502    CONTROLLER_REGISTRY.read().unwrap().get(block_id).cloned()
503}
504
505/// Register a controller, stopping any previous one for the same block.
506pub fn register_controller(block_id: &str, controller: Arc<dyn Controller>) {
507    let mut registry = CONTROLLER_REGISTRY.write().unwrap();
508    if let Some(old) = registry.remove(block_id) {
509        // Stop the old controller before replacing
510        let _ = old.stop(true, STATUS_DONE);
511    }
512    registry.insert(block_id.to_string(), controller);
513    drop(registry);
514    notify_tracked_blocks_changed();
515    // What was held for this agent while its pane had no controller can go now.
516    crate::backend::reactive::controller_wait::controller_registered();
517}
518
519/// Announce a `CONTROLLER_REGISTRY` membership change to the Process Broker,
520/// if one is running (never set in most unit tests). See
521/// `ProcessBroker::emit_tracked_blocks_changed`'s doc comment for why this
522/// exists: `agent.tracked-blocks` reads this registry directly, but nothing
523/// used to tell a subscriber when a write here changed what that read would
524/// return — Swarm's client-side list depended on two unrelated, independently-
525/// timed events instead, and went stale whenever neither happened to fire for
526/// a given block. See docs/reports/REPORT_SWARM_MOUNT_DEPENDENT_TRACKING_GAP_2026_09_15.md.
527fn notify_tracked_blocks_changed() {
528    if let Some(broker) = crate::broker::process::global() {
529        broker.emit_tracked_blocks_changed();
530    }
531}
532
533/// Remove a controller from `CONTROLLER_REGISTRY` only — does NOT touch the
534/// process tracker or the Process Broker's cached status, unlike
535/// `delete_controller` below. For `resync_controller`'s replace path
536/// (session restart), where a NEW controller for the same block is about
537/// to be registered right after this call: `AgentProcessRegistry::
538/// ensure_tracker` is idempotent by design ("the job survives controller
539/// re-creation" — its own doc comment), so leaving the tracker alone here
540/// means any declared-background descendant (e.g. `task dev`) the old
541/// controller's process spawned stays alive and gets reattached to the new
542/// controller's own `track_spawned` call, instead of dying with the old
543/// one. The caller is responsible for actually terminating the OLD
544/// controller's own process first (via `stop_for_replace`, not `stop`) —
545/// this function only ever touches the registry map. See
546/// docs/specs/SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md.
547fn remove_controller_entry_only(block_id: &str) {
548    CONTROLLER_REGISTRY.write().unwrap().remove(block_id);
549}
550
551/// Blocks whose pane is being closed. Between stopping a block's
552/// controller and deleting its record, a `resync_controller` (frontend
553/// ControllerResync, `agent.open`, ...) would otherwise find the block
554/// still present and spawn a fresh process for it — an orphan the close
555/// never sees. See docs/specs/SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md
556/// §4.2 step 1.
557///
558/// Each entry also carries a completion signal (`true` once the block's
559/// process has exited), so a reopen racing the close can wait for the old
560/// process instead of starting a second `--resume` on the same session
561/// (spec §9.6).
562static CLOSING_BLOCKS: std::sync::LazyLock<RwLock<HashMap<String, tokio::sync::watch::Sender<bool>>>> =
563    std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
564
565/// Refuse to (re)spawn a controller for `block_id` until [`unmark_closing`].
566pub fn mark_closing(block_id: &str) {
567    CLOSING_BLOCKS
568        .write()
569        .unwrap()
570        .entry(block_id.to_string())
571        .or_insert_with(|| tokio::sync::watch::channel(false).0);
572}
573
574/// Signal that a closing block's process has exited. The block stays marked
575/// closing (no respawn) until [`unmark_closing`].
576pub fn mark_closing_stopped(block_id: &str) {
577    if let Some(tx) = CLOSING_BLOCKS.read().unwrap().get(block_id) {
578        tx.send_replace(true);
579    }
580}
581
582/// Lift [`mark_closing`]. Called once the block's record is gone (or the
583/// close failed and the block stays). Wakes anyone still waiting.
584pub fn unmark_closing(block_id: &str) {
585    if let Some(tx) = CLOSING_BLOCKS.write().unwrap().remove(block_id) {
586        tx.send_replace(true);
587    }
588}
589
590pub fn is_closing(block_id: &str) -> bool {
591    CLOSING_BLOCKS.read().unwrap().contains_key(block_id)
592}
593
594/// Blocks mid-close whose process has not exited yet. Their controllers have
595/// already left `CONTROLLER_REGISTRY`, so a registry scan can't see them.
596pub fn closing_blocks_still_running() -> Vec<String> {
597    CLOSING_BLOCKS
598        .read()
599        .unwrap()
600        .iter()
601        .filter(|(_, stopped)| !*stopped.borrow())
602        .map(|(id, _)| id.clone())
603        .collect()
604}
605
606/// Wait until a closing block's process has exited, or `timeout`. Returns
607/// immediately for a block that isn't closing.
608pub async fn wait_closing_stopped(block_id: &str, timeout: std::time::Duration) {
609    let rx = CLOSING_BLOCKS.read().unwrap().get(block_id).map(|tx| tx.subscribe());
610    if let Some(mut rx) = rx {
611        let _ = tokio::time::timeout(timeout, rx.wait_for(|stopped| *stopped)).await;
612    }
613}
614
615/// Unregister (delete) a controller by block ID, stopping it first.
616/// Removes from the registry before calling stop() so no new callers can reach it.
617pub fn delete_controller(block_id: &str) {
618    let ctrl = take_controller(block_id);
619    if let Some(ctrl) = ctrl {
620        let _ = ctrl.stop(true, STATUS_DONE);
621    }
622    release_block_processes(block_id);
623    term_size::forget(block_id);
624    // Messages a replaced subprocess controller left for a replacement that will not come.
625    subprocess::forget_left_for_replacement(block_id);
626}
627
628/// Remove a controller from `CONTROLLER_REGISTRY` and hand it back, without
629/// stopping it — for the graceful close, which awaits
630/// [`Controller::shutdown`] and only then calls [`release_block_processes`].
631/// Once removed, no new input reaches it.
632pub fn take_controller(block_id: &str) -> Option<Arc<dyn Controller>> {
633    CONTROLLER_REGISTRY.write().unwrap().remove(block_id)
634}
635
636/// Drop the block's process tracker (killing anything left in its tree) and
637/// its Process Broker entry. The second half of [`delete_controller`]; a
638/// graceful close calls it only after the process has exited.
639pub fn release_block_processes(block_id: &str) {
640    // Drop the process tracker for this block: the Windows job's
641    // `KILL_ON_JOB_CLOSE`, the Linux cgroup tracker's `Drop` (`cgroup.kill`)
642    // and the `ScanTracker`'s `Drop` (its tagged tree, best effort: macOS,
643    // Linux without delegation) end the whole descendant tree. Nothing on the
644    // stub (Unix terminals). No-op if the tracker global isn't initialized.
645    if let Some(registry) = crate::backend::process_tracker::registry::global() {
646        registry.remove(block_id);
647    }
648    // Drop the Process Broker's cached status for this block, so a closed
649    // pane's stale entry doesn't linger unreachable (get_all_controllers()
650    // already won't list it — see ProcessBroker::forget's doc comment).
651    if let Some(broker) = crate::broker::process::global() {
652        broker.forget(block_id);
653        broker.emit_tracked_blocks_changed();
654    }
655    // Identity M4a: the block's "spawned with a token" record goes with it.
656    crate::backend::identity_spawn::forget_block(block_id);
657    // And its latest rate-limit report (`agents::limit_reset`).
658    crate::agents::limit_reset::forget(block_id);
659    crate::backend::context_reading::forget(block_id);
660    crate::backend::agent_runtime_latest::forget(block_id);
661}
662
663// ---- Close-on-exit handler (SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md §10) ----
664
665/// `shell/lifecycle.rs`'s PTY wait/cleanup task needs to actually CLOSE a
666/// pane (delete its block, prune it from the owning tab's layout tree, and
667/// notify any connected frontend) when the shell inside it exits — but that
668/// task lives deep in `backend::blockcontroller`, which has no `AppState`
669/// handle (only the individual `Store`/`EventBus`/`Broker` pieces
670/// `ShellController` was constructed with). The actual close logic
671/// (`crate::sagas::delete_block::run`) needs the full `AppState` — its
672/// reducer state, saga-id allocator, and saga log, not just those three
673/// pieces. Rather than threading `AppState` through every
674/// `ShellController::new`/`resync_controller` call site (a much larger,
675/// architecture-inverting change), this mirrors the exact shape
676/// `crate::broker::process::set_global`/`global` already use for the
677/// identical class of problem (`broker::process`'s `AppState`-derived
678/// `ProcessBroker` also needs to be reachable from deep in `blockcontroller`
679/// without a direct dependency): a process-wide callback slot, set once at
680/// boot from `bootstrap::install_close_on_exit_handler` (which has
681/// `AppState` in scope) and read from `shell/lifecycle.rs`.
682type CloseOnExitFn = Arc<dyn Fn(String, String) + Send + Sync>;
683
684static CLOSE_ON_EXIT_HANDLER: std::sync::OnceLock<CloseOnExitFn> = std::sync::OnceLock::new();
685
686/// Install the close-on-exit callback. Called exactly once, from
687/// `bootstrap::install_close_on_exit_handler` right after `AppState` is
688/// built in `main.rs` — see that function's doc comment for what the
689/// callback actually does. A second call is a no-op (`OnceLock::set`
690/// silently returns `Err` on an already-initialized cell, which this
691/// discards — matching `broker::process::set_global`'s identical
692/// fire-and-forget style; there is exactly one legitimate caller).
693pub fn set_close_on_exit_handler(f: CloseOnExitFn) {
694    let _ = CLOSE_ON_EXIT_HANDLER.set(f);
695}
696
697/// Trigger the installed close-on-exit handler for `(tab_id, block_id)`, if
698/// one has been installed. Fire-and-forget: the handler owns spawning
699/// whatever async work it needs (the saga call is `async`; this function
700/// itself is not). A missing handler (astronomically early in boot, before
701/// `main.rs` finishes wiring `AppState` — no real caller can reach this
702/// before then, since nothing spawns a PTY that early) just skips closing;
703/// the pane sits inert the same way it did before this feature existed, not
704/// a hard failure.
705pub(crate) fn close_on_exit(tab_id: String, block_id: String) {
706    match CLOSE_ON_EXIT_HANDLER.get() {
707        Some(f) => f(tab_id, block_id),
708        None => {
709            tracing::warn!(
710                block_id = %block_id,
711                "close_on_exit: handler not installed yet, skipping pane close"
712            );
713        }
714    }
715}
716
717/// Get all controllers (snapshot).
718pub fn get_all_controllers() -> HashMap<String, Arc<dyn Controller>> {
719    CONTROLLER_REGISTRY.read().unwrap().clone()
720}
721
722/// Stop all running controllers gracefully.
723#[allow(dead_code)]
724pub fn stop_all_controllers() {
725    let controllers = get_all_controllers();
726    for (_, ctrl) in controllers {
727        let _ = ctrl.stop(true, STATUS_DONE);
728    }
729}
730
731// ---- Public API functions ----
732
733/// Get the runtime status for a block's controller.
734/// Returns None if no controller is registered.
735pub fn get_block_controller_status(block_id: &str) -> Option<BlockControllerRuntimeStatus> {
736    get_controller(block_id).map(|c| c.get_runtime_status())
737}
738
739/// Stop a block's controller gracefully.
740#[allow(dead_code)]
741pub fn stop_block_controller(block_id: &str) -> Result<(), String> {
742    match get_controller(block_id) {
743        Some(ctrl) => ctrl.stop(true, STATUS_DONE),
744        None => Ok(()), // No controller = already stopped
745    }
746}
747
748/// Send input to a block's controller.
749pub fn send_input(block_id: &str, input: BlockInputUnion, seq: Option<u64>) -> Result<(), String> {
750    let resize = input
751        .term_size
752        .as_ref()
753        .filter(|ts| ts.rows > 0 && ts.cols > 0)
754        .map(|ts| (ts.rows.min(u16::MAX as i64) as u16, ts.cols.min(u16::MAX as i64) as u16));
755    match get_controller(block_id) {
756        Some(ctrl) => {
757            ctrl.send_input(input, seq)?;
758            // The size a paired device watching the terminal renders at.
759            if let Some((rows, cols)) = resize {
760                term_size::record(block_id, rows, cols);
761            }
762            Ok(())
763        }
764        None => Err(format!("no controller for block {block_id}")),
765    }
766}
767
768/// What an automated send to a persistent agent did with one message.
769///
770/// A live process gets it at once, mid-turn or not; it is queued only while
771/// the process cannot take a write (starting up, restarting, stopping).
772/// Spec: `docs/specs/SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md` §2.1.
773#[derive(Debug, Clone, Copy, PartialEq, Eq)]
774pub enum SendOutcome {
775    /// Written to the agent's input now.
776    Sent,
777    /// Queued because the agent's process is starting up, restarting or
778    /// stopping (or behind older messages queued for that reason); written as
779    /// soon as the process can take it.
780    Deferred,
781}
782
783/// How a controller-aware agent message was delivered.
784#[derive(Debug)]
785pub enum AgentDelivery {
786    /// Accepted on the controller's structured input channel — a persistent
787    /// stream-json stdin line or an ACP `session/prompt` — and written now. No
788    /// PTY keystrokes are needed.
789    Structured,
790    /// Accepted like [`AgentDelivery::Structured`], but queued because the
791    /// agent's process is starting up, restarting or stopping; written as soon
792    /// as it can take it. The controller has taken responsibility for it; the
793    /// agent has not seen it yet.
794    StructuredDeferred,
795    /// The controller is PTY/terminal-based (shell/term) or otherwise has no
796    /// structured input channel. The caller should fall back to keystroke
797    /// injection.
798    Pty,
799}
800
801/// Deliver an inter-agent / muxbus message to a running agent the way its controller
802/// expects.
803///
804/// Callers of this function are automated senders by definition — muxbus, the
805/// reactive/jekt handler, MCP `SendMessage`, the messaging bridges. The message
806/// reaches the agent at once, whatever it is doing: the agent gets it as soon
807/// as it can act on it (`docs/specs/SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md`
808/// §2.1). The human operator's own input does not come through here — it goes
809/// via the `agentinput` RPC.
810///
811/// - **Persistent** (stream-json) agents have no PTY: the message is written as a
812///   `{type:"user",…}` line on the live stdin, mid-turn included. It is queued
813///   only while the process is starting up, restarting or stopping.
814/// - **ACP** agents receive the message as a `session/prompt` (the ACP controller's
815///   `send_input` already wraps raw input that way). They take one prompt at a time, so a message
816///   that arrives mid-turn is queued and sent when the turn ends ([`AgentDelivery::StructuredDeferred`]).
817/// - **App Server** (Codex) agents have no PTY either: the message is queued/dispatched
818///   as a `turn/start` request via [`app_server_controller::AppServerController::send_message`].
819/// - Everything else (shell/term PTY agents, one-shot subprocess agents) is reported
820///   as [`AgentDelivery::Pty`] so the caller uses keystroke injection — preserving
821///   today's behavior.
822///
823/// This is the controller-aware delivery primitive muxbus Tier-1 needs: PTY
824/// keystrokes silently fail to reach a persistent stream-json agent (it rejects raw
825/// input). Spec: docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md §6 (Phase 3).
826#[cfg(test)]
827pub fn deliver_agent_message(block_id: &str, message: &str) -> Result<AgentDelivery, String> {
828    deliver_agent_message_from(block_id, message, None, MessageOrigin::system(), &[], None)
829}
830
831/// [`deliver_agent_message`], saying who the input is from (turn provenance,
832/// SPEC_AGENT_SELF_QUIT §6.3). Only the persistent controller records it
833/// (see `send_user_message_outcome_from`); ACP and App Server turns carry no
834/// turn provenance, but both store `from` with the message in the transcript.
835///
836/// `from` says where the message came from, for the record of it
837/// (`message_origin`): a producer that doesn't say doesn't compile.
838///
839/// `expires_at_ms` is the sender's expiry (`InjectionRequest::expires_at_ms`,
840/// issue #3894): only the persistent controller's deferred queue uses it — a
841/// message queued while its process was starting, restarting or stopping is
842/// dropped at write time once the expiry has passed. Every other controller
843/// delivers at once, so it ignores it.
844pub fn deliver_agent_message_from(
845    block_id: &str,
846    message: &str,
847    origin: Option<health::TurnInput>,
848    from: MessageOrigin,
849    inline: &[serde_json::Value],
850    expires_at_ms: Option<i64>,
851) -> Result<AgentDelivery, String> {
852    let ctrl =
853        get_controller(block_id).ok_or_else(|| format!("no controller for block {block_id}"))?;
854    // The person's own words carry the mark only srv writes; every other origin has its marker in the text already.
855    let message = from.as_model_text(message);
856    // srv's held `[AgentMux]` notes go with this message; they are held
857    // again if it doesn't go, or goes as keystrokes.
858    let (message, held) = crate::backend::reactive::held_notes::attach(block_id, &message);
859
860    if let Some(persistent_ctrl) = ctrl
861        .as_any()
862        .downcast_ref::<persistent::PersistentSubprocessController>()
863    {
864        let record = RecordOrigin { origin: from, notes: held.note_texts(), resend: false };
865        let outcome = persistent_ctrl.send_user_message_with_images_from(message, origin, inline.to_vec(), record, expires_at_ms, held.keyed_notes())?;
866        held.delivered();
867        return Ok(match outcome {
868            SendOutcome::Sent => AgentDelivery::Structured,
869            SendOutcome::Deferred => AgentDelivery::StructuredDeferred,
870        });
871    }
872
873    if let Some(agent) = session_agent::session_agent(ctrl.as_ref()) {
874        let outcome = agent.send_message(message, None, Some(&RecordOrigin { origin: from, notes: held.note_texts(), resend: false }))?;
875        held.delivered();
876        return Ok(match outcome {
877            SendOutcome::Sent => AgentDelivery::Structured,
878            SendOutcome::Deferred => AgentDelivery::StructuredDeferred,
879        });
880    }
881
882    if let Some(app_server_ctrl) = ctrl
883        .as_any()
884        .downcast_ref::<app_server_controller::AppServerController>()
885    {
886        app_server_ctrl.send_message_from(message, Vec::new(), false, Some(&RecordOrigin { origin: from, notes: held.note_texts(), resend: false }))?;
887        held.delivered();
888        return Ok(AgentDelivery::Structured);
889    }
890
891    Ok(AgentDelivery::Pty)
892}
893
894/// srv's own note `text` for the agent in `block_id`, about the work at hand:
895/// into its running turn where the controller can join one atomically (a
896/// persistent agent: `PersistentSubprocessController::note_into_turn_or_hold`),
897/// else held under `key` for its next turn. It never starts a turn; the other
898/// controllers can only queue a message as a turn of its own, so theirs is
899/// always held. Returns whether it joined a turn.
900pub fn system_note_into_turn_or_hold(block_id: &str, key: &str, text: &str) -> bool {
901    let text = crate::backend::reactive::sanitize::with_system_note_marker(text);
902    let text = text.as_ref();
903    if let Some(ctrl) = get_controller(block_id) {
904        if let Some(p) = ctrl.as_any().downcast_ref::<persistent::PersistentSubprocessController>() {
905            return p.note_into_turn_or_hold(key, text);
906        }
907    }
908    crate::backend::reactive::held_notes::hold(block_id, key, text);
909    false
910}
911
912/// Is this forced replace merely a runtime-config change (model / effort /
913/// permission) on a controller that stays persistent — i.e. the one case that
914/// may be deferred to the end of an in-flight turn rather than killing it?
915///
916/// Requires the type to be persistent on BOTH sides. Checking only the
917/// existing side was a real bug (reagent P2 on PR #2858): the container-agent
918/// override in `resync_controller` rewrites the target persistent ->
919/// subprocess, so a forced resync landing mid-turn on such a block would defer
920/// and silently keep the persistent controller — precisely the
921/// incompatibility that override exists to correct.
922///
923/// A genuine type change must replace immediately, mid-turn or not; losing an
924/// in-flight turn is the lesser harm against running a container agent on a
925/// controller that cannot do per-turn `docker exec` at all.
926fn is_runtime_config_only_replace(existing_type: &str, target_type: &str, force: bool) -> bool {
927    force
928        && existing_type == BLOCK_CONTROLLER_PERSISTENT
929        && target_type == BLOCK_CONTROLLER_PERSISTENT
930}
931
932/// A controller is about to (re)start an agent: its bound skills are written first, so a skill bound after its
933/// first launch is on disk when the CLI reads its project.
934fn refresh_agent_skill_files(meta: &MetaMapType, mstore: &Option<Arc<Store>>, identity_store: &Option<Arc<Store>>) {
935    if let (Some(m), Some(i)) = (mstore, identity_store) {
936        crate::backend::agent_skill_files::refresh_for_block(meta, m, i);
937    }
938}
939
940/// Resync a block's controller — the main entry point for starting/restarting blocks.
941/// Port of Go's `ResyncController`.
942///
943/// Logic, for the `block` passed in:
944/// 1. Determine controller type from meta["controller"]
945/// 2. If the existing controller needs replacing (type changed, conn changed, force), stop it
946/// 3. Create a new controller if needed
947/// 4. Start it if status is init, or done when `respawn_if_done` allows (below)
948///
949/// `respawn_if_done`: when the existing controller's status is
950/// `STATUS_DONE` (its process already exited), should this call revive it
951/// via `ctrl.start()` (the historical, unconditional behavior — pass
952/// `true`), or leave it dead and return `Err(RESYNC_ERR_ALREADY_EXITED)`
953/// instead (pass `false`)? `true` is correct for crash/backend-restart
954/// recovery (the WS `ControllerResyncCommand` path, `TermResyncHandler` —
955/// see its own doc comment for why a dead PTY must come back transparently
956/// there). `false` is for a caller that needs to tell "this exited on
957/// purpose" apart from "this needs reviving" using the SAME status read
958/// `resync_controller` itself makes, rather than checking status in the
959/// caller first and racing a StatusDone transition landing between that
960/// check and this call — `try_attach_to_existing_shell`
961/// (`server/mod.rs`, PtyShellCreate's pane-shell-reuse path) is the one
962/// caller that needs this; see
963/// `docs/specs/SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md` §7.
964pub fn resync_controller(
965    block: &Block,
966    tab_id: &str,
967    rt_opts: Option<serde_json::Value>,
968    force: bool,
969    respawn_if_done: bool,
970    broker: Option<Arc<Broker>>,
971    event_bus: Option<Arc<EventBus>>,
972    mstore: Option<Arc<Store>>,
973    filestore: Option<Arc<FileStore>>,
974    // `id_store`/`identity_store`: the Layer 3 identity/credential spawn
975    // gate's dependencies (`identity::resolver::inject_identity_env`, per
976    // `SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md`). Only consulted
977    // by `PersistentSubprocessController::start()`'s eager-resume path
978    // (`SPEC_PERSISTENT_CONTROLLER_EAGER_RESUME_ON_RECONNECT_2026_09_20.md`)
979    // — every other controller type ignores them. `None` here does not
980    // disable the gate for a LIVE message send (that path, `agent_handlers::
981    // input`, has its own direct access to these stores) — it only means a
982    // controller CONSTRUCTED via this call can't eager-resume at all, and
983    // falls back to today's lazy "wait for the first message" behavior even
984    // when `agent:sessionid` is present. That fallback is the deliberately
985    // safe default: spawning an eager resume WITHOUT the gate would spawn a
986    // possibly-deauthed agent on whatever ambient credential is lying
987    // around, silently reintroducing the exact vulnerability class that gate
988    // was built to close. See `PersistentSubprocessController::start()`'s
989    // own doc comment.
990    id_store: Option<Arc<Store>>,
991    identity_store: Option<Arc<Store>>,
992    registry: Option<Arc<crate::registry::Registry>>,
993    boot_id: Arc<str>,
994    auth_key: &str,
995    // The live, file-watched config (`AppState::config_watcher`). Only the
996    // shell/cmd controller reads it, for the global `cmd:env` defaults its
997    // interactive-shell spawn applies. `None` (tests) means no global
998    // defaults.
999    config: Option<Arc<crate::backend::wconfig::ConfigState>>,
1000) -> Result<(), String> {
1001    let block_id = &block.oid;
1002
1003    // Get controller type from block meta
1004    let controller_type = super::obj::meta_get_string(&block.meta, META_KEY_CONTROLLER, "");
1005
1006    if controller_type.is_empty() {
1007        // No controller type = web/static block, nothing to manage
1008        return Ok(());
1009    }
1010
1011    // One resync of this block at a time: see resync_lock.rs. Closing is checked after waiting for it: a
1012    // resync that waited can resume once the pane's teardown has run, and must not start a controller then.
1013    let _one_resync = resync_lock::ResyncGuard::acquire(block_id);
1014
1015    if is_closing(block_id) {
1016        return Err(format!("resync_controller: block {block_id} is closing"));
1017    }
1018
1019    // A pane saved from a harness that was removed starts nothing: its saved command would launch the removed CLI.
1020    let provider = super::obj::meta_get_string(&block.meta, "agentProvider", "");
1021    if let Some(why) = super::providers::retired_reason(&provider) {
1022        return Err(why.to_string());
1023    }
1024
1025    let controller_type = resync_steps::effective_controller_type(block, controller_type)?;
1026
1027    tracing::info!(
1028        block_id = %block_id,
1029        controller_type = %controller_type,
1030        mstore_present = mstore.is_some(),
1031        event_bus_present = event_bus.is_some(),
1032        force,
1033        "[dnd-debug] resync_controller entry"
1034    );
1035
1036    let ctx = resync_steps::ResyncCtx {
1037        block,
1038        tab_id,
1039        rt_opts,
1040        force,
1041        respawn_if_done,
1042        broker,
1043        event_bus,
1044        mstore,
1045        filestore,
1046        id_store,
1047        identity_store,
1048        registry,
1049        boot_id,
1050        auth_key,
1051        config,
1052    };
1053    if let Some(ctrl) = get_controller(block_id) {
1054        if let Some(result) = ctx.resync_existing(&ctrl, &controller_type) {
1055            return result;
1056        }
1057    }
1058    ctx.create_and_start(&controller_type)
1059}
1060
1061/// Publish a controller status event via MPS broker. The sole publish point
1062/// for `controllerstatus`, used by every controller type (persistent CLI,
1063/// subprocess CLI, ACP agents, plain shell/PTY panes — 13 call sites).
1064///
1065/// `persist: 1` so a reconnecting subscriber (WS reconnect, srv restart)
1066/// replays the last known status instead of seeing nothing until the next
1067/// live event — mirrors `EVENT_AGENT_FAILURE`'s identical `persist: 1` in
1068/// `subprocess/host_spawn.rs`. Closes the "missed the one turn-end push,
1069/// stuck showing Working forever" gap for the reconnect case; see
1070/// REPORT_LOGIN_PERSIST_FAILURE_AND_STUCK_WORKING_2026_07_27.md §3/§4 item 5.
1071/// (A same-connection pane remount, which doesn't clear the broker's
1072/// per-route replay tracking, isn't covered by persist alone — see the
1073/// focus-triggered reconcile in `agent-view.tsx` for that case.)
1074pub fn publish_controller_status(
1075    broker: &super::mps::Broker,
1076    status: &BlockControllerRuntimeStatus,
1077) {
1078    broker.publish_event::<super::mps_events::ControllerStatus>(status, vec![format!("block:{}", status.blockid)], 1);
1079}
1080
1081impl BlockControllerRuntimeStatus {
1082    /// This status with the process's spawn time (`TurnActivityTracker::spawned_at_ms`).
1083    pub(crate) fn spawned_at(mut self, spawn_ts_ms: Option<i64>) -> Self {
1084        self.spawn_ts_ms = spawn_ts_ms;
1085        self
1086    }
1087}
1088
1089/// The status an agent-CLI controller reports: a local agent pane with no PID
1090/// or program name, so only these five fields vary between sites. Its own
1091/// snapshot adds the spawn time ([`BlockControllerRuntimeStatus::spawned_at`]).
1092pub(crate) fn agent_runtime_status(
1093    block_id: &str,
1094    version: i32,
1095    proc_status: &str,
1096    exit_code: i32,
1097    turn_active: bool,
1098) -> BlockControllerRuntimeStatus {
1099    BlockControllerRuntimeStatus {
1100        durable: false,
1101        blockid: block_id.to_string(),
1102        version,
1103        shellprocstatus: proc_status.to_string(),
1104        shellprocconnname: "local".to_string(),
1105        shellprocexitcode: exit_code,
1106        shellprocpid: None,
1107        shellprocname: String::new(),
1108        spawn_ts_ms: None,
1109        is_agent_pane: true,
1110        turn_active,
1111    }
1112}
1113
1114/// The `agent-message-accepted` event's payload (`mps_events::AgentMessageAccepted`).
1115#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
1116#[ts(export, export_to = "../../../frontend/types/rpc/")]
1117pub struct MessageAcceptedEvent {
1118    pub block_id: String,
1119    pub message_id: String,
1120}
1121
1122/// Publish `agent-message-accepted` for `message_id` on `block:<id>`, telling
1123/// the frontend to promote that pending entry from queued to in-document.
1124pub(crate) fn publish_message_accepted(broker: &super::mps::Broker, block_id: &str, message_id: &str) {
1125    let payload = MessageAcceptedEvent { block_id: block_id.to_string(), message_id: message_id.to_string() };
1126    broker.publish_event::<super::mps_events::AgentMessageAccepted>(&payload, vec![format!("block:{}", block_id)], 0);
1127}
1128
1129/// The `agent-message-queued` event's payload (`mps_events::AgentMessageQueued`).
1130#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
1131#[ts(export, export_to = "../../../frontend/types/rpc/")]
1132pub struct MessageQueuedEvent {
1133    pub block_id: String,
1134    pub message_id: String,
1135    /// Messages already queued in front of this one, not counting the process that is still running.
1136    #[ts(type = "number")]
1137    pub ahead: usize,
1138}
1139
1140/// Publish `agent-message-queued` for `message_id` on `block:<id>`: the agent's process is still alive, so the message
1141/// waits for it, behind `ahead` others.
1142pub(crate) fn publish_message_queued(broker: &super::mps::Broker, block_id: &str, message_id: &str, ahead: usize) {
1143    let payload = MessageQueuedEvent { block_id: block_id.to_string(), message_id: message_id.to_string(), ahead };
1144    broker.publish_event::<super::mps_events::AgentMessageQueued>(&payload, vec![format!("block:{}", block_id)], 0);
1145}
1146
1147#[cfg(test)]
1148mod cmd_env_tests {
1149    use super::{cmd_env_of, MetaMapType, META_KEY_CMD_ENV};
1150
1151    #[test]
1152    fn cmd_env_reads_the_object_form_and_the_json_string_form() {
1153        let mut meta = MetaMapType::new();
1154        meta.insert(META_KEY_CMD_ENV.to_string(), serde_json::json!({"K": "v", "N": 1}));
1155        let env = cmd_env_of(&meta);
1156        assert_eq!(env.get("K").map(String::as_str), Some("v"));
1157        assert!(!env.contains_key("N"), "non-string values are skipped");
1158
1159        meta.insert(META_KEY_CMD_ENV.to_string(), serde_json::json!("{\"K\":\"w\"}"));
1160        assert_eq!(cmd_env_of(&meta).get("K").map(String::as_str), Some("w"));
1161
1162        meta.insert(META_KEY_CMD_ENV.to_string(), serde_json::json!(["not", "a", "map"]));
1163        assert!(cmd_env_of(&meta).is_empty());
1164        assert!(cmd_env_of(&MetaMapType::new()).is_empty());
1165    }
1166
1167    #[test]
1168    fn agent_id_from_env_prefers_the_canonical_key_and_skips_blanks() {
1169        use super::agent_id_from_env;
1170        let id = |pairs: &[(&'static str, &'static str)]| {
1171            let pairs = pairs.to_vec();
1172            agent_id_from_env(move |k| pairs.iter().find(|(key, _)| *key == k).map(|(_, v)| *v))
1173        };
1174        assert_eq!(id(&[("AGENTMUX_AGENT_ID", " new "), ("WAVEMUX_AGENT_ID", "old")]).as_deref(), Some("new"));
1175        assert_eq!(id(&[("AGENTMUX_AGENT_ID", "  "), ("WAVEMUX_AGENT_ID", "old")]).as_deref(), Some("old"));
1176        assert_eq!(id(&[("WAVEMUX_AGENT_ID", "")]), None);
1177        assert_eq!(id(&[]), None);
1178    }
1179}
1180
1181#[cfg(test)]
1182mod tests;
1183
1184#[cfg(test)]
1185mod container_pane_controller_tests;
1186#[cfg(test)]
1187mod folder_rule_tests;