agentmux_srv/server/
host_http.rs1use axum::http::StatusCode;
7
8use super::HostIpc;
9
10pub(crate) async fn post_to_host(
13 http_client: &reqwest::Client,
14 host: &HostIpc,
15 route: &str,
16 body: serde_json::Value,
17 timeout: Option<std::time::Duration>,
18) -> Result<serde_json::Value, String> {
19 let url = format!("http://127.0.0.1:{}/agentmux/browser/{route}", host.port);
20 let mut request = http_client
21 .post(&url)
22 .header("Authorization", format!("Bearer {}", host.token))
23 .json(&body);
24 if let Some(t) = timeout {
25 request = request.timeout(t);
26 }
27 let resp = request
28 .send()
29 .await
30 .map_err(|e| proxy_error(route, &e))?;
31 if resp.status() == StatusCode::UNAUTHORIZED {
32 return Err(
33 "host rejected our ipc_token — stale registration after a host restart? \
34 will self-heal on the host's next host_ipc.Register call"
35 .to_string(),
36 );
37 }
38 resp.json::<serde_json::Value>()
39 .await
40 .map_err(|e| format!("parse host {route} response: {e}"))
41}
42
43fn proxy_error(route: &str, e: &reqwest::Error) -> String {
46 proxy_error_text(route, e.is_timeout(), &e.to_string())
47}
48
49fn proxy_error_text(route: &str, timed_out: bool, why: &str) -> String {
50 if timed_out {
51 format!("proxy to host {route}: the page did not answer in time ({why}); it may still be loading: Browser wait with until_state load, then try again")
52 } else {
53 format!("proxy to host {route}: {why}")
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::proxy_error_text;
60
61 #[test]
62 fn a_call_that_ran_out_of_time_says_the_page_may_still_be_loading() {
63 let m = proxy_error_text("act", true, "operation timed out");
64 assert!(m.starts_with("proxy to host act: the page did not answer in time") && m.contains("until_state load"), "{m}");
65 }
66
67 #[test]
68 fn any_other_failure_keeps_its_own_words() {
69 assert_eq!(proxy_error_text("act", false, "connection refused"), "proxy to host act: connection refused");
70 }
71}