Skip to main content

agentmux_srv/server/
agent_status_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/agent/status`: `Presence status`. An agent says, in one line,
5//! what it is doing now. The line is kept in its pane's block meta with the
6//! time (`backend::work_facts::live_phrase`), which is where the Swarm row and
7//! `work.goal` read it. A task claim writes the task's title in the same place
8//! (`work_queue::handle_work_claim`).
9
10use axum::extract::State;
11use axum::http::StatusCode;
12use axum::response::{IntoResponse, Json, Response};
13use serde::Deserialize;
14use serde_json::json;
15
16use crate::backend::work_facts::live_phrase;
17
18use super::caller::Caller;
19use super::work_claims_handlers::claimer;
20use super::AppState;
21
22/// `Presence status`'s arguments, plus who is asking (`agent`, `block`: the
23/// MCP's own `AGENTMUX_AGENT_ID` and block id; the request's agent token wins).
24#[derive(Debug, Default, Deserialize)]
25pub struct StatusParams {
26    pub line: Option<String>,
27    pub state: Option<String>,
28    /// With state `waiting`: how long the quiet watch leaves the agent alone, 1 to 240 minutes (30 when absent).
29    pub until_minutes: Option<u64>,
30    pub agent: Option<String>,
31    pub block: Option<String>,
32}
33
34/// The status line is written under this lock: a task's end reads the line and clears it only if it is
35/// still the ended task's, and a write that lands in between would otherwise be erased with it.
36static LINE_WRITES: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
37
38fn bad_request(msg: impl Into<String>) -> Response {
39    (StatusCode::BAD_REQUEST, Json(json!({ "error": msg.into() }))).into_response()
40}
41
42/// Write `meta` to the block's own meta, the way a pane title is set, so the
43/// change is stored and reaches every window.
44pub(super) async fn write_block_meta(state: &AppState, block_id: &str, meta: serde_json::Value) -> Result<(), String> {
45    let call = crate::backend::service::WebCallType {
46        service: "object".to_string(),
47        method: "UpdateObjectMeta".to_string(),
48        uicontext: None,
49        args: vec![json!(format!("block:{block_id}")), meta],
50    };
51    match super::service::run_service_call(state, &call).await.error {
52        Some(e) => Err(e),
53        None => Ok(()),
54    }
55}
56
57/// `POST /api/v1/agent/status`.
58pub(crate) async fn handle_agent_status(
59    State(state): State<AppState>,
60    caller: Option<axum::Extension<Caller>>,
61    Json(p): Json<StatusParams>,
62) -> Response {
63    let (line, cut) = match live_phrase::clean_line(p.line.as_deref().unwrap_or("")) {
64        Ok(v) => v,
65        Err(e) => return bad_request(e),
66    };
67    let status = match live_phrase::clean_state(p.state.as_deref()) {
68        Ok(v) => v,
69        Err(e) => return bad_request(e),
70    };
71    let waiting_minutes = match p.until_minutes {
72        None => None,
73        Some(m) if status != Some("waiting") => {
74            return bad_request(format!("until_minutes ({m}) goes with state \"waiting\": say how long you will be quiet, or leave it out"))
75        }
76        Some(m) if m == 0 || m > live_phrase::WAITING_MAX_MINUTES => {
77            return bad_request(format!("until_minutes is 1 to {} minutes; got {m}", live_phrase::WAITING_MAX_MINUTES))
78        }
79        Some(m) => Some(m),
80    };
81    let Some((agent, _uid, block)) = claimer(&state, caller.as_ref().map(|c| &c.0), p.agent.as_deref(), p.block.as_deref())
82    else {
83        return bad_request("who is setting the status is unknown: this needs an agent started by AgentMux");
84    };
85    let Some(block_id) = block else {
86        return bad_request("this agent has no pane here, so there is nowhere to keep its status line");
87    };
88    let _writing = LINE_WRITES.lock().await;
89    let now = agentmux_common::time::now_ms();
90    let meta = match waiting_minutes {
91        Some(minutes) => live_phrase::set_meta_waiting(&line, live_phrase::SRC_AGENT, now, minutes),
92        None => live_phrase::set_meta(&line, status, live_phrase::SRC_AGENT, now),
93    };
94    if let Err(e) = write_block_meta(&state, &block_id, meta).await {
95        return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("status not saved: {e}") }))).into_response();
96    }
97    Json(json!({
98        "ok": true,
99        "agent": agent,
100        "line": line,
101        "state": status,
102        "set_at": now,
103        "cut_to_fit": cut,
104        "quiet_watch_paused_until": (status == Some("waiting")).then(|| now + waiting_minutes.unwrap_or(live_phrase::WAITING_DEFAULT_MINUTES) as i64 * 60_000),
105        "note": "Shown in the Swarm and in Agents conversations until you set another line or claim a task. Set it again when \
106                 your plan changes, when you are blocked or waiting, and when you are done.",
107    }))
108    .into_response()
109}
110
111/// A task claim: the task's title becomes the claimer's line (source `task`),
112/// replacing a line from the task before. The agent replaces it with its own
113/// words by setting a status. Skipped when the claim names no pane, or a pane that is not the holder's
114/// (`holder` is the claimer's name and UID): a claim's `block_id` is the client's word.
115pub(super) fn task_claimed(state: &AppState, block_id: &str, holder: (&str, &str), task_id: &str, number: Option<i64>, title: &str) {
116    let block_id = block_id.trim();
117    let Some(line) = live_phrase::task_line(number.and_then(|n| u64::try_from(n).ok()), title) else { return };
118    if block_id.is_empty() {
119        return;
120    }
121    let (agent_id, uid) = holder;
122    let is_theirs = state.reactive_handler.list_agents().iter().any(|r| {
123        r.block_id == block_id && r.agent_id.eq_ignore_ascii_case(agent_id) && (uid.is_empty() || r.uid.as_deref().map_or(true, |u| u == uid))
124    });
125    if !is_theirs {
126        return;
127    }
128    let (state, block_id, task_id) = (state.clone(), block_id.to_string(), task_id.to_string());
129    tokio::spawn(async move {
130        let _writing = LINE_WRITES.lock().await;
131        let meta = live_phrase::task_meta(&line, &task_id, agentmux_common::time::now_ms());
132        if let Err(e) = write_block_meta(&state, &block_id, meta).await {
133            tracing::warn!(block_id = %block_id, error = %e, "task claim: could not set the status line");
134        }
135    });
136}
137
138/// A task done or handed back: the line that task wrote goes, so the row does not go on naming work
139/// that ended. A line the agent set itself stays (it said "Done: ..." or something newer), and so does
140/// the line of another task (found by `task_id`, which a rename of the task does not change). Only the
141/// holder's pane is touched: `uid` is the holder's, so another agent that shares its name keeps its line.
142pub(super) fn task_ended(state: &AppState, agent_id: &str, uid: &str, task_id: &str) {
143    let (state, agent_id, uid, task_id) = (state.clone(), agent_id.trim().to_string(), uid.trim().to_string(), task_id.to_string());
144    if agent_id.is_empty() {
145        return;
146    }
147    let ended_at = agentmux_common::time::now_ms().max(0) as u64;
148    tokio::spawn(async move {
149        let blocks: Vec<String> = state
150            .reactive_handler
151            .list_agents()
152            .into_iter()
153            .filter(|r| r.agent_id.eq_ignore_ascii_case(&agent_id))
154            .filter(|r| uid.is_empty() || r.uid.as_deref().map_or(true, |u| u == uid))
155            .map(|r| r.block_id)
156            .collect();
157        for block_id in blocks {
158            let _writing = LINE_WRITES.lock().await;
159            let mstore = state.mstore.clone();
160            let (id, ended) = (block_id.clone(), task_id.clone());
161            let from_task = tokio::task::spawn_blocking(move || {
162                mstore
163                    .get::<crate::backend::obj::Block>(&id)
164                    .ok()
165                    .flatten()
166                    .and_then(|b| live_phrase::declared_of(&b.meta))
167                    .is_some_and(|d| d.src == live_phrase::SRC_TASK && d.at_ms <= ended_at && d.task.as_deref() == Some(ended.as_str()))
168            })
169            .await
170            .unwrap_or(false);
171            if from_task {
172                if let Err(e) = write_block_meta(&state, &block_id, live_phrase::clear_meta()).await {
173                    tracing::warn!(block_id = %block_id, error = %e, "task end: could not clear the status line");
174                }
175            }
176        }
177    });
178}