Skip to main content

agentmux_srv/server/app_api/
workspace_stop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! What an agent can do about a workspace that is going to stop (`App` `workspace` and `keep_running`).
5//!
6//! - `GET /api/v1/app/workspace`: whether a stop is pending, when and why (the reason ids and phrases of the
7//!   `workspace:stop` event), and what an agent last asked for.
8//! - `POST /api/v1/agent/keep-running { minutes }`: ask for the pending stop to be pushed back by 1 to 240
9//!   minutes. It is recorded as the agent that asked (`agent:<id>`); srv hands the request to its registered
10//!   external host with the next activity answer, and the host decides whether to honour it. With no stop
11//!   pending there is nothing to put back and it is refused. Both work for host and container agents alike.
12
13use 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
24/// The workspace's stop as an agent reads it.
25pub(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
35/// `GET /api/v1/app/workspace`.
36pub(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
50/// `POST /api/v1/agent/keep-running`.
51pub(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;