Skip to main content

agentmux_srv/server/app_api/
container_update.rs

1//! A container agent whose container runs an older agent image than this AgentMux: telling its
2//! pane once, and updating the container when asked (a button in the pane, or `Agents
3//! update_container`). See `backend::container::drift` for what an update does. `Agents update_container` with a
4//! `container_image` also changes which of the two shipped images the agent runs.
5
6use std::collections::HashSet;
7use std::sync::{Arc, Mutex, OnceLock};
8
9use axum::http::StatusCode;
10
11use crate::backend::cli_notice;
12use crate::backend::container::ContainerManager;
13use crate::backend::container::image::{current_image_for, is_agent_base_image, resolve_container_image};
14use crate::server::AppState;
15
16/// The version this AgentMux ships the agent image for.
17const CURRENT: &str = env!("CARGO_PKG_VERSION");
18
19/// Containers (by name and running version) whose pane has been told, so one srv run says it
20/// once per container.
21fn told() -> std::sync::MutexGuard<'static, HashSet<String>> {
22    static TOLD: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
23    TOLD.get_or_init(Default::default).lock().unwrap()
24}
25
26fn already_told(container_name: &str, running: &str) -> bool {
27    told().contains(&format!("{container_name}@{running}"))
28}
29
30/// Whether the container named `container_name` runs another image version than `current`, and has
31/// not been reported yet. Marks it reported.
32fn first_report(container_name: &str, running: &str, current: &str) -> bool {
33    running != current && told().insert(format!("{container_name}@{running}"))
34}
35
36/// Whether this AgentMux's own agent image of the kind `configured` (its stored `agent:container_image`) can be
37/// had: on this machine, or from the registry. When it can't (a build ahead of its release), a container is on
38/// the floating tag because nothing newer exists.
39async fn current_image_available(cm: &ContainerManager, configured: &str) -> bool {
40    let image = current_image_for(&resolve_container_image(configured));
41    cm.has_image_locally(&image).await
42        || crate::backend::registry_probe::probe_anonymous(&image).await == crate::backend::rpc_types::ContainerImageAccess::Public
43}
44
45/// [`current_image_available`] for the check made on every turn: a registry answer is kept for a
46/// while, so a slow or unreachable registry does not delay each message.
47async fn current_image_available_cached(cm: &ContainerManager, configured: &str) -> bool {
48    // By the image asked about: the base and the developer variant are two registry answers.
49    static SEEN: OnceLock<Mutex<std::collections::HashMap<String, (std::time::Instant, bool)>>> = OnceLock::new();
50    const KEEP: std::time::Duration = std::time::Duration::from_secs(600);
51    let seen = SEEN.get_or_init(Default::default);
52    let key = current_image_for(&resolve_container_image(configured));
53    let kept = seen.lock().unwrap().get(&key).copied();
54    if let Some((at, available)) = kept {
55        if at.elapsed() < KEEP {
56            return available;
57        }
58    }
59    let available = current_image_available(cm, configured).await;
60    seen.lock().unwrap().insert(key, (std::time::Instant::now(), available));
61    available
62}
63
64/// Writes one pane row, and one log line, when an existing container runs another agent image
65/// version than this AgentMux.
66pub(crate) async fn note_outdated(
67    cm: &ContainerManager,
68    container_name: &str,
69    configured_image: &str,
70    provider: &str,
71    block_id: &str,
72    broker: &Arc<crate::backend::mps::Broker>,
73    filestore: &Arc<crate::backend::storage::filestore::FileStore>,
74    mstore: &Arc<crate::backend::storage::store::Store>,
75) {
76    let Some(running) = cm.base_image_version(container_name).await else { return };
77    if running == CURRENT || already_told(container_name, &running) || !current_image_available_cached(cm, configured_image).await {
78        return;
79    }
80    if !first_report(container_name, &running, CURRENT) {
81        return;
82    }
83    tracing::info!(container = container_name, running = %running, current = CURRENT, "container runs an older agent image than this AgentMux");
84    let frame = cli_notice::container_image_frame(provider, block_id, "outdated", &running, CURRENT);
85    cli_notice::append_to_pane(broker, filestore, mstore, block_id, &frame);
86}
87
88/// Why an agent configured with `configured` (its stored `agent:container_image`, empty for the default) can't be
89/// moved to this AgentMux's agent image: it runs its own image, or is pinned to another version.
90fn image_blocks_update(configured: &str) -> Option<String> {
91    let image = resolve_container_image(configured);
92    if !is_agent_base_image(&image) {
93        return Some(format!("this agent runs its own image ({image}); updating the container would start it from the same image"));
94    }
95    // `resolve_container_image` turns the default and `:latest` into this version's tag, so any
96    // other reference (another version, a digest, another tag) is a pin the update would keep.
97    if image != current_image_for(&image) {
98        return Some(format!("this agent is pinned to {image}; change its container image to update it"));
99    }
100    None
101}
102
103/// Whether version `running` is older than `current`, comparing their numeric dotted parts (`0.59.41` < `0.60.2`).
104/// A version that does not parse is not older: it is left alone rather than replaced.
105fn is_older(running: &str, current: &str) -> bool {
106    fn parts(v: &str) -> Option<Vec<u64>> {
107        let core = v.trim().trim_start_matches('v').split(['-', '+']).next()?;
108        core.split('.').map(|p| p.parse::<u64>().ok()).collect()
109    }
110    match (parts(running), parts(current)) {
111        (Some(r), Some(c)) => r < c,
112        _ => false,
113    }
114}
115
116/// The container's update gate taken exclusively, or None while a turn (or another update) holds it.
117fn take_update_gate(container_name: &str) -> Option<tokio::sync::OwnedRwLockWriteGuard<()>> {
118    crate::backend::container::drift::update_gate(container_name).try_write_owned().ok()
119}
120
121/// Moves an idle agent's container to this AgentMux's agent image: when it runs an older one, the agent follows
122/// the default image (no pin, no image of its own), the current image is already on this machine, and no turn is
123/// using the container. The container is removed (workspace, memory and the CLI volume stay; tools installed inside it are
124/// installed again) and the pane is told; the start that follows creates it from the current image. Returns whether
125/// it did. Anything else leaves the "outdated" row and its button as they are.
126///
127/// Run where nothing is mid-turn (the pre-start): a turn holds the update gate shared for its whole length, so
128/// called from inside a turn this finds the gate taken and does nothing.
129#[allow(clippy::too_many_arguments)]
130pub(crate) async fn update_if_idle(
131    cm: &ContainerManager,
132    container_name: &str,
133    configured_image: &str,
134    provider: &str,
135    block_id: &str,
136    broker: &Arc<crate::backend::mps::Broker>,
137    filestore: &Arc<crate::backend::storage::filestore::FileStore>,
138    mstore: &Arc<crate::backend::storage::store::Store>,
139) -> bool {
140    if image_blocks_update(configured_image).is_some() {
141        return false;
142    }
143    // Taken first: a turn holds the gate shared, and then nothing below is worth asking the daemon.
144    let Some(_updating) = take_update_gate(container_name) else { return false };
145    let Some(running) = cm.base_image_version(container_name).await else { return false };
146    // Only forward: after a downgrade the container is on a NEWER image, which a banner reports but an update would
147    // replace with an older one. And only to an image already on this machine: the container is removed before the
148    // start pulls anything, so a download that then failed (offline, a slow registry) would leave an agent that
149    // used to run with nothing to run. When the image is not here yet, the banner and its button stay.
150    if !is_older(&running, CURRENT) || !cm.has_image_locally(&current_image_for(&resolve_container_image(configured_image))).await {
151        return false;
152    }
153    if let Err(e) = cm.update_container(container_name).await {
154        tracing::warn!(container = container_name, error = %e.user_message(), "could not move an idle container to the current agent image");
155        return false;
156    }
157    told().retain(|k| !k.starts_with(&format!("{container_name}@")));
158    let frame = cli_notice::container_image_frame(provider, block_id, "auto_updated", &running, CURRENT);
159    cli_notice::append_to_pane(broker, filestore, mstore, block_id, &frame);
160    tracing::info!(block_id, container = container_name, from = %running, to = CURRENT, "idle container moved to the current agent image");
161    true
162}
163
164/// Removes `block_id`'s container so its next message starts it from this AgentMux's agent
165/// image. Only between turns. Returns the image version the next start uses.
166pub(crate) async fn update_for_block(state: &AppState, block_id: &str) -> Result<String, String> {
167    use crate::backend::obj::{meta_get_string, Block};
168    let block = state.mstore.get::<Block>(block_id).ok().flatten().ok_or("no such pane")?;
169    if !crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container() {
170        return Err("this agent does not run in a container".into());
171    }
172    let configured = meta_get_string(&block.meta, "agent:container_image", "");
173    if let Some(why) = image_blocks_update(&configured) {
174        return Err(why);
175    }
176    let agent_id = meta_get_string(&block.meta, "agentId", "");
177    let container_name = crate::backend::container::container_name_for_slug(&agent_id);
178    let cm = state.container_manager.get().await.ok_or("Docker is not available on this machine")?;
179    if !current_image_available(&cm, &configured).await {
180        return Err(format!("the agent image for AgentMux {CURRENT} is not available yet, so a new container would start from the same image"));
181    }
182    // Every turn of this agent holds the gate shared, and one that starts meanwhile is turned away.
183    let gate = crate::backend::container::drift::update_gate(&container_name);
184    let _updating = gate.try_write_owned().map_err(|_| "a turn is running; update the container when it has finished")?;
185    cm.update_container(&container_name).await.map_err(|e| e.user_message())?;
186    told().retain(|k| !k.starts_with(&format!("{container_name}@")));
187    let provider = meta_get_string(&block.meta, "agentProvider", "claude");
188    let frame = cli_notice::container_image_frame(&provider, block_id, "updated", "", CURRENT);
189    cli_notice::append_to_pane(&state.broker, &state.filestore, &state.mstore, block_id, &frame);
190    tracing::info!(block_id, container = %container_name, "container removed; the next message starts it from the current agent image");
191    Ok(CURRENT.to_string())
192}
193
194/// Changes which agent image the container agent `uid` runs: the definition (so every later open and the next
195/// open pane agree), the open pane's own record of it, and the container, removed so that the next message creates
196/// it from the new image. Only between turns, and only to one of the two images AgentMux ships; an agent's own image
197/// is set by editing its definition in the window.
198async fn set_image(
199    state: &AppState,
200    uid: &str,
201    def: &crate::backend::storage::AgentDefinition,
202    requested: &str,
203    by: &str,
204) -> Result<serde_json::Value, crate::server::app_api::container_limits::Refusal> {
205    use crate::server::app_api::container_limits::Refusal;
206    let fail = |status: StatusCode, message: String| -> Refusal { (status, message) };
207    let image = crate::server::agent_handlers::chosen_container_image(Some(requested), "container", "")
208        .map_err(|m| fail(StatusCode::BAD_REQUEST, m))?;
209    let container_name = crate::backend::container::container_name_for_slug(uid);
210    // Every turn of this agent holds the gate shared, and one that starts meanwhile is turned away.
211    let gate = crate::backend::container::drift::update_gate(&container_name);
212    let _changing = gate
213        .try_write_owned()
214        .map_err(|_| fail(StatusCode::CONFLICT, "a turn is running; change the container image when it has finished".to_string()))?;
215
216    let was = def.container_image.clone();
217    let mut changed = def.clone();
218    changed.container_image = image.clone();
219    state
220        .mstore
221        .agent_def_update(&mut changed)
222        .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("container image: {e}")))?;
223
224    // The agent's pane keeps its own record of the image, which each turn reads. Every pane of the agent gets
225    // it, found by the agent and not by its live registration: a pane with no registration (stopped, or
226    // registered under another name) kept the old image, and its next start made the container from that (#47725).
227    let registration = crate::backend::reactive::handler::get_global_handler().get_agent(&def.slug);
228    let mut panes: Vec<String> = crate::server::app_api::agent_block::agent_blocks_by_uid(&state.mstore, uid)
229        .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("container image: {e}")))?
230        .into_iter()
231        .map(|b| b.block.oid)
232        .collect();
233    if let Some(r) = registration.as_ref().filter(|r| !panes.contains(&r.block_id)) {
234        panes.push(r.block_id.clone());
235    }
236    let mut meta = crate::backend::obj::MetaMapType::new();
237    meta.insert("agent:container_image".to_string(), serde_json::json!(&image));
238    for block_id in &panes {
239        crate::server::service::object_helpers::update_object_meta(&state.mstore, &format!("block:{block_id}"), &meta)
240            .map_err(|e| fail(StatusCode::INTERNAL_SERVER_ERROR, format!("container image: the pane could not be updated: {e}")))?;
241    }
242
243    // The definition has changed, whatever happens to the container: say so now.
244    told().retain(|k| !k.starts_with(&format!("{container_name}@")));
245    broker_agents_changed(state);
246    let mut removed = false;
247    if let Some(cm) = state.container_manager.get().await {
248        match cm.update_container(&container_name).await {
249            Ok(()) => removed = true,
250            // Never started, or already removed: nothing stands in the way of the next start.
251            Err(e) if container_is_gone(&e) => {}
252            Err(e) => {
253                return Err(fail(
254                    StatusCode::CONFLICT,
255                    format!("the image is set to {image} but the old container is still in place ({}); run update_container again", e.user_message()),
256                ));
257            }
258        }
259    }
260    // The pane's notice says the container was updated, so it is added only when one was removed.
261    if let Some(registration) = registration.filter(|_| removed) {
262        let provider = match state.mstore.get::<crate::backend::obj::Block>(&registration.block_id) {
263            Ok(Some(block)) => crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "claude"),
264            _ => "claude".to_string(),
265        };
266        let frame = cli_notice::container_image_frame(&provider, &registration.block_id, "updated", "", CURRENT);
267        cli_notice::append_to_pane(&state.broker, &state.filestore, &state.mstore, &registration.block_id, &frame);
268    }
269    tracing::info!(agent = %def.slug, %by, from = %was, to = %image, container_removed = removed, "container image changed");
270    Ok(serde_json::json!({
271        "status": "image_set",
272        "agent": def.name,
273        "container_image": image,
274        "container_removed": removed,
275        "note": if removed {
276            "the agent's next message starts a new container from this image (its workspace, memory and CLI home are kept; tools installed inside the old container are gone)"
277        } else {
278            "no container was removed (Docker is not available here, or there was none); the agent's next start uses this image"
279        },
280    }))
281}
282
283/// Docker answers 404 when the container to remove does not exist.
284fn container_is_gone(e: &crate::backend::container::ContainerError) -> bool {
285    matches!(e, crate::backend::container::ContainerError::Docker(bollard::errors::Error::DockerResponseServerError { status_code: 404, .. }))
286}
287
288fn broker_agents_changed(state: &AppState) {
289    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
290}
291
292/// `POST /api/v1/agent/container/update`: `Agents update_container`, for the agent named in
293/// `agent`. With `container_image` (one of the two images AgentMux ships) it also changes the image first.
294#[derive(serde::Deserialize)]
295pub(crate) struct UpdateContainerRequest {
296    agent: String,
297    #[serde(default)]
298    container_image: Option<String>,
299}
300
301pub(crate) async fn handle_update_container(
302    axum::extract::State(state): axum::extract::State<AppState>,
303    caller: Option<axum::Extension<crate::server::caller::Caller>>,
304    axum::Json(req): axum::Json<UpdateContainerRequest>,
305) -> axum::response::Response {
306    use axum::response::IntoResponse;
307    if let Some(image) = req.container_image.as_deref() {
308        return match change_image(&state, caller.map(|axum::Extension(c)| c).as_ref(), req.agent.trim(), image).await {
309            Ok(body) => axum::Json(body).into_response(),
310            Err((status, message)) => (status, axum::Json(serde_json::json!({ "error": message }))).into_response(),
311        };
312    }
313    let target = req.agent.trim();
314    let registration = crate::backend::reactive::handler::get_global_handler().get_agent(target);
315    let Some(registration) = registration else {
316        let body = serde_json::json!({ "error": format!("no agent named {target} is open here") });
317        return (axum::http::StatusCode::NOT_FOUND, axum::Json(body)).into_response();
318    };
319    match update_for_block(&state, &registration.block_id).await {
320        Ok(version) => axum::Json(serde_json::json!({ "status": "updated", "next_start_uses": version })).into_response(),
321        Err(why) => (axum::http::StatusCode::CONFLICT, axum::Json(serde_json::json!({ "error": why }))).into_response(),
322    }
323}
324
325/// [`set_image`] for the agent `named` (an id or slug, open or not), asked for by `caller`. A container agent
326/// cannot change an image, its own included: like a container's limits, that is for a host agent, the steward or
327/// the operator.
328async fn change_image(
329    state: &AppState,
330    caller: Option<&crate::server::caller::Caller>,
331    named: &str,
332    image: &str,
333) -> Result<serde_json::Value, crate::server::app_api::container_limits::Refusal> {
334    let (uid, def) = crate::server::app_api::container_limits::container_agent(state, named)?;
335    let mut by = "you".to_string();
336    if let Some(caller_uid) = caller.and_then(crate::server::caller::Caller::uid) {
337        let caller_def = state
338            .mstore
339            .agent_def_get(caller_uid)
340            .ok()
341            .flatten()
342            .ok_or((StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine".to_string()))?;
343        if caller_def.runtime().is_container() {
344            return Err((
345                StatusCode::FORBIDDEN,
346                "CONTAINER_AGENT: a container agent cannot change a container's image, its own included. Ask a host agent, \
347                 your steward or the operator"
348                    .to_string(),
349            ));
350        }
351        by = caller_def.name;
352    }
353    set_image(state, &uid, &def, image, &by).await
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    fn seeded_block(state: &AppState) -> String {
361        let tab = state.mstore.get_all::<crate::backend::obj::Tab>().unwrap().into_iter().next().expect("seeded tab");
362        tab.blockids.first().expect("seeded agent block").clone()
363    }
364
365    fn set_meta(state: &AppState, block_id: &str, pairs: &[(&str, &str)]) {
366        let mut meta = crate::backend::obj::MetaMapType::new();
367        for (k, v) in pairs {
368            meta.insert((*k).to_string(), serde_json::json!(v));
369        }
370        crate::server::service::object_helpers::update_object_meta(&state.mstore, &format!("block:{block_id}"), &meta).unwrap();
371    }
372
373    #[tokio::test]
374    async fn only_a_container_agent_on_the_current_image_is_updated() {
375        let state = crate::server::tests::test_state();
376        let block_id = seeded_block(&state);
377        set_meta(&state, &block_id, &[("agentMode", "host")]);
378        let err = update_for_block(&state, &block_id).await.unwrap_err();
379        assert!(err.contains("does not run in a container"), "{err}");
380
381        // An agent on its own image is told: updating would start it from the same image.
382        set_meta(&state, &block_id, &[("agentMode", "container"), ("agent:container_image", "my/own:1")]);
383        let err = update_for_block(&state, &block_id).await.unwrap_err();
384        assert!(err.contains("runs its own image (my/own:1)"), "{err}");
385
386        // An agent pinned to another version of the image is told, not silently left or moved.
387        set_meta(&state, &block_id, &[("agentMode", "container"), ("agent:container_image", "ghcr.io/agentmuxai/agent-base:0.59.41")]);
388        let err = update_for_block(&state, &block_id).await.unwrap_err();
389        assert!(err.contains("pinned to ghcr.io/agentmuxai/agent-base:0.59.41"), "{err}");
390
391        // So is one pinned by digest: the next start would use the same image.
392        set_meta(&state, &block_id, &[("agentMode", "container"), ("agent:container_image", "ghcr.io/agentmuxai/agent-base@sha256:abc")]);
393        let err = update_for_block(&state, &block_id).await.unwrap_err();
394        assert!(err.contains("pinned to ghcr.io/agentmuxai/agent-base@sha256:abc"), "{err}");
395
396        assert!(update_for_block(&state, "no-such-block").await.unwrap_err().contains("no such pane"));
397    }
398
399    fn container_agent_def(state: &AppState, id: &str, agent_type: &str) -> crate::backend::storage::AgentDefinition {
400        let mut def = crate::backend::storage::agents::test_agent_def(id, &format!("Agent {id}"), "claude", agent_type, 1, "");
401        state.mstore.agent_def_insert(&mut def).unwrap();
402        def
403    }
404
405    fn stored_image(state: &AppState, id: &str) -> String {
406        state.mstore.agent_def_get(id).unwrap().unwrap().container_image
407    }
408
409    #[tokio::test]
410    async fn an_agents_image_becomes_one_of_the_two_shipped_images_and_nothing_else() {
411        use crate::backend::container::image::{DEFAULT_AGENT_IMAGE, DEFAULT_DEVELOPER_IMAGE};
412        let state = crate::server::tests::test_state();
413        let def = container_agent_def(&state, "cimg-1", "container");
414
415        let (status, why) = set_image(&state, &def.id, &def, "my/own:1", "tester").await.unwrap_err();
416        assert_eq!(status, StatusCode::BAD_REQUEST);
417        assert!(why.contains("container_image must be"), "{why}");
418        let (status, _) = set_image(&state, &def.id, &def, "ghcr.io/agentmuxai/agent-base:0.59.1", "tester").await.unwrap_err();
419        assert_eq!(status, StatusCode::BAD_REQUEST, "a pinned version is set on the definition in the window, not here");
420        assert_eq!(stored_image(&state, &def.id), "", "a refused image changes nothing");
421
422        let out = set_image(&state, &def.id, &def, DEFAULT_DEVELOPER_IMAGE, "tester").await.unwrap();
423        assert_eq!((out["status"].as_str(), out["container_image"].as_str()), (Some("image_set"), Some(DEFAULT_DEVELOPER_IMAGE)));
424        assert_eq!(out["container_removed"], false, "no Docker in this state: nothing to remove, and it says so");
425        assert_eq!(stored_image(&state, &def.id), DEFAULT_DEVELOPER_IMAGE);
426
427        set_image(&state, &def.id, &state.mstore.agent_def_get(&def.id).unwrap().unwrap(), &format!(" {DEFAULT_AGENT_IMAGE} "), "tester").await.unwrap();
428        assert_eq!(stored_image(&state, &def.id), DEFAULT_AGENT_IMAGE, "and back");
429    }
430
431    /// The pane's own record of the image is what the next start reads, so a changed image must reach it
432    /// even when the agent has no live registration (stopped, or registered under another name), or the next
433    /// container is made from the old image (#47725).
434    #[tokio::test]
435    async fn the_next_start_uses_the_new_image_even_for_a_pane_with_no_live_registration() {
436        use crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE;
437        let state = crate::server::tests::test_state();
438        let def = container_agent_def(&state, "cimg-pane", "container");
439        let block_id = seeded_block(&state);
440        set_meta(&state, &block_id, &[("agentId", &def.id), ("agentMode", "container"), ("agent:container_image", "ghcr.io/agentmuxai/agent-claude:latest")]);
441
442        set_image(&state, &def.id, &def, DEFAULT_DEVELOPER_IMAGE, "tester").await.unwrap();
443
444        let block = state.mstore.get::<crate::backend::obj::Block>(&block_id).unwrap().unwrap();
445        assert_eq!(crate::backend::obj::meta_get_string(&block.meta, "agent:container_image", ""), DEFAULT_DEVELOPER_IMAGE);
446        assert_eq!(stored_image(&state, &def.id), DEFAULT_DEVELOPER_IMAGE);
447    }
448
449    #[test]
450    fn a_container_that_does_not_exist_is_not_an_error_but_any_other_failure_is() {
451        use crate::backend::container::ContainerError;
452        let docker = |status_code: u16| ContainerError::Docker(bollard::errors::Error::DockerResponseServerError { status_code, message: "x".into() });
453        assert!(container_is_gone(&docker(404)), "no such container: nothing to remove");
454        assert!(!container_is_gone(&docker(500)));
455        assert!(!container_is_gone(&docker(409)), "a removal already in progress is not 'gone'");
456        assert!(!container_is_gone(&ContainerError::NotAvailable("Docker is down".into())));
457    }
458
459    #[tokio::test]
460    async fn the_image_is_not_changed_while_a_turn_runs() {
461        let state = crate::server::tests::test_state();
462        let def = container_agent_def(&state, "cimg-2", "container");
463        let name = crate::backend::container::container_name_for_slug(&def.id);
464        let turn = crate::backend::container::drift::update_gate(&name).try_read_owned().expect("a turn takes the gate shared");
465        let (status, why) = set_image(&state, &def.id, &def, crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE, "tester").await.unwrap_err();
466        assert_eq!(status, StatusCode::CONFLICT);
467        assert!(why.contains("a turn is running"), "{why}");
468        assert_eq!(stored_image(&state, &def.id), "");
469        drop(turn);
470        assert!(set_image(&state, &def.id, &def, crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE, "tester").await.is_ok());
471    }
472
473    #[tokio::test]
474    async fn only_a_container_agent_has_an_image_and_a_container_agent_cannot_change_one() {
475        let state = crate::server::tests::test_state();
476        let native = container_agent_def(&state, "cimg-native", "host");
477        let (status, why) = change_image(&state, None, &native.id, crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE).await.unwrap_err();
478        assert_eq!(status, StatusCode::CONFLICT);
479        assert!(why.contains("does not run in a container"), "{why}");
480
481        let target = container_agent_def(&state, "cimg-target", "container");
482        let container_caller = container_agent_def(&state, "cimg-caller-c", "container");
483        let as_container = crate::server::caller::Caller::Agent { uid: container_caller.id.clone() };
484        let (status, why) = change_image(&state, Some(&as_container), &target.id, crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE).await.unwrap_err();
485        assert_eq!(status, StatusCode::FORBIDDEN);
486        assert!(why.starts_with("CONTAINER_AGENT"), "{why}");
487        assert_eq!(stored_image(&state, &target.id), "");
488
489        let host_caller = container_agent_def(&state, "cimg-caller-h", "host");
490        let as_host = crate::server::caller::Caller::Agent { uid: host_caller.id.clone() };
491        let out = change_image(&state, Some(&as_host), &target.id, crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE).await.unwrap();
492        assert_eq!(out["container_image"], crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE);
493        assert_eq!(stored_image(&state, &target.id), crate::backend::container::image::DEFAULT_DEVELOPER_IMAGE);
494    }
495
496    #[test]
497    fn a_turn_holding_the_gate_stops_the_update_and_an_idle_agent_does_not() {
498        let name = "agentmux-test-gate-for-update-if-idle";
499        let turn = crate::backend::container::drift::update_gate(name).try_read_owned().expect("a turn takes the gate shared");
500        assert!(take_update_gate(name).is_none(), "an update must not start under a turn");
501        drop(turn);
502        let updating = take_update_gate(name).expect("no turn: the update takes the gate");
503        assert!(
504            crate::backend::container::drift::update_gate(name).try_read_owned().is_err(),
505            "a turn must not start inside an update"
506        );
507        drop(updating);
508    }
509
510    #[test]
511    fn only_an_older_image_is_moved_forward() {
512        assert!(is_older("0.59.41", "0.60.2"));
513        assert!(is_older("0.60.5", "0.60.6"));
514        assert!(is_older("0.9.0", "0.10.0"), "numeric, not text");
515        assert!(!is_older("0.60.6", "0.60.6"), "the same");
516        assert!(!is_older("0.60.7", "0.60.6"), "newer: after a downgrade it is left alone");
517        assert!(!is_older("latest", "0.60.6"), "unparseable: left alone");
518        assert!(!is_older("", "0.60.6"));
519    }
520
521    #[test]
522    fn only_an_agent_on_the_default_image_follows_it() {
523        assert!(image_blocks_update("").is_none(), "the default image");
524        assert!(image_blocks_update("ghcr.io/agentmuxai/agent-base:latest").is_none(), ":latest follows the version");
525        assert!(image_blocks_update("my/own:1").unwrap().contains("runs its own image (my/own:1)"));
526        assert!(image_blocks_update("ghcr.io/agentmuxai/agent-base:0.59.41").unwrap().contains("pinned to"));
527        assert!(image_blocks_update("ghcr.io/agentmuxai/agent-base@sha256:abc").unwrap().contains("pinned to"));
528    }
529
530    #[test]
531    fn the_developer_variant_follows_its_own_version_and_is_pinned_like_the_base() {
532        assert!(image_blocks_update("ghcr.io/agentmuxai/agent-base:developer").is_none(), ":developer follows the version, like :latest");
533        assert!(image_blocks_update(&crate::backend::container::image::versioned_developer_image()).is_none());
534        assert!(image_blocks_update("ghcr.io/agentmuxai/agent-base:0.59.41-developer").unwrap().contains("pinned to"), "another version's developer image");
535        // The base image's current tag is not the developer image's: an agent set to one is not on the other.
536        assert_eq!(current_image_for("ghcr.io/agentmuxai/agent-base:developer"), crate::backend::container::image::versioned_developer_image());
537        assert_eq!(current_image_for("ghcr.io/agentmuxai/agent-base:latest"), crate::backend::container::image::versioned_agent_image());
538    }
539
540    #[test]
541    fn a_container_is_reported_once_per_running_version_and_never_when_current() {
542        assert!(!first_report("agentmux-t1", "0.60.2", "0.60.2"));
543        assert!(first_report("agentmux-t1", "0.59.41", "0.60.2"));
544        assert!(!first_report("agentmux-t1", "0.59.41", "0.60.2"), "once");
545        assert!(first_report("agentmux-t1", "0.59.40", "0.60.2"), "another running version is news");
546        assert!(first_report("agentmux-t2", "0.59.41", "0.60.2"), "another container");
547    }
548}