Skip to main content

agentmux_srv/server/remote_ops/
upgrade_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Telling an agent how the upgrade it asked another machine for ended.
5//!
6//! An agent that files `app.upgrade` on another machine gets the request's id and no more: the person
7//! there may veto the countdown, the restart may not be confirmed, the release may not verify, or the
8//! machine may restart into the new version, and until now the agent learned that only by asking again.
9//! This module reads how the request stands for it and tells it once, as an `[AgentMux]` system note,
10//! never as a message from an agent.
11//!
12//! It reads, it is not told. The other machine has no way to speak as one of this machine's agents, and
13//! nothing here gives it one: this srv holds the requesting agent's LAN key and asks `app.upgrade` with
14//! `status` and `app.version` for it, the same two reads the agent can make itself. So the other machine
15//! can say nothing the requester could not have asked, and the note is built here from words this file
16//! knows, with the machine's own text left out.
17//!
18//! The note goes only to the agent that asked, from the machine it asked, once. An agent that is not
19//! running is tried again at each read until it can take it, and the watch ends after a day with nothing
20//! said. It is kept in memory: a restart of this srv forgets it, and the agent can still read the status.
21
22use std::collections::HashSet;
23use std::sync::{LazyLock, Mutex};
24use std::time::Duration;
25
26use serde_json::{json, Value};
27
28use super::op::{OpStatus, RemoteOpResult};
29use super::send;
30use crate::server::AppState;
31
32/// Between reads while the request is young: a veto or a restart is a matter of minutes.
33const POLL_YOUNG: Duration = Duration::from_secs(20);
34/// Between reads after the first quarter hour, to the end of the day: each read is an audit row on both machines.
35const POLL_OLD: Duration = Duration::from_secs(300);
36const YOUNG_FOR: Duration = Duration::from_secs(15 * 60);
37/// After this the agent is not told at all.
38const GIVE_UP_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
39/// Watches at once, so a flood of requests cannot become a flood of reads.
40const MAX_WATCHES: usize = 32;
41
42const READ_REASON: &str = "read how my upgrade request ended, to tell the agent that asked";
43
44/// How a request on the other machine ended, as far as an agent is told.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub(super) enum Ended {
47    /// The super agent said no.
48    Denied,
49    /// The person stopped it in the countdown.
50    Vetoed,
51    /// Withdrawn.
52    Cancelled,
53    /// Nobody decided in time.
54    Expired,
55    /// The operation could not go ahead.
56    Failed,
57    /// The release did not download or did not verify.
58    NotDownloaded,
59    /// The restart was asked for and did not go ahead; `why` is one of the status's words, `at_ms` its time.
60    NotConfirmed { why: String, at_ms: u64 },
61    /// The machine came back on the release.
62    Restarted,
63}
64
65/// Where a request stands while it has not ended.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub(super) enum Phase {
68    /// Asked, counting down, or the operation is starting.
69    Open,
70    /// The operation ran: the release downloads, then the machine restarts into it.
71    Ran,
72}
73
74/// What one read of the request's status says to do next.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub(super) enum Step {
77    Wait(Phase),
78    /// The request is gone from the machine, or the machine does not answer: it may have restarted, which its
79    /// version says. The phase stays what it was.
80    CheckVersion,
81    End(Ended),
82}
83
84/// One read of `app.upgrade` with `status`, in `phase`, for the release `version`.
85pub(super) fn read_status(phase: Phase, answer: &RemoteOpResult, version: &str) -> Step {
86    if answer.status != OpStatus::Done {
87        // The machine may have restarted into the release since the last read and forgotten the request (its
88        // requests are kept in memory), whatever the request was doing then: its version says.
89        return Step::CheckVersion;
90    }
91    let r = &answer.result;
92    match r.get("status").and_then(Value::as_str).unwrap_or_default() {
93        "asked" | "pending" | "running" => Step::Wait(Phase::Open),
94        "denied" => Step::End(Ended::Denied),
95        "vetoed" => Step::End(Ended::Vetoed),
96        "cancelled" => Step::End(Ended::Cancelled),
97        "expired" => Step::End(Ended::Expired),
98        "failed" => Step::End(Ended::Failed),
99        "done" => {
100            let restart = &r["restart"];
101            let this_release = restart["version"].as_str() == Some(version);
102            match (restart["state"].as_str(), restart["not_confirmed"].as_str(), restart["not_confirmed_at"].as_u64()) {
103                (Some("ready"), Some(why), Some(at_ms)) if this_release => Step::End(Ended::NotConfirmed { why: why.to_string(), at_ms }),
104                (Some("failed"), _, _) if this_release => Step::End(Ended::NotDownloaded),
105                _ => Step::Wait(Phase::Ran),
106            }
107        }
108        _ => Step::Wait(phase),
109    }
110}
111
112/// One read of `app.version`: whether the machine now runs `version`.
113pub(super) fn read_version(answer: &RemoteOpResult, version: &str) -> bool {
114    answer.status == OpStatus::Done && answer.result["version"].as_str() == Some(version)
115}
116
117/// `ms` (Unix) as "16:33 UTC".
118fn clock(ms: u64) -> String {
119    chrono::DateTime::from_timestamp_millis(ms as i64).map_or_else(|| "an unknown time".into(), |t| t.format("%H:%M UTC").to_string())
120}
121
122fn why_words(why: &str) -> &'static str {
123    match why {
124        "no" => "the person answered No",
125        "timed_out" => "nobody answered the prompt before it closed itself",
126        "too_late" => "an answer came after the prompt had lapsed",
127        "unanswered" => "the launcher did not restart AgentMux in time",
128        _ => "the restart was declined",
129    }
130}
131
132/// The note: which machine, which release, how it ended and when. Every word is this file's own, but for the
133/// machine's name and the release, which are quoted like any text a note carries that srv did not write.
134pub(super) fn note_for(host: &str, version: &str, ended: &Ended, seen_ms: u64) -> String {
135    use crate::backend::reactive::sanitize::quote_in_system_note as q;
136    let (host, version) = (q(host), q(version));
137    let at = clock(seen_ms);
138    match ended {
139        Ended::Denied => format!("[AgentMux] Your request to upgrade {host} to {version} was denied (seen at {at}). Nothing was installed."),
140        Ended::Vetoed => format!("[AgentMux] The person at {host} stopped your request to upgrade it to {version} (seen at {at}). Nothing was installed."),
141        Ended::Cancelled => format!("[AgentMux] Your request to upgrade {host} to {version} was withdrawn (seen at {at})."),
142        Ended::Expired => format!("[AgentMux] Nobody decided your request to upgrade {host} to {version} in time (seen at {at}). Nothing was installed."),
143        Ended::Failed => format!("[AgentMux] Your request to upgrade {host} to {version} could not go ahead (seen at {at}). Read it with App upgrade, host {host}, for the reason."),
144        Ended::NotDownloaded => format!("[AgentMux] {host} could not download or verify {version} (seen at {at}), so it was not installed. Ask again if it is still wanted."),
145        Ended::NotConfirmed { why, at_ms } => format!(
146            "[AgentMux] The upgrade of {host} to {version} did not happen: the restart did not go ahead at {}: {}. The release is downloaded and waiting there. Ask again if it is still wanted.",
147            clock(*at_ms),
148            why_words(why)
149        ),
150        Ended::Restarted => format!("[AgentMux] {host} restarted and now runs {version} (seen at {at})."),
151    }
152}
153
154/// One request being followed.
155#[derive(Debug, Clone, PartialEq, Eq, Hash)]
156pub(super) struct Watch {
157    /// The requesting agent, by name: the key that signs the reads.
158    pub slug: String,
159    /// Its uid on this machine: whom the note goes to.
160    pub uid: String,
161    /// The machine as the agent named it (`machine`, or `machine/channel/install` to tell two instances of
162    /// one machine apart): every read names it the same way, so each one reaches the instance that was asked.
163    pub host: String,
164    pub id: String,
165    pub version: String,
166}
167
168static WATCHING: LazyLock<Mutex<HashSet<(String, String, String)>>> = LazyLock::new(Default::default);
169
170fn key(w: &Watch) -> (String, String, String) {
171    (w.uid.clone(), w.host.to_ascii_lowercase(), w.id.clone())
172}
173
174/// Start following `w` in `set`: false when it already is, or when `max` are.
175fn register_in(set: &mut HashSet<(String, String, String)>, w: &Watch, max: usize) -> bool {
176    if set.len() >= max {
177        return false;
178    }
179    set.insert(key(w))
180}
181
182fn register(w: &Watch) -> bool {
183    register_in(&mut WATCHING.lock().unwrap_or_else(|e| e.into_inner()), w, MAX_WATCHES)
184}
185
186fn unregister(w: &Watch) {
187    WATCHING.lock().unwrap_or_else(|e| e.into_inner()).remove(&key(w));
188}
189
190/// The watch an answer to `app.upgrade` starts, if it is the answer to filing a request: not a read of one
191/// (`status`), and `requested` with the request's id.
192pub(super) fn watch_for(slug: &str, uid: &str, host: &str, params: &Value, answer: &RemoteOpResult) -> Option<Watch> {
193    if params.get("status").is_some() || answer.status != OpStatus::Done {
194        return None;
195    }
196    let r = &answer.result;
197    if r["status"].as_str() != Some("requested") {
198        return None;
199    }
200    let (id, version) = (r["id"].as_str()?.trim(), r["version"].as_str()?.trim());
201    if id.is_empty() || version.is_empty() {
202        return None;
203    }
204    Some(Watch { slug: slug.to_string(), uid: uid.to_string(), host: host.trim().to_string(), id: id.to_string(), version: version.to_string() })
205}
206
207/// Called with every answer to a remote `app.upgrade` this machine's agents get: follows a request just filed.
208pub(super) fn note_asked(state: &AppState, slug: &str, uid: &str, host: &str, params: &Value, answer: &RemoteOpResult) {
209    let Some(w) = watch_for(slug, uid, host, params, answer) else { return };
210    if !register(&w) {
211        return;
212    }
213    tracing::info!(agent = %w.slug, host = %w.host, request = %w.id, "upgrade: following a request on another machine to tell its agent how it ends");
214    let state = state.clone();
215    tokio::spawn(async move {
216        run(&state, &w).await;
217        unregister(&w);
218    });
219}
220
221/// Tell `w`'s agent: whether it was delivered (an agent that is not running is not an error: it is tried again).
222fn tell(w: &Watch, note: &str) -> bool {
223    crate::sagas::sensitive_window::tell_one(&w.uid, note)
224}
225
226async fn run(state: &AppState, w: &Watch) {
227    let began = tokio::time::Instant::now();
228    let mut phase = Phase::Open;
229    let mut ended: Option<Ended> = None;
230    loop {
231        let waited = began.elapsed();
232        if waited >= GIVE_UP_AFTER {
233            tracing::info!(agent = %w.slug, host = %w.host, request = %w.id, "upgrade: gave up telling the agent how its request on another machine ended");
234            return;
235        }
236        tokio::time::sleep(if waited < YOUNG_FOR { POLL_YOUNG } else { POLL_OLD }).await;
237        if ended.is_none() {
238            let answer = send::call(state, &w.slug, &w.host, "app.upgrade", json!({ "status": w.id }), READ_REASON).await;
239            match read_status(phase, &answer, &w.version) {
240                Step::Wait(next) => phase = next,
241                Step::End(e) => ended = Some(e),
242                Step::CheckVersion => {
243                    let version = send::call(state, &w.slug, &w.host, "app.version", json!({}), READ_REASON).await;
244                    if read_version(&version, &w.version) {
245                        ended = Some(Ended::Restarted);
246                    }
247                }
248            }
249        }
250        if let Some(e) = &ended {
251            if tell(w, &note_for(&w.host, &w.version, e, agentmux_common::time::now_ms_u64())) {
252                return;
253            }
254        }
255    }
256}
257
258#[cfg(test)]
259#[path = "upgrade_watch_tests.rs"]
260mod tests;