Skip to main content

agentmux_srv_core/backend/container/
drift.rs

1//! A container made from an older agent image than this AgentMux: noticing it, and updating it.
2//!
3//! The release workflow tags `agent-base` with the AgentMux version (also on the image's
4//! `org.opencontainers.image.version` label), so the `agentmux-mcp` and `agentmux-bashwrap`
5//! inside match one srv. A container keeps the image it was created from, so after an upgrade
6//! it can run an older one; it is not recreated on its own, because tools installed inside it
7//! would be lost. [`ContainerManager::update_container`] does that, on request.
8
9use super::{ContainerError, ContainerManager};
10use crate::backend::container::image::is_agent_base_image;
11
12/// Held shared by every turn that runs in a container, and exclusively while the container is
13/// being updated: a turn cannot start inside an update, and an update cannot start under a turn.
14pub fn update_gate(container_name: &str) -> std::sync::Arc<tokio::sync::RwLock<()>> {
15    use std::collections::HashMap;
16    use std::sync::{Arc, Mutex, OnceLock};
17    static GATES: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::RwLock<()>>>>> = OnceLock::new();
18    GATES.get_or_init(Default::default).lock().unwrap().entry(container_name.to_string()).or_default().clone()
19}
20
21/// The label the release workflow's metadata step puts the version in.
22const VERSION_LABEL: &str = "org.opencontainers.image.version";
23
24/// The version an image reference or its labels name: the label, else a numeric tag.
25fn version_of(label: Option<&str>, image_ref: &str) -> Option<String> {
26    let label = label.map(str::trim).filter(|v| !v.is_empty());
27    if let Some(v) = label {
28        return Some(v.to_string());
29    }
30    let tag = image_ref.rsplit_once(':')?.1;
31    // The developer variant's tag is `<version>-developer`: the version is what the pane compares.
32    let tag = tag.strip_suffix("-developer").unwrap_or(tag);
33    tag.starts_with(|c: char| c.is_ascii_digit()).then(|| tag.to_string())
34}
35
36impl ContainerManager {
37    /// The AgentMux version of the base image `container_name` was created from, or `None`
38    /// when it isn't the base image (a custom image is the user's), or can't be read.
39    pub async fn base_image_version(&self, container_name: &str) -> Option<String> {
40        let details = self.inner.docker.inspect_container(container_name, None).await.ok()?;
41        let image_ref = details.config.as_ref()?.image.clone()?;
42        if !is_agent_base_image(&image_ref) {
43            return None;
44        }
45        let labels = match details.image.as_deref() {
46            Some(id) => self.inner.docker.inspect_image(id).await.ok().and_then(|i| i.config?.labels),
47            None => None,
48        };
49        version_of(labels.as_ref().and_then(|l| l.get(VERSION_LABEL)).map(String::as_str), &image_ref)
50    }
51
52    /// Removes the container so the next turn creates it again from the current image. The
53    /// per-agent volumes (CLI, Claude home) and the bind-mounted workspace and memory stay;
54    /// whatever else was installed inside the container is gone.
55    pub async fn update_container(&self, container_name: &str) -> Result<(), ContainerError> {
56        let _ = self.stop(container_name, 10).await;
57        self.remove(container_name, true).await
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn the_label_wins_and_a_numeric_tag_is_the_fallback() {
67        assert_eq!(version_of(Some("0.60.2"), "ghcr.io/agentmuxai/agent-base:latest").as_deref(), Some("0.60.2"));
68        assert_eq!(version_of(Some("  "), "ghcr.io/agentmuxai/agent-base:0.59.41").as_deref(), Some("0.59.41"));
69        assert_eq!(version_of(None, "ghcr.io/agentmuxai/agent-base:0.60.7-developer").as_deref(), Some("0.60.7"), "the developer variant's tag carries the version");
70        assert_eq!(version_of(None, "ghcr.io/agentmuxai/agent-base:latest"), None);
71        assert_eq!(version_of(None, "ghcr.io/agentmuxai/agent-base:developer"), None);
72        assert_eq!(version_of(None, "ghcr.io/agentmuxai/agent-base"), None);
73    }
74}
75
76#[cfg(test)]
77mod itest;