Skip to main content

agentmux_mcp/tools/
app_tool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! App: this AgentMux itself (docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md
5//! §5.1, phase 4). `version` says what is running and whether a newer
6//! release exists; `upgrade` asks for it. A tool of its own, like Stop,
7//! because an upgrade restarts every agent: a harness can gate it
8//! (SPEC_MUXAPI_TOOL_CONSOLIDATION_2026_10_15.md §4.1).
9
10use agentmux_common::api_types::RequestUpgradeRequest;
11
12use super::*;
13
14pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
15    match name {
16        "App" => match str_arg(arguments, "action").as_deref() {
17            Some("version") => match remote_op::host_arg(arguments) {
18                Some(host) => remote_version(arguments, cx, &host).await,
19                None => version(cx).await,
20            },
21            Some("health") => match remote_op::host_arg(arguments) {
22                Some(host) => remote_health(arguments, cx, &host).await,
23                None => local_health(cx).await,
24            },
25            Some("upgrade") => match remote_op::host_arg(arguments) {
26                Some(host) => remote_upgrade(arguments, cx, &host).await,
27                None => upgrade(arguments, cx).await,
28            },
29            Some("network") => network(cx).await,
30            Some("history_reclaim") => match remote_op::host_arg(arguments) {
31                Some(host) => remote_history_reclaim(arguments, cx, &host).await,
32                None => history_reclaim(arguments, cx).await,
33            },
34            Some("logs") => logs(arguments, cx).await,
35            Some("disk") => disk(arguments, cx).await,
36            Some("record") => super::app_record::record(arguments, cx).await,
37            Some("workspace") => super::app_workspace::workspace(cx).await,
38            Some("keep_running") => super::app_workspace::keep_running(arguments, cx).await,
39            other => anyhow::bail!("App: unknown action {other:?}; use \"version\", \"health\", \"upgrade\", \"network\", \"history_reclaim\", \"logs\", \"disk\", \"record\", \"workspace\" or \"keep_running\""),
40        },
41        _ => Err(not_in_family()),
42    }
43}
44
45/// An AgentMux in words, from its `app.version` answer: "AgentMux 0.60.22 (a release, build 0.60.22,
46/// data in channel local-main-b28b7a-0000000a, linux)". What kind of build it is comes from the machine's
47/// own `build_kind`, never from the channel's name: an upgraded release keeps the channel of the build it
48/// replaced, and the channel only says where the data is. An AgentMux from before `build_kind` says nothing
49/// about its kind.
50fn describe_identity(r: &Value) -> String {
51    let kind = match s(r, "build_kind") {
52        "release" => "a release, ",
53        "local" => "a local build, ",
54        "dev" => "a dev build, ",
55        _ => "",
56    };
57    format!("AgentMux {} ({kind}build {}, data in channel {}, {})", s(r, "version"), s(r, "build"), s(r, "channel"), s(r, "os"))
58}
59
60/// `version` with a `host`: the AgentMux on that machine, from its own answer.
61async fn remote_version(arguments: &Value, cx: &ToolCtx<'_>, host: &str) -> Result<String> {
62    let answer = ask(arguments, cx, host, "app.version").await?;
63    let r = &answer["result"];
64    Ok(format!("{host} runs {}. {}", describe_identity(r), describe_status(&r["update"])))
65}
66
67/// `health` with a `host`: what a steward checks after an upgrade, on that machine.
68async fn remote_health(arguments: &Value, cx: &ToolCtx<'_>, host: &str) -> Result<String> {
69    let answer = ask(arguments, cx, host, "app.health").await?;
70    Ok(remote_op::pretty(host, &answer))
71}
72
73/// `health` on this machine, from the same report a remote call gets.
74async fn local_health(cx: &ToolCtx<'_>) -> Result<String> {
75    let url = format!("{}/api/v1/app/health", cx.local_url.trim_end_matches('/'));
76    let resp = cx.client.get(&url).header(AUTH_KEY_HEADER, cx.auth_key).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
77    let status = resp.status();
78    let body: Value = resp.json().await.unwrap_or(Value::Null);
79    if !status.is_success() {
80        anyhow::bail!("App health: srv answered {status}: {body}");
81    }
82    Ok(format!("This machine:
83{}", serde_json::to_string_pretty(&body).unwrap_or_else(|_| body.to_string())))
84}
85
86/// Run a read-only operation on `host`; an error carries the machine's refusal in words.
87async fn ask(arguments: &Value, cx: &ToolCtx<'_>, host: &str, op: &str) -> Result<Value> {
88    ask_with(arguments, cx, host, op, json!({})).await
89}
90
91/// [`ask`] with the operation's parameters.
92async fn ask_with(arguments: &Value, cx: &ToolCtx<'_>, host: &str, op: &str, params: Value) -> Result<Value> {
93    let reason = str_arg(arguments, "reason").unwrap_or_else(|| format!("App {}", op.trim_start_matches("app.")));
94    let answer = remote_op::remote_op_call(cx, host, op, params, &reason).await?;
95    match remote_op::explain_not_done(host, op, &answer) {
96        Some(problem) => anyhow::bail!("{problem}"),
97        None => Ok(answer),
98    }
99}
100
101async fn network(cx: &ToolCtx<'_>) -> Result<String> {
102    let url = format!("{}/api/v1/app/connectivity", cx.local_url.trim_end_matches('/'));
103    let resp = cx
104        .client
105        .get(&url)
106        .header(AUTH_KEY_HEADER, cx.auth_key)
107        .send()
108        .await
109        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
110    let status = resp.status();
111    let body: Value = resp.json().await.unwrap_or(Value::Null);
112    if !status.is_success() {
113        anyhow::bail!("App network: srv answered {status}: {body}");
114    }
115    Ok(describe_network(&body, agentmux_common::time::now_ms()))
116}
117
118/// `network`'s answer, from srv's `ConnectivityStatus`: one line per service, then what to make of it.
119fn describe_network(status: &Value, now_ms: i64) -> String {
120    let services = status["services"].as_array().map(Vec::as_slice).unwrap_or_default();
121    if services.is_empty() {
122        return "AgentMux hasn't checked the network yet.".to_string();
123    }
124    let mut out = String::from("What AgentMux can reach right now (its own checks, not your shell's):");
125    let mut down = Vec::new();
126    for svc in services {
127        let label = s(svc, "label");
128        let line = match s(svc, "state") {
129            "online" => "online".to_string(),
130            "unknown" => "not checked yet".to_string(),
131            state => {
132                down.push(label);
133                let error = s(svc, "last_error");
134                let why = if error.is_empty() { String::new() } else { format!(" ({error})") };
135                format!("{} for {}{why}", if state == "degraded" { "degraded" } else { "OFFLINE" }, ago(now_ms, &svc["since_ms"]))
136            }
137        };
138        out.push_str(&format!("\n- {label}: {line}"));
139    }
140    if down.is_empty() {
141        out.push_str(
142            "\nNothing AgentMux has checked is down. It tracks only the services listed, and an online service is not re-probed; \
143             \"not checked yet\" and any service not listed are unknown, so this does not rule the network out.",
144        );
145    } else {
146        out.push_str(&format!(
147            "\nDown or failing: {}. A turn that stalls or retries on one of these may be the network; AgentMux keeps checking it and \
148             this changes when it answers. A service not listed here is not tracked.",
149            down.join(", ")
150        ));
151    }
152    out
153}
154
155/// "5 min" or "2 h 10 min" for the time from `since_ms` to `now_ms`.
156pub(super) fn ago(now_ms: i64, since_ms: &Value) -> String {
157    let Some(since) = since_ms.as_i64() else { return "an unknown time".to_string() };
158    let secs = ((now_ms - since) / 1000).max(0);
159    match secs {
160        0..=89 => format!("{secs} s"),
161        90..=5399 => format!("{} min", (secs + 30) / 60),
162        _ => format!("{} h {} min", secs / 3600, (secs % 3600) / 60),
163    }
164}
165
166async fn version(cx: &ToolCtx<'_>) -> Result<String> {
167    // `check=1`: ask GitHub now (srv limits it to once every 30 seconds).
168    let url = format!("{}/api/v1/app/update-status?check=1", cx.local_url.trim_end_matches('/'));
169    let resp = cx
170        .client
171        .get(&url)
172        .header(AUTH_KEY_HEADER, cx.auth_key)
173        .send()
174        .await
175        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
176    let status = resp.status();
177    let body: Value = resp.json().await.unwrap_or(Value::Null);
178    if !status.is_success() {
179        anyhow::bail!("App version: srv answered {status}: {body}");
180    }
181    Ok(describe_status(&body))
182}
183
184async fn upgrade(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
185    require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
186    let reason = str_arg(arguments, "reason").ok_or_else(|| anyhow::anyhow!("App upgrade needs a reason"))?;
187    let request = RequestUpgradeRequest {
188        auth: sign_ui_automation_auth()?,
189        reason,
190        user_instruction: str_arg(arguments, "user_instruction").unwrap_or_default(),
191        version: str_arg(arguments, "version"),
192    };
193    let url = format!("{}/api/v1/agent/self/upgrade", cx.local_url.trim_end_matches('/'));
194    let resp = cx
195        .client
196        .post(&url)
197        .header(AUTH_KEY_HEADER, cx.auth_key)
198        .json(&request)
199        .send()
200        .await
201        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
202    let status = resp.status();
203    let body: Value = resp.json().await.unwrap_or(Value::Null);
204    if !status.is_success() {
205        anyhow::bail!("App upgrade: srv answered {status}: {}", body["error"].as_str().unwrap_or(&body.to_string()));
206    }
207    Ok(describe_outcome(&body))
208}
209
210/// `upgrade` with a `host`: ask that machine to upgrade itself. It is filed there as the sensitive request a local
211/// agent's `upgrade` files: its super agent decides and the person at that machine can veto the countdown, so this
212/// never starts anything by itself. With `request_id`, read where an earlier request stands instead.
213async fn remote_upgrade(arguments: &Value, cx: &ToolCtx<'_>, host: &str) -> Result<String> {
214    if let Some(id) = str_arg(arguments, "request_id") {
215        let answer = ask_with(arguments, cx, host, "app.upgrade", json!({ "status": id })).await?;
216        return Ok(describe_remote_request(host, &answer["result"]));
217    }
218    let reason = str_arg(arguments, "reason").ok_or_else(|| anyhow::anyhow!("App upgrade needs a reason"))?;
219    let mut params = json!({ "reason": reason });
220    if let Some(version) = str_arg(arguments, "version") {
221        params["version"] = json!(version);
222    }
223    let answer = ask_with(arguments, cx, host, "app.upgrade", params).await?;
224    let r = &answer["result"];
225    if s(r, "status") == "requested" {
226        return Ok(format!(
227            "Asked {host} to upgrade to {} as a sensitive operation ({}). If its super agent approves, the person at {host} \
228             sees a banner with a countdown and can veto it, and the upgrade starts when it ends. AgentMux tells you once, in a \
229             note, how it ends (denied, stopped by the person, not confirmed, or restarted into the release); you can also \
230             read it with App upgrade, host {host}, request_id {}.",
231            s(r, "version"),
232            s(r, "review"),
233            s(r, "id")
234        ));
235    }
236    Ok(format!("{host}: {}", describe_outcome(r)))
237}
238
239/// A sensitive request's state on another machine, from `app.upgrade` with a `status`.
240fn describe_remote_request(host: &str, r: &Value) -> String {
241    let mut out = format!("On {host}: {} is {}", s(r, "summary"), s(r, "status"));
242    if !s(r, "decided_by").is_empty() {
243        out.push_str(&format!(", decided by {}", s(r, "decided_by")));
244    }
245    if r["deadline_ms"].is_number() {
246        out.push_str(" (its countdown is running; the person there can still veto it)");
247    }
248    if !s(r, "deny_reason").is_empty() {
249        out.push_str(&format!(". Denied: {}", s(r, "deny_reason")));
250    }
251    if !s(r, "error").is_empty() {
252        out.push_str(&format!(". It stopped with: {}", s(r, "error")));
253    }
254    out.push('.');
255    out
256}
257
258/// `history_reclaim`: ask for the shared pane-history store's free space to be given back at the next start,
259/// withdraw that, or read where it stands (`/api/v1/agent/history/reclaim`). srv records the request as this agent.
260async fn history_reclaim(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
261    require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
262    let what = str_arg(arguments, "reclaim").unwrap_or_else(|| "status".to_string());
263    let url = format!("{}/api/v1/agent/history/reclaim", cx.local_url.trim_end_matches('/'));
264    let req = match what.as_str() {
265        "status" => cx.client.get(&url),
266        "request" | "cancel" => cx.client.post(&url).json(&json!({ "action": what })),
267        other => anyhow::bail!("App history_reclaim: reclaim is \"request\", \"cancel\" or \"status\", not {other:?}"),
268    };
269    let resp = req.header(AUTH_KEY_HEADER, cx.auth_key).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
270    let status = resp.status();
271    let body: Value = resp.json().await.unwrap_or(Value::Null);
272    if !status.is_success() {
273        anyhow::bail!("App history_reclaim: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
274    }
275    Ok(describe_reclaim(&body, &what))
276}
277
278/// `history_reclaim` with a `host`: the same request, withdrawal or read, on that machine.
279async fn remote_history_reclaim(arguments: &Value, cx: &ToolCtx<'_>, host: &str) -> Result<String> {
280    let what = str_arg(arguments, "reclaim").unwrap_or_else(|| "status".to_string());
281    if !matches!(what.as_str(), "request" | "cancel" | "status") {
282        anyhow::bail!("App history_reclaim: reclaim is \"request\", \"cancel\" or \"status\", not {what:?}");
283    }
284    let answer = ask_with(arguments, cx, host, "app.history_reclaim", json!({ "action": what })).await?;
285    Ok(format!("On {host}: {}", describe_reclaim(&answer["result"], &what)))
286}
287
288/// `logs`: the last lines of AgentMux's own srv or host log, on another machine (`app.logs.tail`) or, without a
289/// `host`, on this one (`GET /api/v1/app/logs`: through srv, so a container agent reads it too).
290/// `level` and `contains` are applied before the last `lines` are taken.
291async fn logs(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
292    let which = str_arg(arguments, "log").unwrap_or_else(|| "srv".to_string());
293    let mut params = json!({ "which": which });
294    if let Some(n) = arguments.get("lines").and_then(Value::as_u64) {
295        params["lines"] = json!(n);
296    }
297    if let Some(level) = str_arg(arguments, "level") {
298        params["level"] = json!(level);
299    }
300    if let Some(text) = contains_arg(arguments) {
301        params["contains"] = json!(text);
302    }
303    let Some(host) = remote_op::host_arg(arguments) else {
304        let url = format!("{}/api/v1/app/logs", cx.local_url.trim_end_matches('/'));
305        let mut query = vec![("log", which.clone())];
306        if let Some(n) = params.get("lines").and_then(Value::as_u64) {
307            query.push(("lines", n.to_string()));
308        }
309        for key in ["level", "contains"] {
310            if let Some(v) = params.get(key).and_then(Value::as_str) {
311                query.push((key, v.to_string()));
312            }
313        }
314        let resp = cx
315            .client
316            .get(&url)
317            .header(AUTH_KEY_HEADER, cx.auth_key)
318            .query(&query)
319            .send()
320            .await
321            .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
322        let status = resp.status();
323        let body: Value = resp.json().await.unwrap_or(Value::Null);
324        if !status.is_success() {
325            anyhow::bail!("App logs: srv answered {status}: {}", s(&body, "error"));
326        }
327        return Ok(describe_logs("This machine's", &params, &body));
328    };
329    let answer = ask_with(arguments, cx, &host, "app.logs.tail", params.clone()).await?;
330    Ok(describe_logs(&format!("{host}'s"), &params, &answer["result"]))
331}
332
333/// A log read in words: which log, what was asked of it, how many lines passed and how many came back.
334fn describe_logs(whose: &str, asked: &Value, r: &Value) -> String {
335    let note = if r["shortened"].as_bool() == Some(true) { " (shortened to fit)" } else { "" };
336    let mut filters = Vec::new();
337    if let Some(level) = asked["level"].as_str() {
338        filters.push(format!("level {level} or above"));
339    }
340    if let Some(text) = asked["contains"].as_str() {
341        filters.push(format!("containing {text:?}"));
342    }
343    // An AgentMux from before the filters says nothing of what it searched.
344    let searched = match r["searched"].as_u64() {
345        Some(n) => {
346            let scope = if r["whole_file"].as_bool() == Some(true) { "the whole file".to_string() } else { format!("the last {:.1} MB of the file", r["searched_bytes"].as_u64().unwrap_or(0) as f64 / 1_048_576.0) };
347            format!(" {} of {n} lines in {scope} matched;", r["matched"].as_u64().unwrap_or(0))
348        }
349        None => String::new(),
350    };
351    // An AgentMux from before the filters ignores them and returns its plain last lines: do not say they were filtered.
352    if !filters.is_empty() && r["searched"].is_null() {
353        return format!(
354            "{whose} {} log, {} returned. That AgentMux is from before the filters and ignored {}: these are its last lines, unfiltered:\n{}",
355            s(r, "which"),
356            r["lines"],
357            filters.join(" and "),
358            s(r, "text")
359        );
360    }
361    let what = if filters.is_empty() { String::new() } else { format!(" ({})", filters.join(", ")) };
362    format!("{whose} {} log{what},{searched} {} returned{note}:\n{}", s(r, "which"), r["lines"], s(r, "text"))
363}
364
365/// `disk`: what AgentMux filled on another machine's disk (`app.disk.report`), measured there and deleting nothing.
366/// With `clean`, ask that machine to clear its idle build folders (`app.disk.cleanup`), filed there as a
367/// sensitive request; with `request_id`, read where such a request stands.
368async fn disk(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
369    let Some(host) = remote_op::host_arg(arguments) else {
370        anyhow::bail!("App disk works on another machine's disk: name it with host. This machine's disk is yours to look at with a shell.");
371    };
372    if let Some(id) = str_arg(arguments, "request_id") {
373        let answer = ask_with(arguments, cx, &host, "app.disk.cleanup", json!({ "status": id })).await?;
374        return Ok(describe_remote_request(&host, &answer["result"]));
375    }
376    if arguments.get("clean").and_then(Value::as_bool) == Some(true) {
377        let reason = str_arg(arguments, "reason").ok_or_else(|| anyhow::anyhow!("App disk with clean needs a reason"))?;
378        let answer = ask_with(arguments, cx, &host, "app.disk.cleanup", json!({ "reason": reason })).await?;
379        let r = &answer["result"];
380        return Ok(format!(
381            "Asked {host} to clear its idle build folders as a sensitive operation ({}). If its super agent approves, the person at {host} \
382             sees a banner with a countdown and can veto it, and the cleanup runs when it ends: orphan incremental folders and the target \
383             of clones nobody built in for days, never one with a build running. Nothing is sent to you when it moves on: read it with \
384             App disk, host {host}, request_id {}.",
385            s(r, "review"),
386            s(r, "id")
387        ));
388    }
389    let answer = ask(arguments, cx, &host, "app.disk.report").await?;
390    Ok(describe_disk(&host, &answer["result"]))
391}
392
393pub(super) fn gb(bytes: u64) -> String {
394    format!("{:.1} GB", bytes as f64 / 1_073_741_824.0)
395}
396
397fn describe_volume(label: &str, v: &Value) -> Option<String> {
398    let (free, total) = (v["free_bytes"].as_u64()?, v["total_bytes"].as_u64()?);
399    Some(format!("{label}: {} free of {}", gb(free), gb(total)))
400}
401
402/// `disk`'s answer, from the report: volumes, the largest build folders, older versions.
403fn describe_disk(host: &str, r: &Value) -> String {
404    let mut out = format!("{host}'s disk, as AgentMux sees it:");
405    for line in [describe_volume("data volume", &r["data_volume"]), describe_volume("agents volume", &r["agents_volume"])].into_iter().flatten() {
406        out.push_str(&format!("\n- {line}"));
407    }
408    let folders = r["build_folders"].as_array().map(Vec::as_slice).unwrap_or_default();
409    out.push_str(&format!("\nBuild folders (cargo target): {} in all", gb(r["build_folders_total_bytes"].as_u64().unwrap_or(0))));
410    for f in folders {
411        let cut = if f["complete"].as_bool() == Some(false) { "+" } else { "" };
412        out.push_str(&format!("\n- {}: {}{cut} (incremental {})", s(f, "clone"), gb(f["target_bytes"].as_u64().unwrap_or(0)), gb(f["incremental_bytes"].as_u64().unwrap_or(0))));
413    }
414    let versions = r["older_versions"].as_array().map(Vec::as_slice).unwrap_or_default();
415    if !versions.is_empty() {
416        out.push_str("\nOlder version folders:");
417        for v in versions {
418            let cut = if v["complete"].as_bool() == Some(false) { "+" } else { "" };
419            out.push_str(&format!("\n- {}: {}{cut}", s(v, "version"), gb(v["bytes"].as_u64().unwrap_or(0))));
420        }
421    }
422    if r["complete"].as_bool() == Some(false) {
423        out.push_str("\nIt stopped measuring early: the sizes marked + and the totals are lower bounds.");
424    }
425    out.push_str(&format!("\n{}", s(r, "note")));
426    out
427}
428
429/// `history_reclaim`'s answer, from srv's status of the request and the last reclaim.
430fn describe_reclaim(st: &Value, what: &str) -> String {
431    let mut out = String::new();
432    if st["pending"].as_bool() == Some(true) {
433        let by = s(st, "requested_by");
434        out.push_str(&format!(
435            "A reclaim of the pane-history store is asked for{}. It runs at the next start of AgentMux, before the store opens: \
436             the store is rewritten without its free pages, which takes a while for a large store and needs free disk of about \
437             the store's live size plus 1 GB. The person sees it pending in History > Storage and can cancel it there; \
438             App history_reclaim with reclaim \"cancel\" withdraws it too.",
439            if by.is_empty() { String::new() } else { format!(" (by {by})") }
440        ));
441        if what == "request" && !by.is_empty() {
442            out.push_str(" Asking again keeps the first request.");
443        }
444        let waiting = s(st, "waiting_for");
445        if !waiting.is_empty() {
446            out.push_str(&format!(" The last start did not run it: {waiting}."));
447        }
448    } else if what == "cancel" {
449        out.push_str("No reclaim of the pane-history store is asked for now.");
450        let was = s(st, "withdrew_request_of");
451        if !was.is_empty() {
452            out.push_str(&format!(" It withdrew the request made by {was}."));
453        }
454    } else {
455        out.push_str("No reclaim of the pane-history store is asked for. App history_reclaim with reclaim \"request\" asks for one at the next start.");
456    }
457    let error = s(st, "last_error");
458    if !error.is_empty() {
459        out.push_str(&format!(" The last attempt failed: {error}."));
460    }
461    if st["last_done_ms"].as_u64().unwrap_or(0) > 0 {
462        let (before, after) = (st["last_before_bytes"].as_u64().unwrap_or(0), st["last_after_bytes"].as_u64().unwrap_or(0));
463        out.push_str(&format!(" The last reclaim took the store from {} to {}.", mb(before), mb(after)));
464    }
465    out
466}
467
468pub(super) fn mb(bytes: u64) -> String {
469    format!("{:.1} MB", bytes as f64 / 1_048_576.0)
470}
471
472/// `logs`' `contains`, exactly as given: the text is searched for as written, so leading and trailing spaces
473/// are part of it (`" store "` does not match "storefront") and a text of only spaces is a real filter. Only the
474/// empty string means no filter.
475fn contains_arg(args: &Value) -> Option<String> {
476    args.get("contains").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string)
477}
478
479pub(super) fn s<'a>(v: &'a Value, k: &str) -> &'a str {
480    v[k].as_str().unwrap_or("")
481}
482
483/// What a download says about the last restart into it that was asked for and not confirmed, as a sentence to add
484/// after "ready to restart into": when and why (`not_confirmed_at`, `not_confirmed`); empty when there was none.
485fn not_confirmed_words(d: &Value) -> String {
486    let Some(at) = d["not_confirmed_at"].as_u64() else { return String::new() };
487    let secs = at / 1000;
488    let when = format!("{:02}:{:02} UTC", secs / 3600 % 24, secs / 60 % 60);
489    let why = match s(d, "not_confirmed") {
490        "no" => "the user answered No",
491        "timed_out" => "nobody answered the prompt before it closed itself",
492        "too_late" => "an answer came after the prompt had lapsed",
493        "unanswered" => "the launcher didn't restart AgentMux in time",
494        _ => "the restart was declined",
495    };
496    format!(" The last restart into it did not go ahead at {when}: {why}. Ask again if it is still wanted.")
497}
498
499/// `version`'s answer, from srv's `AppUpdateStatus`.
500fn describe_status(st: &Value) -> String {
501    let current = s(st, "current");
502    let install = s(st, "install");
503    let latest = s(st, "latest");
504    let mut out = format!("AgentMux {current} ({install}).");
505    match s(st, "state") {
506        "available" => out.push_str(&format!(" A newer release is out: {latest}.")),
507        "up-to-date" => out.push_str(" This is the latest release."),
508        "local-build" => out.push_str(&format!(" A development build (`task dev`), which doesn't upgrade itself; the latest release is {latest}.")),
509        _ => out.push_str(" Couldn't learn which release is the latest (GitHub didn't answer)."),
510    }
511    if s(st, "state") == "available" {
512        let d = &st["download"];
513        if s(d, "version") == latest {
514            match s(d, "state") {
515                "downloading" | "unpacking" => out.push_str(" It is downloading now."),
516                "ready" => {
517                    out.push_str(" It is downloaded and ready to restart into.");
518                    out.push_str(&not_confirmed_words(d));
519                }
520                "waiting" => out.push_str(" A restart into it is waiting for agents to finish their turn."),
521                "restarting" => out.push_str(" AgentMux is restarting into it now."),
522                // A remote answer carries no error text (srv allow-lists what leaves a machine).
523                "failed" if s(d, "error").is_empty() => out.push_str(" Its download failed."),
524                "failed" => out.push_str(&format!(" Its download failed: {}.", s(d, "error"))),
525                _ => {}
526            }
527        }
528        let first = s(st, "install_first");
529        if !first.is_empty() {
530            out.push_str(&format!(
531                " This version is older than {latest} upgrades from: the user installs {first} first \
532                 (https://github.com/agentmuxai/agentmux/releases/tag/v{first}), then upgrades."
533            ));
534        } else if st["can_download"].as_bool() == Some(true) {
535            out.push_str(" This install can upgrade itself: App with action \"upgrade\" asks for it.");
536        } else {
537            // A remote answer carries no release URL either: the latest release's page is fixed.
538            let url = Some(s(st, "url")).filter(|u| !u.is_empty()).unwrap_or("https://github.com/agentmuxai/agentmux/releases/latest");
539            out.push_str(&format!(" This install can't upgrade itself yet; the user can download it from {url}."));
540        }
541    }
542    out
543}
544
545/// `upgrade`'s answer, from srv's outcome.
546fn describe_outcome(o: &Value) -> String {
547    let version = s(o, "version");
548    match s(o, "status") {
549        "started" => {
550            let mut text = format!(
551                "Upgrade to {version} started: AgentMux downloads it if needed, then restarts once every agent has finished \
552                 its turn and the in-app countdown has ended, with no second dialog. End your turn so you don't hold it up. \
553                 Your session resumes after the restart."
554            );
555            let stopping: Vec<&str> = o["stopping"].as_array().into_iter().flatten().filter_map(|v| v.as_str()).collect();
556            if !stopping.is_empty() {
557                text.push_str(&format!(
558                    " The restart also stops what agents left running in the background: {}. Each agent is told afterwards.",
559                    stopping.join("; ")
560                ));
561            }
562            text
563        }
564        "requested" => format!(
565            "Asked for the upgrade to {version} as a sensitive operation ({}). If the super agent approves, the person \
566             sees a banner with a countdown and can veto it, and the upgrade starts when it ends. You'll get [AgentMux] \
567             notes as it goes; don't ask again meanwhile. Check it with Sensitive status, id {}.",
568            s(o, "review"),
569            s(o, "id")
570        ),
571        "up_to_date" => format!("AgentMux {} is the latest release; nothing to upgrade.", s(o, "current")),
572        "unavailable" => {
573            let mut out = format!("Can't upgrade: {}.", s(o, "message"));
574            if let Some(url) = o["url"].as_str() {
575                out.push_str(&format!(" The release page: {url}"));
576            }
577            out
578        }
579        other => format!("App upgrade: unexpected answer {other:?}: {o}"),
580    }
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586    use serde_json::json;
587
588    #[test]
589    fn a_contains_text_keeps_its_whitespace_and_only_the_empty_text_is_no_filter() {
590        assert_eq!(contains_arg(&json!({ "contains": " store " })).as_deref(), Some(" store "));
591        assert_eq!(contains_arg(&json!({ "contains": "  " })).as_deref(), Some("  "));
592        assert_eq!(contains_arg(&json!({ "contains": "" })), None);
593        assert_eq!(contains_arg(&json!({})), None);
594        assert_eq!(contains_arg(&json!({ "contains": 7 })), None);
595        // `level` is a word, so it is still trimmed.
596        assert_eq!(str_arg(&json!({ "level": " warn " }), "level").as_deref(), Some("warn"));
597    }
598
599    #[test]
600    fn a_machine_is_called_a_release_or_a_local_build_by_its_build_never_by_its_channel() {
601        // A release that a local build was upgraded to keeps that build's channel for its data.
602        let mut r = json!({ "version": "0.60.22", "build": "0.60.22", "build_kind": "release", "channel": "local-main-b28b7a-0000000a", "os": "linux" });
603        assert_eq!(describe_identity(&r), "AgentMux 0.60.22 (a release, build 0.60.22, data in channel local-main-b28b7a-0000000a, linux)");
604        r["build_kind"] = json!("local");
605        r["build"] = json!("0.60.22+g2a5424fe2.1");
606        assert_eq!(describe_identity(&r), "AgentMux 0.60.22 (a local build, build 0.60.22+g2a5424fe2.1, data in channel local-main-b28b7a-0000000a, linux)");
607        // An AgentMux from before it said its kind: nothing is guessed from the channel.
608        let old = json!({ "version": "0.60.20", "build": "0.60.20", "channel": "local-main-b28b7a-0000000a", "os": "linux" });
609        assert_eq!(describe_identity(&old), "AgentMux 0.60.20 (build 0.60.20, data in channel local-main-b28b7a-0000000a, linux)");
610    }
611
612    #[test]
613    fn version_says_what_runs_and_what_the_agent_can_do() {
614        let st = json!({
615            "state": "available", "current": "0.59.26", "latest": "0.59.27", "install": "windows-portable",
616            "can_download": true, "url": "https://github.com/agentmuxai/agentmux/releases/tag/v0.59.27",
617            "download": { "version": "0.59.27", "state": "ready", "received": 1, "total": 1, "waiting_for": 0 },
618            "checked_ms": 1
619        });
620        let text = describe_status(&st);
621        assert!(text.starts_with("AgentMux 0.59.26 (windows-portable). A newer release is out: 0.59.27."), "{text}");
622        assert!(text.contains("downloaded and ready"), "{text}");
623        assert!(text.contains("action \"upgrade\""), "{text}");
624        assert!(!text.contains("not confirmed"), "nothing unconfirmed to say: {text}");
625
626        // A restart that was asked for and not confirmed says when and why, from a word and a time (a remote answer's).
627        for (why, words) in [("timed_out", "nobody answered"), ("no", "answered No"), ("too_late", "had lapsed"), ("unanswered", "didn't restart AgentMux in time"), ("declined", "was declined")] {
628            let mut unconfirmed = st.clone();
629            unconfirmed["download"]["not_confirmed_at"] = json!(1_795_106_021_000u64);
630            unconfirmed["download"]["not_confirmed"] = json!(why);
631            let text = describe_status(&unconfirmed);
632            assert!(text.contains("ready to restart into. The last restart into it did not go ahead at 16:33 UTC") && text.contains(words), "{why}: {text}");
633        }
634
635        let setup = json!({ "state": "available", "current": "0.59.26", "latest": "0.59.27", "install": "windows-setup",
636            "can_download": false, "url": "https://example/r", "checked_ms": 1 });
637        assert!(describe_status(&setup).contains("can't upgrade itself yet; the user can download it from https://example/r"));
638        let same = json!({ "state": "up-to-date", "current": "0.59.27", "latest": "0.59.27", "install": "windows-portable", "checked_ms": 1 });
639        assert!(describe_status(&same).ends_with("This is the latest release."));
640        let old = json!({ "state": "available", "current": "0.57.3", "latest": "0.60.0", "install": "windows-portable",
641            "can_download": false, "install_first": "0.58.0", "checked_ms": 1 });
642        let text = describe_status(&old);
643        assert!(text.contains("older than 0.60.0 upgrades from: the user installs 0.58.0 first"), "{text}");
644        assert!(!text.contains("action \"upgrade\""), "{text}");
645    }
646
647    #[test]
648    fn disk_lists_volumes_build_folders_and_says_when_sizes_are_lower_bounds() {
649        let gb = 1_073_741_824u64;
650        let report = json!({
651            "data_volume": { "free_bytes": 10 * gb, "total_bytes": 100 * gb },
652            "agents_volume": null,
653            "build_folders": [
654                { "clone": "korp/agentmux", "target_bytes": 30 * gb, "incremental_bytes": 5 * gb, "complete": false },
655                { "clone": "posa/agentmux", "target_bytes": 2 * gb, "incremental_bytes": 0, "complete": true }
656            ],
657            "build_folders_total_bytes": 32 * gb,
658            "older_versions": [{ "version": "0.60.7", "bytes": 3 * gb, "complete": true }, { "version": "0.60.6", "bytes": gb, "complete": false }],
659            "complete": false,
660            "note": "Older version folders are removed by a person."
661        });
662        let text = describe_disk("area54", &report);
663        assert!(text.contains("data volume: 10.0 GB free of 100.0 GB"), "{text}");
664        assert!(!text.contains("agents volume"), "{text}");
665        assert!(text.contains("korp/agentmux: 30.0 GB+ (incremental 5.0 GB)"), "{text}");
666        assert!(text.contains("posa/agentmux: 2.0 GB (incremental 0.0 GB)"), "{text}");
667        assert!(text.contains("0.60.7: 3.0 GB"), "{text}");
668        assert!(text.contains("0.60.6: 1.0 GB+"), "{text}");
669        assert!(text.contains("lower bounds"), "{text}");
670    }
671
672    #[test]
673    fn history_reclaim_says_who_asked_when_it_runs_and_how_to_take_it_back() {
674        let pending = json!({ "pending": true, "requested_by": "loap-3", "requested_at_ms": 1, "last_done_ms": 0, "last_before_bytes": 0, "last_after_bytes": 0 });
675        let text = describe_reclaim(&pending, "request");
676        assert!(text.contains("is asked for (by loap-3)"), "{text}");
677        assert!(text.contains("next start of AgentMux") && text.contains("History > Storage"), "{text}");
678        assert!(text.contains("reclaim \"cancel\"") && text.contains("keeps the first request"), "{text}");
679        assert!(!describe_reclaim(&pending, "status").contains("keeps the first request"));
680
681        let none = json!({ "pending": false, "last_done_ms": 0, "last_before_bytes": 0, "last_after_bytes": 0 });
682        assert!(describe_reclaim(&none, "cancel").starts_with("No reclaim of the pane-history store is asked for now."));
683        assert!(describe_reclaim(&none, "status").contains("reclaim \"request\" asks for one"));
684        let taken = json!({ "pending": false, "withdrew_request_of": "operator" });
685        assert!(describe_reclaim(&taken, "cancel").contains("withdrew the request made by operator"));
686
687        let done = json!({ "pending": false, "last_done_ms": 5, "last_before_bytes": 3u64 << 30, "last_after_bytes": 1u64 << 30 });
688        assert!(describe_reclaim(&done, "status").contains("from 3072.0 MB to 1024.0 MB"));
689        let failed = json!({ "pending": true, "requested_by": "operator", "waiting_for": "another AgentMux is running", "last_error": "disk full" });
690        let text = describe_reclaim(&failed, "status");
691        assert!(text.contains("did not run it: another AgentMux is running") && text.contains("failed: disk full"), "{text}");
692    }
693
694    #[test]
695    fn network_names_each_service_and_what_is_down() {
696        let now = 10_000_000;
697        let all_up = json!({ "revision": 1, "services": [
698            { "service": "internet", "label": "Internet", "state": "online", "since_ms": 1, "last_error": null },
699            { "service": "model_api:anthropic", "label": "Anthropic API", "state": "unknown", "since_ms": 1, "last_error": null },
700        ] });
701        let text = describe_network(&all_up, now);
702        assert!(text.contains("- Internet: online") && text.contains("- Anthropic API: not checked yet"), "{text}");
703        assert!(text.contains("Nothing AgentMux has checked is down") && text.contains("does not rule the network out"), "{text}");
704
705        let down = json!({ "revision": 2, "services": [
706            { "service": "internet", "label": "Internet", "state": "online", "since_ms": 1, "last_error": null },
707            { "service": "muxbus", "label": "MuxBus", "state": "offline", "since_ms": now - 7_500_000, "last_error": "connection reset" },
708            { "service": "model_api:anthropic", "label": "Anthropic API", "state": "degraded", "since_ms": now - 30_000, "last_error": null },
709        ] });
710        let text = describe_network(&down, now);
711        assert!(text.contains("- MuxBus: OFFLINE for 2 h 5 min (connection reset)"), "{text}");
712        assert!(text.contains("- Anthropic API: degraded for 30 s"), "{text}");
713        assert!(text.contains("Down or failing: MuxBus, Anthropic API"), "{text}");
714        assert!(!text.contains("Nothing AgentMux has checked is down") && text.contains("may be the network"), "{text}");
715
716        assert_eq!(describe_network(&json!({ "services": [] }), now), "AgentMux hasn't checked the network yet.");
717    }
718
719    #[test]
720    fn a_log_read_says_what_was_asked_how_much_was_searched_and_how_many_matched() {
721        let filtered = json!({ "which": "host", "lines": 2, "matched": 7, "searched": 30000, "searched_bytes": 4194304, "whole_file": false, "text": "a\nb" });
722        let asked = json!({ "level": "warn", "contains": "store" });
723        assert_eq!(
724            describe_logs("Area54's", &asked, &filtered),
725            "Area54's host log (level warn or above, containing \"store\"), 7 of 30000 lines in the last 4.0 MB of the file matched; 2 returned:\na\nb"
726        );
727        let plain = json!({ "which": "srv", "lines": 1, "matched": 1, "searched": 1, "searched_bytes": 90, "whole_file": true, "shortened": true, "text": "x" });
728        assert_eq!(
729            describe_logs("This machine's", &json!({}), &plain),
730            "This machine's srv log, 1 of 1 lines in the whole file matched; 1 returned (shortened to fit):\nx"
731        );
732        // An AgentMux from before the filters says nothing of what it searched.
733        let old = json!({ "which": "srv", "lines": 3, "text": "x" });
734        assert_eq!(describe_logs("Old's", &json!({}), &old), "Old's srv log, 3 returned:\nx");
735        // ...and when a filter was asked of it, the answer says the filter was not applied.
736        let asked = json!({ "level": "warn", "contains": "store" });
737        assert_eq!(
738            describe_logs("Old's", &asked, &old),
739            "Old's srv log, 3 returned. That AgentMux is from before the filters and ignored level warn or above and containing \"store\": these are its last lines, unfiltered:\nx"
740        );
741    }
742
743    #[test]
744    fn a_remote_status_without_a_url_or_an_error_still_reads_whole() {
745        // What `app.version` gives: srv leaves the release URL and the download's error text out.
746        let st = json!({ "state": "available", "current": "0.60.7", "latest": "0.60.8", "install": "windows-portable",
747            "can_download": false, "checked_ms": 1 });
748        let text = describe_status(&st);
749        assert!(text.contains("download it from https://github.com/agentmuxai/agentmux/releases/latest."), "{text}");
750        let failed = json!({ "state": "available", "current": "0.60.7", "latest": "0.60.8", "install": "windows-setup",
751            "can_download": true, "download": { "version": "0.60.8", "state": "failed" } });
752        let text = describe_status(&failed);
753        assert!(text.contains("Its download failed.") && !text.contains("failed:"), "{text}");
754    }
755
756    #[test]
757    fn every_outcome_tells_the_agent_what_happens_next() {
758        let started = describe_outcome(&json!({ "status": "started", "version": "0.59.27" }));
759        assert!(started.contains("End your turn") && !started.contains("background"), "{started}");
760        let stopping = describe_outcome(&json!({
761            "status": "started",
762            "version": "0.59.27",
763            "stopping": ["Korp: an AgentMux instance (`task dev`), running 9 h"],
764        }));
765        assert!(stopping.contains("also stops what agents left running in the background: Korp: an AgentMux instance"), "{stopping}");
766        let r = describe_outcome(&json!({ "status": "requested", "version": "0.59.27", "id": "r7", "review": "the super agent has been asked" }));
767        assert!(r.contains("sensitive operation (the super agent has been asked)") && r.contains("veto") && r.contains("id r7"), "{r}");
768        assert!(describe_outcome(&json!({ "status": "up_to_date", "current": "0.59.27" })).contains("latest release"));
769        let u = describe_outcome(&json!({ "status": "unavailable", "message": "no", "url": "https://x" }));
770        assert_eq!(u, "Can't upgrade: no. The release page: https://x");
771    }
772}