Skip to main content

agentmux_srv/server/
http_viewer_input.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /agentmux/viewer/agents/:name/input`: a paired device sends a
5//! message to an agent, as the user (agentmux-mobile's
6//! SPEC_SEND_FROM_THE_PHONE_2026_10_13 §4, §5). The one viewer route that
7//! changes anything, so it asks for more than the token:
8//!
9//! - the owner's grant for this device (Settings › Paired devices, Can send);
10//! - a signature by the key the device made at pairing, over method, path,
11//!   time and body (`viewer::signing`), fresh within a minute;
12//! - a `message_id`, so a retry is delivered once (`viewer::sends`), and at
13//!   most 30 sends a minute.
14//!
15//! The agent gets a plain user turn, delivered the way a Swarm broadcast is:
16//! a running agent reads it at its next step, mid-turn included; an idle or
17//! stopped one starts a turn. The stored record says which device sent it
18//! (`viewer::origin`), for the desktop pane's note and the phone's own
19//! "Sending…" line.
20
21use axum::body::Bytes;
22use axum::extract::rejection::BytesRejection;
23use axum::extract::Path;
24use serde::Deserialize;
25
26use super::http_viewer::{agent_hidden, ViewerCaller};
27use super::*;
28use crate::backend::blockcontroller::health::TurnInput;
29use crate::backend::message_origin::MessageOrigin;
30use crate::backend::reactive::{device_turn_message, SenderDelivery, MAX_MESSAGE_LENGTH};
31use crate::backend::viewer::audit::{self, Proof, ViewerActor};
32use crate::backend::viewer::origin::{self, DeviceOrigin};
33use crate::backend::viewer::sends::{Admit, Sent};
34use crate::backend::viewer::signing::{self, DeviceKey};
35use crate::bootstrap::AgentRoute;
36use crate::server::agent_handlers::{run_agent_turn, AgentTurnDeps, TurnRegistration};
37
38/// The largest request body: a message at `MAX_MESSAGE_LENGTH` bytes, JSON
39/// escaped, with room to spare.
40pub(crate) const MAX_INPUT_BODY: usize = 64 * 1024;
41
42#[derive(Deserialize)]
43struct InputBody {
44    message: String,
45    message_id: String,
46    /// The person on a sending computer, as it names them (signed with the body, but its claim): stored beside
47    /// the message and named in its Audit row. Ignored from a phone.
48    #[serde(default)]
49    user: Option<String>,
50}
51
52fn refuse(status: StatusCode, reason: Option<&str>, error: &str) -> Response {
53    let mut body = json!({ "error": error });
54    if let Some(reason) = reason {
55        body["reason"] = json!(reason);
56    }
57    (status, Json(body)).into_response()
58}
59
60/// Why delivery failed, for the phone: `starting` and `needs_login` pass;
61/// `not_running` means nothing will take it until the agent is opened.
62fn delivery_refusal(error: &str) -> Response {
63    let lower = error.to_lowercase();
64    let reason = if lower.contains("identity spawn gate") || lower.contains("log in") || lower.contains("sign in") {
65        "needs_login"
66    } else if lower.contains("starting up") || lower.contains("stopping") || lower.contains("queue is full") {
67        "starting"
68    } else if lower.contains("no controller") {
69        "not_running"
70    } else {
71        "failed"
72    };
73    refuse(StatusCode::CONFLICT, Some(reason), error)
74}
75
76/// After a delivery from `device` to `agent`: the send ledger learns how it went (a failed one may be retried); a
77/// delivered one shows the device as driving the agent on the host, and a failed one's origin is forgotten.
78fn settle(state: &AppState, (device_id, agent): (&str, &str), block_id: &str, message_id: &str, sent: Option<Sent>) {
79    state.viewer.sends.lock().finish(device_id, message_id, sent);
80    match sent {
81        Some(_) => state.viewer.note_sent(device_id, agent, agentmux_common::time::now_ms()),
82        None => forgotten(block_id, message_id),
83    }
84}
85
86/// A message that was not delivered: nothing is stored for it, and its Audit row says it failed. (A delivered one's
87/// row is written when its line is stored, `audit::note_landed`.)
88fn forgotten(block_id: &str, message_id: &str) {
89    if let Some((actor, agent)) = origin::forget(block_id, message_id).and_then(|o| o.sender) {
90        audit::record(&actor, "send", &agent, Proof::Signed, None, Some("not delivered"));
91    }
92}
93
94/// Whether `body`, sent to `path`, is signed by `key` within a minute of this computer's clock: else the
95/// refusal's reason and text.
96fn check_signed(key: &DeviceKey, path: &str, headers: &axum::http::HeaderMap, body: &[u8]) -> Result<(), (&'static str, &'static str)> {
97    let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).map(str::trim);
98    let (Some(timestamp), Some(signature)) = (header(signing::TIMESTAMP_HEADER), header(signing::SIGNATURE_HEADER)) else {
99        return Err(("bad_signature", "the request is not signed"));
100    };
101    let Ok(timestamp_ms) = timestamp.parse::<i64>() else {
102        return Err(("bad_signature", "the signing time is not a number"));
103    };
104    let signed = signing::signed_text("POST", path, timestamp_ms, body);
105    if !key.verifies(signed.as_bytes(), signature) {
106        tracing::warn!("viewer input: signature did not verify");
107        return Err(("bad_signature", "the signature does not verify"));
108    }
109    if !signing::fresh(timestamp_ms, agentmux_common::time::now_ms()) {
110        return Err(("stale_timestamp", "the request was signed more than a minute from this computer's clock"));
111    }
112    Ok(())
113}
114
115/// Deliver `text` to `block_id` as the user's turn, the way a Swarm
116/// broadcast is (`app_api::fleet::deliver_broadcast_turn`).
117async fn deliver(state: &AppState, block_id: &str, text: &str) -> Result<Sent, Response> {
118    let input = TurnInput { from: MessageOrigin::user(), text: text.to_string(), joins_turn: None };
119    match crate::bootstrap::route_agent_message_from(block_id, text, Some(input), MessageOrigin::user(), &[], None) {
120        Ok(AgentRoute::Sent(SenderDelivery::Delivered)) => Ok(Sent::Delivered),
121        Ok(AgentRoute::Sent(SenderDelivery::Deferred)) => Ok(Sent::Queued),
122        Ok(AgentRoute::Sent(SenderDelivery::Pty)) => Err(refuse(
123            StatusCode::CONFLICT,
124            Some("not_supported"),
125            "this pane runs in a terminal; messages can't be sent to it",
126        )),
127        // Not running, or a kind that takes a turn per message: start one.
128        // The block came from the agent registry, so it is registered.
129        Ok(AgentRoute::StartTurn { .. }) => {
130            let deps = AgentTurnDeps::from_state(state);
131            run_agent_turn(&deps, block_id.to_string(), text.to_string(), None, TurnRegistration::Skip, MessageOrigin::user(), Vec::new())
132                .await
133                .map(|()| Sent::Delivered)
134                .map_err(|e| delivery_refusal(&e))
135        }
136        Err(e) => Err(delivery_refusal(&e)),
137    }
138}
139
140/// `POST /agentmux/viewer/agents/:name/input`: `{message, message_id}`,
141/// signed; `202 {message_id, state}`. See the module comment and the spec's
142/// §5.2.1 for every refusal.
143pub(crate) async fn handle_viewer_input(
144    State(state): State<AppState>,
145    Extension(caller): Extension<ViewerCaller>,
146    Path(name): Path<String>,
147    uri: axum::extract::OriginalUri,
148    headers: axum::http::HeaderMap,
149    body: Result<Bytes, BytesRejection>,
150) -> Response {
151    let Ok(body) = body else {
152        return refuse(StatusCode::PAYLOAD_TOO_LARGE, None, "the request is too large");
153    };
154    let device = match state.mstore.viewer_device_get(&caller.device_id) {
155        Ok(Some(device)) => device,
156        // Revoked between the token check and here.
157        Ok(None) => return super::auth::unauthorized(),
158        Err(e) => {
159            tracing::warn!(error = %e, "viewer input: could not read the device");
160            return refuse(StatusCode::INTERNAL_SERVER_ERROR, None, "could not read the device");
161        }
162    };
163    if !device.can_send {
164        audit::record(&ViewerActor::of(&device, None), "send", &name, Proof::Token, None, Some("sending is off for this device"));
165        return refuse(
166            StatusCode::FORBIDDEN,
167            Some("send_off"),
168            "sending is off for this device: turn it on in AgentMux › Settings › Paired devices",
169        );
170    }
171    let Ok(key) = DeviceKey::parse(&device.device_key) else {
172        audit::record(&ViewerActor::of(&device, None), "send", &name, Proof::Token, None, Some("the device has no key"));
173        return refuse(StatusCode::FORBIDDEN, Some("pair_again"), "this device has no key: pair it again to send");
174    };
175
176    // The signature, before anything in the body is trusted.
177    if let Err((reason, error)) = check_signed(&key, uri.0.path(), &headers, &body) {
178        audit::record(&ViewerActor::of(&device, None), "send", &name, Proof::Token, None, Some(error));
179        return refuse(StatusCode::FORBIDDEN, Some(reason), error);
180    }
181
182    let Ok(input) = serde_json::from_slice::<InputBody>(&body) else {
183        return refuse(StatusCode::BAD_REQUEST, None, "expected {message, message_id}");
184    };
185    let message = input.message.trim_end();
186    if message.trim().is_empty() {
187        return refuse(StatusCode::BAD_REQUEST, None, "the message is empty");
188    }
189    if message.len() > MAX_MESSAGE_LENGTH {
190        return refuse(StatusCode::PAYLOAD_TOO_LARGE, None, &format!("a message is at most {MAX_MESSAGE_LENGTH} bytes"));
191    }
192    if uuid::Uuid::parse_str(&input.message_id).is_err() {
193        return refuse(StatusCode::BAD_REQUEST, None, "message_id must be a UUID");
194    }
195
196    let Some(agent) = state.reactive_handler.get_agent(&name) else {
197        return refuse(StatusCode::NOT_FOUND, None, "no such agent");
198    };
199    // Hidden agents are 404, as in the list and the feed: not even named.
200    if agent_hidden(&state, &agent.block_id) {
201        return refuse(StatusCode::NOT_FOUND, None, "no such agent");
202    }
203
204    let admitted = state.viewer.sends.lock().admit(&device.device_id, &input.message_id, std::time::Instant::now());
205    match admitted {
206        Admit::New => {}
207        Admit::Duplicate(sent) => {
208            return (
209                StatusCode::ACCEPTED,
210                Json(json!({ "message_id": input.message_id, "state": sent.as_str(), "duplicate": true })),
211            )
212                .into_response()
213        }
214        Admit::InFlight => {
215            return refuse(StatusCode::CONFLICT, Some("in_flight"), "this message is being sent; try again in a moment")
216        }
217        Admit::RateLimited(wait) => {
218            let secs = wait.as_secs().max(1).to_string();
219            let mut resp = refuse(StatusCode::TOO_MANY_REQUESTS, None, "too many messages; wait a moment");
220            if let Ok(v) = axum::http::HeaderValue::from_str(&secs) {
221                resp.headers_mut().insert(header::RETRY_AFTER, v);
222            }
223            return resp;
224        }
225    }
226
227    // Delivered and recorded in a task of its own: a phone that drops the
228    // connection mid-request must not leave the id in flight (a retry would
229    // get `in_flight` for 10 minutes) or a delivery half done.
230    let text = device_turn_message(message);
231    let block_id = agent.block_id.clone();
232    let message_id = input.message_id.clone();
233    let task = tokio::spawn({
234        let state = state.clone();
235        let device_id = device.device_id.clone();
236        let sender = (ViewerActor::of(&device, input.user.as_deref()), agent.agent_id.clone());
237        let origin = DeviceOrigin { device: device.device_name.clone(), message_id: message_id.clone(), sender: Some(sender) };
238        let (message_id, agent_name) = (message_id.clone(), agent.agent_id.clone());
239        async move {
240            origin::expect(&block_id, &text, origin);
241            let outcome = deliver(&state, &block_id, &text).await;
242            settle(&state, (&device_id, &agent_name), &block_id, &message_id, outcome.as_ref().ok().copied());
243            outcome
244        }
245    });
246    match task.await {
247        Ok(Ok(sent)) => {
248            tracing::info!(device = %device.device_id, agent = %name, state = sent.as_str(), "viewer input: sent");
249            (StatusCode::ACCEPTED, Json(json!({ "message_id": message_id, "state": sent.as_str() }))).into_response()
250        }
251        Ok(Err(resp)) => resp,
252        Err(e) => {
253            // The task panicked: nothing recorded it as sent, so a retry tries again.
254            tracing::warn!(error = %e, "viewer input: delivery task failed");
255            state.viewer.sends.lock().finish(&device.device_id, &message_id, None);
256            forgotten(&agent.block_id, &message_id);
257            refuse(StatusCode::INTERNAL_SERVER_ERROR, Some("failed"), "delivery failed")
258        }
259    }
260}
261
262#[cfg(test)]
263#[path = "tests/viewer/viewer_input_tests.rs"]
264mod tests;