agentmux_srv/server/app_api/
workspace_stop.rs1use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::{json, Value};
19
20use crate::server::caller::Caller;
21use crate::server::host_control::{self, KeepRefusal, KeepRunning, Stop};
22use crate::server::AppState;
23
24pub(crate) fn workspace_view(stop: Option<Stop>, keep: Option<KeepRunning>) -> Value {
26 json!({
27 "stopping": stop.is_some(),
28 "stop_at_ms": stop.map(|s| s.at_ms),
29 "reason_id": stop.map(|s| s.reason.id()),
30 "reason": stop.map(|s| s.reason.phrase()),
31 "keep_running": keep.map(|k| json!({ "minutes": k.minutes, "by": k.by, "at_ms": k.at_ms })),
32 })
33}
34
35pub(crate) async fn handle_workspace() -> Response {
37 let (stop, keep) = host_control::current();
38 Json(workspace_view(stop, keep)).into_response()
39}
40
41#[derive(Debug, Deserialize)]
42pub(crate) struct KeepRunningRequest {
43 minutes: u32,
44}
45
46fn refusal(status: StatusCode, message: &str) -> Response {
47 (status, Json(json!({ "ok": false, "error": message }))).into_response()
48}
49
50pub(crate) async fn handle_keep_running(
52 State(state): State<AppState>,
53 caller: Option<Extension<Caller>>,
54 Json(req): Json<KeepRunningRequest>,
55) -> Response {
56 let Some(uid) = caller.as_deref().and_then(Caller::uid) else {
57 return refusal(StatusCode::UNAUTHORIZED, "no agent token: keep_running is recorded as the agent that asks");
58 };
59 let slug = match state.mstore.agent_def_get(uid) {
60 Ok(Some(def)) => def.slug,
61 Ok(None) => return refusal(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"),
62 Err(e) => return refusal(StatusCode::INTERNAL_SERVER_ERROR, &format!("keep_running: {e}")),
63 };
64 match host_control::ask_keep_running(req.minutes, &format!("agent:{slug}")) {
65 Ok(k) => {
66 tracing::info!(by = %k.by, minutes = k.minutes, "an agent asked for the workspace's stop to be put back");
67 Json(json!({
68 "ok": true,
69 "minutes": k.minutes,
70 "by": k.by,
71 "note": "recorded as yours; the workspace's timer decides whether to honour it: read App workspace to see the stop time",
72 }))
73 .into_response()
74 }
75 Err(e @ KeepRefusal::Minutes) => refusal(StatusCode::BAD_REQUEST, e.message()),
76 Err(e @ KeepRefusal::NoStop) => refusal(StatusCode::CONFLICT, e.message()),
77 }
78}
79
80#[cfg(test)]
81#[path = "workspace_stop_tests.rs"]
82mod tests;