Skip to main content

agentmux_srv/server/agent_handlers/
container_turn.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! Getting a container agent's container ready for a turn: the container is
4//! running, and the provider CLI is installed in it.
5//!
6//! This is the first thing a container turn does, inside the turn's own task
7//! (`SubprocessController::spawn_container_turn`), NOT inside the RPC handler
8//! that accepted the message: downloading the image takes minutes, and the RPC
9//! engine drops a handler after five seconds, which cancelled the download for
10//! good. The handler only records the [`ContainerStartup`] on the controller
11//! and queues the turn.
12//!
13//! Spec: docs/specs/SPEC_CONTAINER_AGENTS_AT_PARITY_2026_10_27.md (P0, P1, P2),
14//! docs/specs/SPEC_CONTAINER_AGENTS_WORK_FOR_EVERYONE_2026_10_07.md.
15
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::Arc;
18use std::time::Instant;
19
20use serde_json::{json, Value};
21
22use crate::backend::cli_notice::{self, ContainerStartState, InstallState};
23use crate::backend::container::{CliProvision, ContainerError, ContainerManager, ContainerMountSpec, StartEvent, StartObserver};
24use crate::backend::container::cli::CliInstall;
25use crate::backend::container::image::resolve_container_image;
26use crate::backend::runtime_adapter::{ContainerAdapter, ContainerLaunch, RuntimeAdapter, RuntimeKind};
27
28/// Everything needed to get a container agent's container ready, owned, so it
29/// can outlive the request that asked for it.
30pub(crate) struct ContainerStartup {
31    pub cm: ContainerManager,
32    pub block_id: String,
33    pub container_name: String,
34    /// The stored `agent:container_image`; empty means the default image.
35    pub image: String,
36    pub volumes: Vec<String>,
37    pub mount_spec: ContainerMountSpec,
38    pub provider_id: String,
39    pub container_command: String,
40    pub broker: Arc<crate::backend::mps::Broker>,
41    pub filestore: Arc<crate::backend::storage::filestore::FileStore>,
42    pub mstore: Arc<crate::backend::storage::store::Store>,
43}
44
45/// The step the controller runs at the start of each container turn.
46pub(crate) fn startup_step(startup: ContainerStartup) -> crate::backend::blockcontroller::subprocess::StartupStep {
47    let startup = Arc::new(startup);
48    Arc::new(move || {
49        let startup = Arc::clone(&startup);
50        Box::pin(async move { startup.run().await })
51    })
52}
53
54impl ContainerStartup {
55    /// For the container agent in `block_meta`: its container, and the mounts for the account bound to it
56    /// (`env_vars` as the identity injection left them) and its workspace. `AGENTMUX_LOCAL_URL` in
57    /// `env_vars` is rewritten to how the container reaches this srv. The turn's start-up and the
58    /// pre-start both build theirs here, so the container is the same whichever comes first.
59    #[allow(clippy::too_many_arguments)]
60    pub(crate) fn for_block(
61        cm: ContainerManager,
62        block_id: &str,
63        block_meta: &crate::backend::obj::MetaMapType,
64        env_vars: &mut std::collections::HashMap<String, String>,
65        working_dir: &str,
66        broker: Arc<crate::backend::mps::Broker>,
67        filestore: Arc<crate::backend::storage::filestore::FileStore>,
68        mstore: Arc<crate::backend::storage::store::Store>,
69    ) -> Self {
70        let mut spec = ContainerSpec::of(block_meta, env_vars, working_dir);
71        spec.mount_spec.limits = crate::backend::container::limits::ContainerLimits::of_agent(&mstore, &crate::backend::obj::meta_get_string(block_meta, "agentId", ""));
72        // What `set_files` may upload from: the folder the container sees as /workspace.
73        crate::backend::spawn_env::workspaces::record_container_workspace(block_id, spec.mount_spec.workspace_host_dir.as_deref());
74        Self {
75            cm,
76            block_id: block_id.to_string(),
77            container_name: spec.container_name,
78            image: spec.image,
79            volumes: spec.volumes,
80            mount_spec: spec.mount_spec,
81            provider_id: spec.provider_id,
82            container_command: spec.container_command,
83            broker,
84            filestore,
85            mstore,
86        }
87    }
88}
89
90/// The adapter for the container agent in `block_meta`: its container is readied at the start of each
91/// turn, and a turn is a `docker exec` in it. See [`ContainerStartup::for_block`] for what `env_vars` and
92/// `working_dir` are used for.
93#[allow(clippy::too_many_arguments)]
94pub(crate) fn container_adapter_for_block(
95    cm: ContainerManager,
96    block_id: &str,
97    block_meta: &crate::backend::obj::MetaMapType,
98    env_vars: &mut std::collections::HashMap<String, String>,
99    working_dir: &str,
100    broker: Arc<crate::backend::mps::Broker>,
101    filestore: Arc<crate::backend::storage::filestore::FileStore>,
102    mstore: Arc<crate::backend::storage::store::Store>,
103) -> ContainerAdapter {
104    let startup = ContainerStartup::for_block(cm.clone(), block_id, block_meta, env_vars, working_dir, broker, filestore, mstore);
105    let image = resolve_container_image(&startup.image);
106    let launch = ContainerLaunch {
107        cm,
108        container_name: startup.container_name.clone(),
109        container_command: startup.container_command.clone(),
110        provider_id: startup.provider_id.clone(),
111        startup: startup_step(startup),
112    };
113    tracing::info!(
114        block_id = %block_id,
115        container = %launch.container_name,
116        image = %image,
117        "container agent turn: bollard exec (env via Docker socket, not argv)",
118    );
119    ContainerAdapter::with_launch(launch)
120}
121
122/// What a container agent's pane says about its container, apart from the services that run it.
123struct ContainerSpec {
124    container_name: String,
125    image: String,
126    volumes: Vec<String>,
127    mount_spec: ContainerMountSpec,
128    provider_id: String,
129    container_command: String,
130}
131
132impl ContainerSpec {
133    fn of(block_meta: &crate::backend::obj::MetaMapType, env_vars: &mut std::collections::HashMap<String, String>, working_dir: &str) -> Self {
134        use crate::backend::obj::meta_get_string;
135        // The agent id (a UUID) is always valid as a Docker name; a display name can have spaces.
136        let agent_id = meta_get_string(block_meta, "agentId", "");
137        let volumes_json = meta_get_string(block_meta, "agent:container_volumes", "[]");
138        // `CLAUDE_CONFIG_DIR` is a host path, host-only (`agent_env_scope`), so mounting it is the
139        // only way the in-container CLI sees the bound account's credentials.
140        let mount_spec = ContainerMountSpec::for_agent(env_vars, working_dir);
141        // A container can't reach the loopback address this process sees.
142        if let Ok(local_url) = std::env::var("AGENTMUX_LOCAL_URL") {
143            env_vars.insert("AGENTMUX_LOCAL_URL".to_string(), RuntimeKind::Container.adapter().srv_endpoint(&local_url));
144        }
145        Self {
146            container_name: crate::backend::container::container_name_for_slug(&agent_id),
147            image: meta_get_string(block_meta, "agent:container_image", ""),
148            volumes: serde_json::from_str(&volumes_json).unwrap_or_default(),
149            mount_spec,
150            provider_id: meta_get_string(block_meta, "agentProvider", "claude"),
151            container_command: meta_get_string(block_meta, "agent:container_command", "claude"),
152        }
153    }
154}
155
156/// Whether a pre-start applies: a container agent whose pane has run nothing yet. A pane that is running a
157/// turn, or has run one, is left to the turn's own start-up.
158fn prestart_applies(agent_mode: &str, runtime_status: &str) -> bool {
159    RuntimeKind::of_agent_mode(agent_mode).is_container() && runtime_status == crate::backend::blockcontroller::STATUS_INIT
160}
161
162/// Where a block's pre-start is.
163enum Prestart {
164    /// Preparing; no task yet.
165    Preparing,
166    /// The pane closed before the task existed: it must not start one.
167    Cancelled,
168    /// Running; closing the pane aborts it.
169    Running(tokio::task::AbortHandle),
170}
171
172/// Blocks whose pre-start is under way, so a second request for one does nothing, and how to end it.
173static PRESTARTING: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, Prestart>>> =
174    std::sync::LazyLock::new(Default::default);
175
176struct PrestartSlot(String);
177
178impl PrestartSlot {
179    fn take(block_id: &str) -> Option<Self> {
180        let mut map = PRESTARTING.lock().unwrap_or_else(|e| e.into_inner());
181        match map.entry(block_id.to_string()) {
182            std::collections::hash_map::Entry::Occupied(_) => None,
183            std::collections::hash_map::Entry::Vacant(v) => {
184                v.insert(Prestart::Preparing);
185                Some(Self(block_id.to_string()))
186            }
187        }
188    }
189
190    /// Whether the pane closed while this was preparing.
191    fn cancelled(&self) -> bool {
192        matches!(PRESTARTING.lock().unwrap_or_else(|e| e.into_inner()).get(&self.0), Some(Prestart::Cancelled))
193            || crate::backend::blockcontroller::is_closing(&self.0)
194    }
195
196    /// The task exists. If the pane closed since `cancelled` was asked, it ends here.
197    fn running(&self, task: tokio::task::AbortHandle) {
198        let mut map = PRESTARTING.lock().unwrap_or_else(|e| e.into_inner());
199        match map.get_mut(&self.0) {
200            Some(state @ Prestart::Preparing) => *state = Prestart::Running(task),
201            _ => task.abort(),
202        }
203    }
204}
205
206/// End the pre-start of a pane that is closing, so a start still pulling its image can't create and run a
207/// container for a pane that is gone. The caller stops the container afterwards. Nothing under way: nothing done.
208pub(crate) fn cancel_prestart(block_id: &str) {
209    // Aborted outside the lock: ending the task drops its slot, which takes the lock.
210    let task = match PRESTARTING.lock().unwrap_or_else(|e| e.into_inner()).get_mut(block_id) {
211        Some(state @ Prestart::Preparing) => {
212            *state = Prestart::Cancelled;
213            None
214        }
215        Some(Prestart::Running(task)) => Some(task.clone()),
216        _ => None,
217    };
218    if let Some(task) = task {
219        task.abort();
220    }
221}
222
223impl Drop for PrestartSlot {
224    fn drop(&mut self) {
225        PRESTARTING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
226    }
227}
228
229/// Begin a new container agent's start (image, container, CLI) in the background, so its first message
230/// finds a warm container. Only for a container agent whose pane has run nothing, and only once its account
231/// resolves (the mounts carry the account's credentials: starting without them would make the wrong
232/// container). The first message's own start-up shares the container's locks, so nothing is done twice.
233pub(crate) async fn prestart(deps: &super::input::AgentTurnDeps, block_id: String) -> Result<(), String> {
234    let Some(block) = deps.mstore.get::<crate::backend::obj::Block>(&block_id).map_err(|e| format!("prestart: load block: {e}"))? else {
235        return Ok(());
236    };
237    let agent_mode = crate::backend::obj::meta_get_string(&block.meta, "agentMode", "host");
238    let status = crate::backend::blockcontroller::get_controller(&block_id).map(|c| c.get_runtime_status().shellprocstatus);
239    if !prestart_applies(&agent_mode, status.as_deref().unwrap_or("")) {
240        return Ok(());
241    }
242    let Some(slot) = PrestartSlot::take(&block_id) else { return Ok(()) };
243    let began = Instant::now();
244    let cm = match deps.container_manager.get_or_explain().await {
245        Ok(cm) => cm,
246        Err(e) => {
247            // Nobody asked for this start, so no turn ends with the reason: the pane's start row says it.
248            let provider = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "claude");
249            let frame = cli_notice::container_start_frame(&uuid::Uuid::new_v4().to_string(), &provider, "", ContainerStartState::Failed, None, None, Some(&e));
250            cli_notice::append_to_pane(&deps.broker, &deps.filestore_gate, &deps.mstore, &block_id, &frame);
251            return Err(e);
252        }
253    };
254    let working_dir = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
255    let mut env_vars = match crate::backend::spawn_env::build::build_persistent_spawn_env(
256        deps.mstore.clone(),
257        deps.id_store.clone(),
258        deps.identity_store.clone(),
259        Some(deps.broker.clone()),
260        &block.meta,
261        &block_id,
262        &deps.auth_key,
263        crate::backend::blockcontroller::cmd_env_of(&block.meta),
264    )
265    .await
266    {
267        Ok(env) => env,
268        Err(e) => {
269            tracing::info!(block_id = %block_id, error = %e, "container pre-start skipped: no account to start it with yet");
270            return Ok(());
271        }
272    };
273    let startup = ContainerStartup::for_block(
274        cm,
275        &block_id,
276        &block.meta,
277        &mut env_vars,
278        &working_dir,
279        deps.broker.clone(),
280        deps.filestore_gate.clone(),
281        deps.mstore.clone(),
282    );
283    // The pane may have closed while the account and mounts were resolved; closing sees the entry from here on.
284    if slot.cancelled() {
285        return Ok(());
286    }
287    // The slot outlives the task (the waiter below drops it), so the handle is always set on a live entry.
288    let task = tokio::spawn({
289        let slot_block = block_id.clone();
290        async move {
291            // A failure is on the pane as the start row's Failed state; the first message tries again.
292            match startup.run_quietly().await {
293                Ok(()) => startup.note_waiting_for_message(began.elapsed().as_secs_f64()),
294                Err(e) => tracing::info!(block_id = %slot_block, error = %e, "container pre-start did not finish"),
295            }
296        }
297    });
298    slot.running(task.abort_handle());
299    tokio::spawn(async move {
300        // Holds the slot until the pre-start ends, however it ends (finished, failed or aborted).
301        let _ = task.await;
302        drop(slot);
303    });
304    Ok(())
305}
306
307/// The `result` frame that ends a turn with an error and carries `message`.
308pub(crate) fn error_result_frame(message: &str) -> Value {
309    json!({
310        "type": "result",
311        "is_error": true,
312        "subtype": "error_during_execution",
313        "error": {"message": format!("[AgentMux] {message}")}
314    })
315}
316
317/// Runs `f` when dropped unless [disarmed](Self::disarm): closes a pane row
318/// whose work was cancelled (a stop drops the start-up future mid-way).
319struct IfDropped<F: Fn()> {
320    armed: AtomicBool,
321    f: F,
322}
323
324impl<F: Fn()> IfDropped<F> {
325    fn new(f: F) -> Self {
326        Self { armed: AtomicBool::new(true), f }
327    }
328
329    fn disarm(&self) {
330        self.armed.store(false, Ordering::Relaxed);
331    }
332}
333
334impl<F: Fn()> Drop for IfDropped<F> {
335    fn drop(&mut self) {
336        if self.armed.load(Ordering::Relaxed) {
337            (self.f)();
338        }
339    }
340}
341
342/// What a container agent's turn does to its workspace folder on the host before the container has it: the
343/// folder is marked as a container agent's, so a host agent given it later gets only the MCP servers AgentMux
344/// writes (`mcp_folder_rule`), and signing keys an earlier launch left in its `.mcp.json` come out.
345fn before_the_container_has_the_folder(dir: &str) {
346    crate::backend::mcp_folder_rule::mark(dir);
347    crate::backend::mcp_json_identity::strip_workspace_signing_keys(dir);
348}
349
350impl ContainerStartup {
351    /// Start the container, then make sure the provider CLI is in it. The pane
352    /// shows each step that takes time (frames persisted, so they survive a
353    /// reload). On failure it gets a plain-language error frame and the same
354    /// text is returned.
355    pub(crate) async fn run(&self) -> Result<(), String> {
356        self.run_reporting(true).await
357    }
358
359    /// [`run`](Self::run) for a start nobody asked for yet (the pre-start): a failure shows as its start or
360    /// install row, with no error result on the pane, since no turn is there to end with one.
361    pub(crate) async fn run_quietly(&self) -> Result<(), String> {
362        // No turn holds the container here, so an agent whose container runs an older agent image than this
363        // AgentMux moves to the current one before it starts, and the pane says so. (A turn's own start holds the
364        // update gate shared for the whole turn, so it cannot do this: it would always find the gate taken.)
365        crate::server::app_api::container_update::update_if_idle(
366            &self.cm,
367            &self.container_name,
368            &self.image,
369            &self.provider_id,
370            &self.block_id,
371            &self.broker,
372            &self.filestore,
373            &self.mstore,
374        )
375        .await;
376        self.run_reporting(false).await
377    }
378
379    async fn run_reporting(&self, report_failure: bool) -> Result<(), String> {
380        // The workspace is mounted into the container: signing keys an earlier launch wrote into its
381        // .mcp.json come out before it starts (and a launch no longer writes them), and it is marked.
382        if let Some(dir) = self.mount_spec.workspace_host_dir.clone() {
383            let _ = tokio::task::spawn_blocking(move || before_the_container_has_the_folder(&dir)).await;
384        }
385        // The container is never given the account's own credentials file: its login is staged as a copy for this container.
386        let mut mount_spec = self.mount_spec.clone();
387        if mount_spec.claude_config_host_dir.is_none() {
388            if let Some(config_dir) = mount_spec.staged_login_config_dir.clone() {
389                match self.cm.stage_login(&self.container_name, &config_dir, &mount_spec).await {
390                    Ok(dir) => mount_spec.claude_config_host_dir = Some(dir),
391                    // Stop before anything is pulled: a container with no login can only sit there signed out.
392                    Err(reason) => return Err(self.fail(&ContainerError::NoLogin(reason), report_failure)),
393                }
394            }
395        }
396        let image = resolve_container_image(&self.image);
397        let began = Instant::now();
398        let start_id = uuid::Uuid::new_v4().to_string();
399        // Whether anything was shown: a container that was already up says
400        // nothing, so a normal turn gets no start-up row.
401        let shown = AtomicBool::new(false);
402        let start_row = |state: ContainerStartState, percent: Option<u8>, image: &str, error: Option<&str>| {
403            let seconds = matches!(state, ContainerStartState::Ready).then(|| began.elapsed().as_secs_f64());
404            let frame = cli_notice::container_start_frame(&start_id, &self.provider_id, image, state, percent, seconds, error);
405            cli_notice::append_to_pane(&self.broker, &self.filestore, &self.mstore, &self.block_id, &frame);
406        };
407        // A stop drops this future while the row says "Downloading…"; the
408        // guard then ends that row so a reload doesn't show it for good.
409        let row_open = IfDropped::new(|| {
410            if shown.load(Ordering::Relaxed) {
411                start_row(ContainerStartState::Failed, None, &image, Some("Stopped before the container was ready"));
412            }
413        });
414        let observe = |event: StartEvent<'_>| {
415            shown.store(true, Ordering::Relaxed);
416            match event {
417                StartEvent::Pulling { image, progress } => {
418                    start_row(ContainerStartState::Pulling, progress.map(|p| p.percent()), image, None)
419                }
420                StartEvent::Starting => start_row(ContainerStartState::Starting, None, &image, None),
421            }
422        };
423        if let Err(e) = self.ensure_container(&image, &mount_spec, &observe).await {
424            if shown.load(Ordering::Relaxed) {
425                start_row(ContainerStartState::Failed, None, &image, Some(&e.user_message()));
426            }
427            row_open.disarm();
428            return Err(self.fail(&e, report_failure));
429        }
430        // Dev servers the agent asked to have kept up come back with the container.
431        crate::backend::dev_keepalive::restore_in_background(&self.cm, &self.container_name);
432        self.note_large_caches();
433        if shown.load(Ordering::Relaxed) {
434            start_row(ContainerStartState::Ready, None, &image, None);
435        } else {
436            let (cm, name) = (&self.cm, &self.container_name);
437            crate::server::app_api::container_update::note_outdated(cm, name, &self.image, &self.provider_id, &self.block_id, &self.broker, &self.filestore, &self.mstore).await;
438        }
439        row_open.disarm();
440
441        let Some(install) = CliInstall::for_provider(&self.provider_id, &self.container_command) else {
442            return Ok(());
443        };
444        let install_id = uuid::Uuid::new_v4().to_string();
445        let notice = |state: InstallState, seconds: Option<f64>, error: Option<&str>| {
446            let frame = cli_notice::install_frame(&install_id, &install.provider_id, &install.version, state, seconds, error);
447            cli_notice::append_to_pane(&self.broker, &self.filestore, &self.mstore, &self.block_id, &frame);
448        };
449
450        let started_install = AtomicBool::new(false);
451        // Same for a stop during the install, which also reaps it in the container.
452        let install_open = IfDropped::new(|| {
453            if started_install.load(Ordering::Relaxed) {
454                notice(InstallState::Failed, None, Some("Stopped before the install finished"));
455            }
456        });
457        let outcome = self
458            .cm
459            .provision_cli(&self.container_name, &install, || {
460                started_install.store(true, Ordering::Relaxed);
461                notice(InstallState::Installing, None, None);
462            })
463            .await;
464        install_open.disarm();
465        match outcome {
466            Ok(CliProvision::Present) => Ok(()),
467            Ok(CliProvision::Installed { seconds }) => {
468                notice(InstallState::Installed, Some(seconds), None);
469                Ok(())
470            }
471            Err(e) => {
472                if started_install.load(Ordering::Relaxed) {
473                    let detail = match &e {
474                        ContainerError::CliInstall { detail, .. } => detail.clone(),
475                        other => other.to_string(),
476                    };
477                    notice(InstallState::Failed, None, Some(&detail));
478                }
479                Err(self.fail(&e, report_failure))
480            }
481        }
482    }
483
484    /// The container up with its tools in it. A container started anew ran nothing before, so the rows the pane's
485    /// dock still holds for what ran in the old one can only be stale: they end here.
486    async fn ensure_container(&self, image: &str, mount_spec: &ContainerMountSpec, observe: StartObserver<'_>) -> Result<(), ContainerError> {
487        let started = self.cm.ensure_running_observed(&self.container_name, image, &self.volumes, &[], mount_spec, observe).await?;
488        if started {
489            crate::backend::background_task_exit::end_for_restarted_container(&self.mstore, &self.broker, &self.block_id);
490        }
491        self.cm.check_image_tools(&self.container_name, image).await
492    }
493
494    /// Once per agent per run: a row in the pane when the agent's cache volumes have grown past the warning level.
495    /// Docker's disk-usage report can be slow, so it runs on its own.
496    fn note_large_caches(&self) {
497        let (cm, name, block_id) = (self.cm.clone(), self.container_name.clone(), self.block_id.clone());
498        let (broker, filestore, mstore) = (self.broker.clone(), self.filestore.clone(), self.mstore.clone());
499        tokio::spawn(async move {
500            crate::server::app_api::container_caches::note_if_large(&cm, &name, &block_id, &broker, &filestore, &mstore).await;
501        });
502    }
503
504    /// A pre-start of a fresh pane that finished with no message on its way: the pane would sit silent, so say it is ready
505    /// and waiting for the user. Nothing is said when a turn has begun (its own rows speak) or the pane has closed.
506    fn note_waiting_for_message(&self, seconds: f64) {
507        let status = crate::backend::blockcontroller::get_controller(&self.block_id).map(|c| c.get_runtime_status().shellprocstatus);
508        if !prestart_applies("container", status.as_deref().unwrap_or("")) {
509            return;
510        }
511        // A resumed pane has its history and composer on screen, and is not "starting": it gets no row at each reopen.
512        let resumed = match self.mstore.get::<crate::backend::obj::Block>(&self.block_id) {
513            Ok(Some(block)) => !crate::backend::obj::meta_get_string(&block.meta, "agent:sessionid", "").is_empty(),
514            _ => true,
515        };
516        if resumed {
517            return;
518        }
519        let frame = cli_notice::agent_ready_frame(&uuid::Uuid::new_v4().to_string(), &self.provider_id, seconds);
520        cli_notice::append_to_pane(&self.broker, &self.filestore, &self.mstore, &self.block_id, &frame);
521    }
522
523    /// Log `e`, write its plain-language message to the pane, and return it.
524    fn fail(&self, e: &ContainerError, report: bool) -> String {
525        tracing::warn!(block_id = %self.block_id, container = %self.container_name, error = %e, "container agent could not start");
526        let message = e.user_message();
527        if !report {
528            return message;
529        }
530        let line = format!("{}\n", error_result_frame(&message));
531        let zone = crate::backend::transcript::append::resolve_global_output_zone(
532            &Some(self.mstore.clone()),
533            &self.block_id,
534        );
535        crate::backend::blockcontroller::shell::handle_append_block_file(
536            &self.broker,
537            &self.block_id,
538            crate::backend::blockcontroller::subprocess::SUBPROCESS_OUTPUT_SUBJECT,
539            line.as_bytes(),
540            Some(&self.filestore),
541            zone.as_deref(),
542        );
543        message
544    }
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    #[test]
552    fn a_prestart_applies_only_to_a_container_pane_that_has_run_nothing() {
553        use crate::backend::blockcontroller::{STATUS_DONE, STATUS_INIT, STATUS_RUNNING};
554        assert!(prestart_applies("container", STATUS_INIT));
555        assert!(!prestart_applies("container", STATUS_RUNNING), "a turn is running: its own start-up has it");
556        assert!(!prestart_applies("container", STATUS_DONE), "a turn has run");
557        assert!(!prestart_applies("container", ""), "no controller yet");
558        assert!(!prestart_applies("host", STATUS_INIT));
559    }
560
561    #[test]
562    fn a_second_prestart_for_the_same_block_does_nothing_until_the_first_ends() {
563        let first = PrestartSlot::take("block-prestart-slot").expect("the first takes it");
564        assert!(PrestartSlot::take("block-prestart-slot").is_none());
565        assert!(PrestartSlot::take("block-prestart-other").is_some(), "another block is its own");
566        drop(first);
567        assert!(PrestartSlot::take("block-prestart-slot").is_some(), "free again once it ended");
568    }
569
570    #[tokio::test]
571    async fn closing_a_pane_ends_its_prestart_and_frees_its_slot() {
572        let slot = PrestartSlot::take("block-prestart-cancel").expect("the first takes it");
573        assert!(!slot.cancelled());
574        let task = tokio::spawn(std::future::pending::<()>());
575        slot.running(task.abort_handle());
576        let waiter = tokio::spawn(async move {
577            let _ = task.await;
578            drop(slot);
579        });
580        cancel_prestart("block-prestart-cancel");
581        waiter.await.unwrap();
582        assert!(PrestartSlot::take("block-prestart-cancel").is_some(), "free once it ended");
583        // Nothing under way, or no such block: nothing happens.
584        cancel_prestart("block-prestart-cancel");
585        cancel_prestart("block-never-prestarted");
586    }
587
588    #[tokio::test]
589    async fn a_pane_closed_while_the_prestart_prepares_never_starts_it() {
590        let slot = PrestartSlot::take("block-prestart-early").expect("taken");
591        cancel_prestart("block-prestart-early");
592        assert!(slot.cancelled(), "the prestart sees the close before it spawns");
593        // Closed in the instant between that check and the spawn: the task ends as soon as it is registered.
594        let task = tokio::spawn(std::future::pending::<()>());
595        slot.running(task.abort_handle());
596        assert!(task.await.unwrap_err().is_cancelled());
597        drop(slot);
598        assert!(PrestartSlot::take("block-prestart-early").is_some(), "free again");
599    }
600
601    #[test]
602    fn the_spec_comes_from_the_panes_meta_and_the_env_the_turn_would_use() {
603        let mut meta = crate::backend::obj::MetaMapType::new();
604        meta.insert("agentId".into(), json!("3f2a-agent"));
605        meta.insert("agent:container_image".into(), json!("example/agent:1"));
606        meta.insert("agent:container_volumes".into(), json!(r#"["/a:/b"]"#));
607        meta.insert("agentProvider".into(), json!("codex"));
608        meta.insert("agent:container_command".into(), json!("codex"));
609        let mut env = std::collections::HashMap::new();
610        let spec = ContainerSpec::of(&meta, &mut env, "/work");
611        assert_eq!(spec.container_name, crate::backend::container::container_name_for_slug("3f2a-agent"));
612        assert_eq!((spec.image.as_str(), spec.provider_id.as_str(), spec.container_command.as_str()), ("example/agent:1", "codex", "codex"));
613        assert_eq!(spec.volumes, vec!["/a:/b".to_string()]);
614        // Nothing set: the defaults the turn uses.
615        let bare = ContainerSpec::of(&crate::backend::obj::MetaMapType::new(), &mut env, "");
616        assert_eq!((bare.provider_id.as_str(), bare.container_command.as_str(), bare.image.as_str()), ("claude", "claude", ""));
617    }
618
619    #[test]
620    fn the_error_frame_is_a_terminal_error_result_with_the_agentmux_prefix() {
621        let frame = error_result_frame("Couldn't start the container for this agent: x");
622        assert_eq!(frame["type"], "result");
623        assert_eq!(frame["is_error"], true);
624        assert_eq!(
625            frame["error"]["message"],
626            "[AgentMux] Couldn't start the container for this agent: x"
627        );
628    }
629}