Skip to main content

agentmux_srv_core/backend/blockcontroller/
resync_steps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of [`resync_controller`], one function each: pick the effective controller type,
5//! decide what to do with a controller the block already has, then build and start a new one of
6//! the right type. Moved out of `resync_controller` without a change in behaviour.
7
8use super::*;
9
10/// Everything `resync_controller` was called with, gathered so the steps share one value
11/// instead of fifteen parameters.
12pub(super) struct ResyncCtx<'a> {
13    pub block: &'a Block,
14    pub tab_id: &'a str,
15    pub rt_opts: Option<serde_json::Value>,
16    pub force: bool,
17    pub respawn_if_done: bool,
18    pub broker: Option<Arc<Broker>>,
19    pub event_bus: Option<Arc<EventBus>>,
20    pub mstore: Option<Arc<Store>>,
21    pub filestore: Option<Arc<FileStore>>,
22    pub id_store: Option<Arc<Store>>,
23    pub identity_store: Option<Arc<Store>>,
24    pub registry: Option<Arc<crate::registry::Registry>>,
25    pub boot_id: Arc<str>,
26    pub auth_key: &'a str,
27    pub config: Option<Arc<crate::backend::wconfig::ConfigState>>,
28}
29
30/// The controllers that start the agent's CLI themselves, on the machine srv runs on.
31const HOST_SIDE_CONTROLLERS: [&str; 3] = [BLOCK_CONTROLLER_ACP, BLOCK_CONTROLLER_MSP, BLOCK_CONTROLLER_APP_SERVER];
32
33/// Container agents (agentMode == "container") require a subprocess controller for
34/// per-turn docker exec. Persistent is incompatible. Override any stale "persistent"
35/// value that may have been written before this invariant was enforced at creation time.
36/// A controller that starts the CLI on this computer (ACP, MSP, app-server) is refused for a container
37/// agent's pane, whatever its meta says: the agent runs in its container.
38pub(super) fn effective_controller_type(block: &Block, controller_type: String) -> Result<String, String> {
39    let runtime = super::super::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).adapter();
40    if runtime.kind().is_container() && HOST_SIDE_CONTROLLERS.contains(&controller_type.as_str()) {
41        tracing::warn!(block_id = %block.oid, controller_type = %controller_type, "container agent's pane has a host-side controller in meta — refusing to start it");
42        return Err(format!(
43            "this agent runs in its container; its pane's {controller_type} controller would start it on this computer, so it is not started"
44        ));
45    }
46    if !runtime.accepts_persistent_controller() && controller_type == BLOCK_CONTROLLER_PERSISTENT {
47        tracing::warn!(
48            block_id = %block.oid,
49            "container agent has persistent controller in meta — overriding to subprocess"
50        );
51        Ok(BLOCK_CONTROLLER_SUBPROCESS.to_string())
52    } else {
53        Ok(controller_type)
54    }
55}
56
57impl ResyncCtx<'_> {
58    /// Decide what to do with the controller the block already has. `Some(result)` ends the
59    /// resync with that result; `None` means the old controller was stopped and removed, so a
60    /// new one is to be created.
61    pub(super) fn resync_existing(
62        &self,
63        ctrl: &Arc<dyn Controller>,
64        controller_type: &str,
65    ) -> Option<Result<(), String>> {
66        let block_id = &self.block.oid;
67        let block_meta = &self.block.meta;
68        let needs_replace = if ctrl.controller_type() != controller_type || self.force {
69            true // Type changed or forced restart
70        } else {
71            let status = ctrl.get_runtime_status();
72            // Check if connection changed
73            let new_conn = super::super::obj::meta_get_string(block_meta, META_KEY_CONNECTION, "local");
74            status.shellprocconnname != new_conn
75        };
76
77        // A forced resync that lands mid-turn on a persistent agent must NOT
78        // tear the controller down: doing so kills the CLI process with the
79        // user's in-flight message already written to its stdin, and nothing
80        // replays it — `stop_process` records a `StopRequested` (which the
81        // resume machine reads as an explicit user stop and so suppresses the
82        // retry), the old controller's queue is discarded with it, and the
83        // replacement "spawns on first message", i.e. does nothing. The turn
84        // vanished with no response and no error. Diagnosed live on AgentX,
85        // 2026-08-28.
86        //
87        // Instead the controller restarts itself the moment the turn ends,
88        // picking up the new `cmd:args` (rebuilt from block meta at spawn) on
89        // the next message. Nothing is lost by waiting: model/effort flags are
90        // baked in at spawn, so they could never have applied to the turn
91        // already running.
92        //
93        // Scoped to a runtime-config tweak: the controller must be persistent
94        // now AND still be persistent afterwards. A controller-TYPE change is a
95        // genuine replacement that has to happen immediately, even mid-turn.
96        //
97        // Checking only the EXISTING type was a real bug: the container-agent
98        // override (`effective_controller_type`) rewrites `controller_type`
99        // persistent -> subprocess, so a forced resync landing mid-turn on such
100        // a block would have deferred and silently kept the persistent
101        // controller — the exact incompatibility that override exists to
102        // correct, and the opposite of what this comment claims.
103        if needs_replace
104            && is_runtime_config_only_replace(ctrl.controller_type(), controller_type, self.force)
105        {
106            if let Some(p) = ctrl
107                .as_any()
108                .downcast_ref::<persistent::PersistentSubprocessController>()
109            {
110                if p.request_restart_when_idle() {
111                    return Some(Ok(()));
112                }
113            }
114        }
115
116        if needs_replace {
117            // stop_for_replace + remove_controller_entry_only, NOT stop +
118            // delete_controller: a session restart/resync must not tear
119            // down the block's shared process tracker — only the old
120            // controller's own CLI process should die. See
121            // docs/specs/SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md.
122            let _ = crate::backend::teardown_hooks::hooks().replace_now(ctrl.as_ref());
123            if let Some(old) = ctrl.as_any().downcast_ref::<super::subprocess::SubprocessController>() {
124                old.hand_over_held_to_replacement();
125            }
126            remove_controller_entry_only(block_id);
127            return None;
128        }
129
130        // Existing controller is fine, just check if it needs starting
131        let status = ctrl.get_runtime_status();
132        tracing::info!(
133            block_id = %block_id,
134            status = %status.shellprocstatus,
135            "[dnd-debug] existing controller — skipping spawn (no cmd:cwd seed)"
136        );
137        if status.shellprocstatus == STATUS_INIT {
138            return Some(self.restart_existing(ctrl));
139        }
140        if status.shellprocstatus == STATUS_DONE {
141            if self.respawn_if_done {
142                return Some(self.restart_existing(ctrl));
143            }
144            return Some(Err(RESYNC_ERR_ALREADY_EXITED.to_string()));
145        }
146        Some(Ok(()))
147    }
148
149    fn restart_existing(&self, ctrl: &Arc<dyn Controller>) -> Result<(), String> {
150        refresh_agent_skill_files(&self.block.meta, &self.mstore, &self.identity_store);
151        ctrl.start(self.block.meta.clone(), self.rt_opts.clone(), self.force)
152    }
153
154    /// Create a controller of `controller_type`, register it and start it.
155    ///
156    /// Not in a folder a container agent can write, for a controller that starts the agent's CLI itself
157    /// ([`start_refusal`]).
158    pub(super) fn create_and_start(self, controller_type: &str) -> Result<(), String> {
159        if let Some(why) = start_refusal(controller_type, &self.block.meta) {
160            return Err(why);
161        }
162        refresh_agent_skill_files(&self.block.meta, &self.mstore, &self.identity_store);
163        match controller_type {
164            // A durable SSH pane: the shell lives in the helper's session on the
165            // host, reached over ssh (durable_ssh.rs). Same `shell` type and
166            // connection name as the meta says, so a resync keeps it.
167            BLOCK_CONTROLLER_SHELL
168                if durable_mode::wants(
169                    &self.block.meta,
170                    self.config.as_ref().map(|c| c.get_full_config()).as_deref(),
171                ) =>
172            {
173                self.start_durable_ssh()
174            }
175            BLOCK_CONTROLLER_SHELL | BLOCK_CONTROLLER_CMD => self.start_shell(controller_type),
176            BLOCK_CONTROLLER_SUBPROCESS => self.start_subprocess(),
177            BLOCK_CONTROLLER_PERSISTENT => self.start_persistent(),
178            BLOCK_CONTROLLER_ACP => self.start_acp(),
179            BLOCK_CONTROLLER_MSP => self.start_msp(),
180            BLOCK_CONTROLLER_APP_SERVER => self.start_app_server(),
181            _ => Err(format!("unknown controller type: {controller_type}")),
182        }
183    }
184
185    /// When the user declines the helper, the pane restarts as a plain
186    /// SSH terminal: the same resync, forced, which then finds the
187    /// pane no longer durable (durable_mode::wants).
188    fn durable_fallback(&self) -> durable_ssh::Fallback {
189        let block_id = self.block.oid.clone();
190        let (tab_id, rt_opts) = (self.tab_id.to_string(), self.rt_opts.clone());
191        let (broker, event_bus, mstore, filestore) = (
192            self.broker.clone(),
193            self.event_bus.clone(),
194            self.mstore.clone(),
195            self.filestore.clone(),
196        );
197        let (id_store, identity_store, registry) =
198            (self.id_store.clone(), self.identity_store.clone(), self.registry.clone());
199        let (boot_id, auth_key, config) = (self.boot_id.clone(), self.auth_key.to_string(), self.config.clone());
200        Arc::new(move || {
201            let Some(block) = mstore.as_ref().and_then(|s| s.get::<Block>(&block_id).ok().flatten()) else {
202                return false;
203            };
204            // Still durable: a restart would only start the same
205            // durable controller again. Leave the pane stopped.
206            if durable_mode::wants(&block.meta, config.as_ref().map(|c| c.get_full_config()).as_deref()) {
207                tracing::warn!(block_id = %block_id, "durable ssh: still durable, not falling back");
208                return false;
209            }
210            if let Err(e) = resync_controller(
211                &block,
212                &tab_id,
213                rt_opts.clone(),
214                true,
215                true,
216                broker.clone(),
217                event_bus.clone(),
218                mstore.clone(),
219                filestore.clone(),
220                id_store.clone(),
221                identity_store.clone(),
222                registry.clone(),
223                boot_id.clone(),
224                &auth_key,
225                config.clone(),
226            ) {
227                tracing::warn!(block_id = %block_id, error = %e, "durable ssh: plain terminal fallback failed");
228                return false;
229            }
230            true
231        })
232    }
233
234    fn start_durable_ssh(self) -> Result<(), String> {
235        let fallback = self.durable_fallback();
236        let ctrl = Arc::new(durable_ssh::DurableSshController::new(
237            self.block.oid.clone(),
238            self.broker,
239            self.event_bus,
240            self.mstore,
241            self.filestore,
242            self.auth_key.to_string(),
243            self.config.clone(),
244            Some(fallback),
245        ));
246        register_controller(&self.block.oid, ctrl.clone());
247        ctrl.start(self.block.meta.clone(), self.rt_opts, self.force)
248    }
249
250    fn start_shell(self, controller_type: &str) -> Result<(), String> {
251        let ctrl = shell::ShellController::new(
252            controller_type.to_string(),
253            self.tab_id.to_string(),
254            self.block.oid.clone(),
255            self.broker,
256            self.event_bus,
257            self.mstore,
258            self.filestore,
259            self.auth_key.to_string(),
260        )
261        .with_config(self.config);
262        let ctrl = Arc::new(ctrl);
263        register_controller(&self.block.oid, ctrl.clone());
264        let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
265        // ShellController::new starts with is_agent_pane: false and start()
266        // only sets it (synchronously, before returning — shell/lifecycle.rs's
267        // start()) after actually spawning. register_controller's notification
268        // above therefore fired before list_agent_panes()'s is_agent() filter
269        // would have included this block; notify again now that start() has
270        // run so the classified state gets an authoritative announcement too,
271        // instead of depending solely on a proxy event or the poll.
272        notify_tracked_blocks_changed();
273        result
274    }
275
276    fn start_subprocess(self) -> Result<(), String> {
277        let ctrl = subprocess::SubprocessController::new(
278            self.tab_id.to_string(),
279            self.block.oid.clone(),
280            self.broker,
281            self.event_bus,
282            self.mstore,
283            self.filestore,
284            self.registry,
285            self.boot_id,
286        );
287        let ctrl = Arc::new(ctrl);
288        ctrl.set_self_ref();
289        register_controller(&self.block.oid, ctrl.clone());
290        // What the controller this one replaces had queued behind its turn runs now.
291        ctrl.run_queue_left_by_replaced();
292        let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
293        notify_tracked_blocks_changed();
294        result
295    }
296
297    fn start_persistent(self) -> Result<(), String> {
298        let ctrl = persistent::PersistentSubprocessController::new(
299            self.tab_id.to_string(),
300            self.block.oid.clone(),
301            self.broker,
302            self.event_bus,
303            self.mstore,
304            self.filestore,
305        )
306        .with_identity_stores(self.id_store, self.identity_store, self.auth_key.to_string())
307        // One live instance per agent (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24).
308        .with_agent_lease_store(self.registry, self.boot_id);
309        let ctrl = Arc::new(ctrl);
310        ctrl.set_self_ref();
311        register_controller(&self.block.oid, ctrl.clone());
312        let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
313        notify_tracked_blocks_changed();
314        result
315    }
316
317    fn start_acp(self) -> Result<(), String> {
318        if let Some(refusal) = handed_over_start_refusal(&self.mstore, &self.block.meta) {
319            return Err(refusal);
320        }
321        let ctrl = acp::AcpController::new(
322            self.tab_id.to_string(),
323            self.block.oid.clone(),
324            self.broker,
325            self.event_bus,
326            self.mstore,
327            self.filestore,
328        )
329        .with_auth_key(self.auth_key.to_string());
330        let ctrl = Arc::new(ctrl);
331        register_controller(&self.block.oid, ctrl.clone());
332        let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
333        notify_tracked_blocks_changed();
334        result
335    }
336
337    fn start_msp(self) -> Result<(), String> {
338        if let Some(refusal) = handed_over_start_refusal(&self.mstore, &self.block.meta) {
339            return Err(refusal);
340        }
341        let ctrl = msp::MspController::new(
342            self.block.oid.clone(),
343            self.broker,
344            self.event_bus,
345            self.mstore,
346            self.filestore,
347        )
348        .with_auth_key(self.auth_key.to_string());
349        let ctrl = Arc::new(ctrl);
350        register_controller(&self.block.oid, ctrl.clone());
351        let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
352        notify_tracked_blocks_changed();
353        result
354    }
355
356    fn start_app_server(self) -> Result<(), String> {
357        if let Some(refusal) = handed_over_start_refusal(&self.mstore, &self.block.meta) {
358            return Err(refusal);
359        }
360        let ctrl = app_server_controller::AppServerController::new(
361            self.block.oid.clone(),
362            self.broker,
363            self.event_bus,
364            self.mstore,
365            self.filestore,
366        );
367        let ctrl = Arc::new(ctrl);
368        ctrl.set_self_ref();
369        register_controller(&self.block.oid, ctrl.clone());
370        ctrl.start(self.block.meta.clone(), self.rt_opts, self.force)
371    }
372}
373
374/// The refusal to start a pane's agent here while its shared record says it was handed to another computer: the controllers
375/// below have no lease path of their own, and a resync reaches them without a turn.
376fn handed_over_start_refusal(mstore: &Option<Arc<Store>>, meta: &crate::backend::obj::MetaMapType) -> Option<String> {
377    let uid = crate::backend::obj::meta_get_string(meta, "agentId", "");
378    let name = crate::backend::obj::meta_get_string(meta, "agentName", "");
379    crate::backend::agent_admission::handed_over_check(mstore.as_ref()?, &uid, &name)
380}
381
382/// Why a controller of `controller_type` is not created for the agent on a pane with `meta`: its CLI starts
383/// with the controller (a terminal agent, a session agent, an app-server agent), and in a folder a container
384/// agent can write nothing on that path keeps a CLI to the MCP servers set in AgentMux, Claude Code included
385/// (`mcp_folder_rule::refusal`). A turn-based agent's controller (subprocess, persistent) starts no CLI: each
386/// turn starts it, and asks `mcp_folder_rule::turn_refusal` there.
387pub(super) fn start_refusal(controller_type: &str, meta: &crate::backend::obj::MetaMapType) -> Option<String> {
388    if matches!(controller_type, BLOCK_CONTROLLER_SUBPROCESS | BLOCK_CONTROLLER_PERSISTENT) {
389        return None;
390    }
391    crate::backend::mcp_folder_rule::refusal(meta)
392}