1use axum::extract::rejection::JsonRejection;
16use axum::extract::State;
17use axum::http::StatusCode;
18use axum::response::{IntoResponse, Response};
19use axum::{Extension, Json};
20use serde_json::json;
21
22use agentmux_common::api_types::WpsPublishRequest;
23use agentmux_common::client_events::CompactionStarted;
24
25use crate::backend::container::credential::ContainerGrant;
26use crate::server::AppState;
27
28pub(crate) const MAX_BODY_BYTES: usize = 4 * 1024;
30
31const PERSIST: usize = 0;
36
37fn refuse(status: StatusCode, why: impl Into<String>) -> Response {
38 (status, Json(json!({ "error": why.into() }))).into_response()
39}
40
41fn check(block_id: &str, req: &WpsPublishRequest) -> Result<CompactionStarted, Response> {
43 if req.event != "compaction_started" {
44 return Err(refuse(StatusCode::FORBIDDEN, "this route takes compaction_started only"));
45 }
46 if req.scopes != [format!("block:{block_id}")] {
47 return Err(refuse(StatusCode::FORBIDDEN, "a container agent's compaction goes to its own pane only"));
48 }
49 serde_json::from_value::<CompactionStarted>(req.data.clone())
50 .map_err(|e| refuse(StatusCode::BAD_REQUEST, format!("compaction_started: {e}")))
51}
52
53pub(crate) async fn handle_container_compaction_started(
54 State(state): State<AppState>,
55 grant: Option<Extension<ContainerGrant>>,
56 body: Result<Json<WpsPublishRequest>, JsonRejection>,
57) -> Response {
58 let Some(Extension(grant)) = grant else {
59 return refuse(StatusCode::FORBIDDEN, "this route is for container agents");
60 };
61 let req = match body {
62 Ok(Json(req)) => req,
63 Err(rejection) => return refuse(rejection.status(), rejection.body_text()),
64 };
65 let started = match check(&grant.block_id, &req) {
66 Ok(started) => started,
67 Err(refusal) => return refusal,
68 };
69 state
70 .broker
71 .publish_event::<crate::backend::mps_events::CompactionStarted>(&started, req.scopes, PERSIST);
72 Json(json!({ "ok": true })).into_response()
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78 use axum::body::Body;
79 use axum::http::Request;
80 use tower::ServiceExt;
81
82 fn started() -> serde_json::Value {
83 json!({ "trigger": "manual", "sessionId": "sess-1", "startedAt": "2026-10-31T00:00:00Z" })
84 }
85
86 fn body(event: &str, scopes: &[&str], data: serde_json::Value) -> serde_json::Value {
87 json!({ "event": event, "scopes": scopes, "persist": 999_999, "data": data })
88 }
89
90 async fn post(token: &str, body: String) -> (StatusCode, serde_json::Value) {
91 let state = crate::server::tests::test_state();
92 let app = crate::server::build_router(state);
93 let req = Request::builder()
94 .method("POST")
95 .uri("/api/v1/agent/compaction-started")
96 .header("X-AuthKey", token)
97 .header("Content-Type", "application/json")
98 .body(Body::from(body))
99 .unwrap();
100 let resp = app.oneshot(req).await.unwrap();
101 let status = resp.status();
102 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
103 (status, serde_json::from_slice(&bytes).unwrap_or_default())
104 }
105
106 #[tokio::test]
107 async fn a_container_reports_its_own_compaction_only() {
108 let mine = crate::backend::container::credential::token_for_block("cs-block-a", None);
109 let own = ["block:cs-block-a"];
110 let (status, _) = post(&mine, body("compaction_started", &own, started()).to_string()).await;
111 assert_eq!(status, StatusCode::OK);
112
113 for scopes in [&["block:cs-block-b"][..], &[], &["block:cs-block-a", "block:cs-block-b"], &["tab:cs-block-a"]] {
115 let (status, _) = post(&mine, body("compaction_started", scopes, started()).to_string()).await;
116 assert_eq!(status, StatusCode::FORBIDDEN, "{scopes:?}");
117 }
118 for event in ["tool_chunk", "agent_event:cs-block-a", "controllerstatus", "custom:thing"] {
120 let (status, _) = post(&mine, body(event, &own, started()).to_string()).await;
121 assert_eq!(status, StatusCode::FORBIDDEN, "{event}");
122 }
123 let (status, _) = post(&mine, body("compaction_started", &own, json!({ "trigger": "sideways" })).to_string()).await;
125 assert_eq!(status, StatusCode::BAD_REQUEST);
126 }
127
128 #[tokio::test]
129 async fn a_request_over_the_cap_is_413() {
130 let mine = crate::backend::container::credential::token_for_block("cs-block-big", None);
131 let mut big = started();
132 big["sessionId"] = json!("x".repeat(MAX_BODY_BYTES));
133 let (status, _) = post(&mine, body("compaction_started", &["block:cs-block-big"], big).to_string()).await;
134 assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
135 }
136
137 #[tokio::test]
138 async fn the_route_is_a_container_agents_and_the_generic_relay_stays_refused() {
139 let (status, _) = post("test-secret-key", body("compaction_started", &["block:b"], started()).to_string()).await;
141 assert_eq!(status, StatusCode::FORBIDDEN);
142 assert!(!crate::backend::container::credential::container_route_allowed("/agentmux/wps/publish", crate::server::route_table::serves));
143 assert!(crate::backend::container::credential::container_route_allowed("/api/v1/agent/compaction-started", crate::server::route_table::serves));
144 }
145
146 #[tokio::test]
147 async fn the_start_reaches_the_panes_live_subscribers_and_is_not_kept() {
148 let state = crate::server::tests::test_state();
149 let token = crate::backend::container::credential::token_for_block("cs-block-live", None);
150 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
151 let sink = seen.clone();
152 state.broker.add_observer(std::sync::Arc::new(move |e: &crate::backend::mps::MuxEvent| {
153 if e.scopes == ["block:cs-block-live"] {
154 sink.lock().unwrap().push(e.clone());
155 }
156 }));
157 let app = crate::server::build_router(state);
158 let req = Request::builder()
159 .method("POST")
160 .uri("/api/v1/agent/compaction-started")
161 .header("X-AuthKey", &token)
162 .header("Content-Type", "application/json")
163 .body(Body::from(body("compaction_started", &["block:cs-block-live"], started()).to_string()))
164 .unwrap();
165 assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);
166 let seen = seen.lock().unwrap();
167 assert_eq!(seen.len(), 1);
168 assert_eq!(seen[0].event, "compaction_started");
169 assert_eq!(seen[0].data.as_ref().unwrap()["sessionId"], "sess-1");
170 assert_eq!(seen[0].persist, PERSIST, "a start is never replayed");
171 }
172}